sqlite3.c 6.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.10.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.10.1"
  310. #define SQLITE_VERSION_NUMBER 3010001
  311. #define SQLITE_SOURCE_ID "2016-01-13 21:41:56 254419c36766225ca542ae873ed38255e3fb8588"
  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_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  666. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  667. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  668. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  669. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  670. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  671. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  672. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  673. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  674. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  675. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  676. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  677. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  678. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  679. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  680. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  681. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  682. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  683. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  684. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  685. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  686. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  687. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  688. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  689. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  690. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  691. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  692. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  693. /*
  694. ** CAPI3REF: Flags For File Open Operations
  695. **
  696. ** These bit values are intended for use in the
  697. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  698. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  699. */
  700. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  701. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  702. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  703. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  704. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  705. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  706. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  707. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  708. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  709. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  710. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  711. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  712. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  713. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  714. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  715. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  716. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  717. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  718. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  719. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  720. /* Reserved: 0x00F00000 */
  721. /*
  722. ** CAPI3REF: Device Characteristics
  723. **
  724. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  725. ** object returns an integer which is a vector of these
  726. ** bit values expressing I/O characteristics of the mass storage
  727. ** device that holds the file that the [sqlite3_io_methods]
  728. ** refers to.
  729. **
  730. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  731. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  732. ** mean that writes of blocks that are nnn bytes in size and
  733. ** are aligned to an address which is an integer multiple of
  734. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  735. ** that when data is appended to a file, the data is appended
  736. ** first then the size of the file is extended, never the other
  737. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  738. ** information is written to disk in the same order as calls
  739. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  740. ** after reboot following a crash or power loss, the only bytes in a
  741. ** file that were written at the application level might have changed
  742. ** and that adjacent bytes, even bytes within the same sector are
  743. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  744. ** flag indicate that a file cannot be deleted when open. The
  745. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  746. ** read-only media and cannot be changed even by processes with
  747. ** elevated privileges.
  748. */
  749. #define SQLITE_IOCAP_ATOMIC 0x00000001
  750. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  751. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  752. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  753. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  754. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  755. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  756. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  757. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  758. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  759. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  760. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  761. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  762. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  763. /*
  764. ** CAPI3REF: File Locking Levels
  765. **
  766. ** SQLite uses one of these integer values as the second
  767. ** argument to calls it makes to the xLock() and xUnlock() methods
  768. ** of an [sqlite3_io_methods] object.
  769. */
  770. #define SQLITE_LOCK_NONE 0
  771. #define SQLITE_LOCK_SHARED 1
  772. #define SQLITE_LOCK_RESERVED 2
  773. #define SQLITE_LOCK_PENDING 3
  774. #define SQLITE_LOCK_EXCLUSIVE 4
  775. /*
  776. ** CAPI3REF: Synchronization Type Flags
  777. **
  778. ** When SQLite invokes the xSync() method of an
  779. ** [sqlite3_io_methods] object it uses a combination of
  780. ** these integer values as the second argument.
  781. **
  782. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  783. ** sync operation only needs to flush data to mass storage. Inode
  784. ** information need not be flushed. If the lower four bits of the flag
  785. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  786. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  787. ** to use Mac OS X style fullsync instead of fsync().
  788. **
  789. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  790. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  791. ** settings. The [synchronous pragma] determines when calls to the
  792. ** xSync VFS method occur and applies uniformly across all platforms.
  793. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  794. ** energetic or rigorous or forceful the sync operations are and
  795. ** only make a difference on Mac OSX for the default SQLite code.
  796. ** (Third-party VFS implementations might also make the distinction
  797. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  798. ** operating systems natively supported by SQLite, only Mac OSX
  799. ** cares about the difference.)
  800. */
  801. #define SQLITE_SYNC_NORMAL 0x00002
  802. #define SQLITE_SYNC_FULL 0x00003
  803. #define SQLITE_SYNC_DATAONLY 0x00010
  804. /*
  805. ** CAPI3REF: OS Interface Open File Handle
  806. **
  807. ** An [sqlite3_file] object represents an open file in the
  808. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  809. ** implementations will
  810. ** want to subclass this object by appending additional fields
  811. ** for their own use. The pMethods entry is a pointer to an
  812. ** [sqlite3_io_methods] object that defines methods for performing
  813. ** I/O operations on the open file.
  814. */
  815. typedef struct sqlite3_file sqlite3_file;
  816. struct sqlite3_file {
  817. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  818. };
  819. /*
  820. ** CAPI3REF: OS Interface File Virtual Methods Object
  821. **
  822. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  823. ** [sqlite3_file] object (or, more commonly, a subclass of the
  824. ** [sqlite3_file] object) with a pointer to an instance of this object.
  825. ** This object defines the methods used to perform various operations
  826. ** against the open file represented by the [sqlite3_file] object.
  827. **
  828. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  829. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  830. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  831. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  832. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  833. ** to NULL.
  834. **
  835. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  836. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  837. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  838. ** flag may be ORed in to indicate that only the data of the file
  839. ** and not its inode needs to be synced.
  840. **
  841. ** The integer values to xLock() and xUnlock() are one of
  842. ** <ul>
  843. ** <li> [SQLITE_LOCK_NONE],
  844. ** <li> [SQLITE_LOCK_SHARED],
  845. ** <li> [SQLITE_LOCK_RESERVED],
  846. ** <li> [SQLITE_LOCK_PENDING], or
  847. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  848. ** </ul>
  849. ** xLock() increases the lock. xUnlock() decreases the lock.
  850. ** The xCheckReservedLock() method checks whether any database connection,
  851. ** either in this process or in some other process, is holding a RESERVED,
  852. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  853. ** if such a lock exists and false otherwise.
  854. **
  855. ** The xFileControl() method is a generic interface that allows custom
  856. ** VFS implementations to directly control an open file using the
  857. ** [sqlite3_file_control()] interface. The second "op" argument is an
  858. ** integer opcode. The third argument is a generic pointer intended to
  859. ** point to a structure that may contain arguments or space in which to
  860. ** write return values. Potential uses for xFileControl() might be
  861. ** functions to enable blocking locks with timeouts, to change the
  862. ** locking strategy (for example to use dot-file locks), to inquire
  863. ** about the status of a lock, or to break stale locks. The SQLite
  864. ** core reserves all opcodes less than 100 for its own use.
  865. ** A [file control opcodes | list of opcodes] less than 100 is available.
  866. ** Applications that define a custom xFileControl method should use opcodes
  867. ** greater than 100 to avoid conflicts. VFS implementations should
  868. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  869. ** recognize.
  870. **
  871. ** The xSectorSize() method returns the sector size of the
  872. ** device that underlies the file. The sector size is the
  873. ** minimum write that can be performed without disturbing
  874. ** other bytes in the file. The xDeviceCharacteristics()
  875. ** method returns a bit vector describing behaviors of the
  876. ** underlying device:
  877. **
  878. ** <ul>
  879. ** <li> [SQLITE_IOCAP_ATOMIC]
  880. ** <li> [SQLITE_IOCAP_ATOMIC512]
  881. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  882. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  883. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  884. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  885. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  886. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  887. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  888. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  889. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  890. ** </ul>
  891. **
  892. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  893. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  894. ** mean that writes of blocks that are nnn bytes in size and
  895. ** are aligned to an address which is an integer multiple of
  896. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  897. ** that when data is appended to a file, the data is appended
  898. ** first then the size of the file is extended, never the other
  899. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  900. ** information is written to disk in the same order as calls
  901. ** to xWrite().
  902. **
  903. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  904. ** in the unread portions of the buffer with zeros. A VFS that
  905. ** fails to zero-fill short reads might seem to work. However,
  906. ** failure to zero-fill short reads will eventually lead to
  907. ** database corruption.
  908. */
  909. typedef struct sqlite3_io_methods sqlite3_io_methods;
  910. struct sqlite3_io_methods {
  911. int iVersion;
  912. int (*xClose)(sqlite3_file*);
  913. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  914. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  915. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  916. int (*xSync)(sqlite3_file*, int flags);
  917. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  918. int (*xLock)(sqlite3_file*, int);
  919. int (*xUnlock)(sqlite3_file*, int);
  920. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  921. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  922. int (*xSectorSize)(sqlite3_file*);
  923. int (*xDeviceCharacteristics)(sqlite3_file*);
  924. /* Methods above are valid for version 1 */
  925. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  926. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  927. void (*xShmBarrier)(sqlite3_file*);
  928. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  929. /* Methods above are valid for version 2 */
  930. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  931. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  932. /* Methods above are valid for version 3 */
  933. /* Additional methods may be added in future releases */
  934. };
  935. /*
  936. ** CAPI3REF: Standard File Control Opcodes
  937. ** KEYWORDS: {file control opcodes} {file control opcode}
  938. **
  939. ** These integer constants are opcodes for the xFileControl method
  940. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  941. ** interface.
  942. **
  943. ** <ul>
  944. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  945. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  946. ** opcode causes the xFileControl method to write the current state of
  947. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  948. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  949. ** into an integer that the pArg argument points to. This capability
  950. ** is used during testing and is only available when the SQLITE_TEST
  951. ** compile-time option is used.
  952. **
  953. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  954. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  955. ** layer a hint of how large the database file will grow to be during the
  956. ** current transaction. This hint is not guaranteed to be accurate but it
  957. ** is often close. The underlying VFS might choose to preallocate database
  958. ** file space based on this hint in order to help writes to the database
  959. ** file run faster.
  960. **
  961. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  962. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  963. ** extends and truncates the database file in chunks of a size specified
  964. ** by the user. The fourth argument to [sqlite3_file_control()] should
  965. ** point to an integer (type int) containing the new chunk-size to use
  966. ** for the nominated database. Allocating database file space in large
  967. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  968. ** improve performance on some systems.
  969. **
  970. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  971. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  972. ** to the [sqlite3_file] object associated with a particular database
  973. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  974. **
  975. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  976. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  977. ** to the [sqlite3_file] object associated with the journal file (either
  978. ** the [rollback journal] or the [write-ahead log]) for a particular database
  979. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  980. **
  981. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  982. ** No longer in use.
  983. **
  984. ** <li>[[SQLITE_FCNTL_SYNC]]
  985. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  986. ** sent to the VFS immediately before the xSync method is invoked on a
  987. ** database file descriptor. Or, if the xSync method is not invoked
  988. ** because the user has configured SQLite with
  989. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  990. ** of the xSync method. In most cases, the pointer argument passed with
  991. ** this file-control is NULL. However, if the database file is being synced
  992. ** as part of a multi-database commit, the argument points to a nul-terminated
  993. ** string containing the transactions master-journal file name. VFSes that
  994. ** do not need this signal should silently ignore this opcode. Applications
  995. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  996. ** disrupt the operation of the specialized VFSes that do require it.
  997. **
  998. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  999. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1000. ** and sent to the VFS after a transaction has been committed immediately
  1001. ** but before the database is unlocked. VFSes that do not need this signal
  1002. ** should silently ignore this opcode. Applications should not call
  1003. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1004. ** operation of the specialized VFSes that do require it.
  1005. **
  1006. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1007. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1008. ** retry counts and intervals for certain disk I/O operations for the
  1009. ** windows [VFS] in order to provide robustness in the presence of
  1010. ** anti-virus programs. By default, the windows VFS will retry file read,
  1011. ** file write, and file delete operations up to 10 times, with a delay
  1012. ** of 25 milliseconds before the first retry and with the delay increasing
  1013. ** by an additional 25 milliseconds with each subsequent retry. This
  1014. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1015. ** to be adjusted. The values are changed for all database connections
  1016. ** within the same process. The argument is a pointer to an array of two
  1017. ** integers where the first integer i the new retry count and the second
  1018. ** integer is the delay. If either integer is negative, then the setting
  1019. ** is not changed but instead the prior value of that setting is written
  1020. ** into the array entry, allowing the current retry settings to be
  1021. ** interrogated. The zDbName parameter is ignored.
  1022. **
  1023. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1024. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1025. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1026. ** write ahead log and shared memory files used for transaction control
  1027. ** are automatically deleted when the latest connection to the database
  1028. ** closes. Setting persistent WAL mode causes those files to persist after
  1029. ** close. Persisting the files is useful when other processes that do not
  1030. ** have write permission on the directory containing the database file want
  1031. ** to read the database file, as the WAL and shared memory files must exist
  1032. ** in order for the database to be readable. The fourth parameter to
  1033. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1034. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1035. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1036. ** WAL persistence setting.
  1037. **
  1038. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1039. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1040. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1041. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1042. ** xDeviceCharacteristics methods. The fourth parameter to
  1043. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1044. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1045. ** mode. If the integer is -1, then it is overwritten with the current
  1046. ** zero-damage mode setting.
  1047. **
  1048. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1049. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1050. ** a write transaction to indicate that, unless it is rolled back for some
  1051. ** reason, the entire database file will be overwritten by the current
  1052. ** transaction. This is used by VACUUM operations.
  1053. **
  1054. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1055. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1056. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1057. ** final bottom-level VFS are written into memory obtained from
  1058. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1059. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1060. ** The caller is responsible for freeing the memory when done. As with
  1061. ** all file-control actions, there is no guarantee that this will actually
  1062. ** do anything. Callers should initialize the char* variable to a NULL
  1063. ** pointer in case this file-control is not implemented. This file-control
  1064. ** is intended for diagnostic use only.
  1065. **
  1066. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1067. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1068. ** [VFSes] currently in use. ^(The argument X in
  1069. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1070. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1071. ** to a pointer to the top-level VFS.)^
  1072. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1073. ** upper-most shim only.
  1074. **
  1075. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1076. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1077. ** file control is sent to the open [sqlite3_file] object corresponding
  1078. ** to the database file to which the pragma statement refers. ^The argument
  1079. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1080. ** pointers to strings (char**) in which the second element of the array
  1081. ** is the name of the pragma and the third element is the argument to the
  1082. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1083. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1084. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1085. ** or the equivalent and that string will become the result of the pragma or
  1086. ** the error message if the pragma fails. ^If the
  1087. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1088. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1089. ** file control returns [SQLITE_OK], then the parser assumes that the
  1090. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1091. ** prepared statement if result string is NULL, or that returns a copy
  1092. ** of the result string if the string is non-NULL.
  1093. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1094. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1095. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1096. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1097. ** file control occurs at the beginning of pragma statement analysis and so
  1098. ** it is able to override built-in [PRAGMA] statements.
  1099. **
  1100. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1101. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1102. ** file-control may be invoked by SQLite on the database file handle
  1103. ** shortly after it is opened in order to provide a custom VFS with access
  1104. ** to the connections busy-handler callback. The argument is of type (void **)
  1105. ** - an array of two (void *) values. The first (void *) actually points
  1106. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1107. ** busy-handler, this function should be invoked with the second (void *) in
  1108. ** the array as the only argument. If it returns non-zero, then the operation
  1109. ** should be retried. If it returns zero, the custom VFS should abandon the
  1110. ** current operation.
  1111. **
  1112. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1113. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1114. ** to have SQLite generate a
  1115. ** temporary filename using the same algorithm that is followed to generate
  1116. ** temporary filenames for TEMP tables and other internal uses. The
  1117. ** argument should be a char** which will be filled with the filename
  1118. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1119. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1120. **
  1121. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1122. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1123. ** maximum number of bytes that will be used for memory-mapped I/O.
  1124. ** The argument is a pointer to a value of type sqlite3_int64 that
  1125. ** is an advisory maximum number of bytes in the file to memory map. The
  1126. ** pointer is overwritten with the old value. The limit is not changed if
  1127. ** the value originally pointed to is negative, and so the current limit
  1128. ** can be queried by passing in a pointer to a negative number. This
  1129. ** file-control is used internally to implement [PRAGMA mmap_size].
  1130. **
  1131. ** <li>[[SQLITE_FCNTL_TRACE]]
  1132. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1133. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1134. ** This file control is used by some VFS activity tracing [shims].
  1135. ** The argument is a zero-terminated string. Higher layers in the
  1136. ** SQLite stack may generate instances of this file control if
  1137. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1138. **
  1139. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1140. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1141. ** pointer to an integer and it writes a boolean into that integer depending
  1142. ** on whether or not the file has been renamed, moved, or deleted since it
  1143. ** was first opened.
  1144. **
  1145. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1146. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1147. ** opcode causes the xFileControl method to swap the file handle with the one
  1148. ** pointed to by the pArg argument. This capability is used during testing
  1149. ** and only needs to be supported when SQLITE_TEST is defined.
  1150. **
  1151. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1152. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1153. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1154. ** available. The WAL subsystem issues this signal during rare
  1155. ** circumstances in order to fix a problem with priority inversion.
  1156. ** Applications should <em>not</em> use this file-control.
  1157. **
  1158. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  1159. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  1160. ** VFS should return SQLITE_NOTFOUND for this opcode.
  1161. **
  1162. ** <li>[[SQLITE_FCNTL_RBU]]
  1163. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  1164. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  1165. ** this opcode.
  1166. ** </ul>
  1167. */
  1168. #define SQLITE_FCNTL_LOCKSTATE 1
  1169. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  1170. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  1171. #define SQLITE_FCNTL_LAST_ERRNO 4
  1172. #define SQLITE_FCNTL_SIZE_HINT 5
  1173. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1174. #define SQLITE_FCNTL_FILE_POINTER 7
  1175. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1176. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1177. #define SQLITE_FCNTL_PERSIST_WAL 10
  1178. #define SQLITE_FCNTL_OVERWRITE 11
  1179. #define SQLITE_FCNTL_VFSNAME 12
  1180. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1181. #define SQLITE_FCNTL_PRAGMA 14
  1182. #define SQLITE_FCNTL_BUSYHANDLER 15
  1183. #define SQLITE_FCNTL_TEMPFILENAME 16
  1184. #define SQLITE_FCNTL_MMAP_SIZE 18
  1185. #define SQLITE_FCNTL_TRACE 19
  1186. #define SQLITE_FCNTL_HAS_MOVED 20
  1187. #define SQLITE_FCNTL_SYNC 21
  1188. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  1189. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  1190. #define SQLITE_FCNTL_WAL_BLOCK 24
  1191. #define SQLITE_FCNTL_ZIPVFS 25
  1192. #define SQLITE_FCNTL_RBU 26
  1193. #define SQLITE_FCNTL_VFS_POINTER 27
  1194. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  1195. /* deprecated names */
  1196. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  1197. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  1198. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  1199. /*
  1200. ** CAPI3REF: Mutex Handle
  1201. **
  1202. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1203. ** abstract type for a mutex object. The SQLite core never looks
  1204. ** at the internal representation of an [sqlite3_mutex]. It only
  1205. ** deals with pointers to the [sqlite3_mutex] object.
  1206. **
  1207. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1208. */
  1209. typedef struct sqlite3_mutex sqlite3_mutex;
  1210. /*
  1211. ** CAPI3REF: OS Interface Object
  1212. **
  1213. ** An instance of the sqlite3_vfs object defines the interface between
  1214. ** the SQLite core and the underlying operating system. The "vfs"
  1215. ** in the name of the object stands for "virtual file system". See
  1216. ** the [VFS | VFS documentation] for further information.
  1217. **
  1218. ** The value of the iVersion field is initially 1 but may be larger in
  1219. ** future versions of SQLite. Additional fields may be appended to this
  1220. ** object when the iVersion value is increased. Note that the structure
  1221. ** of the sqlite3_vfs object changes in the transaction between
  1222. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1223. ** modified.
  1224. **
  1225. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1226. ** structure used by this VFS. mxPathname is the maximum length of
  1227. ** a pathname in this VFS.
  1228. **
  1229. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1230. ** the pNext pointer. The [sqlite3_vfs_register()]
  1231. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1232. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1233. ** searches the list. Neither the application code nor the VFS
  1234. ** implementation should use the pNext pointer.
  1235. **
  1236. ** The pNext field is the only field in the sqlite3_vfs
  1237. ** structure that SQLite will ever modify. SQLite will only access
  1238. ** or modify this field while holding a particular static mutex.
  1239. ** The application should never modify anything within the sqlite3_vfs
  1240. ** object once the object has been registered.
  1241. **
  1242. ** The zName field holds the name of the VFS module. The name must
  1243. ** be unique across all VFS modules.
  1244. **
  1245. ** [[sqlite3_vfs.xOpen]]
  1246. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1247. ** is either a NULL pointer or string obtained
  1248. ** from xFullPathname() with an optional suffix added.
  1249. ** ^If a suffix is added to the zFilename parameter, it will
  1250. ** consist of a single "-" character followed by no more than
  1251. ** 11 alphanumeric and/or "-" characters.
  1252. ** ^SQLite further guarantees that
  1253. ** the string will be valid and unchanged until xClose() is
  1254. ** called. Because of the previous sentence,
  1255. ** the [sqlite3_file] can safely store a pointer to the
  1256. ** filename if it needs to remember the filename for some reason.
  1257. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1258. ** must invent its own temporary name for the file. ^Whenever the
  1259. ** xFilename parameter is NULL it will also be the case that the
  1260. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1261. **
  1262. ** The flags argument to xOpen() includes all bits set in
  1263. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1264. ** or [sqlite3_open16()] is used, then flags includes at least
  1265. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1266. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1267. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1268. **
  1269. ** ^(SQLite will also add one of the following flags to the xOpen()
  1270. ** call, depending on the object being opened:
  1271. **
  1272. ** <ul>
  1273. ** <li> [SQLITE_OPEN_MAIN_DB]
  1274. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1275. ** <li> [SQLITE_OPEN_TEMP_DB]
  1276. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1277. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1278. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1279. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1280. ** <li> [SQLITE_OPEN_WAL]
  1281. ** </ul>)^
  1282. **
  1283. ** The file I/O implementation can use the object type flags to
  1284. ** change the way it deals with files. For example, an application
  1285. ** that does not care about crash recovery or rollback might make
  1286. ** the open of a journal file a no-op. Writes to this journal would
  1287. ** also be no-ops, and any attempt to read the journal would return
  1288. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1289. ** file will be doing page-aligned sector reads and writes in a random
  1290. ** order and set up its I/O subsystem accordingly.
  1291. **
  1292. ** SQLite might also add one of the following flags to the xOpen method:
  1293. **
  1294. ** <ul>
  1295. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1296. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1297. ** </ul>
  1298. **
  1299. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1300. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1301. ** will be set for TEMP databases and their journals, transient
  1302. ** databases, and subjournals.
  1303. **
  1304. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1305. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1306. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1307. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1308. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1309. ** be created, and that it is an error if it already exists.
  1310. ** It is <i>not</i> used to indicate the file should be opened
  1311. ** for exclusive access.
  1312. **
  1313. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1314. ** to hold the [sqlite3_file] structure passed as the third
  1315. ** argument to xOpen. The xOpen method does not have to
  1316. ** allocate the structure; it should just fill it in. Note that
  1317. ** the xOpen method must set the sqlite3_file.pMethods to either
  1318. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1319. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1320. ** element will be valid after xOpen returns regardless of the success
  1321. ** or failure of the xOpen call.
  1322. **
  1323. ** [[sqlite3_vfs.xAccess]]
  1324. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1325. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1326. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1327. ** to test whether a file is at least readable. The file can be a
  1328. ** directory.
  1329. **
  1330. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1331. ** output buffer xFullPathname. The exact size of the output buffer
  1332. ** is also passed as a parameter to both methods. If the output buffer
  1333. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1334. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1335. ** to prevent this by setting mxPathname to a sufficiently large value.
  1336. **
  1337. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1338. ** interfaces are not strictly a part of the filesystem, but they are
  1339. ** included in the VFS structure for completeness.
  1340. ** The xRandomness() function attempts to return nBytes bytes
  1341. ** of good-quality randomness into zOut. The return value is
  1342. ** the actual number of bytes of randomness obtained.
  1343. ** The xSleep() method causes the calling thread to sleep for at
  1344. ** least the number of microseconds given. ^The xCurrentTime()
  1345. ** method returns a Julian Day Number for the current date and time as
  1346. ** a floating point value.
  1347. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1348. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1349. ** a 24-hour day).
  1350. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1351. ** date and time if that method is available (if iVersion is 2 or
  1352. ** greater and the function pointer is not NULL) and will fall back
  1353. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1354. **
  1355. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1356. ** are not used by the SQLite core. These optional interfaces are provided
  1357. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1358. ** system calls with functions under its control, a test program can
  1359. ** simulate faults and error conditions that would otherwise be difficult
  1360. ** or impossible to induce. The set of system calls that can be overridden
  1361. ** varies from one VFS to another, and from one version of the same VFS to the
  1362. ** next. Applications that use these interfaces must be prepared for any
  1363. ** or all of these interfaces to be NULL or for their behavior to change
  1364. ** from one release to the next. Applications must not attempt to access
  1365. ** any of these methods if the iVersion of the VFS is less than 3.
  1366. */
  1367. typedef struct sqlite3_vfs sqlite3_vfs;
  1368. typedef void (*sqlite3_syscall_ptr)(void);
  1369. struct sqlite3_vfs {
  1370. int iVersion; /* Structure version number (currently 3) */
  1371. int szOsFile; /* Size of subclassed sqlite3_file */
  1372. int mxPathname; /* Maximum file pathname length */
  1373. sqlite3_vfs *pNext; /* Next registered VFS */
  1374. const char *zName; /* Name of this virtual file system */
  1375. void *pAppData; /* Pointer to application-specific data */
  1376. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1377. int flags, int *pOutFlags);
  1378. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1379. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1380. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1381. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1382. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1383. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1384. void (*xDlClose)(sqlite3_vfs*, void*);
  1385. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1386. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1387. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1388. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1389. /*
  1390. ** The methods above are in version 1 of the sqlite_vfs object
  1391. ** definition. Those that follow are added in version 2 or later
  1392. */
  1393. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1394. /*
  1395. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1396. ** Those below are for version 3 and greater.
  1397. */
  1398. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1399. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1400. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1401. /*
  1402. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1403. ** New fields may be appended in figure versions. The iVersion
  1404. ** value will increment whenever this happens.
  1405. */
  1406. };
  1407. /*
  1408. ** CAPI3REF: Flags for the xAccess VFS method
  1409. **
  1410. ** These integer constants can be used as the third parameter to
  1411. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1412. ** what kind of permissions the xAccess method is looking for.
  1413. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1414. ** simply checks whether the file exists.
  1415. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1416. ** checks whether the named directory is both readable and writable
  1417. ** (in other words, if files can be added, removed, and renamed within
  1418. ** the directory).
  1419. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1420. ** [temp_store_directory pragma], though this could change in a future
  1421. ** release of SQLite.
  1422. ** With SQLITE_ACCESS_READ, the xAccess method
  1423. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1424. ** currently unused, though it might be used in a future release of
  1425. ** SQLite.
  1426. */
  1427. #define SQLITE_ACCESS_EXISTS 0
  1428. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1429. #define SQLITE_ACCESS_READ 2 /* Unused */
  1430. /*
  1431. ** CAPI3REF: Flags for the xShmLock VFS method
  1432. **
  1433. ** These integer constants define the various locking operations
  1434. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1435. ** following are the only legal combinations of flags to the
  1436. ** xShmLock method:
  1437. **
  1438. ** <ul>
  1439. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1440. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1441. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1442. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1443. ** </ul>
  1444. **
  1445. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1446. ** was given on the corresponding lock.
  1447. **
  1448. ** The xShmLock method can transition between unlocked and SHARED or
  1449. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1450. ** and EXCLUSIVE.
  1451. */
  1452. #define SQLITE_SHM_UNLOCK 1
  1453. #define SQLITE_SHM_LOCK 2
  1454. #define SQLITE_SHM_SHARED 4
  1455. #define SQLITE_SHM_EXCLUSIVE 8
  1456. /*
  1457. ** CAPI3REF: Maximum xShmLock index
  1458. **
  1459. ** The xShmLock method on [sqlite3_io_methods] may use values
  1460. ** between 0 and this upper bound as its "offset" argument.
  1461. ** The SQLite core will never attempt to acquire or release a
  1462. ** lock outside of this range
  1463. */
  1464. #define SQLITE_SHM_NLOCK 8
  1465. /*
  1466. ** CAPI3REF: Initialize The SQLite Library
  1467. **
  1468. ** ^The sqlite3_initialize() routine initializes the
  1469. ** SQLite library. ^The sqlite3_shutdown() routine
  1470. ** deallocates any resources that were allocated by sqlite3_initialize().
  1471. ** These routines are designed to aid in process initialization and
  1472. ** shutdown on embedded systems. Workstation applications using
  1473. ** SQLite normally do not need to invoke either of these routines.
  1474. **
  1475. ** A call to sqlite3_initialize() is an "effective" call if it is
  1476. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1477. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1478. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1479. ** of sqlite3_initialize() does any initialization. All other calls
  1480. ** are harmless no-ops.)^
  1481. **
  1482. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1483. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1484. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1485. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1486. **
  1487. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1488. ** is not. The sqlite3_shutdown() interface must only be called from a
  1489. ** single thread. All open [database connections] must be closed and all
  1490. ** other SQLite resources must be deallocated prior to invoking
  1491. ** sqlite3_shutdown().
  1492. **
  1493. ** Among other things, ^sqlite3_initialize() will invoke
  1494. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1495. ** will invoke sqlite3_os_end().
  1496. **
  1497. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1498. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1499. ** the library (perhaps it is unable to allocate a needed resource such
  1500. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1501. **
  1502. ** ^The sqlite3_initialize() routine is called internally by many other
  1503. ** SQLite interfaces so that an application usually does not need to
  1504. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1505. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1506. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1507. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1508. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1509. ** are omitted and the application must call sqlite3_initialize() directly
  1510. ** prior to using any other SQLite interface. For maximum portability,
  1511. ** it is recommended that applications always invoke sqlite3_initialize()
  1512. ** directly prior to using any other SQLite interface. Future releases
  1513. ** of SQLite may require this. In other words, the behavior exhibited
  1514. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1515. ** default behavior in some future release of SQLite.
  1516. **
  1517. ** The sqlite3_os_init() routine does operating-system specific
  1518. ** initialization of the SQLite library. The sqlite3_os_end()
  1519. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1520. ** performed by these routines include allocation or deallocation
  1521. ** of static resources, initialization of global variables,
  1522. ** setting up a default [sqlite3_vfs] module, or setting up
  1523. ** a default configuration using [sqlite3_config()].
  1524. **
  1525. ** The application should never invoke either sqlite3_os_init()
  1526. ** or sqlite3_os_end() directly. The application should only invoke
  1527. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1528. ** interface is called automatically by sqlite3_initialize() and
  1529. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1530. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1531. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1532. ** When [custom builds | built for other platforms]
  1533. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1534. ** option) the application must supply a suitable implementation for
  1535. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1536. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1537. ** must return [SQLITE_OK] on success and some other [error code] upon
  1538. ** failure.
  1539. */
  1540. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
  1541. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
  1542. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
  1543. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
  1544. /*
  1545. ** CAPI3REF: Configuring The SQLite Library
  1546. **
  1547. ** The sqlite3_config() interface is used to make global configuration
  1548. ** changes to SQLite in order to tune SQLite to the specific needs of
  1549. ** the application. The default configuration is recommended for most
  1550. ** applications and so this routine is usually not necessary. It is
  1551. ** provided to support rare applications with unusual needs.
  1552. **
  1553. ** <b>The sqlite3_config() interface is not threadsafe. The application
  1554. ** must ensure that no other SQLite interfaces are invoked by other
  1555. ** threads while sqlite3_config() is running.</b>
  1556. **
  1557. ** The sqlite3_config() interface
  1558. ** may only be invoked prior to library initialization using
  1559. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1560. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1561. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1562. ** Note, however, that ^sqlite3_config() can be called as part of the
  1563. ** implementation of an application-defined [sqlite3_os_init()].
  1564. **
  1565. ** The first argument to sqlite3_config() is an integer
  1566. ** [configuration option] that determines
  1567. ** what property of SQLite is to be configured. Subsequent arguments
  1568. ** vary depending on the [configuration option]
  1569. ** in the first argument.
  1570. **
  1571. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1572. ** ^If the option is unknown or SQLite is unable to set the option
  1573. ** then this routine returns a non-zero [error code].
  1574. */
  1575. SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
  1576. /*
  1577. ** CAPI3REF: Configure database connections
  1578. ** METHOD: sqlite3
  1579. **
  1580. ** The sqlite3_db_config() interface is used to make configuration
  1581. ** changes to a [database connection]. The interface is similar to
  1582. ** [sqlite3_config()] except that the changes apply to a single
  1583. ** [database connection] (specified in the first argument).
  1584. **
  1585. ** The second argument to sqlite3_db_config(D,V,...) is the
  1586. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1587. ** that indicates what aspect of the [database connection] is being configured.
  1588. ** Subsequent arguments vary depending on the configuration verb.
  1589. **
  1590. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1591. ** the call is considered successful.
  1592. */
  1593. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
  1594. /*
  1595. ** CAPI3REF: Memory Allocation Routines
  1596. **
  1597. ** An instance of this object defines the interface between SQLite
  1598. ** and low-level memory allocation routines.
  1599. **
  1600. ** This object is used in only one place in the SQLite interface.
  1601. ** A pointer to an instance of this object is the argument to
  1602. ** [sqlite3_config()] when the configuration option is
  1603. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1604. ** By creating an instance of this object
  1605. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1606. ** during configuration, an application can specify an alternative
  1607. ** memory allocation subsystem for SQLite to use for all of its
  1608. ** dynamic memory needs.
  1609. **
  1610. ** Note that SQLite comes with several [built-in memory allocators]
  1611. ** that are perfectly adequate for the overwhelming majority of applications
  1612. ** and that this object is only useful to a tiny minority of applications
  1613. ** with specialized memory allocation requirements. This object is
  1614. ** also used during testing of SQLite in order to specify an alternative
  1615. ** memory allocator that simulates memory out-of-memory conditions in
  1616. ** order to verify that SQLite recovers gracefully from such
  1617. ** conditions.
  1618. **
  1619. ** The xMalloc, xRealloc, and xFree methods must work like the
  1620. ** malloc(), realloc() and free() functions from the standard C library.
  1621. ** ^SQLite guarantees that the second argument to
  1622. ** xRealloc is always a value returned by a prior call to xRoundup.
  1623. **
  1624. ** xSize should return the allocated size of a memory allocation
  1625. ** previously obtained from xMalloc or xRealloc. The allocated size
  1626. ** is always at least as big as the requested size but may be larger.
  1627. **
  1628. ** The xRoundup method returns what would be the allocated size of
  1629. ** a memory allocation given a particular requested size. Most memory
  1630. ** allocators round up memory allocations at least to the next multiple
  1631. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1632. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1633. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1634. ** that causes the corresponding memory allocation to fail.
  1635. **
  1636. ** The xInit method initializes the memory allocator. For example,
  1637. ** it might allocate any require mutexes or initialize internal data
  1638. ** structures. The xShutdown method is invoked (indirectly) by
  1639. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1640. ** by xInit. The pAppData pointer is used as the only parameter to
  1641. ** xInit and xShutdown.
  1642. **
  1643. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1644. ** the xInit method, so the xInit method need not be threadsafe. The
  1645. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1646. ** not need to be threadsafe either. For all other methods, SQLite
  1647. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1648. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1649. ** it is by default) and so the methods are automatically serialized.
  1650. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1651. ** methods must be threadsafe or else make their own arrangements for
  1652. ** serialization.
  1653. **
  1654. ** SQLite will never invoke xInit() more than once without an intervening
  1655. ** call to xShutdown().
  1656. */
  1657. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1658. struct sqlite3_mem_methods {
  1659. void *(*xMalloc)(int); /* Memory allocation function */
  1660. void (*xFree)(void*); /* Free a prior allocation */
  1661. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1662. int (*xSize)(void*); /* Return the size of an allocation */
  1663. int (*xRoundup)(int); /* Round up request size to allocation size */
  1664. int (*xInit)(void*); /* Initialize the memory allocator */
  1665. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1666. void *pAppData; /* Argument to xInit() and xShutdown() */
  1667. };
  1668. /*
  1669. ** CAPI3REF: Configuration Options
  1670. ** KEYWORDS: {configuration option}
  1671. **
  1672. ** These constants are the available integer configuration options that
  1673. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1674. **
  1675. ** New configuration options may be added in future releases of SQLite.
  1676. ** Existing configuration options might be discontinued. Applications
  1677. ** should check the return code from [sqlite3_config()] to make sure that
  1678. ** the call worked. The [sqlite3_config()] interface will return a
  1679. ** non-zero [error code] if a discontinued or unsupported configuration option
  1680. ** is invoked.
  1681. **
  1682. ** <dl>
  1683. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1684. ** <dd>There are no arguments to this option. ^This option sets the
  1685. ** [threading mode] to Single-thread. In other words, it disables
  1686. ** all mutexing and puts SQLite into a mode where it can only be used
  1687. ** by a single thread. ^If SQLite is compiled with
  1688. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1689. ** it is not possible to change the [threading mode] from its default
  1690. ** value of Single-thread and so [sqlite3_config()] will return
  1691. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1692. ** configuration option.</dd>
  1693. **
  1694. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1695. ** <dd>There are no arguments to this option. ^This option sets the
  1696. ** [threading mode] to Multi-thread. In other words, it disables
  1697. ** mutexing on [database connection] and [prepared statement] objects.
  1698. ** The application is responsible for serializing access to
  1699. ** [database connections] and [prepared statements]. But other mutexes
  1700. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1701. ** environment as long as no two threads attempt to use the same
  1702. ** [database connection] at the same time. ^If SQLite is compiled with
  1703. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1704. ** it is not possible to set the Multi-thread [threading mode] and
  1705. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1706. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1707. **
  1708. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1709. ** <dd>There are no arguments to this option. ^This option sets the
  1710. ** [threading mode] to Serialized. In other words, this option enables
  1711. ** all mutexes including the recursive
  1712. ** mutexes on [database connection] and [prepared statement] objects.
  1713. ** In this mode (which is the default when SQLite is compiled with
  1714. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1715. ** to [database connections] and [prepared statements] so that the
  1716. ** application is free to use the same [database connection] or the
  1717. ** same [prepared statement] in different threads at the same time.
  1718. ** ^If SQLite is compiled with
  1719. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1720. ** it is not possible to set the Serialized [threading mode] and
  1721. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1722. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1723. **
  1724. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1725. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  1726. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  1727. ** The argument specifies
  1728. ** alternative low-level memory allocation routines to be used in place of
  1729. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1730. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1731. ** before the [sqlite3_config()] call returns.</dd>
  1732. **
  1733. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1734. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  1735. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  1736. ** The [sqlite3_mem_methods]
  1737. ** structure is filled with the currently defined memory allocation routines.)^
  1738. ** This option can be used to overload the default memory allocation
  1739. ** routines with a wrapper that simulations memory allocation failure or
  1740. ** tracks memory usage, for example. </dd>
  1741. **
  1742. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1743. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  1744. ** interpreted as a boolean, which enables or disables the collection of
  1745. ** memory allocation statistics. ^(When memory allocation statistics are
  1746. ** disabled, the following SQLite interfaces become non-operational:
  1747. ** <ul>
  1748. ** <li> [sqlite3_memory_used()]
  1749. ** <li> [sqlite3_memory_highwater()]
  1750. ** <li> [sqlite3_soft_heap_limit64()]
  1751. ** <li> [sqlite3_status64()]
  1752. ** </ul>)^
  1753. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1754. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1755. ** allocation statistics are disabled by default.
  1756. ** </dd>
  1757. **
  1758. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1759. ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
  1760. ** that SQLite can use for scratch memory. ^(There are three arguments
  1761. ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
  1762. ** aligned memory buffer from which the scratch allocations will be
  1763. ** drawn, the size of each scratch allocation (sz),
  1764. ** and the maximum number of scratch allocations (N).)^
  1765. ** The first argument must be a pointer to an 8-byte aligned buffer
  1766. ** of at least sz*N bytes of memory.
  1767. ** ^SQLite will not use more than one scratch buffers per thread.
  1768. ** ^SQLite will never request a scratch buffer that is more than 6
  1769. ** times the database page size.
  1770. ** ^If SQLite needs needs additional
  1771. ** scratch memory beyond what is provided by this configuration option, then
  1772. ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
  1773. ** ^When the application provides any amount of scratch memory using
  1774. ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
  1775. ** [sqlite3_malloc|heap allocations].
  1776. ** This can help [Robson proof|prevent memory allocation failures] due to heap
  1777. ** fragmentation in low-memory embedded systems.
  1778. ** </dd>
  1779. **
  1780. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1781. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  1782. ** that SQLite can use for the database page cache with the default page
  1783. ** cache implementation.
  1784. ** This configuration option is a no-op if an application-define page
  1785. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  1786. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  1787. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  1788. ** and the number of cache lines (N).
  1789. ** The sz argument should be the size of the largest database page
  1790. ** (a power of two between 512 and 65536) plus some extra bytes for each
  1791. ** page header. ^The number of extra bytes needed by the page header
  1792. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  1793. ** ^It is harmless, apart from the wasted memory,
  1794. ** for the sz parameter to be larger than necessary. The pMem
  1795. ** argument must be either a NULL pointer or a pointer to an 8-byte
  1796. ** aligned block of memory of at least sz*N bytes, otherwise
  1797. ** subsequent behavior is undefined.
  1798. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  1799. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  1800. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  1801. ** is exhausted.
  1802. ** ^If pMem is NULL and N is non-zero, then each database connection
  1803. ** does an initial bulk allocation for page cache memory
  1804. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  1805. ** of -1024*N bytes if N is negative, . ^If additional
  1806. ** page cache memory is needed beyond what is provided by the initial
  1807. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  1808. ** additional cache line. </dd>
  1809. **
  1810. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1811. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  1812. ** that SQLite will use for all of its dynamic memory allocation needs
  1813. ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
  1814. ** [SQLITE_CONFIG_PAGECACHE].
  1815. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  1816. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  1817. ** [SQLITE_ERROR] if invoked otherwise.
  1818. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  1819. ** An 8-byte aligned pointer to the memory,
  1820. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1821. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1822. ** to using its default memory allocator (the system malloc() implementation),
  1823. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1824. ** memory pointer is not NULL then the alternative memory
  1825. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1826. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1827. ** boundary or subsequent behavior of SQLite will be undefined.
  1828. ** The minimum allocation size is capped at 2**12. Reasonable values
  1829. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1830. **
  1831. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1832. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  1833. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  1834. ** The argument specifies alternative low-level mutex routines to be used
  1835. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  1836. ** the content of the [sqlite3_mutex_methods] structure before the call to
  1837. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1838. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1839. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1840. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1841. ** return [SQLITE_ERROR].</dd>
  1842. **
  1843. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1844. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  1845. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  1846. ** [sqlite3_mutex_methods]
  1847. ** structure is filled with the currently defined mutex routines.)^
  1848. ** This option can be used to overload the default mutex allocation
  1849. ** routines with a wrapper used to track mutex usage for performance
  1850. ** profiling or testing, for example. ^If SQLite is compiled with
  1851. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1852. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1853. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1854. ** return [SQLITE_ERROR].</dd>
  1855. **
  1856. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1857. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  1858. ** the default size of lookaside memory on each [database connection].
  1859. ** The first argument is the
  1860. ** size of each lookaside buffer slot and the second is the number of
  1861. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  1862. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1863. ** option to [sqlite3_db_config()] can be used to change the lookaside
  1864. ** configuration on individual connections.)^ </dd>
  1865. **
  1866. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1867. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  1868. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  1869. ** the interface to a custom page cache implementation.)^
  1870. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  1871. **
  1872. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1873. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  1874. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  1875. ** the current page cache implementation into that object.)^ </dd>
  1876. **
  1877. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1878. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1879. ** global [error log].
  1880. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1881. ** function with a call signature of void(*)(void*,int,const char*),
  1882. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1883. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1884. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1885. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1886. ** passed through as the first parameter to the application-defined logger
  1887. ** function whenever that function is invoked. ^The second parameter to
  1888. ** the logger function is a copy of the first parameter to the corresponding
  1889. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1890. ** [extended result code]. ^The third parameter passed to the logger is
  1891. ** log message after formatting via [sqlite3_snprintf()].
  1892. ** The SQLite logging interface is not reentrant; the logger function
  1893. ** supplied by the application must not invoke any SQLite interface.
  1894. ** In a multi-threaded application, the application-defined logger
  1895. ** function must be threadsafe. </dd>
  1896. **
  1897. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1898. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  1899. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  1900. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  1901. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  1902. ** [sqlite3_open16()] or
  1903. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1904. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1905. ** connection is opened. ^If it is globally disabled, filenames are
  1906. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1907. ** database connection is opened. ^(By default, URI handling is globally
  1908. ** disabled. The default value may be changed by compiling with the
  1909. ** [SQLITE_USE_URI] symbol defined.)^
  1910. **
  1911. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1912. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  1913. ** argument which is interpreted as a boolean in order to enable or disable
  1914. ** the use of covering indices for full table scans in the query optimizer.
  1915. ** ^The default setting is determined
  1916. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1917. ** if that compile-time option is omitted.
  1918. ** The ability to disable the use of covering indices for full table scans
  1919. ** is because some incorrectly coded legacy applications might malfunction
  1920. ** when the optimization is enabled. Providing the ability to
  1921. ** disable the optimization allows the older, buggy application code to work
  1922. ** without change even with newer versions of SQLite.
  1923. **
  1924. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1925. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1926. ** <dd> These options are obsolete and should not be used by new code.
  1927. ** They are retained for backwards compatibility but are now no-ops.
  1928. ** </dd>
  1929. **
  1930. ** [[SQLITE_CONFIG_SQLLOG]]
  1931. ** <dt>SQLITE_CONFIG_SQLLOG
  1932. ** <dd>This option is only available if sqlite is compiled with the
  1933. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1934. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1935. ** The second should be of type (void*). The callback is invoked by the library
  1936. ** in three separate circumstances, identified by the value passed as the
  1937. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1938. ** passed as the second argument has just been opened. The third argument
  1939. ** points to a buffer containing the name of the main database file. If the
  1940. ** fourth parameter is 1, then the SQL statement that the third parameter
  1941. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1942. ** the connection being passed as the second parameter is being closed. The
  1943. ** third parameter is passed NULL In this case. An example of using this
  1944. ** configuration option can be seen in the "test_sqllog.c" source file in
  1945. ** the canonical SQLite source tree.</dd>
  1946. **
  1947. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1948. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1949. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1950. ** that are the default mmap size limit (the default setting for
  1951. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1952. ** ^The default setting can be overridden by each database connection using
  1953. ** either the [PRAGMA mmap_size] command, or by using the
  1954. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1955. ** will be silently truncated if necessary so that it does not exceed the
  1956. ** compile-time maximum mmap size set by the
  1957. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1958. ** ^If either argument to this option is negative, then that argument is
  1959. ** changed to its compile-time default.
  1960. **
  1961. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  1962. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  1963. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  1964. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  1965. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  1966. ** that specifies the maximum size of the created heap.
  1967. **
  1968. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  1969. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  1970. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  1971. ** is a pointer to an integer and writes into that integer the number of extra
  1972. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  1973. ** The amount of extra space required can change depending on the compiler,
  1974. ** target platform, and SQLite version.
  1975. **
  1976. ** [[SQLITE_CONFIG_PMASZ]]
  1977. ** <dt>SQLITE_CONFIG_PMASZ
  1978. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  1979. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  1980. ** sorter to that integer. The default minimum PMA Size is set by the
  1981. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  1982. ** to help with sort operations when multithreaded sorting
  1983. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  1984. ** to be sorted exceeds the page size times the minimum of the
  1985. ** [PRAGMA cache_size] setting and this value.
  1986. ** </dl>
  1987. */
  1988. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1989. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1990. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1991. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1992. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1993. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1994. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1995. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1996. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1997. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1998. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1999. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2000. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2001. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2002. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2003. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2004. #define SQLITE_CONFIG_URI 17 /* int */
  2005. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2006. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2007. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2008. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2009. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2010. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  2011. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  2012. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  2013. /*
  2014. ** CAPI3REF: Database Connection Configuration Options
  2015. **
  2016. ** These constants are the available integer configuration options that
  2017. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2018. **
  2019. ** New configuration options may be added in future releases of SQLite.
  2020. ** Existing configuration options might be discontinued. Applications
  2021. ** should check the return code from [sqlite3_db_config()] to make sure that
  2022. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2023. ** non-zero [error code] if a discontinued or unsupported configuration option
  2024. ** is invoked.
  2025. **
  2026. ** <dl>
  2027. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2028. ** <dd> ^This option takes three additional arguments that determine the
  2029. ** [lookaside memory allocator] configuration for the [database connection].
  2030. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2031. ** pointer to a memory buffer to use for lookaside memory.
  2032. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2033. ** may be NULL in which case SQLite will allocate the
  2034. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2035. ** size of each lookaside buffer slot. ^The third argument is the number of
  2036. ** slots. The size of the buffer in the first argument must be greater than
  2037. ** or equal to the product of the second and third arguments. The buffer
  2038. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2039. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2040. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2041. ** configuration for a database connection can only be changed when that
  2042. ** connection is not currently using lookaside memory, or in other words
  2043. ** when the "current value" returned by
  2044. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2045. ** Any attempt to change the lookaside memory configuration when lookaside
  2046. ** memory is in use leaves the configuration unchanged and returns
  2047. ** [SQLITE_BUSY].)^</dd>
  2048. **
  2049. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2050. ** <dd> ^This option is used to enable or disable the enforcement of
  2051. ** [foreign key constraints]. There should be two additional arguments.
  2052. ** The first argument is an integer which is 0 to disable FK enforcement,
  2053. ** positive to enable FK enforcement or negative to leave FK enforcement
  2054. ** unchanged. The second parameter is a pointer to an integer into which
  2055. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2056. ** following this call. The second parameter may be a NULL pointer, in
  2057. ** which case the FK enforcement setting is not reported back. </dd>
  2058. **
  2059. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2060. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2061. ** There should be two additional arguments.
  2062. ** The first argument is an integer which is 0 to disable triggers,
  2063. ** positive to enable triggers or negative to leave the setting unchanged.
  2064. ** The second parameter is a pointer to an integer into which
  2065. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2066. ** following this call. The second parameter may be a NULL pointer, in
  2067. ** which case the trigger setting is not reported back. </dd>
  2068. **
  2069. ** </dl>
  2070. */
  2071. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2072. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2073. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2074. /*
  2075. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2076. ** METHOD: sqlite3
  2077. **
  2078. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2079. ** [extended result codes] feature of SQLite. ^The extended result
  2080. ** codes are disabled by default for historical compatibility.
  2081. */
  2082. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
  2083. /*
  2084. ** CAPI3REF: Last Insert Rowid
  2085. ** METHOD: sqlite3
  2086. **
  2087. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  2088. ** has a unique 64-bit signed
  2089. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2090. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2091. ** names are not also used by explicitly declared columns. ^If
  2092. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2093. ** is another alias for the rowid.
  2094. **
  2095. ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
  2096. ** most recent successful [INSERT] into a rowid table or [virtual table]
  2097. ** on database connection D.
  2098. ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  2099. ** ^If no successful [INSERT]s into rowid tables
  2100. ** have ever occurred on the database connection D,
  2101. ** then sqlite3_last_insert_rowid(D) returns zero.
  2102. **
  2103. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  2104. ** method, then this routine will return the [rowid] of the inserted
  2105. ** row as long as the trigger or virtual table method is running.
  2106. ** But once the trigger or virtual table method ends, the value returned
  2107. ** by this routine reverts to what it was before the trigger or virtual
  2108. ** table method began.)^
  2109. **
  2110. ** ^An [INSERT] that fails due to a constraint violation is not a
  2111. ** successful [INSERT] and does not change the value returned by this
  2112. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2113. ** and INSERT OR ABORT make no changes to the return value of this
  2114. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2115. ** encounters a constraint violation, it does not fail. The
  2116. ** INSERT continues to completion after deleting rows that caused
  2117. ** the constraint problem so INSERT OR REPLACE will always change
  2118. ** the return value of this interface.)^
  2119. **
  2120. ** ^For the purposes of this routine, an [INSERT] is considered to
  2121. ** be successful even if it is subsequently rolled back.
  2122. **
  2123. ** This function is accessible to SQL statements via the
  2124. ** [last_insert_rowid() SQL function].
  2125. **
  2126. ** If a separate thread performs a new [INSERT] on the same
  2127. ** database connection while the [sqlite3_last_insert_rowid()]
  2128. ** function is running and thus changes the last insert [rowid],
  2129. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2130. ** unpredictable and might not equal either the old or the new
  2131. ** last insert [rowid].
  2132. */
  2133. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
  2134. /*
  2135. ** CAPI3REF: Count The Number Of Rows Modified
  2136. ** METHOD: sqlite3
  2137. **
  2138. ** ^This function returns the number of rows modified, inserted or
  2139. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  2140. ** statement on the database connection specified by the only parameter.
  2141. ** ^Executing any other type of SQL statement does not modify the value
  2142. ** returned by this function.
  2143. **
  2144. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  2145. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  2146. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  2147. **
  2148. ** Changes to a view that are intercepted by
  2149. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  2150. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  2151. ** DELETE statement run on a view is always zero. Only changes made to real
  2152. ** tables are counted.
  2153. **
  2154. ** Things are more complicated if the sqlite3_changes() function is
  2155. ** executed while a trigger program is running. This may happen if the
  2156. ** program uses the [changes() SQL function], or if some other callback
  2157. ** function invokes sqlite3_changes() directly. Essentially:
  2158. **
  2159. ** <ul>
  2160. ** <li> ^(Before entering a trigger program the value returned by
  2161. ** sqlite3_changes() function is saved. After the trigger program
  2162. ** has finished, the original value is restored.)^
  2163. **
  2164. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  2165. ** statement sets the value returned by sqlite3_changes()
  2166. ** upon completion as normal. Of course, this value will not include
  2167. ** any changes performed by sub-triggers, as the sqlite3_changes()
  2168. ** value will be saved and restored after each sub-trigger has run.)^
  2169. ** </ul>
  2170. **
  2171. ** ^This means that if the changes() SQL function (or similar) is used
  2172. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  2173. ** returns the value as set when the calling statement began executing.
  2174. ** ^If it is used by the second or subsequent such statement within a trigger
  2175. ** program, the value returned reflects the number of rows modified by the
  2176. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  2177. **
  2178. ** See also the [sqlite3_total_changes()] interface, the
  2179. ** [count_changes pragma], and the [changes() SQL function].
  2180. **
  2181. ** If a separate thread makes changes on the same database connection
  2182. ** while [sqlite3_changes()] is running then the value returned
  2183. ** is unpredictable and not meaningful.
  2184. */
  2185. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
  2186. /*
  2187. ** CAPI3REF: Total Number Of Rows Modified
  2188. ** METHOD: sqlite3
  2189. **
  2190. ** ^This function returns the total number of rows inserted, modified or
  2191. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  2192. ** since the database connection was opened, including those executed as
  2193. ** part of trigger programs. ^Executing any other type of SQL statement
  2194. ** does not affect the value returned by sqlite3_total_changes().
  2195. **
  2196. ** ^Changes made as part of [foreign key actions] are included in the
  2197. ** count, but those made as part of REPLACE constraint resolution are
  2198. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  2199. ** are not counted.
  2200. **
  2201. ** See also the [sqlite3_changes()] interface, the
  2202. ** [count_changes pragma], and the [total_changes() SQL function].
  2203. **
  2204. ** If a separate thread makes changes on the same database connection
  2205. ** while [sqlite3_total_changes()] is running then the value
  2206. ** returned is unpredictable and not meaningful.
  2207. */
  2208. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
  2209. /*
  2210. ** CAPI3REF: Interrupt A Long-Running Query
  2211. ** METHOD: sqlite3
  2212. **
  2213. ** ^This function causes any pending database operation to abort and
  2214. ** return at its earliest opportunity. This routine is typically
  2215. ** called in response to a user action such as pressing "Cancel"
  2216. ** or Ctrl-C where the user wants a long query operation to halt
  2217. ** immediately.
  2218. **
  2219. ** ^It is safe to call this routine from a thread different from the
  2220. ** thread that is currently running the database operation. But it
  2221. ** is not safe to call this routine with a [database connection] that
  2222. ** is closed or might close before sqlite3_interrupt() returns.
  2223. **
  2224. ** ^If an SQL operation is very nearly finished at the time when
  2225. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2226. ** to be interrupted and might continue to completion.
  2227. **
  2228. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2229. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2230. ** that is inside an explicit transaction, then the entire transaction
  2231. ** will be rolled back automatically.
  2232. **
  2233. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2234. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2235. ** that are started after the sqlite3_interrupt() call and before the
  2236. ** running statements reaches zero are interrupted as if they had been
  2237. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2238. ** that are started after the running statement count reaches zero are
  2239. ** not effected by the sqlite3_interrupt().
  2240. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2241. ** SQL statements is a no-op and has no effect on SQL statements
  2242. ** that are started after the sqlite3_interrupt() call returns.
  2243. **
  2244. ** If the database connection closes while [sqlite3_interrupt()]
  2245. ** is running then bad things will likely happen.
  2246. */
  2247. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
  2248. /*
  2249. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2250. **
  2251. ** These routines are useful during command-line input to determine if the
  2252. ** currently entered text seems to form a complete SQL statement or
  2253. ** if additional input is needed before sending the text into
  2254. ** SQLite for parsing. ^These routines return 1 if the input string
  2255. ** appears to be a complete SQL statement. ^A statement is judged to be
  2256. ** complete if it ends with a semicolon token and is not a prefix of a
  2257. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2258. ** string literals or quoted identifier names or comments are not
  2259. ** independent tokens (they are part of the token in which they are
  2260. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2261. ** and comments that follow the final semicolon are ignored.
  2262. **
  2263. ** ^These routines return 0 if the statement is incomplete. ^If a
  2264. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2265. **
  2266. ** ^These routines do not parse the SQL statements thus
  2267. ** will not detect syntactically incorrect SQL.
  2268. **
  2269. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2270. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2271. ** automatically by sqlite3_complete16(). If that initialization fails,
  2272. ** then the return value from sqlite3_complete16() will be non-zero
  2273. ** regardless of whether or not the input SQL is complete.)^
  2274. **
  2275. ** The input to [sqlite3_complete()] must be a zero-terminated
  2276. ** UTF-8 string.
  2277. **
  2278. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2279. ** UTF-16 string in native byte order.
  2280. */
  2281. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
  2282. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
  2283. /*
  2284. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2285. ** KEYWORDS: {busy-handler callback} {busy handler}
  2286. ** METHOD: sqlite3
  2287. **
  2288. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2289. ** that might be invoked with argument P whenever
  2290. ** an attempt is made to access a database table associated with
  2291. ** [database connection] D when another thread
  2292. ** or process has the table locked.
  2293. ** The sqlite3_busy_handler() interface is used to implement
  2294. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2295. **
  2296. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2297. ** is returned immediately upon encountering the lock. ^If the busy callback
  2298. ** is not NULL, then the callback might be invoked with two arguments.
  2299. **
  2300. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2301. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2302. ** the busy handler callback is the number of times that the busy handler has
  2303. ** been invoked previously for the same locking event. ^If the
  2304. ** busy callback returns 0, then no additional attempts are made to
  2305. ** access the database and [SQLITE_BUSY] is returned
  2306. ** to the application.
  2307. ** ^If the callback returns non-zero, then another attempt
  2308. ** is made to access the database and the cycle repeats.
  2309. **
  2310. ** The presence of a busy handler does not guarantee that it will be invoked
  2311. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2312. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2313. ** to the application instead of invoking the
  2314. ** busy handler.
  2315. ** Consider a scenario where one process is holding a read lock that
  2316. ** it is trying to promote to a reserved lock and
  2317. ** a second process is holding a reserved lock that it is trying
  2318. ** to promote to an exclusive lock. The first process cannot proceed
  2319. ** because it is blocked by the second and the second process cannot
  2320. ** proceed because it is blocked by the first. If both processes
  2321. ** invoke the busy handlers, neither will make any progress. Therefore,
  2322. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2323. ** will induce the first process to release its read lock and allow
  2324. ** the second process to proceed.
  2325. **
  2326. ** ^The default busy callback is NULL.
  2327. **
  2328. ** ^(There can only be a single busy handler defined for each
  2329. ** [database connection]. Setting a new busy handler clears any
  2330. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2331. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2332. ** busy handler and thus clear any previously set busy handler.
  2333. **
  2334. ** The busy callback should not take any actions which modify the
  2335. ** database connection that invoked the busy handler. In other words,
  2336. ** the busy handler is not reentrant. Any such actions
  2337. ** result in undefined behavior.
  2338. **
  2339. ** A busy handler must not close the database connection
  2340. ** or [prepared statement] that invoked the busy handler.
  2341. */
  2342. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2343. /*
  2344. ** CAPI3REF: Set A Busy Timeout
  2345. ** METHOD: sqlite3
  2346. **
  2347. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2348. ** for a specified amount of time when a table is locked. ^The handler
  2349. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2350. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2351. ** the handler returns 0 which causes [sqlite3_step()] to return
  2352. ** [SQLITE_BUSY].
  2353. **
  2354. ** ^Calling this routine with an argument less than or equal to zero
  2355. ** turns off all busy handlers.
  2356. **
  2357. ** ^(There can only be a single busy handler for a particular
  2358. ** [database connection] at any given moment. If another busy handler
  2359. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2360. ** this routine, that other busy handler is cleared.)^
  2361. **
  2362. ** See also: [PRAGMA busy_timeout]
  2363. */
  2364. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
  2365. /*
  2366. ** CAPI3REF: Convenience Routines For Running Queries
  2367. ** METHOD: sqlite3
  2368. **
  2369. ** This is a legacy interface that is preserved for backwards compatibility.
  2370. ** Use of this interface is not recommended.
  2371. **
  2372. ** Definition: A <b>result table</b> is memory data structure created by the
  2373. ** [sqlite3_get_table()] interface. A result table records the
  2374. ** complete query results from one or more queries.
  2375. **
  2376. ** The table conceptually has a number of rows and columns. But
  2377. ** these numbers are not part of the result table itself. These
  2378. ** numbers are obtained separately. Let N be the number of rows
  2379. ** and M be the number of columns.
  2380. **
  2381. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2382. ** There are (N+1)*M elements in the array. The first M pointers point
  2383. ** to zero-terminated strings that contain the names of the columns.
  2384. ** The remaining entries all point to query results. NULL values result
  2385. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2386. ** string representation as returned by [sqlite3_column_text()].
  2387. **
  2388. ** A result table might consist of one or more memory allocations.
  2389. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2390. ** A result table should be deallocated using [sqlite3_free_table()].
  2391. **
  2392. ** ^(As an example of the result table format, suppose a query result
  2393. ** is as follows:
  2394. **
  2395. ** <blockquote><pre>
  2396. ** Name | Age
  2397. ** -----------------------
  2398. ** Alice | 43
  2399. ** Bob | 28
  2400. ** Cindy | 21
  2401. ** </pre></blockquote>
  2402. **
  2403. ** There are two column (M==2) and three rows (N==3). Thus the
  2404. ** result table has 8 entries. Suppose the result table is stored
  2405. ** in an array names azResult. Then azResult holds this content:
  2406. **
  2407. ** <blockquote><pre>
  2408. ** azResult&#91;0] = "Name";
  2409. ** azResult&#91;1] = "Age";
  2410. ** azResult&#91;2] = "Alice";
  2411. ** azResult&#91;3] = "43";
  2412. ** azResult&#91;4] = "Bob";
  2413. ** azResult&#91;5] = "28";
  2414. ** azResult&#91;6] = "Cindy";
  2415. ** azResult&#91;7] = "21";
  2416. ** </pre></blockquote>)^
  2417. **
  2418. ** ^The sqlite3_get_table() function evaluates one or more
  2419. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2420. ** string of its 2nd parameter and returns a result table to the
  2421. ** pointer given in its 3rd parameter.
  2422. **
  2423. ** After the application has finished with the result from sqlite3_get_table(),
  2424. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2425. ** release the memory that was malloced. Because of the way the
  2426. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2427. ** function must not try to call [sqlite3_free()] directly. Only
  2428. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2429. **
  2430. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2431. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2432. ** to any internal data structures of SQLite. It uses only the public
  2433. ** interface defined here. As a consequence, errors that occur in the
  2434. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2435. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2436. ** [sqlite3_errmsg()].
  2437. */
  2438. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  2439. sqlite3 *db, /* An open database */
  2440. const char *zSql, /* SQL to be evaluated */
  2441. char ***pazResult, /* Results of the query */
  2442. int *pnRow, /* Number of result rows written here */
  2443. int *pnColumn, /* Number of result columns written here */
  2444. char **pzErrmsg /* Error msg written here */
  2445. );
  2446. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
  2447. /*
  2448. ** CAPI3REF: Formatted String Printing Functions
  2449. **
  2450. ** These routines are work-alikes of the "printf()" family of functions
  2451. ** from the standard C library.
  2452. ** These routines understand most of the common K&R formatting options,
  2453. ** plus some additional non-standard formats, detailed below.
  2454. ** Note that some of the more obscure formatting options from recent
  2455. ** C-library standards are omitted from this implementation.
  2456. **
  2457. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2458. ** results into memory obtained from [sqlite3_malloc()].
  2459. ** The strings returned by these two routines should be
  2460. ** released by [sqlite3_free()]. ^Both routines return a
  2461. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2462. ** memory to hold the resulting string.
  2463. **
  2464. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2465. ** the standard C library. The result is written into the
  2466. ** buffer supplied as the second parameter whose size is given by
  2467. ** the first parameter. Note that the order of the
  2468. ** first two parameters is reversed from snprintf().)^ This is an
  2469. ** historical accident that cannot be fixed without breaking
  2470. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2471. ** returns a pointer to its buffer instead of the number of
  2472. ** characters actually written into the buffer.)^ We admit that
  2473. ** the number of characters written would be a more useful return
  2474. ** value but we cannot change the implementation of sqlite3_snprintf()
  2475. ** now without breaking compatibility.
  2476. **
  2477. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2478. ** guarantees that the buffer is always zero-terminated. ^The first
  2479. ** parameter "n" is the total size of the buffer, including space for
  2480. ** the zero terminator. So the longest string that can be completely
  2481. ** written will be n-1 characters.
  2482. **
  2483. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2484. **
  2485. ** These routines all implement some additional formatting
  2486. ** options that are useful for constructing SQL statements.
  2487. ** All of the usual printf() formatting options apply. In addition, there
  2488. ** is are "%q", "%Q", "%w" and "%z" options.
  2489. **
  2490. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2491. ** string from the argument list. But %q also doubles every '\'' character.
  2492. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2493. ** character it escapes that character and allows it to be inserted into
  2494. ** the string.
  2495. **
  2496. ** For example, assume the string variable zText contains text as follows:
  2497. **
  2498. ** <blockquote><pre>
  2499. ** char *zText = "It's a happy day!";
  2500. ** </pre></blockquote>
  2501. **
  2502. ** One can use this text in an SQL statement as follows:
  2503. **
  2504. ** <blockquote><pre>
  2505. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2506. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2507. ** sqlite3_free(zSQL);
  2508. ** </pre></blockquote>
  2509. **
  2510. ** Because the %q format string is used, the '\'' character in zText
  2511. ** is escaped and the SQL generated is as follows:
  2512. **
  2513. ** <blockquote><pre>
  2514. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2515. ** </pre></blockquote>
  2516. **
  2517. ** This is correct. Had we used %s instead of %q, the generated SQL
  2518. ** would have looked like this:
  2519. **
  2520. ** <blockquote><pre>
  2521. ** INSERT INTO table1 VALUES('It's a happy day!');
  2522. ** </pre></blockquote>
  2523. **
  2524. ** This second example is an SQL syntax error. As a general rule you should
  2525. ** always use %q instead of %s when inserting text into a string literal.
  2526. **
  2527. ** ^(The %Q option works like %q except it also adds single quotes around
  2528. ** the outside of the total string. Additionally, if the parameter in the
  2529. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2530. ** single quotes).)^ So, for example, one could say:
  2531. **
  2532. ** <blockquote><pre>
  2533. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2534. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2535. ** sqlite3_free(zSQL);
  2536. ** </pre></blockquote>
  2537. **
  2538. ** The code above will render a correct SQL statement in the zSQL
  2539. ** variable even if the zText variable is a NULL pointer.
  2540. **
  2541. ** ^(The "%w" formatting option is like "%q" except that it expects to
  2542. ** be contained within double-quotes instead of single quotes, and it
  2543. ** escapes the double-quote character instead of the single-quote
  2544. ** character.)^ The "%w" formatting option is intended for safely inserting
  2545. ** table and column names into a constructed SQL statement.
  2546. **
  2547. ** ^(The "%z" formatting option works like "%s" but with the
  2548. ** addition that after the string has been read and copied into
  2549. ** the result, [sqlite3_free()] is called on the input string.)^
  2550. */
  2551. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
  2552. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
  2553. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
  2554. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
  2555. /*
  2556. ** CAPI3REF: Memory Allocation Subsystem
  2557. **
  2558. ** The SQLite core uses these three routines for all of its own
  2559. ** internal memory allocation needs. "Core" in the previous sentence
  2560. ** does not include operating-system specific VFS implementation. The
  2561. ** Windows VFS uses native malloc() and free() for some operations.
  2562. **
  2563. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2564. ** of memory at least N bytes in length, where N is the parameter.
  2565. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2566. ** memory, it returns a NULL pointer. ^If the parameter N to
  2567. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2568. ** a NULL pointer.
  2569. **
  2570. ** ^The sqlite3_malloc64(N) routine works just like
  2571. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2572. ** of a signed 32-bit integer.
  2573. **
  2574. ** ^Calling sqlite3_free() with a pointer previously returned
  2575. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2576. ** that it might be reused. ^The sqlite3_free() routine is
  2577. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2578. ** to sqlite3_free() is harmless. After being freed, memory
  2579. ** should neither be read nor written. Even reading previously freed
  2580. ** memory might result in a segmentation fault or other severe error.
  2581. ** Memory corruption, a segmentation fault, or other severe error
  2582. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2583. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2584. **
  2585. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2586. ** prior memory allocation X to be at least N bytes.
  2587. ** ^If the X parameter to sqlite3_realloc(X,N)
  2588. ** is a NULL pointer then its behavior is identical to calling
  2589. ** sqlite3_malloc(N).
  2590. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2591. ** negative then the behavior is exactly the same as calling
  2592. ** sqlite3_free(X).
  2593. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2594. ** of at least N bytes in size or NULL if insufficient memory is available.
  2595. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2596. ** of the prior allocation are copied into the beginning of buffer returned
  2597. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2598. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2599. ** prior allocation is not freed.
  2600. **
  2601. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2602. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2603. ** of a 32-bit signed integer.
  2604. **
  2605. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2606. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2607. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2608. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2609. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2610. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2611. ** the beginning of memory allocation, or if it points to a formerly
  2612. ** valid memory allocation that has now been freed, then the behavior
  2613. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2614. **
  2615. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2616. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2617. ** is always aligned to at least an 8 byte boundary, or to a
  2618. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2619. ** option is used.
  2620. **
  2621. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2622. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2623. ** implementation of these routines to be omitted. That capability
  2624. ** is no longer provided. Only built-in memory allocators can be used.
  2625. **
  2626. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2627. ** the system malloc() and free() directly when converting
  2628. ** filenames between the UTF-8 encoding used by SQLite
  2629. ** and whatever filename encoding is used by the particular Windows
  2630. ** installation. Memory allocation errors were detected, but
  2631. ** they were reported back as [SQLITE_CANTOPEN] or
  2632. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2633. **
  2634. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2635. ** must be either NULL or else pointers obtained from a prior
  2636. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2637. ** not yet been released.
  2638. **
  2639. ** The application must not read or write any part of
  2640. ** a block of memory after it has been released using
  2641. ** [sqlite3_free()] or [sqlite3_realloc()].
  2642. */
  2643. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
  2644. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
  2645. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
  2646. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
  2647. SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
  2648. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
  2649. /*
  2650. ** CAPI3REF: Memory Allocator Statistics
  2651. **
  2652. ** SQLite provides these two interfaces for reporting on the status
  2653. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2654. ** routines, which form the built-in memory allocation subsystem.
  2655. **
  2656. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2657. ** of memory currently outstanding (malloced but not freed).
  2658. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2659. ** value of [sqlite3_memory_used()] since the high-water mark
  2660. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2661. ** [sqlite3_memory_highwater()] include any overhead
  2662. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2663. ** but not overhead added by the any underlying system library
  2664. ** routines that [sqlite3_malloc()] may call.
  2665. **
  2666. ** ^The memory high-water mark is reset to the current value of
  2667. ** [sqlite3_memory_used()] if and only if the parameter to
  2668. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2669. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2670. ** prior to the reset.
  2671. */
  2672. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
  2673. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
  2674. /*
  2675. ** CAPI3REF: Pseudo-Random Number Generator
  2676. **
  2677. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2678. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2679. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2680. ** the build-in random() and randomblob() SQL functions. This interface allows
  2681. ** applications to access the same PRNG for other purposes.
  2682. **
  2683. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2684. ** ^The P parameter can be a NULL pointer.
  2685. **
  2686. ** ^If this routine has not been previously called or if the previous
  2687. ** call had N less than one or a NULL pointer for P, then the PRNG is
  2688. ** seeded using randomness obtained from the xRandomness method of
  2689. ** the default [sqlite3_vfs] object.
  2690. ** ^If the previous call to this routine had an N of 1 or more and a
  2691. ** non-NULL P then the pseudo-randomness is generated
  2692. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2693. ** method.
  2694. */
  2695. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
  2696. /*
  2697. ** CAPI3REF: Compile-Time Authorization Callbacks
  2698. ** METHOD: sqlite3
  2699. **
  2700. ** ^This routine registers an authorizer callback with a particular
  2701. ** [database connection], supplied in the first argument.
  2702. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2703. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2704. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2705. ** points during the compilation process, as logic is being created
  2706. ** to perform various actions, the authorizer callback is invoked to
  2707. ** see if those actions are allowed. ^The authorizer callback should
  2708. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2709. ** specific action but allow the SQL statement to continue to be
  2710. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2711. ** rejected with an error. ^If the authorizer callback returns
  2712. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2713. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2714. ** the authorizer will fail with an error message.
  2715. **
  2716. ** When the callback returns [SQLITE_OK], that means the operation
  2717. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2718. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2719. ** authorizer will fail with an error message explaining that
  2720. ** access is denied.
  2721. **
  2722. ** ^The first parameter to the authorizer callback is a copy of the third
  2723. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2724. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2725. ** the particular action to be authorized. ^The third through sixth parameters
  2726. ** to the callback are zero-terminated strings that contain additional
  2727. ** details about the action to be authorized.
  2728. **
  2729. ** ^If the action code is [SQLITE_READ]
  2730. ** and the callback returns [SQLITE_IGNORE] then the
  2731. ** [prepared statement] statement is constructed to substitute
  2732. ** a NULL value in place of the table column that would have
  2733. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2734. ** return can be used to deny an untrusted user access to individual
  2735. ** columns of a table.
  2736. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2737. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2738. ** [truncate optimization] is disabled and all rows are deleted individually.
  2739. **
  2740. ** An authorizer is used when [sqlite3_prepare | preparing]
  2741. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2742. ** do not try to access data they are not allowed to see, or that they do not
  2743. ** try to execute malicious statements that damage the database. For
  2744. ** example, an application may allow a user to enter arbitrary
  2745. ** SQL queries for evaluation by a database. But the application does
  2746. ** not want the user to be able to make arbitrary changes to the
  2747. ** database. An authorizer could then be put in place while the
  2748. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2749. ** disallows everything except [SELECT] statements.
  2750. **
  2751. ** Applications that need to process SQL from untrusted sources
  2752. ** might also consider lowering resource limits using [sqlite3_limit()]
  2753. ** and limiting database size using the [max_page_count] [PRAGMA]
  2754. ** in addition to using an authorizer.
  2755. **
  2756. ** ^(Only a single authorizer can be in place on a database connection
  2757. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2758. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2759. ** The authorizer is disabled by default.
  2760. **
  2761. ** The authorizer callback must not do anything that will modify
  2762. ** the database connection that invoked the authorizer callback.
  2763. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2764. ** database connections for the meaning of "modify" in this paragraph.
  2765. **
  2766. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2767. ** statement might be re-prepared during [sqlite3_step()] due to a
  2768. ** schema change. Hence, the application should ensure that the
  2769. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2770. **
  2771. ** ^Note that the authorizer callback is invoked only during
  2772. ** [sqlite3_prepare()] or its variants. Authorization is not
  2773. ** performed during statement evaluation in [sqlite3_step()], unless
  2774. ** as stated in the previous paragraph, sqlite3_step() invokes
  2775. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2776. */
  2777. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  2778. sqlite3*,
  2779. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2780. void *pUserData
  2781. );
  2782. /*
  2783. ** CAPI3REF: Authorizer Return Codes
  2784. **
  2785. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2786. ** return either [SQLITE_OK] or one of these two constants in order
  2787. ** to signal SQLite whether or not the action is permitted. See the
  2788. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2789. ** information.
  2790. **
  2791. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2792. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2793. */
  2794. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2795. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2796. /*
  2797. ** CAPI3REF: Authorizer Action Codes
  2798. **
  2799. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2800. ** that is invoked to authorize certain SQL statement actions. The
  2801. ** second parameter to the callback is an integer code that specifies
  2802. ** what action is being authorized. These are the integer action codes that
  2803. ** the authorizer callback may be passed.
  2804. **
  2805. ** These action code values signify what kind of operation is to be
  2806. ** authorized. The 3rd and 4th parameters to the authorization
  2807. ** callback function will be parameters or NULL depending on which of these
  2808. ** codes is used as the second parameter. ^(The 5th parameter to the
  2809. ** authorizer callback is the name of the database ("main", "temp",
  2810. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2811. ** is the name of the inner-most trigger or view that is responsible for
  2812. ** the access attempt or NULL if this access attempt is directly from
  2813. ** top-level SQL code.
  2814. */
  2815. /******************************************* 3rd ************ 4th ***********/
  2816. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2817. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2818. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2819. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2820. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2821. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2822. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2823. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2824. #define SQLITE_DELETE 9 /* Table Name NULL */
  2825. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2826. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2827. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2828. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2829. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2830. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2831. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2832. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2833. #define SQLITE_INSERT 18 /* Table Name NULL */
  2834. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2835. #define SQLITE_READ 20 /* Table Name Column Name */
  2836. #define SQLITE_SELECT 21 /* NULL NULL */
  2837. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2838. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2839. #define SQLITE_ATTACH 24 /* Filename NULL */
  2840. #define SQLITE_DETACH 25 /* Database Name NULL */
  2841. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2842. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2843. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2844. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2845. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2846. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2847. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2848. #define SQLITE_COPY 0 /* No longer used */
  2849. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  2850. /*
  2851. ** CAPI3REF: Tracing And Profiling Functions
  2852. ** METHOD: sqlite3
  2853. **
  2854. ** These routines register callback functions that can be used for
  2855. ** tracing and profiling the execution of SQL statements.
  2856. **
  2857. ** ^The callback function registered by sqlite3_trace() is invoked at
  2858. ** various times when an SQL statement is being run by [sqlite3_step()].
  2859. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2860. ** SQL statement text as the statement first begins executing.
  2861. ** ^(Additional sqlite3_trace() callbacks might occur
  2862. ** as each triggered subprogram is entered. The callbacks for triggers
  2863. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2864. **
  2865. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2866. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2867. **
  2868. ** ^The callback function registered by sqlite3_profile() is invoked
  2869. ** as each SQL statement finishes. ^The profile callback contains
  2870. ** the original statement text and an estimate of wall-clock time
  2871. ** of how long that statement took to run. ^The profile callback
  2872. ** time is in units of nanoseconds, however the current implementation
  2873. ** is only capable of millisecond resolution so the six least significant
  2874. ** digits in the time are meaningless. Future versions of SQLite
  2875. ** might provide greater resolution on the profiler callback. The
  2876. ** sqlite3_profile() function is considered experimental and is
  2877. ** subject to change in future versions of SQLite.
  2878. */
  2879. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2880. SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
  2881. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2882. /*
  2883. ** CAPI3REF: Query Progress Callbacks
  2884. ** METHOD: sqlite3
  2885. **
  2886. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2887. ** function X to be invoked periodically during long running calls to
  2888. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2889. ** database connection D. An example use for this
  2890. ** interface is to keep a GUI updated during a large query.
  2891. **
  2892. ** ^The parameter P is passed through as the only parameter to the
  2893. ** callback function X. ^The parameter N is the approximate number of
  2894. ** [virtual machine instructions] that are evaluated between successive
  2895. ** invocations of the callback X. ^If N is less than one then the progress
  2896. ** handler is disabled.
  2897. **
  2898. ** ^Only a single progress handler may be defined at one time per
  2899. ** [database connection]; setting a new progress handler cancels the
  2900. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2901. ** ^The progress handler is also disabled by setting N to a value less
  2902. ** than 1.
  2903. **
  2904. ** ^If the progress callback returns non-zero, the operation is
  2905. ** interrupted. This feature can be used to implement a
  2906. ** "Cancel" button on a GUI progress dialog box.
  2907. **
  2908. ** The progress handler callback must not do anything that will modify
  2909. ** the database connection that invoked the progress handler.
  2910. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2911. ** database connections for the meaning of "modify" in this paragraph.
  2912. **
  2913. */
  2914. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2915. /*
  2916. ** CAPI3REF: Opening A New Database Connection
  2917. ** CONSTRUCTOR: sqlite3
  2918. **
  2919. ** ^These routines open an SQLite database file as specified by the
  2920. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2921. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2922. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2923. ** returned in *ppDb, even if an error occurs. The only exception is that
  2924. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2925. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2926. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2927. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2928. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2929. ** an English language description of the error following a failure of any
  2930. ** of the sqlite3_open() routines.
  2931. **
  2932. ** ^The default encoding will be UTF-8 for databases created using
  2933. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  2934. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  2935. **
  2936. ** Whether or not an error occurs when it is opened, resources
  2937. ** associated with the [database connection] handle should be released by
  2938. ** passing it to [sqlite3_close()] when it is no longer required.
  2939. **
  2940. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2941. ** except that it accepts two additional parameters for additional control
  2942. ** over the new database connection. ^(The flags parameter to
  2943. ** sqlite3_open_v2() can take one of
  2944. ** the following three values, optionally combined with the
  2945. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2946. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2947. **
  2948. ** <dl>
  2949. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2950. ** <dd>The database is opened in read-only mode. If the database does not
  2951. ** already exist, an error is returned.</dd>)^
  2952. **
  2953. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2954. ** <dd>The database is opened for reading and writing if possible, or reading
  2955. ** only if the file is write protected by the operating system. In either
  2956. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2957. **
  2958. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2959. ** <dd>The database is opened for reading and writing, and is created if
  2960. ** it does not already exist. This is the behavior that is always used for
  2961. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2962. ** </dl>
  2963. **
  2964. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2965. ** combinations shown above optionally combined with other
  2966. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2967. ** then the behavior is undefined.
  2968. **
  2969. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2970. ** opens in the multi-thread [threading mode] as long as the single-thread
  2971. ** mode has not been set at compile-time or start-time. ^If the
  2972. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2973. ** in the serialized [threading mode] unless single-thread was
  2974. ** previously selected at compile-time or start-time.
  2975. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2976. ** eligible to use [shared cache mode], regardless of whether or not shared
  2977. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2978. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2979. ** participate in [shared cache mode] even if it is enabled.
  2980. **
  2981. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2982. ** [sqlite3_vfs] object that defines the operating system interface that
  2983. ** the new database connection should use. ^If the fourth parameter is
  2984. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2985. **
  2986. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2987. ** is created for the connection. ^This in-memory database will vanish when
  2988. ** the database connection is closed. Future versions of SQLite might
  2989. ** make use of additional special filenames that begin with the ":" character.
  2990. ** It is recommended that when a database filename actually does begin with
  2991. ** a ":" character you should prefix the filename with a pathname such as
  2992. ** "./" to avoid ambiguity.
  2993. **
  2994. ** ^If the filename is an empty string, then a private, temporary
  2995. ** on-disk database will be created. ^This private database will be
  2996. ** automatically deleted as soon as the database connection is closed.
  2997. **
  2998. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2999. **
  3000. ** ^If [URI filename] interpretation is enabled, and the filename argument
  3001. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  3002. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  3003. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  3004. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  3005. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  3006. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  3007. ** by default, but future releases of SQLite might enable URI filename
  3008. ** interpretation by default. See "[URI filenames]" for additional
  3009. ** information.
  3010. **
  3011. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  3012. ** authority, then it must be either an empty string or the string
  3013. ** "localhost". ^If the authority is not an empty string or "localhost", an
  3014. ** error is returned to the caller. ^The fragment component of a URI, if
  3015. ** present, is ignored.
  3016. **
  3017. ** ^SQLite uses the path component of the URI as the name of the disk file
  3018. ** which contains the database. ^If the path begins with a '/' character,
  3019. ** then it is interpreted as an absolute path. ^If the path does not begin
  3020. ** with a '/' (meaning that the authority section is omitted from the URI)
  3021. ** then the path is interpreted as a relative path.
  3022. ** ^(On windows, the first component of an absolute path
  3023. ** is a drive specification (e.g. "C:").)^
  3024. **
  3025. ** [[core URI query parameters]]
  3026. ** The query component of a URI may contain parameters that are interpreted
  3027. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  3028. ** SQLite and its built-in [VFSes] interpret the
  3029. ** following query parameters:
  3030. **
  3031. ** <ul>
  3032. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  3033. ** a VFS object that provides the operating system interface that should
  3034. ** be used to access the database file on disk. ^If this option is set to
  3035. ** an empty string the default VFS object is used. ^Specifying an unknown
  3036. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  3037. ** present, then the VFS specified by the option takes precedence over
  3038. ** the value passed as the fourth parameter to sqlite3_open_v2().
  3039. **
  3040. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3041. ** "rwc", or "memory". Attempting to set it to any other value is
  3042. ** an error)^.
  3043. ** ^If "ro" is specified, then the database is opened for read-only
  3044. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3045. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3046. ** "rw", then the database is opened for read-write (but not create)
  3047. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3048. ** been set. ^Value "rwc" is equivalent to setting both
  3049. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3050. ** set to "memory" then a pure [in-memory database] that never reads
  3051. ** or writes from disk is used. ^It is an error to specify a value for
  3052. ** the mode parameter that is less restrictive than that specified by
  3053. ** the flags passed in the third parameter to sqlite3_open_v2().
  3054. **
  3055. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3056. ** "private". ^Setting it to "shared" is equivalent to setting the
  3057. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3058. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3059. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3060. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3061. ** a URI filename, its value overrides any behavior requested by setting
  3062. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3063. **
  3064. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  3065. ** [powersafe overwrite] property does or does not apply to the
  3066. ** storage media on which the database file resides.
  3067. **
  3068. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  3069. ** which if set disables file locking in rollback journal modes. This
  3070. ** is useful for accessing a database on a filesystem that does not
  3071. ** support locking. Caution: Database corruption might result if two
  3072. ** or more processes write to the same database and any one of those
  3073. ** processes uses nolock=1.
  3074. **
  3075. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  3076. ** parameter that indicates that the database file is stored on
  3077. ** read-only media. ^When immutable is set, SQLite assumes that the
  3078. ** database file cannot be changed, even by a process with higher
  3079. ** privilege, and so the database is opened read-only and all locking
  3080. ** and change detection is disabled. Caution: Setting the immutable
  3081. ** property on a database file that does in fact change can result
  3082. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  3083. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  3084. **
  3085. ** </ul>
  3086. **
  3087. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3088. ** error. Future versions of SQLite might understand additional query
  3089. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3090. ** additional information.
  3091. **
  3092. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3093. **
  3094. ** <table border="1" align=center cellpadding=5>
  3095. ** <tr><th> URI filenames <th> Results
  3096. ** <tr><td> file:data.db <td>
  3097. ** Open the file "data.db" in the current directory.
  3098. ** <tr><td> file:/home/fred/data.db<br>
  3099. ** file:///home/fred/data.db <br>
  3100. ** file://localhost/home/fred/data.db <br> <td>
  3101. ** Open the database file "/home/fred/data.db".
  3102. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3103. ** An error. "darkstar" is not a recognized authority.
  3104. ** <tr><td style="white-space:nowrap">
  3105. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3106. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3107. ** C:. Note that the %20 escaping in this example is not strictly
  3108. ** necessary - space characters can be used literally
  3109. ** in URI filenames.
  3110. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3111. ** Open file "data.db" in the current directory for read-only access.
  3112. ** Regardless of whether or not shared-cache mode is enabled by
  3113. ** default, use a private cache.
  3114. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  3115. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  3116. ** that uses dot-files in place of posix advisory locking.
  3117. ** <tr><td> file:data.db?mode=readonly <td>
  3118. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3119. ** </table>
  3120. **
  3121. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3122. ** query components of a URI. A hexadecimal escape sequence consists of a
  3123. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3124. ** specifying an octet value. ^Before the path or query components of a
  3125. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3126. ** hexadecimal escape sequences replaced by a single byte containing the
  3127. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3128. ** the results are undefined.
  3129. **
  3130. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3131. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3132. ** codepage is currently defined. Filenames containing international
  3133. ** characters must be converted to UTF-8 prior to passing them into
  3134. ** sqlite3_open() or sqlite3_open_v2().
  3135. **
  3136. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3137. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3138. ** features that require the use of temporary files may fail.
  3139. **
  3140. ** See also: [sqlite3_temp_directory]
  3141. */
  3142. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  3143. const char *filename, /* Database filename (UTF-8) */
  3144. sqlite3 **ppDb /* OUT: SQLite db handle */
  3145. );
  3146. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  3147. const void *filename, /* Database filename (UTF-16) */
  3148. sqlite3 **ppDb /* OUT: SQLite db handle */
  3149. );
  3150. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  3151. const char *filename, /* Database filename (UTF-8) */
  3152. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3153. int flags, /* Flags */
  3154. const char *zVfs /* Name of VFS module to use */
  3155. );
  3156. /*
  3157. ** CAPI3REF: Obtain Values For URI Parameters
  3158. **
  3159. ** These are utility routines, useful to VFS implementations, that check
  3160. ** to see if a database file was a URI that contained a specific query
  3161. ** parameter, and if so obtains the value of that query parameter.
  3162. **
  3163. ** If F is the database filename pointer passed into the xOpen() method of
  3164. ** a VFS implementation when the flags parameter to xOpen() has one or
  3165. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3166. ** P is the name of the query parameter, then
  3167. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3168. ** parameter if it exists or a NULL pointer if P does not appear as a
  3169. ** query parameter on F. If P is a query parameter of F
  3170. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3171. ** a pointer to an empty string.
  3172. **
  3173. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3174. ** parameter and returns true (1) or false (0) according to the value
  3175. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3176. ** value of query parameter P is one of "yes", "true", or "on" in any
  3177. ** case or if the value begins with a non-zero number. The
  3178. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3179. ** query parameter P is one of "no", "false", or "off" in any case or
  3180. ** if the value begins with a numeric zero. If P is not a query
  3181. ** parameter on F or if the value of P is does not match any of the
  3182. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3183. **
  3184. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3185. ** 64-bit signed integer and returns that integer, or D if P does not
  3186. ** exist. If the value of P is something other than an integer, then
  3187. ** zero is returned.
  3188. **
  3189. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3190. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3191. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3192. ** VFS method, then the behavior of this routine is undefined and probably
  3193. ** undesirable.
  3194. */
  3195. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3196. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3197. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3198. /*
  3199. ** CAPI3REF: Error Codes And Messages
  3200. ** METHOD: sqlite3
  3201. **
  3202. ** ^If the most recent sqlite3_* API call associated with
  3203. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  3204. ** returns the numeric [result code] or [extended result code] for that
  3205. ** API call.
  3206. ** If the most recent API call was successful,
  3207. ** then the return value from sqlite3_errcode() is undefined.
  3208. ** ^The sqlite3_extended_errcode()
  3209. ** interface is the same except that it always returns the
  3210. ** [extended result code] even when extended result codes are
  3211. ** disabled.
  3212. **
  3213. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3214. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3215. ** ^(Memory to hold the error message string is managed internally.
  3216. ** The application does not need to worry about freeing the result.
  3217. ** However, the error string might be overwritten or deallocated by
  3218. ** subsequent calls to other SQLite interface functions.)^
  3219. **
  3220. ** ^The sqlite3_errstr() interface returns the English-language text
  3221. ** that describes the [result code], as UTF-8.
  3222. ** ^(Memory to hold the error message string is managed internally
  3223. ** and must not be freed by the application)^.
  3224. **
  3225. ** When the serialized [threading mode] is in use, it might be the
  3226. ** case that a second error occurs on a separate thread in between
  3227. ** the time of the first error and the call to these interfaces.
  3228. ** When that happens, the second error will be reported since these
  3229. ** interfaces always report the most recent result. To avoid
  3230. ** this, each thread can obtain exclusive use of the [database connection] D
  3231. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3232. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3233. ** all calls to the interfaces listed here are completed.
  3234. **
  3235. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3236. ** was invoked incorrectly by the application. In that case, the
  3237. ** error code and message may or may not be set.
  3238. */
  3239. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
  3240. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
  3241. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
  3242. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
  3243. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
  3244. /*
  3245. ** CAPI3REF: Prepared Statement Object
  3246. ** KEYWORDS: {prepared statement} {prepared statements}
  3247. **
  3248. ** An instance of this object represents a single SQL statement that
  3249. ** has been compiled into binary form and is ready to be evaluated.
  3250. **
  3251. ** Think of each SQL statement as a separate computer program. The
  3252. ** original SQL text is source code. A prepared statement object
  3253. ** is the compiled object code. All SQL must be converted into a
  3254. ** prepared statement before it can be run.
  3255. **
  3256. ** The life-cycle of a prepared statement object usually goes like this:
  3257. **
  3258. ** <ol>
  3259. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  3260. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  3261. ** interfaces.
  3262. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3263. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  3264. ** to step 2. Do this zero or more times.
  3265. ** <li> Destroy the object using [sqlite3_finalize()].
  3266. ** </ol>
  3267. */
  3268. typedef struct sqlite3_stmt sqlite3_stmt;
  3269. /*
  3270. ** CAPI3REF: Run-time Limits
  3271. ** METHOD: sqlite3
  3272. **
  3273. ** ^(This interface allows the size of various constructs to be limited
  3274. ** on a connection by connection basis. The first parameter is the
  3275. ** [database connection] whose limit is to be set or queried. The
  3276. ** second parameter is one of the [limit categories] that define a
  3277. ** class of constructs to be size limited. The third parameter is the
  3278. ** new limit for that construct.)^
  3279. **
  3280. ** ^If the new limit is a negative number, the limit is unchanged.
  3281. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3282. ** [limits | hard upper bound]
  3283. ** set at compile-time by a C preprocessor macro called
  3284. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3285. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3286. ** ^Attempts to increase a limit above its hard upper bound are
  3287. ** silently truncated to the hard upper bound.
  3288. **
  3289. ** ^Regardless of whether or not the limit was changed, the
  3290. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3291. ** ^Hence, to find the current value of a limit without changing it,
  3292. ** simply invoke this interface with the third parameter set to -1.
  3293. **
  3294. ** Run-time limits are intended for use in applications that manage
  3295. ** both their own internal database and also databases that are controlled
  3296. ** by untrusted external sources. An example application might be a
  3297. ** web browser that has its own databases for storing history and
  3298. ** separate databases controlled by JavaScript applications downloaded
  3299. ** off the Internet. The internal databases can be given the
  3300. ** large, default limits. Databases managed by external sources can
  3301. ** be given much smaller limits designed to prevent a denial of service
  3302. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3303. ** interface to further control untrusted SQL. The size of the database
  3304. ** created by an untrusted script can be contained using the
  3305. ** [max_page_count] [PRAGMA].
  3306. **
  3307. ** New run-time limit categories may be added in future releases.
  3308. */
  3309. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
  3310. /*
  3311. ** CAPI3REF: Run-Time Limit Categories
  3312. ** KEYWORDS: {limit category} {*limit categories}
  3313. **
  3314. ** These constants define various performance limits
  3315. ** that can be lowered at run-time using [sqlite3_limit()].
  3316. ** The synopsis of the meanings of the various limits is shown below.
  3317. ** Additional information is available at [limits | Limits in SQLite].
  3318. **
  3319. ** <dl>
  3320. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3321. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3322. **
  3323. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3324. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3325. **
  3326. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3327. ** <dd>The maximum number of columns in a table definition or in the
  3328. ** result set of a [SELECT] or the maximum number of columns in an index
  3329. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3330. **
  3331. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3332. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3333. **
  3334. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3335. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3336. **
  3337. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3338. ** <dd>The maximum number of instructions in a virtual machine program
  3339. ** used to implement an SQL statement. This limit is not currently
  3340. ** enforced, though that might be added in some future release of
  3341. ** SQLite.</dd>)^
  3342. **
  3343. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3344. ** <dd>The maximum number of arguments on a function.</dd>)^
  3345. **
  3346. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3347. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3348. **
  3349. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3350. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3351. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3352. ** [GLOB] operators.</dd>)^
  3353. **
  3354. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3355. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3356. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3357. **
  3358. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3359. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3360. **
  3361. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3362. ** <dd>The maximum number of auxiliary worker threads that a single
  3363. ** [prepared statement] may start.</dd>)^
  3364. ** </dl>
  3365. */
  3366. #define SQLITE_LIMIT_LENGTH 0
  3367. #define SQLITE_LIMIT_SQL_LENGTH 1
  3368. #define SQLITE_LIMIT_COLUMN 2
  3369. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3370. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3371. #define SQLITE_LIMIT_VDBE_OP 5
  3372. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3373. #define SQLITE_LIMIT_ATTACHED 7
  3374. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3375. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3376. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3377. #define SQLITE_LIMIT_WORKER_THREADS 11
  3378. /*
  3379. ** CAPI3REF: Compiling An SQL Statement
  3380. ** KEYWORDS: {SQL statement compiler}
  3381. ** METHOD: sqlite3
  3382. ** CONSTRUCTOR: sqlite3_stmt
  3383. **
  3384. ** To execute an SQL query, it must first be compiled into a byte-code
  3385. ** program using one of these routines.
  3386. **
  3387. ** The first argument, "db", is a [database connection] obtained from a
  3388. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3389. ** [sqlite3_open16()]. The database connection must not have been closed.
  3390. **
  3391. ** The second argument, "zSql", is the statement to be compiled, encoded
  3392. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3393. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3394. ** use UTF-16.
  3395. **
  3396. ** ^If the nByte argument is negative, then zSql is read up to the
  3397. ** first zero terminator. ^If nByte is positive, then it is the
  3398. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  3399. ** statement is generated.
  3400. ** If the caller knows that the supplied string is nul-terminated, then
  3401. ** there is a small performance advantage to passing an nByte parameter that
  3402. ** is the number of bytes in the input string <i>including</i>
  3403. ** the nul-terminator.
  3404. **
  3405. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3406. ** past the end of the first SQL statement in zSql. These routines only
  3407. ** compile the first statement in zSql, so *pzTail is left pointing to
  3408. ** what remains uncompiled.
  3409. **
  3410. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3411. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3412. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3413. ** string or a comment) then *ppStmt is set to NULL.
  3414. ** The calling procedure is responsible for deleting the compiled
  3415. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3416. ** ppStmt may not be NULL.
  3417. **
  3418. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3419. ** otherwise an [error code] is returned.
  3420. **
  3421. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3422. ** recommended for all new programs. The two older interfaces are retained
  3423. ** for backwards compatibility, but their use is discouraged.
  3424. ** ^In the "v2" interfaces, the prepared statement
  3425. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3426. ** original SQL text. This causes the [sqlite3_step()] interface to
  3427. ** behave differently in three ways:
  3428. **
  3429. ** <ol>
  3430. ** <li>
  3431. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3432. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3433. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3434. ** retries will occur before sqlite3_step() gives up and returns an error.
  3435. ** </li>
  3436. **
  3437. ** <li>
  3438. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3439. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3440. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3441. ** and the application would have to make a second call to [sqlite3_reset()]
  3442. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3443. ** interfaces, the underlying reason for the error is returned immediately.
  3444. ** </li>
  3445. **
  3446. ** <li>
  3447. ** ^If the specific value bound to [parameter | host parameter] in the
  3448. ** WHERE clause might influence the choice of query plan for a statement,
  3449. ** then the statement will be automatically recompiled, as if there had been
  3450. ** a schema change, on the first [sqlite3_step()] call following any change
  3451. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3452. ** ^The specific value of WHERE-clause [parameter] might influence the
  3453. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3454. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3455. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3456. ** </li>
  3457. ** </ol>
  3458. */
  3459. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  3460. sqlite3 *db, /* Database handle */
  3461. const char *zSql, /* SQL statement, UTF-8 encoded */
  3462. int nByte, /* Maximum length of zSql in bytes. */
  3463. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3464. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3465. );
  3466. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  3467. sqlite3 *db, /* Database handle */
  3468. const char *zSql, /* SQL statement, UTF-8 encoded */
  3469. int nByte, /* Maximum length of zSql in bytes. */
  3470. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3471. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3472. );
  3473. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  3474. sqlite3 *db, /* Database handle */
  3475. const void *zSql, /* SQL statement, UTF-16 encoded */
  3476. int nByte, /* Maximum length of zSql in bytes. */
  3477. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3478. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3479. );
  3480. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  3481. sqlite3 *db, /* Database handle */
  3482. const void *zSql, /* SQL statement, UTF-16 encoded */
  3483. int nByte, /* Maximum length of zSql in bytes. */
  3484. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3485. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3486. );
  3487. /*
  3488. ** CAPI3REF: Retrieving Statement SQL
  3489. ** METHOD: sqlite3_stmt
  3490. **
  3491. ** ^This interface can be used to retrieve a saved copy of the original
  3492. ** SQL text used to create a [prepared statement] if that statement was
  3493. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3494. */
  3495. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
  3496. /*
  3497. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3498. ** METHOD: sqlite3_stmt
  3499. **
  3500. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3501. ** and only if the [prepared statement] X makes no direct changes to
  3502. ** the content of the database file.
  3503. **
  3504. ** Note that [application-defined SQL functions] or
  3505. ** [virtual tables] might change the database indirectly as a side effect.
  3506. ** ^(For example, if an application defines a function "eval()" that
  3507. ** calls [sqlite3_exec()], then the following SQL statement would
  3508. ** change the database file through side-effects:
  3509. **
  3510. ** <blockquote><pre>
  3511. ** SELECT eval('DELETE FROM t1') FROM t2;
  3512. ** </pre></blockquote>
  3513. **
  3514. ** But because the [SELECT] statement does not change the database file
  3515. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3516. **
  3517. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3518. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3519. ** since the statements themselves do not actually modify the database but
  3520. ** rather they control the timing of when other statements modify the
  3521. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3522. ** sqlite3_stmt_readonly() to return true since, while those statements
  3523. ** change the configuration of a database connection, they do not make
  3524. ** changes to the content of the database files on disk.
  3525. */
  3526. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3527. /*
  3528. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3529. ** METHOD: sqlite3_stmt
  3530. **
  3531. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3532. ** [prepared statement] S has been stepped at least once using
  3533. ** [sqlite3_step(S)] but has neither run to completion (returned
  3534. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  3535. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3536. ** interface returns false if S is a NULL pointer. If S is not a
  3537. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3538. ** object, then the behavior is undefined and probably undesirable.
  3539. **
  3540. ** This interface can be used in combination [sqlite3_next_stmt()]
  3541. ** to locate all prepared statements associated with a database
  3542. ** connection that are in need of being reset. This can be used,
  3543. ** for example, in diagnostic routines to search for prepared
  3544. ** statements that are holding a transaction open.
  3545. */
  3546. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
  3547. /*
  3548. ** CAPI3REF: Dynamically Typed Value Object
  3549. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3550. **
  3551. ** SQLite uses the sqlite3_value object to represent all values
  3552. ** that can be stored in a database table. SQLite uses dynamic typing
  3553. ** for the values it stores. ^Values stored in sqlite3_value objects
  3554. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3555. **
  3556. ** An sqlite3_value object may be either "protected" or "unprotected".
  3557. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3558. ** will accept either a protected or an unprotected sqlite3_value.
  3559. ** Every interface that accepts sqlite3_value arguments specifies
  3560. ** whether or not it requires a protected sqlite3_value. The
  3561. ** [sqlite3_value_dup()] interface can be used to construct a new
  3562. ** protected sqlite3_value from an unprotected sqlite3_value.
  3563. **
  3564. ** The terms "protected" and "unprotected" refer to whether or not
  3565. ** a mutex is held. An internal mutex is held for a protected
  3566. ** sqlite3_value object but no mutex is held for an unprotected
  3567. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3568. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3569. ** or if SQLite is run in one of reduced mutex modes
  3570. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3571. ** then there is no distinction between protected and unprotected
  3572. ** sqlite3_value objects and they can be used interchangeably. However,
  3573. ** for maximum code portability it is recommended that applications
  3574. ** still make the distinction between protected and unprotected
  3575. ** sqlite3_value objects even when not strictly required.
  3576. **
  3577. ** ^The sqlite3_value objects that are passed as parameters into the
  3578. ** implementation of [application-defined SQL functions] are protected.
  3579. ** ^The sqlite3_value object returned by
  3580. ** [sqlite3_column_value()] is unprotected.
  3581. ** Unprotected sqlite3_value objects may only be used with
  3582. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3583. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3584. ** interfaces require protected sqlite3_value objects.
  3585. */
  3586. typedef struct Mem sqlite3_value;
  3587. /*
  3588. ** CAPI3REF: SQL Function Context Object
  3589. **
  3590. ** The context in which an SQL function executes is stored in an
  3591. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3592. ** is always first parameter to [application-defined SQL functions].
  3593. ** The application-defined SQL function implementation will pass this
  3594. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3595. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3596. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3597. ** and/or [sqlite3_set_auxdata()].
  3598. */
  3599. typedef struct sqlite3_context sqlite3_context;
  3600. /*
  3601. ** CAPI3REF: Binding Values To Prepared Statements
  3602. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3603. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3604. ** METHOD: sqlite3_stmt
  3605. **
  3606. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3607. ** literals may be replaced by a [parameter] that matches one of following
  3608. ** templates:
  3609. **
  3610. ** <ul>
  3611. ** <li> ?
  3612. ** <li> ?NNN
  3613. ** <li> :VVV
  3614. ** <li> @VVV
  3615. ** <li> $VVV
  3616. ** </ul>
  3617. **
  3618. ** In the templates above, NNN represents an integer literal,
  3619. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3620. ** parameters (also called "host parameter names" or "SQL parameters")
  3621. ** can be set using the sqlite3_bind_*() routines defined here.
  3622. **
  3623. ** ^The first argument to the sqlite3_bind_*() routines is always
  3624. ** a pointer to the [sqlite3_stmt] object returned from
  3625. ** [sqlite3_prepare_v2()] or its variants.
  3626. **
  3627. ** ^The second argument is the index of the SQL parameter to be set.
  3628. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3629. ** SQL parameter is used more than once, second and subsequent
  3630. ** occurrences have the same index as the first occurrence.
  3631. ** ^The index for named parameters can be looked up using the
  3632. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3633. ** for "?NNN" parameters is the value of NNN.
  3634. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3635. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3636. **
  3637. ** ^The third argument is the value to bind to the parameter.
  3638. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3639. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3640. ** is ignored and the end result is the same as sqlite3_bind_null().
  3641. **
  3642. ** ^(In those routines that have a fourth argument, its value is the
  3643. ** number of bytes in the parameter. To be clear: the value is the
  3644. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3645. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3646. ** is negative, then the length of the string is
  3647. ** the number of bytes up to the first zero terminator.
  3648. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3649. ** the behavior is undefined.
  3650. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3651. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3652. ** that parameter must be the byte offset
  3653. ** where the NUL terminator would occur assuming the string were NUL
  3654. ** terminated. If any NUL characters occur at byte offsets less than
  3655. ** the value of the fourth parameter then the resulting string value will
  3656. ** contain embedded NULs. The result of expressions involving strings
  3657. ** with embedded NULs is undefined.
  3658. **
  3659. ** ^The fifth argument to the BLOB and string binding interfaces
  3660. ** is a destructor used to dispose of the BLOB or
  3661. ** string after SQLite has finished with it. ^The destructor is called
  3662. ** to dispose of the BLOB or string even if the call to bind API fails.
  3663. ** ^If the fifth argument is
  3664. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3665. ** information is in static, unmanaged space and does not need to be freed.
  3666. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3667. ** SQLite makes its own private copy of the data immediately, before
  3668. ** the sqlite3_bind_*() routine returns.
  3669. **
  3670. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3671. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3672. ** to specify the encoding of the text in the third parameter. If
  3673. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3674. ** allowed values shown above, or if the text encoding is different
  3675. ** from the encoding specified by the sixth parameter, then the behavior
  3676. ** is undefined.
  3677. **
  3678. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3679. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3680. ** (just an integer to hold its size) while it is being processed.
  3681. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3682. ** content is later written using
  3683. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3684. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3685. **
  3686. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3687. ** for the [prepared statement] or with a prepared statement for which
  3688. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3689. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3690. ** routine is passed a [prepared statement] that has been finalized, the
  3691. ** result is undefined and probably harmful.
  3692. **
  3693. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3694. ** ^Unbound parameters are interpreted as NULL.
  3695. **
  3696. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3697. ** [error code] if anything goes wrong.
  3698. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  3699. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  3700. ** [SQLITE_MAX_LENGTH].
  3701. ** ^[SQLITE_RANGE] is returned if the parameter
  3702. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3703. **
  3704. ** See also: [sqlite3_bind_parameter_count()],
  3705. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3706. */
  3707. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3708. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  3709. void(*)(void*));
  3710. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
  3711. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
  3712. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3713. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
  3714. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  3715. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3716. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  3717. void(*)(void*), unsigned char encoding);
  3718. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3719. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3720. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  3721. /*
  3722. ** CAPI3REF: Number Of SQL Parameters
  3723. ** METHOD: sqlite3_stmt
  3724. **
  3725. ** ^This routine can be used to find the number of [SQL parameters]
  3726. ** in a [prepared statement]. SQL parameters are tokens of the
  3727. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3728. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3729. ** to the parameters at a later time.
  3730. **
  3731. ** ^(This routine actually returns the index of the largest (rightmost)
  3732. ** parameter. For all forms except ?NNN, this will correspond to the
  3733. ** number of unique parameters. If parameters of the ?NNN form are used,
  3734. ** there may be gaps in the list.)^
  3735. **
  3736. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3737. ** [sqlite3_bind_parameter_name()], and
  3738. ** [sqlite3_bind_parameter_index()].
  3739. */
  3740. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
  3741. /*
  3742. ** CAPI3REF: Name Of A Host Parameter
  3743. ** METHOD: sqlite3_stmt
  3744. **
  3745. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3746. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3747. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3748. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3749. ** respectively.
  3750. ** In other words, the initial ":" or "$" or "@" or "?"
  3751. ** is included as part of the name.)^
  3752. ** ^Parameters of the form "?" without a following integer have no name
  3753. ** and are referred to as "nameless" or "anonymous parameters".
  3754. **
  3755. ** ^The first host parameter has an index of 1, not 0.
  3756. **
  3757. ** ^If the value N is out of range or if the N-th parameter is
  3758. ** nameless, then NULL is returned. ^The returned string is
  3759. ** always in UTF-8 encoding even if the named parameter was
  3760. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3761. ** [sqlite3_prepare16_v2()].
  3762. **
  3763. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3764. ** [sqlite3_bind_parameter_count()], and
  3765. ** [sqlite3_bind_parameter_index()].
  3766. */
  3767. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3768. /*
  3769. ** CAPI3REF: Index Of A Parameter With A Given Name
  3770. ** METHOD: sqlite3_stmt
  3771. **
  3772. ** ^Return the index of an SQL parameter given its name. ^The
  3773. ** index value returned is suitable for use as the second
  3774. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3775. ** is returned if no matching parameter is found. ^The parameter
  3776. ** name must be given in UTF-8 even if the original statement
  3777. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3778. **
  3779. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3780. ** [sqlite3_bind_parameter_count()], and
  3781. ** [sqlite3_bind_parameter_name()].
  3782. */
  3783. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3784. /*
  3785. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3786. ** METHOD: sqlite3_stmt
  3787. **
  3788. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3789. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3790. ** ^Use this routine to reset all host parameters to NULL.
  3791. */
  3792. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
  3793. /*
  3794. ** CAPI3REF: Number Of Columns In A Result Set
  3795. ** METHOD: sqlite3_stmt
  3796. **
  3797. ** ^Return the number of columns in the result set returned by the
  3798. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3799. ** statement that does not return data (for example an [UPDATE]).
  3800. **
  3801. ** See also: [sqlite3_data_count()]
  3802. */
  3803. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
  3804. /*
  3805. ** CAPI3REF: Column Names In A Result Set
  3806. ** METHOD: sqlite3_stmt
  3807. **
  3808. ** ^These routines return the name assigned to a particular column
  3809. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3810. ** interface returns a pointer to a zero-terminated UTF-8 string
  3811. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3812. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3813. ** that implements the [SELECT] statement. ^The second parameter is the
  3814. ** column number. ^The leftmost column is number 0.
  3815. **
  3816. ** ^The returned string pointer is valid until either the [prepared statement]
  3817. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3818. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3819. ** or until the next call to
  3820. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3821. **
  3822. ** ^If sqlite3_malloc() fails during the processing of either routine
  3823. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3824. ** NULL pointer is returned.
  3825. **
  3826. ** ^The name of a result column is the value of the "AS" clause for
  3827. ** that column, if there is an AS clause. If there is no AS clause
  3828. ** then the name of the column is unspecified and may change from
  3829. ** one release of SQLite to the next.
  3830. */
  3831. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
  3832. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
  3833. /*
  3834. ** CAPI3REF: Source Of Data In A Query Result
  3835. ** METHOD: sqlite3_stmt
  3836. **
  3837. ** ^These routines provide a means to determine the database, table, and
  3838. ** table column that is the origin of a particular result column in
  3839. ** [SELECT] statement.
  3840. ** ^The name of the database or table or column can be returned as
  3841. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3842. ** the database name, the _table_ routines return the table name, and
  3843. ** the origin_ routines return the column name.
  3844. ** ^The returned string is valid until the [prepared statement] is destroyed
  3845. ** using [sqlite3_finalize()] or until the statement is automatically
  3846. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3847. ** or until the same information is requested
  3848. ** again in a different encoding.
  3849. **
  3850. ** ^The names returned are the original un-aliased names of the
  3851. ** database, table, and column.
  3852. **
  3853. ** ^The first argument to these interfaces is a [prepared statement].
  3854. ** ^These functions return information about the Nth result column returned by
  3855. ** the statement, where N is the second function argument.
  3856. ** ^The left-most column is column 0 for these routines.
  3857. **
  3858. ** ^If the Nth column returned by the statement is an expression or
  3859. ** subquery and is not a column value, then all of these functions return
  3860. ** NULL. ^These routine might also return NULL if a memory allocation error
  3861. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3862. ** or column that query result column was extracted from.
  3863. **
  3864. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3865. ** UTF-16 encoded strings and the other functions return UTF-8.
  3866. **
  3867. ** ^These APIs are only available if the library was compiled with the
  3868. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3869. **
  3870. ** If two or more threads call one or more of these routines against the same
  3871. ** prepared statement and column at the same time then the results are
  3872. ** undefined.
  3873. **
  3874. ** If two or more threads call one or more
  3875. ** [sqlite3_column_database_name | column metadata interfaces]
  3876. ** for the same [prepared statement] and result column
  3877. ** at the same time then the results are undefined.
  3878. */
  3879. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
  3880. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
  3881. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
  3882. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
  3883. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
  3884. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3885. /*
  3886. ** CAPI3REF: Declared Datatype Of A Query Result
  3887. ** METHOD: sqlite3_stmt
  3888. **
  3889. ** ^(The first parameter is a [prepared statement].
  3890. ** If this statement is a [SELECT] statement and the Nth column of the
  3891. ** returned result set of that [SELECT] is a table column (not an
  3892. ** expression or subquery) then the declared type of the table
  3893. ** column is returned.)^ ^If the Nth column of the result set is an
  3894. ** expression or subquery, then a NULL pointer is returned.
  3895. ** ^The returned string is always UTF-8 encoded.
  3896. **
  3897. ** ^(For example, given the database schema:
  3898. **
  3899. ** CREATE TABLE t1(c1 VARIANT);
  3900. **
  3901. ** and the following statement to be compiled:
  3902. **
  3903. ** SELECT c1 + 1, c1 FROM t1;
  3904. **
  3905. ** this routine would return the string "VARIANT" for the second result
  3906. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3907. **
  3908. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3909. ** is declared to contain a particular type does not mean that the
  3910. ** data stored in that column is of the declared type. SQLite is
  3911. ** strongly typed, but the typing is dynamic not static. ^Type
  3912. ** is associated with individual values, not with the containers
  3913. ** used to hold those values.
  3914. */
  3915. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
  3916. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
  3917. /*
  3918. ** CAPI3REF: Evaluate An SQL Statement
  3919. ** METHOD: sqlite3_stmt
  3920. **
  3921. ** After a [prepared statement] has been prepared using either
  3922. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3923. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3924. ** must be called one or more times to evaluate the statement.
  3925. **
  3926. ** The details of the behavior of the sqlite3_step() interface depend
  3927. ** on whether the statement was prepared using the newer "v2" interface
  3928. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3929. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3930. ** new "v2" interface is recommended for new applications but the legacy
  3931. ** interface will continue to be supported.
  3932. **
  3933. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3934. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3935. ** ^With the "v2" interface, any of the other [result codes] or
  3936. ** [extended result codes] might be returned as well.
  3937. **
  3938. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3939. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3940. ** or occurs outside of an explicit transaction, then you can retry the
  3941. ** statement. If the statement is not a [COMMIT] and occurs within an
  3942. ** explicit transaction then you should rollback the transaction before
  3943. ** continuing.
  3944. **
  3945. ** ^[SQLITE_DONE] means that the statement has finished executing
  3946. ** successfully. sqlite3_step() should not be called again on this virtual
  3947. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3948. ** machine back to its initial state.
  3949. **
  3950. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3951. ** is returned each time a new row of data is ready for processing by the
  3952. ** caller. The values may be accessed using the [column access functions].
  3953. ** sqlite3_step() is called again to retrieve the next row of data.
  3954. **
  3955. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3956. ** violation) has occurred. sqlite3_step() should not be called again on
  3957. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3958. ** ^With the legacy interface, a more specific error code (for example,
  3959. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3960. ** can be obtained by calling [sqlite3_reset()] on the
  3961. ** [prepared statement]. ^In the "v2" interface,
  3962. ** the more specific error code is returned directly by sqlite3_step().
  3963. **
  3964. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3965. ** Perhaps it was called on a [prepared statement] that has
  3966. ** already been [sqlite3_finalize | finalized] or on one that had
  3967. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3968. ** be the case that the same database connection is being used by two or
  3969. ** more threads at the same moment in time.
  3970. **
  3971. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3972. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3973. ** other than [SQLITE_ROW] before any subsequent invocation of
  3974. ** sqlite3_step(). Failure to reset the prepared statement using
  3975. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3976. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3977. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3978. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3979. ** break because any application that ever receives an SQLITE_MISUSE error
  3980. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3981. ** can be used to restore the legacy behavior.
  3982. **
  3983. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3984. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3985. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3986. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3987. ** specific [error codes] that better describes the error.
  3988. ** We admit that this is a goofy design. The problem has been fixed
  3989. ** with the "v2" interface. If you prepare all of your SQL statements
  3990. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3991. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3992. ** then the more specific [error codes] are returned directly
  3993. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3994. */
  3995. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
  3996. /*
  3997. ** CAPI3REF: Number of columns in a result set
  3998. ** METHOD: sqlite3_stmt
  3999. **
  4000. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  4001. ** current row of the result set of [prepared statement] P.
  4002. ** ^If prepared statement P does not have results ready to return
  4003. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  4004. ** interfaces) then sqlite3_data_count(P) returns 0.
  4005. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  4006. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  4007. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  4008. ** will return non-zero if previous call to [sqlite3_step](P) returned
  4009. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  4010. ** where it always returns zero since each step of that multi-step
  4011. ** pragma returns 0 columns of data.
  4012. **
  4013. ** See also: [sqlite3_column_count()]
  4014. */
  4015. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
  4016. /*
  4017. ** CAPI3REF: Fundamental Datatypes
  4018. ** KEYWORDS: SQLITE_TEXT
  4019. **
  4020. ** ^(Every value in SQLite has one of five fundamental datatypes:
  4021. **
  4022. ** <ul>
  4023. ** <li> 64-bit signed integer
  4024. ** <li> 64-bit IEEE floating point number
  4025. ** <li> string
  4026. ** <li> BLOB
  4027. ** <li> NULL
  4028. ** </ul>)^
  4029. **
  4030. ** These constants are codes for each of those types.
  4031. **
  4032. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4033. ** for a completely different meaning. Software that links against both
  4034. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4035. ** SQLITE_TEXT.
  4036. */
  4037. #define SQLITE_INTEGER 1
  4038. #define SQLITE_FLOAT 2
  4039. #define SQLITE_BLOB 4
  4040. #define SQLITE_NULL 5
  4041. #ifdef SQLITE_TEXT
  4042. # undef SQLITE_TEXT
  4043. #else
  4044. # define SQLITE_TEXT 3
  4045. #endif
  4046. #define SQLITE3_TEXT 3
  4047. /*
  4048. ** CAPI3REF: Result Values From A Query
  4049. ** KEYWORDS: {column access functions}
  4050. ** METHOD: sqlite3_stmt
  4051. **
  4052. ** ^These routines return information about a single column of the current
  4053. ** result row of a query. ^In every case the first argument is a pointer
  4054. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4055. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4056. ** and the second argument is the index of the column for which information
  4057. ** should be returned. ^The leftmost column of the result set has the index 0.
  4058. ** ^The number of columns in the result can be determined using
  4059. ** [sqlite3_column_count()].
  4060. **
  4061. ** If the SQL statement does not currently point to a valid row, or if the
  4062. ** column index is out of range, the result is undefined.
  4063. ** These routines may only be called when the most recent call to
  4064. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4065. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4066. ** If any of these routines are called after [sqlite3_reset()] or
  4067. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4068. ** something other than [SQLITE_ROW], the results are undefined.
  4069. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4070. ** are called from a different thread while any of these routines
  4071. ** are pending, then the results are undefined.
  4072. **
  4073. ** ^The sqlite3_column_type() routine returns the
  4074. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4075. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4076. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4077. ** returned by sqlite3_column_type() is only meaningful if no type
  4078. ** conversions have occurred as described below. After a type conversion,
  4079. ** the value returned by sqlite3_column_type() is undefined. Future
  4080. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4081. ** following a type conversion.
  4082. **
  4083. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4084. ** routine returns the number of bytes in that BLOB or string.
  4085. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4086. ** the string to UTF-8 and then returns the number of bytes.
  4087. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4088. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4089. ** the number of bytes in that string.
  4090. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4091. **
  4092. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4093. ** routine returns the number of bytes in that BLOB or string.
  4094. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4095. ** the string to UTF-16 and then returns the number of bytes.
  4096. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4097. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4098. ** the number of bytes in that string.
  4099. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4100. **
  4101. ** ^The values returned by [sqlite3_column_bytes()] and
  4102. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4103. ** of the string. ^For clarity: the values returned by
  4104. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4105. ** bytes in the string, not the number of characters.
  4106. **
  4107. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4108. ** even empty strings, are always zero-terminated. ^The return
  4109. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4110. **
  4111. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  4112. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  4113. ** an unprotected sqlite3_value object may only be used safely with
  4114. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  4115. ** If the [unprotected sqlite3_value] object returned by
  4116. ** [sqlite3_column_value()] is used in any other way, including calls
  4117. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4118. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  4119. **
  4120. ** These routines attempt to convert the value where appropriate. ^For
  4121. ** example, if the internal representation is FLOAT and a text result
  4122. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4123. ** conversion automatically. ^(The following table details the conversions
  4124. ** that are applied:
  4125. **
  4126. ** <blockquote>
  4127. ** <table border="1">
  4128. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4129. **
  4130. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4131. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4132. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  4133. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  4134. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4135. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4136. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4137. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  4138. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4139. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  4140. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  4141. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  4142. ** <tr><td> TEXT <td> BLOB <td> No change
  4143. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  4144. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  4145. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4146. ** </table>
  4147. ** </blockquote>)^
  4148. **
  4149. ** Note that when type conversions occur, pointers returned by prior
  4150. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4151. ** sqlite3_column_text16() may be invalidated.
  4152. ** Type conversions and pointer invalidations might occur
  4153. ** in the following cases:
  4154. **
  4155. ** <ul>
  4156. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4157. ** sqlite3_column_text16() is called. A zero-terminator might
  4158. ** need to be added to the string.</li>
  4159. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4160. ** sqlite3_column_text16() is called. The content must be converted
  4161. ** to UTF-16.</li>
  4162. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4163. ** sqlite3_column_text() is called. The content must be converted
  4164. ** to UTF-8.</li>
  4165. ** </ul>
  4166. **
  4167. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4168. ** not invalidate a prior pointer, though of course the content of the buffer
  4169. ** that the prior pointer references will have been modified. Other kinds
  4170. ** of conversion are done in place when it is possible, but sometimes they
  4171. ** are not possible and in those cases prior pointers are invalidated.
  4172. **
  4173. ** The safest policy is to invoke these routines
  4174. ** in one of the following ways:
  4175. **
  4176. ** <ul>
  4177. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4178. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4179. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4180. ** </ul>
  4181. **
  4182. ** In other words, you should call sqlite3_column_text(),
  4183. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4184. ** into the desired format, then invoke sqlite3_column_bytes() or
  4185. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4186. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4187. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4188. ** with calls to sqlite3_column_bytes().
  4189. **
  4190. ** ^The pointers returned are valid until a type conversion occurs as
  4191. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4192. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4193. ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
  4194. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4195. ** [sqlite3_free()].
  4196. **
  4197. ** ^(If a memory allocation error occurs during the evaluation of any
  4198. ** of these routines, a default value is returned. The default value
  4199. ** is either the integer 0, the floating point number 0.0, or a NULL
  4200. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4201. ** [SQLITE_NOMEM].)^
  4202. */
  4203. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4204. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4205. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4206. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
  4207. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
  4208. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4209. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
  4210. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4211. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
  4212. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
  4213. /*
  4214. ** CAPI3REF: Destroy A Prepared Statement Object
  4215. ** DESTRUCTOR: sqlite3_stmt
  4216. **
  4217. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4218. ** ^If the most recent evaluation of the statement encountered no errors
  4219. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4220. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4221. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4222. ** [extended error code].
  4223. **
  4224. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4225. ** the life cycle of [prepared statement] S:
  4226. ** before statement S is ever evaluated, after
  4227. ** one or more calls to [sqlite3_reset()], or after any call
  4228. ** to [sqlite3_step()] regardless of whether or not the statement has
  4229. ** completed execution.
  4230. **
  4231. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4232. **
  4233. ** The application must finalize every [prepared statement] in order to avoid
  4234. ** resource leaks. It is a grievous error for the application to try to use
  4235. ** a prepared statement after it has been finalized. Any use of a prepared
  4236. ** statement after it has been finalized can result in undefined and
  4237. ** undesirable behavior such as segfaults and heap corruption.
  4238. */
  4239. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
  4240. /*
  4241. ** CAPI3REF: Reset A Prepared Statement Object
  4242. ** METHOD: sqlite3_stmt
  4243. **
  4244. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4245. ** object back to its initial state, ready to be re-executed.
  4246. ** ^Any SQL statement variables that had values bound to them using
  4247. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4248. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4249. **
  4250. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4251. ** back to the beginning of its program.
  4252. **
  4253. ** ^If the most recent call to [sqlite3_step(S)] for the
  4254. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4255. ** or if [sqlite3_step(S)] has never before been called on S,
  4256. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4257. **
  4258. ** ^If the most recent call to [sqlite3_step(S)] for the
  4259. ** [prepared statement] S indicated an error, then
  4260. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4261. **
  4262. ** ^The [sqlite3_reset(S)] interface does not change the values
  4263. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4264. */
  4265. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
  4266. /*
  4267. ** CAPI3REF: Create Or Redefine SQL Functions
  4268. ** KEYWORDS: {function creation routines}
  4269. ** KEYWORDS: {application-defined SQL function}
  4270. ** KEYWORDS: {application-defined SQL functions}
  4271. ** METHOD: sqlite3
  4272. **
  4273. ** ^These functions (collectively known as "function creation routines")
  4274. ** are used to add SQL functions or aggregates or to redefine the behavior
  4275. ** of existing SQL functions or aggregates. The only differences between
  4276. ** these routines are the text encoding expected for
  4277. ** the second parameter (the name of the function being created)
  4278. ** and the presence or absence of a destructor callback for
  4279. ** the application data pointer.
  4280. **
  4281. ** ^The first parameter is the [database connection] to which the SQL
  4282. ** function is to be added. ^If an application uses more than one database
  4283. ** connection then application-defined SQL functions must be added
  4284. ** to each database connection separately.
  4285. **
  4286. ** ^The second parameter is the name of the SQL function to be created or
  4287. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4288. ** representation, exclusive of the zero-terminator. ^Note that the name
  4289. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4290. ** ^Any attempt to create a function with a longer name
  4291. ** will result in [SQLITE_MISUSE] being returned.
  4292. **
  4293. ** ^The third parameter (nArg)
  4294. ** is the number of arguments that the SQL function or
  4295. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4296. ** aggregate may take any number of arguments between 0 and the limit
  4297. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4298. ** parameter is less than -1 or greater than 127 then the behavior is
  4299. ** undefined.
  4300. **
  4301. ** ^The fourth parameter, eTextRep, specifies what
  4302. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4303. ** its parameters. The application should set this parameter to
  4304. ** [SQLITE_UTF16LE] if the function implementation invokes
  4305. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4306. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4307. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4308. ** otherwise. ^The same SQL function may be registered multiple times using
  4309. ** different preferred text encodings, with different implementations for
  4310. ** each encoding.
  4311. ** ^When multiple implementations of the same function are available, SQLite
  4312. ** will pick the one that involves the least amount of data conversion.
  4313. **
  4314. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4315. ** to signal that the function will always return the same result given
  4316. ** the same inputs within a single SQL statement. Most SQL functions are
  4317. ** deterministic. The built-in [random()] SQL function is an example of a
  4318. ** function that is not deterministic. The SQLite query planner is able to
  4319. ** perform additional optimizations on deterministic functions, so use
  4320. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4321. **
  4322. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4323. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4324. **
  4325. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4326. ** pointers to C-language functions that implement the SQL function or
  4327. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4328. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4329. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4330. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4331. ** SQL function or aggregate, pass NULL pointers for all three function
  4332. ** callbacks.
  4333. **
  4334. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4335. ** then it is destructor for the application data pointer.
  4336. ** The destructor is invoked when the function is deleted, either by being
  4337. ** overloaded or when the database connection closes.)^
  4338. ** ^The destructor is also invoked if the call to
  4339. ** sqlite3_create_function_v2() fails.
  4340. ** ^When the destructor callback of the tenth parameter is invoked, it
  4341. ** is passed a single argument which is a copy of the application data
  4342. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4343. **
  4344. ** ^It is permitted to register multiple implementations of the same
  4345. ** functions with the same name but with either differing numbers of
  4346. ** arguments or differing preferred text encodings. ^SQLite will use
  4347. ** the implementation that most closely matches the way in which the
  4348. ** SQL function is used. ^A function implementation with a non-negative
  4349. ** nArg parameter is a better match than a function implementation with
  4350. ** a negative nArg. ^A function where the preferred text encoding
  4351. ** matches the database encoding is a better
  4352. ** match than a function where the encoding is different.
  4353. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4354. ** is a closer match than a function where the encoding difference is
  4355. ** between UTF8 and UTF16.
  4356. **
  4357. ** ^Built-in functions may be overloaded by new application-defined functions.
  4358. **
  4359. ** ^An application-defined function is permitted to call other
  4360. ** SQLite interfaces. However, such calls must not
  4361. ** close the database connection nor finalize or reset the prepared
  4362. ** statement in which the function is running.
  4363. */
  4364. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  4365. sqlite3 *db,
  4366. const char *zFunctionName,
  4367. int nArg,
  4368. int eTextRep,
  4369. void *pApp,
  4370. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4371. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4372. void (*xFinal)(sqlite3_context*)
  4373. );
  4374. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  4375. sqlite3 *db,
  4376. const void *zFunctionName,
  4377. int nArg,
  4378. int eTextRep,
  4379. void *pApp,
  4380. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4381. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4382. void (*xFinal)(sqlite3_context*)
  4383. );
  4384. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  4385. sqlite3 *db,
  4386. const char *zFunctionName,
  4387. int nArg,
  4388. int eTextRep,
  4389. void *pApp,
  4390. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4391. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4392. void (*xFinal)(sqlite3_context*),
  4393. void(*xDestroy)(void*)
  4394. );
  4395. /*
  4396. ** CAPI3REF: Text Encodings
  4397. **
  4398. ** These constant define integer codes that represent the various
  4399. ** text encodings supported by SQLite.
  4400. */
  4401. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  4402. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  4403. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  4404. #define SQLITE_UTF16 4 /* Use native byte order */
  4405. #define SQLITE_ANY 5 /* Deprecated */
  4406. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4407. /*
  4408. ** CAPI3REF: Function Flags
  4409. **
  4410. ** These constants may be ORed together with the
  4411. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4412. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4413. ** [sqlite3_create_function_v2()].
  4414. */
  4415. #define SQLITE_DETERMINISTIC 0x800
  4416. /*
  4417. ** CAPI3REF: Deprecated Functions
  4418. ** DEPRECATED
  4419. **
  4420. ** These functions are [deprecated]. In order to maintain
  4421. ** backwards compatibility with older code, these functions continue
  4422. ** to be supported. However, new applications should avoid
  4423. ** the use of these functions. To encourage programmers to avoid
  4424. ** these functions, we will not explain what they do.
  4425. */
  4426. #ifndef SQLITE_OMIT_DEPRECATED
  4427. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
  4428. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
  4429. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4430. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
  4431. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
  4432. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4433. void*,sqlite3_int64);
  4434. #endif
  4435. /*
  4436. ** CAPI3REF: Obtaining SQL Values
  4437. ** METHOD: sqlite3_value
  4438. **
  4439. ** The C-language implementation of SQL functions and aggregates uses
  4440. ** this set of interface routines to access the parameter values on
  4441. ** the function or aggregate.
  4442. **
  4443. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4444. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4445. ** define callbacks that implement the SQL functions and aggregates.
  4446. ** The 3rd parameter to these callbacks is an array of pointers to
  4447. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4448. ** each parameter to the SQL function. These routines are used to
  4449. ** extract values from the [sqlite3_value] objects.
  4450. **
  4451. ** These routines work only with [protected sqlite3_value] objects.
  4452. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4453. ** object results in undefined behavior.
  4454. **
  4455. ** ^These routines work just like the corresponding [column access functions]
  4456. ** except that these routines take a single [protected sqlite3_value] object
  4457. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4458. **
  4459. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4460. ** in the native byte-order of the host machine. ^The
  4461. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4462. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4463. **
  4464. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4465. ** numeric affinity to the value. This means that an attempt is
  4466. ** made to convert the value to an integer or floating point. If
  4467. ** such a conversion is possible without loss of information (in other
  4468. ** words, if the value is a string that looks like a number)
  4469. ** then the conversion is performed. Otherwise no conversion occurs.
  4470. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4471. **
  4472. ** Please pay particular attention to the fact that the pointer returned
  4473. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4474. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4475. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4476. ** or [sqlite3_value_text16()].
  4477. **
  4478. ** These routines must be called from the same thread as
  4479. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4480. */
  4481. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
  4482. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
  4483. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
  4484. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
  4485. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
  4486. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
  4487. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
  4488. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
  4489. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
  4490. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
  4491. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
  4492. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
  4493. /*
  4494. ** CAPI3REF: Finding The Subtype Of SQL Values
  4495. ** METHOD: sqlite3_value
  4496. **
  4497. ** The sqlite3_value_subtype(V) function returns the subtype for
  4498. ** an [application-defined SQL function] argument V. The subtype
  4499. ** information can be used to pass a limited amount of context from
  4500. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  4501. ** routine to set the subtype for the return value of an SQL function.
  4502. **
  4503. ** SQLite makes no use of subtype itself. It merely passes the subtype
  4504. ** from the result of one [application-defined SQL function] into the
  4505. ** input of another.
  4506. */
  4507. SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value*);
  4508. /*
  4509. ** CAPI3REF: Copy And Free SQL Values
  4510. ** METHOD: sqlite3_value
  4511. **
  4512. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  4513. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  4514. ** is a [protected sqlite3_value] object even if the input is not.
  4515. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  4516. ** memory allocation fails.
  4517. **
  4518. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  4519. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  4520. ** then sqlite3_value_free(V) is a harmless no-op.
  4521. */
  4522. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value*);
  4523. SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value*);
  4524. /*
  4525. ** CAPI3REF: Obtain Aggregate Function Context
  4526. ** METHOD: sqlite3_context
  4527. **
  4528. ** Implementations of aggregate SQL functions use this
  4529. ** routine to allocate memory for storing their state.
  4530. **
  4531. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4532. ** for a particular aggregate function, SQLite
  4533. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4534. ** to the new memory. ^On second and subsequent calls to
  4535. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4536. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4537. ** called once for each invocation of the xStep callback and then one
  4538. ** last time when the xFinal callback is invoked. ^(When no rows match
  4539. ** an aggregate query, the xStep() callback of the aggregate function
  4540. ** implementation is never called and xFinal() is called exactly once.
  4541. ** In those cases, sqlite3_aggregate_context() might be called for the
  4542. ** first time from within xFinal().)^
  4543. **
  4544. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4545. ** when first called if N is less than or equal to zero or if a memory
  4546. ** allocate error occurs.
  4547. **
  4548. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4549. ** determined by the N parameter on first successful call. Changing the
  4550. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4551. ** the same aggregate function instance will not resize the memory
  4552. ** allocation.)^ Within the xFinal callback, it is customary to set
  4553. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4554. ** pointless memory allocations occur.
  4555. **
  4556. ** ^SQLite automatically frees the memory allocated by
  4557. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4558. **
  4559. ** The first parameter must be a copy of the
  4560. ** [sqlite3_context | SQL function context] that is the first parameter
  4561. ** to the xStep or xFinal callback routine that implements the aggregate
  4562. ** function.
  4563. **
  4564. ** This routine must be called from the same thread in which
  4565. ** the aggregate SQL function is running.
  4566. */
  4567. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4568. /*
  4569. ** CAPI3REF: User Data For Functions
  4570. ** METHOD: sqlite3_context
  4571. **
  4572. ** ^The sqlite3_user_data() interface returns a copy of
  4573. ** the pointer that was the pUserData parameter (the 5th parameter)
  4574. ** of the [sqlite3_create_function()]
  4575. ** and [sqlite3_create_function16()] routines that originally
  4576. ** registered the application defined function.
  4577. **
  4578. ** This routine must be called from the same thread in which
  4579. ** the application-defined function is running.
  4580. */
  4581. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
  4582. /*
  4583. ** CAPI3REF: Database Connection For Functions
  4584. ** METHOD: sqlite3_context
  4585. **
  4586. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4587. ** the pointer to the [database connection] (the 1st parameter)
  4588. ** of the [sqlite3_create_function()]
  4589. ** and [sqlite3_create_function16()] routines that originally
  4590. ** registered the application defined function.
  4591. */
  4592. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
  4593. /*
  4594. ** CAPI3REF: Function Auxiliary Data
  4595. ** METHOD: sqlite3_context
  4596. **
  4597. ** These functions may be used by (non-aggregate) SQL functions to
  4598. ** associate metadata with argument values. If the same value is passed to
  4599. ** multiple invocations of the same SQL function during query execution, under
  4600. ** some circumstances the associated metadata may be preserved. An example
  4601. ** of where this might be useful is in a regular-expression matching
  4602. ** function. The compiled version of the regular expression can be stored as
  4603. ** metadata associated with the pattern string.
  4604. ** Then as long as the pattern string remains the same,
  4605. ** the compiled regular expression can be reused on multiple
  4606. ** invocations of the same function.
  4607. **
  4608. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4609. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4610. ** value to the application-defined function. ^If there is no metadata
  4611. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4612. ** returns a NULL pointer.
  4613. **
  4614. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4615. ** argument of the application-defined function. ^Subsequent
  4616. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4617. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4618. ** NULL if the metadata has been discarded.
  4619. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4620. ** SQLite will invoke the destructor function X with parameter P exactly
  4621. ** once, when the metadata is discarded.
  4622. ** SQLite is free to discard the metadata at any time, including: <ul>
  4623. ** <li> when the corresponding function parameter changes, or
  4624. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4625. ** SQL statement, or
  4626. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4627. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4628. ** allocation error occurs. </ul>)^
  4629. **
  4630. ** Note the last bullet in particular. The destructor X in
  4631. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4632. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4633. ** should be called near the end of the function implementation and the
  4634. ** function implementation should not make any use of P after
  4635. ** sqlite3_set_auxdata() has been called.
  4636. **
  4637. ** ^(In practice, metadata is preserved between function calls for
  4638. ** function parameters that are compile-time constants, including literal
  4639. ** values and [parameters] and expressions composed from the same.)^
  4640. **
  4641. ** These routines must be called from the same thread in which
  4642. ** the SQL function is running.
  4643. */
  4644. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
  4645. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4646. /*
  4647. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4648. **
  4649. ** These are special values for the destructor that is passed in as the
  4650. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4651. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4652. ** and will never change. It does not need to be destroyed. ^The
  4653. ** SQLITE_TRANSIENT value means that the content will likely change in
  4654. ** the near future and that SQLite should make its own private copy of
  4655. ** the content before returning.
  4656. **
  4657. ** The typedef is necessary to work around problems in certain
  4658. ** C++ compilers.
  4659. */
  4660. typedef void (*sqlite3_destructor_type)(void*);
  4661. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4662. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4663. /*
  4664. ** CAPI3REF: Setting The Result Of An SQL Function
  4665. ** METHOD: sqlite3_context
  4666. **
  4667. ** These routines are used by the xFunc or xFinal callbacks that
  4668. ** implement SQL functions and aggregates. See
  4669. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4670. ** for additional information.
  4671. **
  4672. ** These functions work very much like the [parameter binding] family of
  4673. ** functions used to bind values to host parameters in prepared statements.
  4674. ** Refer to the [SQL parameter] documentation for additional information.
  4675. **
  4676. ** ^The sqlite3_result_blob() interface sets the result from
  4677. ** an application-defined function to be the BLOB whose content is pointed
  4678. ** to by the second parameter and which is N bytes long where N is the
  4679. ** third parameter.
  4680. **
  4681. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  4682. ** interfaces set the result of the application-defined function to be
  4683. ** a BLOB containing all zero bytes and N bytes in size.
  4684. **
  4685. ** ^The sqlite3_result_double() interface sets the result from
  4686. ** an application-defined function to be a floating point value specified
  4687. ** by its 2nd argument.
  4688. **
  4689. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4690. ** cause the implemented SQL function to throw an exception.
  4691. ** ^SQLite uses the string pointed to by the
  4692. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4693. ** as the text of an error message. ^SQLite interprets the error
  4694. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4695. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4696. ** byte order. ^If the third parameter to sqlite3_result_error()
  4697. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4698. ** message all text up through the first zero character.
  4699. ** ^If the third parameter to sqlite3_result_error() or
  4700. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4701. ** bytes (not characters) from the 2nd parameter as the error message.
  4702. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4703. ** routines make a private copy of the error message text before
  4704. ** they return. Hence, the calling function can deallocate or
  4705. ** modify the text after they return without harm.
  4706. ** ^The sqlite3_result_error_code() function changes the error code
  4707. ** returned by SQLite as a result of an error in a function. ^By default,
  4708. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4709. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4710. **
  4711. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4712. ** error indicating that a string or BLOB is too long to represent.
  4713. **
  4714. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4715. ** error indicating that a memory allocation failed.
  4716. **
  4717. ** ^The sqlite3_result_int() interface sets the return value
  4718. ** of the application-defined function to be the 32-bit signed integer
  4719. ** value given in the 2nd argument.
  4720. ** ^The sqlite3_result_int64() interface sets the return value
  4721. ** of the application-defined function to be the 64-bit signed integer
  4722. ** value given in the 2nd argument.
  4723. **
  4724. ** ^The sqlite3_result_null() interface sets the return value
  4725. ** of the application-defined function to be NULL.
  4726. **
  4727. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4728. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4729. ** set the return value of the application-defined function to be
  4730. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4731. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4732. ** ^The sqlite3_result_text64() interface sets the return value of an
  4733. ** application-defined function to be a text string in an encoding
  4734. ** specified by the fifth (and last) parameter, which must be one
  4735. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  4736. ** ^SQLite takes the text result from the application from
  4737. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4738. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4739. ** is negative, then SQLite takes result text from the 2nd parameter
  4740. ** through the first zero character.
  4741. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4742. ** is non-negative, then as many bytes (not characters) of the text
  4743. ** pointed to by the 2nd parameter are taken as the application-defined
  4744. ** function result. If the 3rd parameter is non-negative, then it
  4745. ** must be the byte offset into the string where the NUL terminator would
  4746. ** appear if the string where NUL terminated. If any NUL characters occur
  4747. ** in the string at a byte offset that is less than the value of the 3rd
  4748. ** parameter, then the resulting string will contain embedded NULs and the
  4749. ** result of expressions operating on strings with embedded NULs is undefined.
  4750. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4751. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4752. ** function as the destructor on the text or BLOB result when it has
  4753. ** finished using that result.
  4754. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4755. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4756. ** assumes that the text or BLOB result is in constant space and does not
  4757. ** copy the content of the parameter nor call a destructor on the content
  4758. ** when it has finished using that result.
  4759. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4760. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4761. ** then SQLite makes a copy of the result into space obtained from
  4762. ** from [sqlite3_malloc()] before it returns.
  4763. **
  4764. ** ^The sqlite3_result_value() interface sets the result of
  4765. ** the application-defined function to be a copy of the
  4766. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4767. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4768. ** so that the [sqlite3_value] specified in the parameter may change or
  4769. ** be deallocated after sqlite3_result_value() returns without harm.
  4770. ** ^A [protected sqlite3_value] object may always be used where an
  4771. ** [unprotected sqlite3_value] object is required, so either
  4772. ** kind of [sqlite3_value] object can be used with this interface.
  4773. **
  4774. ** If these routines are called from within the different thread
  4775. ** than the one containing the application-defined function that received
  4776. ** the [sqlite3_context] pointer, the results are undefined.
  4777. */
  4778. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4779. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
  4780. sqlite3_uint64,void(*)(void*));
  4781. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
  4782. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
  4783. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
  4784. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
  4785. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
  4786. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
  4787. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
  4788. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4789. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
  4790. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4791. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  4792. void(*)(void*), unsigned char encoding);
  4793. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4794. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4795. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4796. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4797. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
  4798. SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  4799. /*
  4800. ** CAPI3REF: Setting The Subtype Of An SQL Function
  4801. ** METHOD: sqlite3_context
  4802. **
  4803. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  4804. ** the result from the [application-defined SQL function] with
  4805. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  4806. ** of the subtype T are preserved in current versions of SQLite;
  4807. ** higher order bits are discarded.
  4808. ** The number of subtype bytes preserved by SQLite might increase
  4809. ** in future releases of SQLite.
  4810. */
  4811. SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context*,unsigned int);
  4812. /*
  4813. ** CAPI3REF: Define New Collating Sequences
  4814. ** METHOD: sqlite3
  4815. **
  4816. ** ^These functions add, remove, or modify a [collation] associated
  4817. ** with the [database connection] specified as the first argument.
  4818. **
  4819. ** ^The name of the collation is a UTF-8 string
  4820. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4821. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4822. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4823. ** considered to be the same name.
  4824. **
  4825. ** ^(The third argument (eTextRep) must be one of the constants:
  4826. ** <ul>
  4827. ** <li> [SQLITE_UTF8],
  4828. ** <li> [SQLITE_UTF16LE],
  4829. ** <li> [SQLITE_UTF16BE],
  4830. ** <li> [SQLITE_UTF16], or
  4831. ** <li> [SQLITE_UTF16_ALIGNED].
  4832. ** </ul>)^
  4833. ** ^The eTextRep argument determines the encoding of strings passed
  4834. ** to the collating function callback, xCallback.
  4835. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4836. ** force strings to be UTF16 with native byte order.
  4837. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4838. ** on an even byte address.
  4839. **
  4840. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4841. ** through as the first argument to the collating function callback.
  4842. **
  4843. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4844. ** ^Multiple collating functions can be registered using the same name but
  4845. ** with different eTextRep parameters and SQLite will use whichever
  4846. ** function requires the least amount of data transformation.
  4847. ** ^If the xCallback argument is NULL then the collating function is
  4848. ** deleted. ^When all collating functions having the same name are deleted,
  4849. ** that collation is no longer usable.
  4850. **
  4851. ** ^The collating function callback is invoked with a copy of the pArg
  4852. ** application data pointer and with two strings in the encoding specified
  4853. ** by the eTextRep argument. The collating function must return an
  4854. ** integer that is negative, zero, or positive
  4855. ** if the first string is less than, equal to, or greater than the second,
  4856. ** respectively. A collating function must always return the same answer
  4857. ** given the same inputs. If two or more collating functions are registered
  4858. ** to the same collation name (using different eTextRep values) then all
  4859. ** must give an equivalent answer when invoked with equivalent strings.
  4860. ** The collating function must obey the following properties for all
  4861. ** strings A, B, and C:
  4862. **
  4863. ** <ol>
  4864. ** <li> If A==B then B==A.
  4865. ** <li> If A==B and B==C then A==C.
  4866. ** <li> If A&lt;B THEN B&gt;A.
  4867. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4868. ** </ol>
  4869. **
  4870. ** If a collating function fails any of the above constraints and that
  4871. ** collating function is registered and used, then the behavior of SQLite
  4872. ** is undefined.
  4873. **
  4874. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4875. ** with the addition that the xDestroy callback is invoked on pArg when
  4876. ** the collating function is deleted.
  4877. ** ^Collating functions are deleted when they are overridden by later
  4878. ** calls to the collation creation functions or when the
  4879. ** [database connection] is closed using [sqlite3_close()].
  4880. **
  4881. ** ^The xDestroy callback is <u>not</u> called if the
  4882. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4883. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4884. ** check the return code and dispose of the application data pointer
  4885. ** themselves rather than expecting SQLite to deal with it for them.
  4886. ** This is different from every other SQLite interface. The inconsistency
  4887. ** is unfortunate but cannot be changed without breaking backwards
  4888. ** compatibility.
  4889. **
  4890. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4891. */
  4892. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  4893. sqlite3*,
  4894. const char *zName,
  4895. int eTextRep,
  4896. void *pArg,
  4897. int(*xCompare)(void*,int,const void*,int,const void*)
  4898. );
  4899. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  4900. sqlite3*,
  4901. const char *zName,
  4902. int eTextRep,
  4903. void *pArg,
  4904. int(*xCompare)(void*,int,const void*,int,const void*),
  4905. void(*xDestroy)(void*)
  4906. );
  4907. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  4908. sqlite3*,
  4909. const void *zName,
  4910. int eTextRep,
  4911. void *pArg,
  4912. int(*xCompare)(void*,int,const void*,int,const void*)
  4913. );
  4914. /*
  4915. ** CAPI3REF: Collation Needed Callbacks
  4916. ** METHOD: sqlite3
  4917. **
  4918. ** ^To avoid having to register all collation sequences before a database
  4919. ** can be used, a single callback function may be registered with the
  4920. ** [database connection] to be invoked whenever an undefined collation
  4921. ** sequence is required.
  4922. **
  4923. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4924. ** then it is passed the names of undefined collation sequences as strings
  4925. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4926. ** the names are passed as UTF-16 in machine native byte order.
  4927. ** ^A call to either function replaces the existing collation-needed callback.
  4928. **
  4929. ** ^(When the callback is invoked, the first argument passed is a copy
  4930. ** of the second argument to sqlite3_collation_needed() or
  4931. ** sqlite3_collation_needed16(). The second argument is the database
  4932. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4933. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4934. ** sequence function required. The fourth parameter is the name of the
  4935. ** required collation sequence.)^
  4936. **
  4937. ** The callback function should register the desired collation using
  4938. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4939. ** [sqlite3_create_collation_v2()].
  4940. */
  4941. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  4942. sqlite3*,
  4943. void*,
  4944. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4945. );
  4946. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  4947. sqlite3*,
  4948. void*,
  4949. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4950. );
  4951. #ifdef SQLITE_HAS_CODEC
  4952. /*
  4953. ** Specify the key for an encrypted database. This routine should be
  4954. ** called right after sqlite3_open().
  4955. **
  4956. ** The code to implement this API is not available in the public release
  4957. ** of SQLite.
  4958. */
  4959. SQLITE_API int SQLITE_STDCALL sqlite3_key(
  4960. sqlite3 *db, /* Database to be rekeyed */
  4961. const void *pKey, int nKey /* The key */
  4962. );
  4963. SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
  4964. sqlite3 *db, /* Database to be rekeyed */
  4965. const char *zDbName, /* Name of the database */
  4966. const void *pKey, int nKey /* The key */
  4967. );
  4968. /*
  4969. ** Change the key on an open database. If the current database is not
  4970. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4971. ** database is decrypted.
  4972. **
  4973. ** The code to implement this API is not available in the public release
  4974. ** of SQLite.
  4975. */
  4976. SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
  4977. sqlite3 *db, /* Database to be rekeyed */
  4978. const void *pKey, int nKey /* The new key */
  4979. );
  4980. SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
  4981. sqlite3 *db, /* Database to be rekeyed */
  4982. const char *zDbName, /* Name of the database */
  4983. const void *pKey, int nKey /* The new key */
  4984. );
  4985. /*
  4986. ** Specify the activation key for a SEE database. Unless
  4987. ** activated, none of the SEE routines will work.
  4988. */
  4989. SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
  4990. const char *zPassPhrase /* Activation phrase */
  4991. );
  4992. #endif
  4993. #ifdef SQLITE_ENABLE_CEROD
  4994. /*
  4995. ** Specify the activation key for a CEROD database. Unless
  4996. ** activated, none of the CEROD routines will work.
  4997. */
  4998. SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
  4999. const char *zPassPhrase /* Activation phrase */
  5000. );
  5001. #endif
  5002. /*
  5003. ** CAPI3REF: Suspend Execution For A Short Time
  5004. **
  5005. ** The sqlite3_sleep() function causes the current thread to suspend execution
  5006. ** for at least a number of milliseconds specified in its parameter.
  5007. **
  5008. ** If the operating system does not support sleep requests with
  5009. ** millisecond time resolution, then the time will be rounded up to
  5010. ** the nearest second. The number of milliseconds of sleep actually
  5011. ** requested from the operating system is returned.
  5012. **
  5013. ** ^SQLite implements this interface by calling the xSleep()
  5014. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  5015. ** of the default VFS is not implemented correctly, or not implemented at
  5016. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  5017. ** in the previous paragraphs.
  5018. */
  5019. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
  5020. /*
  5021. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  5022. **
  5023. ** ^(If this global variable is made to point to a string which is
  5024. ** the name of a folder (a.k.a. directory), then all temporary files
  5025. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  5026. ** will be placed in that directory.)^ ^If this variable
  5027. ** is a NULL pointer, then SQLite performs a search for an appropriate
  5028. ** temporary file directory.
  5029. **
  5030. ** Applications are strongly discouraged from using this global variable.
  5031. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  5032. ** But for all other platforms, it is highly recommended that applications
  5033. ** neither read nor write this variable. This global variable is a relic
  5034. ** that exists for backwards compatibility of legacy applications and should
  5035. ** be avoided in new projects.
  5036. **
  5037. ** It is not safe to read or modify this variable in more than one
  5038. ** thread at a time. It is not safe to read or modify this variable
  5039. ** if a [database connection] is being used at the same time in a separate
  5040. ** thread.
  5041. ** It is intended that this variable be set once
  5042. ** as part of process initialization and before any SQLite interface
  5043. ** routines have been called and that this variable remain unchanged
  5044. ** thereafter.
  5045. **
  5046. ** ^The [temp_store_directory pragma] may modify this variable and cause
  5047. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5048. ** the [temp_store_directory pragma] always assumes that any string
  5049. ** that this variable points to is held in memory obtained from
  5050. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5051. ** using [sqlite3_free].
  5052. ** Hence, if this variable is modified directly, either it should be
  5053. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5054. ** or else the use of the [temp_store_directory pragma] should be avoided.
  5055. ** Except when requested by the [temp_store_directory pragma], SQLite
  5056. ** does not free the memory that sqlite3_temp_directory points to. If
  5057. ** the application wants that memory to be freed, it must do
  5058. ** so itself, taking care to only do so after all [database connection]
  5059. ** objects have been destroyed.
  5060. **
  5061. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  5062. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  5063. ** features that require the use of temporary files may fail. Here is an
  5064. ** example of how to do this using C++ with the Windows Runtime:
  5065. **
  5066. ** <blockquote><pre>
  5067. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  5068. ** &nbsp; TemporaryFolder->Path->Data();
  5069. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  5070. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  5071. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  5072. ** &nbsp; NULL, NULL);
  5073. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  5074. ** </pre></blockquote>
  5075. */
  5076. SQLITE_API char *sqlite3_temp_directory;
  5077. /*
  5078. ** CAPI3REF: Name Of The Folder Holding Database Files
  5079. **
  5080. ** ^(If this global variable is made to point to a string which is
  5081. ** the name of a folder (a.k.a. directory), then all database files
  5082. ** specified with a relative pathname and created or accessed by
  5083. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  5084. ** to be relative to that directory.)^ ^If this variable is a NULL
  5085. ** pointer, then SQLite assumes that all database files specified
  5086. ** with a relative pathname are relative to the current directory
  5087. ** for the process. Only the windows VFS makes use of this global
  5088. ** variable; it is ignored by the unix VFS.
  5089. **
  5090. ** Changing the value of this variable while a database connection is
  5091. ** open can result in a corrupt database.
  5092. **
  5093. ** It is not safe to read or modify this variable in more than one
  5094. ** thread at a time. It is not safe to read or modify this variable
  5095. ** if a [database connection] is being used at the same time in a separate
  5096. ** thread.
  5097. ** It is intended that this variable be set once
  5098. ** as part of process initialization and before any SQLite interface
  5099. ** routines have been called and that this variable remain unchanged
  5100. ** thereafter.
  5101. **
  5102. ** ^The [data_store_directory pragma] may modify this variable and cause
  5103. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5104. ** the [data_store_directory pragma] always assumes that any string
  5105. ** that this variable points to is held in memory obtained from
  5106. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5107. ** using [sqlite3_free].
  5108. ** Hence, if this variable is modified directly, either it should be
  5109. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5110. ** or else the use of the [data_store_directory pragma] should be avoided.
  5111. */
  5112. SQLITE_API char *sqlite3_data_directory;
  5113. /*
  5114. ** CAPI3REF: Test For Auto-Commit Mode
  5115. ** KEYWORDS: {autocommit mode}
  5116. ** METHOD: sqlite3
  5117. **
  5118. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5119. ** zero if the given database connection is or is not in autocommit mode,
  5120. ** respectively. ^Autocommit mode is on by default.
  5121. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5122. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5123. **
  5124. ** If certain kinds of errors occur on a statement within a multi-statement
  5125. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5126. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5127. ** transaction might be rolled back automatically. The only way to
  5128. ** find out whether SQLite automatically rolled back the transaction after
  5129. ** an error is to use this function.
  5130. **
  5131. ** If another thread changes the autocommit status of the database
  5132. ** connection while this routine is running, then the return value
  5133. ** is undefined.
  5134. */
  5135. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
  5136. /*
  5137. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5138. ** METHOD: sqlite3_stmt
  5139. **
  5140. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5141. ** to which a [prepared statement] belongs. ^The [database connection]
  5142. ** returned by sqlite3_db_handle is the same [database connection]
  5143. ** that was the first argument
  5144. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5145. ** create the statement in the first place.
  5146. */
  5147. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
  5148. /*
  5149. ** CAPI3REF: Return The Filename For A Database Connection
  5150. ** METHOD: sqlite3
  5151. **
  5152. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5153. ** associated with database N of connection D. ^The main database file
  5154. ** has the name "main". If there is no attached database N on the database
  5155. ** connection D, or if database N is a temporary or in-memory database, then
  5156. ** a NULL pointer is returned.
  5157. **
  5158. ** ^The filename returned by this function is the output of the
  5159. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5160. ** will be an absolute pathname, even if the filename used
  5161. ** to open the database originally was a URI or relative pathname.
  5162. */
  5163. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5164. /*
  5165. ** CAPI3REF: Determine if a database is read-only
  5166. ** METHOD: sqlite3
  5167. **
  5168. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5169. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5170. ** the name of a database on connection D.
  5171. */
  5172. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5173. /*
  5174. ** CAPI3REF: Find the next prepared statement
  5175. ** METHOD: sqlite3
  5176. **
  5177. ** ^This interface returns a pointer to the next [prepared statement] after
  5178. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5179. ** then this interface returns a pointer to the first prepared statement
  5180. ** associated with the database connection pDb. ^If no prepared statement
  5181. ** satisfies the conditions of this routine, it returns NULL.
  5182. **
  5183. ** The [database connection] pointer D in a call to
  5184. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5185. ** connection and in particular must not be a NULL pointer.
  5186. */
  5187. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5188. /*
  5189. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5190. ** METHOD: sqlite3
  5191. **
  5192. ** ^The sqlite3_commit_hook() interface registers a callback
  5193. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5194. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5195. ** for the same database connection is overridden.
  5196. ** ^The sqlite3_rollback_hook() interface registers a callback
  5197. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5198. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5199. ** for the same database connection is overridden.
  5200. ** ^The pArg argument is passed through to the callback.
  5201. ** ^If the callback on a commit hook function returns non-zero,
  5202. ** then the commit is converted into a rollback.
  5203. **
  5204. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5205. ** return the P argument from the previous call of the same function
  5206. ** on the same [database connection] D, or NULL for
  5207. ** the first call for each function on D.
  5208. **
  5209. ** The commit and rollback hook callbacks are not reentrant.
  5210. ** The callback implementation must not do anything that will modify
  5211. ** the database connection that invoked the callback. Any actions
  5212. ** to modify the database connection must be deferred until after the
  5213. ** completion of the [sqlite3_step()] call that triggered the commit
  5214. ** or rollback hook in the first place.
  5215. ** Note that running any other SQL statements, including SELECT statements,
  5216. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5217. ** the database connections for the meaning of "modify" in this paragraph.
  5218. **
  5219. ** ^Registering a NULL function disables the callback.
  5220. **
  5221. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5222. ** operation is allowed to continue normally. ^If the commit hook
  5223. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5224. ** ^The rollback hook is invoked on a rollback that results from a commit
  5225. ** hook returning non-zero, just as it would be with any other rollback.
  5226. **
  5227. ** ^For the purposes of this API, a transaction is said to have been
  5228. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5229. ** an error or constraint causes an implicit rollback to occur.
  5230. ** ^The rollback callback is not invoked if a transaction is
  5231. ** automatically rolled back because the database connection is closed.
  5232. **
  5233. ** See also the [sqlite3_update_hook()] interface.
  5234. */
  5235. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5236. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5237. /*
  5238. ** CAPI3REF: Data Change Notification Callbacks
  5239. ** METHOD: sqlite3
  5240. **
  5241. ** ^The sqlite3_update_hook() interface registers a callback function
  5242. ** with the [database connection] identified by the first argument
  5243. ** to be invoked whenever a row is updated, inserted or deleted in
  5244. ** a rowid table.
  5245. ** ^Any callback set by a previous call to this function
  5246. ** for the same database connection is overridden.
  5247. **
  5248. ** ^The second argument is a pointer to the function to invoke when a
  5249. ** row is updated, inserted or deleted in a rowid table.
  5250. ** ^The first argument to the callback is a copy of the third argument
  5251. ** to sqlite3_update_hook().
  5252. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5253. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5254. ** to be invoked.
  5255. ** ^The third and fourth arguments to the callback contain pointers to the
  5256. ** database and table name containing the affected row.
  5257. ** ^The final callback parameter is the [rowid] of the row.
  5258. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5259. **
  5260. ** ^(The update hook is not invoked when internal system tables are
  5261. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5262. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  5263. **
  5264. ** ^In the current implementation, the update hook
  5265. ** is not invoked when duplication rows are deleted because of an
  5266. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5267. ** invoked when rows are deleted using the [truncate optimization].
  5268. ** The exceptions defined in this paragraph might change in a future
  5269. ** release of SQLite.
  5270. **
  5271. ** The update hook implementation must not do anything that will modify
  5272. ** the database connection that invoked the update hook. Any actions
  5273. ** to modify the database connection must be deferred until after the
  5274. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5275. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5276. ** database connections for the meaning of "modify" in this paragraph.
  5277. **
  5278. ** ^The sqlite3_update_hook(D,C,P) function
  5279. ** returns the P argument from the previous call
  5280. ** on the same [database connection] D, or NULL for
  5281. ** the first call on D.
  5282. **
  5283. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5284. ** interfaces.
  5285. */
  5286. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  5287. sqlite3*,
  5288. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5289. void*
  5290. );
  5291. /*
  5292. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5293. **
  5294. ** ^(This routine enables or disables the sharing of the database cache
  5295. ** and schema data structures between [database connection | connections]
  5296. ** to the same database. Sharing is enabled if the argument is true
  5297. ** and disabled if the argument is false.)^
  5298. **
  5299. ** ^Cache sharing is enabled and disabled for an entire process.
  5300. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5301. ** sharing was enabled or disabled for each thread separately.
  5302. **
  5303. ** ^(The cache sharing mode set by this interface effects all subsequent
  5304. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5305. ** Existing database connections continue use the sharing mode
  5306. ** that was in effect at the time they were opened.)^
  5307. **
  5308. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5309. ** successfully. An [error code] is returned otherwise.)^
  5310. **
  5311. ** ^Shared cache is disabled by default. But this might change in
  5312. ** future releases of SQLite. Applications that care about shared
  5313. ** cache setting should set it explicitly.
  5314. **
  5315. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  5316. ** and will always return SQLITE_MISUSE. On those systems,
  5317. ** shared cache mode should be enabled per-database connection via
  5318. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  5319. **
  5320. ** This interface is threadsafe on processors where writing a
  5321. ** 32-bit integer is atomic.
  5322. **
  5323. ** See Also: [SQLite Shared-Cache Mode]
  5324. */
  5325. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
  5326. /*
  5327. ** CAPI3REF: Attempt To Free Heap Memory
  5328. **
  5329. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5330. ** of heap memory by deallocating non-essential memory allocations
  5331. ** held by the database library. Memory used to cache database
  5332. ** pages to improve performance is an example of non-essential memory.
  5333. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5334. ** which might be more or less than the amount requested.
  5335. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5336. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5337. **
  5338. ** See also: [sqlite3_db_release_memory()]
  5339. */
  5340. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
  5341. /*
  5342. ** CAPI3REF: Free Memory Used By A Database Connection
  5343. ** METHOD: sqlite3
  5344. **
  5345. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5346. ** memory as possible from database connection D. Unlike the
  5347. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5348. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5349. ** omitted.
  5350. **
  5351. ** See also: [sqlite3_release_memory()]
  5352. */
  5353. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
  5354. /*
  5355. ** CAPI3REF: Impose A Limit On Heap Size
  5356. **
  5357. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5358. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5359. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5360. ** limit by reducing the number of pages held in the page cache
  5361. ** as heap memory usages approaches the limit.
  5362. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5363. ** below the limit, it will exceed the limit rather than generate
  5364. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5365. ** is advisory only.
  5366. **
  5367. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5368. ** the soft heap limit prior to the call, or negative in the case of an
  5369. ** error. ^If the argument N is negative
  5370. ** then no change is made to the soft heap limit. Hence, the current
  5371. ** size of the soft heap limit can be determined by invoking
  5372. ** sqlite3_soft_heap_limit64() with a negative argument.
  5373. **
  5374. ** ^If the argument N is zero then the soft heap limit is disabled.
  5375. **
  5376. ** ^(The soft heap limit is not enforced in the current implementation
  5377. ** if one or more of following conditions are true:
  5378. **
  5379. ** <ul>
  5380. ** <li> The soft heap limit is set to zero.
  5381. ** <li> Memory accounting is disabled using a combination of the
  5382. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5383. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5384. ** <li> An alternative page cache implementation is specified using
  5385. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5386. ** <li> The page cache allocates from its own memory pool supplied
  5387. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5388. ** from the heap.
  5389. ** </ul>)^
  5390. **
  5391. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5392. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5393. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5394. ** the soft heap limit is enforced on every memory allocation. Without
  5395. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5396. ** when memory is allocated by the page cache. Testing suggests that because
  5397. ** the page cache is the predominate memory user in SQLite, most
  5398. ** applications will achieve adequate soft heap limit enforcement without
  5399. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5400. **
  5401. ** The circumstances under which SQLite will enforce the soft heap limit may
  5402. ** changes in future releases of SQLite.
  5403. */
  5404. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5405. /*
  5406. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5407. ** DEPRECATED
  5408. **
  5409. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5410. ** interface. This routine is provided for historical compatibility
  5411. ** only. All new applications should use the
  5412. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5413. */
  5414. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
  5415. /*
  5416. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5417. ** METHOD: sqlite3
  5418. **
  5419. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  5420. ** information about column C of table T in database D
  5421. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  5422. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  5423. ** the final five arguments with appropriate values if the specified
  5424. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  5425. ** SQLITE_ERROR and if the specified column does not exist.
  5426. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  5427. ** NULL pointer, then this routine simply checks for the existance of the
  5428. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  5429. ** does not.
  5430. **
  5431. ** ^The column is identified by the second, third and fourth parameters to
  5432. ** this function. ^(The second parameter is either the name of the database
  5433. ** (i.e. "main", "temp", or an attached database) containing the specified
  5434. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  5435. ** for the table using the same algorithm used by the database engine to
  5436. ** resolve unqualified table references.
  5437. **
  5438. ** ^The third and fourth parameters to this function are the table and column
  5439. ** name of the desired column, respectively.
  5440. **
  5441. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5442. ** and subsequent parameters to this function. ^Any of these arguments may be
  5443. ** NULL, in which case the corresponding element of metadata is omitted.
  5444. **
  5445. ** ^(<blockquote>
  5446. ** <table border="1">
  5447. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5448. **
  5449. ** <tr><td> 5th <td> const char* <td> Data type
  5450. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5451. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5452. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5453. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5454. ** </table>
  5455. ** </blockquote>)^
  5456. **
  5457. ** ^The memory pointed to by the character pointers returned for the
  5458. ** declaration type and collation sequence is valid until the next
  5459. ** call to any SQLite API function.
  5460. **
  5461. ** ^If the specified table is actually a view, an [error code] is returned.
  5462. **
  5463. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  5464. ** is not a [WITHOUT ROWID] table and an
  5465. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5466. ** parameters are set for the explicitly declared column. ^(If there is no
  5467. ** [INTEGER PRIMARY KEY] column, then the outputs
  5468. ** for the [rowid] are set as follows:
  5469. **
  5470. ** <pre>
  5471. ** data type: "INTEGER"
  5472. ** collation sequence: "BINARY"
  5473. ** not null: 0
  5474. ** primary key: 1
  5475. ** auto increment: 0
  5476. ** </pre>)^
  5477. **
  5478. ** ^This function causes all database schemas to be read from disk and
  5479. ** parsed, if that has not already been done, and returns an error if
  5480. ** any errors are encountered while loading the schema.
  5481. */
  5482. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  5483. sqlite3 *db, /* Connection handle */
  5484. const char *zDbName, /* Database name or NULL */
  5485. const char *zTableName, /* Table name */
  5486. const char *zColumnName, /* Column name */
  5487. char const **pzDataType, /* OUTPUT: Declared data type */
  5488. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5489. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5490. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5491. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5492. );
  5493. /*
  5494. ** CAPI3REF: Load An Extension
  5495. ** METHOD: sqlite3
  5496. **
  5497. ** ^This interface loads an SQLite extension library from the named file.
  5498. **
  5499. ** ^The sqlite3_load_extension() interface attempts to load an
  5500. ** [SQLite extension] library contained in the file zFile. If
  5501. ** the file cannot be loaded directly, attempts are made to load
  5502. ** with various operating-system specific extensions added.
  5503. ** So for example, if "samplelib" cannot be loaded, then names like
  5504. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5505. ** be tried also.
  5506. **
  5507. ** ^The entry point is zProc.
  5508. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5509. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5510. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5511. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5512. ** characters in the filename from the last "/" to the first following
  5513. ** "." and omitting any initial "lib".)^
  5514. ** ^The sqlite3_load_extension() interface returns
  5515. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5516. ** ^If an error occurs and pzErrMsg is not 0, then the
  5517. ** [sqlite3_load_extension()] interface shall attempt to
  5518. ** fill *pzErrMsg with error message text stored in memory
  5519. ** obtained from [sqlite3_malloc()]. The calling function
  5520. ** should free this memory by calling [sqlite3_free()].
  5521. **
  5522. ** ^Extension loading must be enabled using
  5523. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5524. ** otherwise an error will be returned.
  5525. **
  5526. ** See also the [load_extension() SQL function].
  5527. */
  5528. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  5529. sqlite3 *db, /* Load the extension into this database connection */
  5530. const char *zFile, /* Name of the shared library containing extension */
  5531. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5532. char **pzErrMsg /* Put error message here if not 0 */
  5533. );
  5534. /*
  5535. ** CAPI3REF: Enable Or Disable Extension Loading
  5536. ** METHOD: sqlite3
  5537. **
  5538. ** ^So as not to open security holes in older applications that are
  5539. ** unprepared to deal with [extension loading], and as a means of disabling
  5540. ** [extension loading] while evaluating user-entered SQL, the following API
  5541. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5542. **
  5543. ** ^Extension loading is off by default.
  5544. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5545. ** to turn extension loading on and call it with onoff==0 to turn
  5546. ** it back off again.
  5547. */
  5548. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5549. /*
  5550. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5551. **
  5552. ** ^This interface causes the xEntryPoint() function to be invoked for
  5553. ** each new [database connection] that is created. The idea here is that
  5554. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5555. ** that is to be automatically loaded into all new database connections.
  5556. **
  5557. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5558. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5559. ** arguments and expects and integer result as if the signature of the
  5560. ** entry point where as follows:
  5561. **
  5562. ** <blockquote><pre>
  5563. ** &nbsp; int xEntryPoint(
  5564. ** &nbsp; sqlite3 *db,
  5565. ** &nbsp; const char **pzErrMsg,
  5566. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5567. ** &nbsp; );
  5568. ** </pre></blockquote>)^
  5569. **
  5570. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5571. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5572. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5573. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5574. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5575. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5576. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5577. **
  5578. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5579. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5580. ** will be called more than once for each database connection that is opened.
  5581. **
  5582. ** See also: [sqlite3_reset_auto_extension()]
  5583. ** and [sqlite3_cancel_auto_extension()]
  5584. */
  5585. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
  5586. /*
  5587. ** CAPI3REF: Cancel Automatic Extension Loading
  5588. **
  5589. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5590. ** initialization routine X that was registered using a prior call to
  5591. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5592. ** routine returns 1 if initialization routine X was successfully
  5593. ** unregistered and it returns 0 if X was not on the list of initialization
  5594. ** routines.
  5595. */
  5596. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5597. /*
  5598. ** CAPI3REF: Reset Automatic Extension Loading
  5599. **
  5600. ** ^This interface disables all automatic extensions previously
  5601. ** registered using [sqlite3_auto_extension()].
  5602. */
  5603. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
  5604. /*
  5605. ** The interface to the virtual-table mechanism is currently considered
  5606. ** to be experimental. The interface might change in incompatible ways.
  5607. ** If this is a problem for you, do not use the interface at this time.
  5608. **
  5609. ** When the virtual-table mechanism stabilizes, we will declare the
  5610. ** interface fixed, support it indefinitely, and remove this comment.
  5611. */
  5612. /*
  5613. ** Structures used by the virtual table interface
  5614. */
  5615. typedef struct sqlite3_vtab sqlite3_vtab;
  5616. typedef struct sqlite3_index_info sqlite3_index_info;
  5617. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5618. typedef struct sqlite3_module sqlite3_module;
  5619. /*
  5620. ** CAPI3REF: Virtual Table Object
  5621. ** KEYWORDS: sqlite3_module {virtual table module}
  5622. **
  5623. ** This structure, sometimes called a "virtual table module",
  5624. ** defines the implementation of a [virtual tables].
  5625. ** This structure consists mostly of methods for the module.
  5626. **
  5627. ** ^A virtual table module is created by filling in a persistent
  5628. ** instance of this structure and passing a pointer to that instance
  5629. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5630. ** ^The registration remains valid until it is replaced by a different
  5631. ** module or until the [database connection] closes. The content
  5632. ** of this structure must not change while it is registered with
  5633. ** any database connection.
  5634. */
  5635. struct sqlite3_module {
  5636. int iVersion;
  5637. int (*xCreate)(sqlite3*, void *pAux,
  5638. int argc, const char *const*argv,
  5639. sqlite3_vtab **ppVTab, char**);
  5640. int (*xConnect)(sqlite3*, void *pAux,
  5641. int argc, const char *const*argv,
  5642. sqlite3_vtab **ppVTab, char**);
  5643. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5644. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5645. int (*xDestroy)(sqlite3_vtab *pVTab);
  5646. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5647. int (*xClose)(sqlite3_vtab_cursor*);
  5648. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5649. int argc, sqlite3_value **argv);
  5650. int (*xNext)(sqlite3_vtab_cursor*);
  5651. int (*xEof)(sqlite3_vtab_cursor*);
  5652. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5653. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5654. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5655. int (*xBegin)(sqlite3_vtab *pVTab);
  5656. int (*xSync)(sqlite3_vtab *pVTab);
  5657. int (*xCommit)(sqlite3_vtab *pVTab);
  5658. int (*xRollback)(sqlite3_vtab *pVTab);
  5659. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5660. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5661. void **ppArg);
  5662. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5663. /* The methods above are in version 1 of the sqlite_module object. Those
  5664. ** below are for version 2 and greater. */
  5665. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5666. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5667. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5668. };
  5669. /*
  5670. ** CAPI3REF: Virtual Table Indexing Information
  5671. ** KEYWORDS: sqlite3_index_info
  5672. **
  5673. ** The sqlite3_index_info structure and its substructures is used as part
  5674. ** of the [virtual table] interface to
  5675. ** pass information into and receive the reply from the [xBestIndex]
  5676. ** method of a [virtual table module]. The fields under **Inputs** are the
  5677. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5678. ** results into the **Outputs** fields.
  5679. **
  5680. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5681. **
  5682. ** <blockquote>column OP expr</blockquote>
  5683. **
  5684. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5685. ** stored in aConstraint[].op using one of the
  5686. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5687. ** ^(The index of the column is stored in
  5688. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5689. ** expr on the right-hand side can be evaluated (and thus the constraint
  5690. ** is usable) and false if it cannot.)^
  5691. **
  5692. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5693. ** and makes other simplifications to the WHERE clause in an attempt to
  5694. ** get as many WHERE clause terms into the form shown above as possible.
  5695. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5696. ** relevant to the particular virtual table being queried.
  5697. **
  5698. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5699. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5700. **
  5701. ** The colUsed field indicates which columns of the virtual table may be
  5702. ** required by the current scan. Virtual table columns are numbered from
  5703. ** zero in the order in which they appear within the CREATE TABLE statement
  5704. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  5705. ** the corresponding bit is set within the colUsed mask if the column may be
  5706. ** required by SQLite. If the table has at least 64 columns and any column
  5707. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  5708. ** set. In other words, column iCol may be required if the expression
  5709. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  5710. ** non-zero.
  5711. **
  5712. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5713. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5714. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5715. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5716. ** is true, then the constraint is assumed to be fully handled by the
  5717. ** virtual table and is not checked again by SQLite.)^
  5718. **
  5719. ** ^The idxNum and idxPtr values are recorded and passed into the
  5720. ** [xFilter] method.
  5721. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5722. ** needToFreeIdxPtr is true.
  5723. **
  5724. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5725. ** the correct order to satisfy the ORDER BY clause so that no separate
  5726. ** sorting step is required.
  5727. **
  5728. ** ^The estimatedCost value is an estimate of the cost of a particular
  5729. ** strategy. A cost of N indicates that the cost of the strategy is similar
  5730. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  5731. ** indicates that the expense of the operation is similar to that of a
  5732. ** binary search on a unique indexed field of an SQLite table with N rows.
  5733. **
  5734. ** ^The estimatedRows value is an estimate of the number of rows that
  5735. ** will be returned by the strategy.
  5736. **
  5737. ** The xBestIndex method may optionally populate the idxFlags field with a
  5738. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  5739. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  5740. ** assumes that the strategy may visit at most one row.
  5741. **
  5742. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  5743. ** SQLite also assumes that if a call to the xUpdate() method is made as
  5744. ** part of the same statement to delete or update a virtual table row and the
  5745. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  5746. ** any database changes. In other words, if the xUpdate() returns
  5747. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  5748. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  5749. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  5750. ** the xUpdate method are automatically rolled back by SQLite.
  5751. **
  5752. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  5753. ** structure for SQLite version 3.8.2. If a virtual table extension is
  5754. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  5755. ** to read or write the estimatedRows field are undefined (but are likely
  5756. ** to included crashing the application). The estimatedRows field should
  5757. ** therefore only be used if [sqlite3_libversion_number()] returns a
  5758. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  5759. ** was added for version 3.9.0. It may therefore only be used if
  5760. ** sqlite3_libversion_number() returns a value greater than or equal to
  5761. ** 3009000.
  5762. */
  5763. struct sqlite3_index_info {
  5764. /* Inputs */
  5765. int nConstraint; /* Number of entries in aConstraint */
  5766. struct sqlite3_index_constraint {
  5767. int iColumn; /* Column on left-hand side of constraint */
  5768. unsigned char op; /* Constraint operator */
  5769. unsigned char usable; /* True if this constraint is usable */
  5770. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5771. } *aConstraint; /* Table of WHERE clause constraints */
  5772. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5773. struct sqlite3_index_orderby {
  5774. int iColumn; /* Column number */
  5775. unsigned char desc; /* True for DESC. False for ASC. */
  5776. } *aOrderBy; /* The ORDER BY clause */
  5777. /* Outputs */
  5778. struct sqlite3_index_constraint_usage {
  5779. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5780. unsigned char omit; /* Do not code a test for this constraint */
  5781. } *aConstraintUsage;
  5782. int idxNum; /* Number used to identify the index */
  5783. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5784. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5785. int orderByConsumed; /* True if output is already ordered */
  5786. double estimatedCost; /* Estimated cost of using this index */
  5787. /* Fields below are only available in SQLite 3.8.2 and later */
  5788. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  5789. /* Fields below are only available in SQLite 3.9.0 and later */
  5790. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  5791. /* Fields below are only available in SQLite 3.10.0 and later */
  5792. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  5793. };
  5794. /*
  5795. ** CAPI3REF: Virtual Table Scan Flags
  5796. */
  5797. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  5798. /*
  5799. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5800. **
  5801. ** These macros defined the allowed values for the
  5802. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5803. ** an operator that is part of a constraint term in the wHERE clause of
  5804. ** a query that uses a [virtual table].
  5805. */
  5806. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5807. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5808. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5809. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5810. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5811. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5812. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  5813. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  5814. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  5815. /*
  5816. ** CAPI3REF: Register A Virtual Table Implementation
  5817. ** METHOD: sqlite3
  5818. **
  5819. ** ^These routines are used to register a new [virtual table module] name.
  5820. ** ^Module names must be registered before
  5821. ** creating a new [virtual table] using the module and before using a
  5822. ** preexisting [virtual table] for the module.
  5823. **
  5824. ** ^The module name is registered on the [database connection] specified
  5825. ** by the first parameter. ^The name of the module is given by the
  5826. ** second parameter. ^The third parameter is a pointer to
  5827. ** the implementation of the [virtual table module]. ^The fourth
  5828. ** parameter is an arbitrary client data pointer that is passed through
  5829. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5830. ** when a new virtual table is be being created or reinitialized.
  5831. **
  5832. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5833. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5834. ** invoke the destructor function (if it is not NULL) when SQLite
  5835. ** no longer needs the pClientData pointer. ^The destructor will also
  5836. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5837. ** ^The sqlite3_create_module()
  5838. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5839. ** destructor.
  5840. */
  5841. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  5842. sqlite3 *db, /* SQLite connection to register module with */
  5843. const char *zName, /* Name of the module */
  5844. const sqlite3_module *p, /* Methods for the module */
  5845. void *pClientData /* Client data for xCreate/xConnect */
  5846. );
  5847. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  5848. sqlite3 *db, /* SQLite connection to register module with */
  5849. const char *zName, /* Name of the module */
  5850. const sqlite3_module *p, /* Methods for the module */
  5851. void *pClientData, /* Client data for xCreate/xConnect */
  5852. void(*xDestroy)(void*) /* Module destructor function */
  5853. );
  5854. /*
  5855. ** CAPI3REF: Virtual Table Instance Object
  5856. ** KEYWORDS: sqlite3_vtab
  5857. **
  5858. ** Every [virtual table module] implementation uses a subclass
  5859. ** of this object to describe a particular instance
  5860. ** of the [virtual table]. Each subclass will
  5861. ** be tailored to the specific needs of the module implementation.
  5862. ** The purpose of this superclass is to define certain fields that are
  5863. ** common to all module implementations.
  5864. **
  5865. ** ^Virtual tables methods can set an error message by assigning a
  5866. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5867. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5868. ** prior to assigning a new string to zErrMsg. ^After the error message
  5869. ** is delivered up to the client application, the string will be automatically
  5870. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5871. */
  5872. struct sqlite3_vtab {
  5873. const sqlite3_module *pModule; /* The module for this virtual table */
  5874. int nRef; /* Number of open cursors */
  5875. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5876. /* Virtual table implementations will typically add additional fields */
  5877. };
  5878. /*
  5879. ** CAPI3REF: Virtual Table Cursor Object
  5880. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5881. **
  5882. ** Every [virtual table module] implementation uses a subclass of the
  5883. ** following structure to describe cursors that point into the
  5884. ** [virtual table] and are used
  5885. ** to loop through the virtual table. Cursors are created using the
  5886. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5887. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5888. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5889. ** of the module. Each module implementation will define
  5890. ** the content of a cursor structure to suit its own needs.
  5891. **
  5892. ** This superclass exists in order to define fields of the cursor that
  5893. ** are common to all implementations.
  5894. */
  5895. struct sqlite3_vtab_cursor {
  5896. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5897. /* Virtual table implementations will typically add additional fields */
  5898. };
  5899. /*
  5900. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5901. **
  5902. ** ^The [xCreate] and [xConnect] methods of a
  5903. ** [virtual table module] call this interface
  5904. ** to declare the format (the names and datatypes of the columns) of
  5905. ** the virtual tables they implement.
  5906. */
  5907. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5908. /*
  5909. ** CAPI3REF: Overload A Function For A Virtual Table
  5910. ** METHOD: sqlite3
  5911. **
  5912. ** ^(Virtual tables can provide alternative implementations of functions
  5913. ** using the [xFindFunction] method of the [virtual table module].
  5914. ** But global versions of those functions
  5915. ** must exist in order to be overloaded.)^
  5916. **
  5917. ** ^(This API makes sure a global version of a function with a particular
  5918. ** name and number of parameters exists. If no such function exists
  5919. ** before this API is called, a new function is created.)^ ^The implementation
  5920. ** of the new function always causes an exception to be thrown. So
  5921. ** the new function is not good for anything by itself. Its only
  5922. ** purpose is to be a placeholder function that can be overloaded
  5923. ** by a [virtual table].
  5924. */
  5925. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5926. /*
  5927. ** The interface to the virtual-table mechanism defined above (back up
  5928. ** to a comment remarkably similar to this one) is currently considered
  5929. ** to be experimental. The interface might change in incompatible ways.
  5930. ** If this is a problem for you, do not use the interface at this time.
  5931. **
  5932. ** When the virtual-table mechanism stabilizes, we will declare the
  5933. ** interface fixed, support it indefinitely, and remove this comment.
  5934. */
  5935. /*
  5936. ** CAPI3REF: A Handle To An Open BLOB
  5937. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5938. **
  5939. ** An instance of this object represents an open BLOB on which
  5940. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5941. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5942. ** and destroyed by [sqlite3_blob_close()].
  5943. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5944. ** can be used to read or write small subsections of the BLOB.
  5945. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5946. */
  5947. typedef struct sqlite3_blob sqlite3_blob;
  5948. /*
  5949. ** CAPI3REF: Open A BLOB For Incremental I/O
  5950. ** METHOD: sqlite3
  5951. ** CONSTRUCTOR: sqlite3_blob
  5952. **
  5953. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5954. ** in row iRow, column zColumn, table zTable in database zDb;
  5955. ** in other words, the same BLOB that would be selected by:
  5956. **
  5957. ** <pre>
  5958. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5959. ** </pre>)^
  5960. **
  5961. ** ^(Parameter zDb is not the filename that contains the database, but
  5962. ** rather the symbolic name of the database. For attached databases, this is
  5963. ** the name that appears after the AS keyword in the [ATTACH] statement.
  5964. ** For the main database file, the database name is "main". For TEMP
  5965. ** tables, the database name is "temp".)^
  5966. **
  5967. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5968. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  5969. ** read-only access.
  5970. **
  5971. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  5972. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  5973. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  5974. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  5975. ** on *ppBlob after this function it returns.
  5976. **
  5977. ** This function fails with SQLITE_ERROR if any of the following are true:
  5978. ** <ul>
  5979. ** <li> ^(Database zDb does not exist)^,
  5980. ** <li> ^(Table zTable does not exist within database zDb)^,
  5981. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  5982. ** <li> ^(Column zColumn does not exist)^,
  5983. ** <li> ^(Row iRow is not present in the table)^,
  5984. ** <li> ^(The specified column of row iRow contains a value that is not
  5985. ** a TEXT or BLOB value)^,
  5986. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  5987. ** constraint and the blob is being opened for read/write access)^,
  5988. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  5989. ** column zColumn is part of a [child key] definition and the blob is
  5990. ** being opened for read/write access)^.
  5991. ** </ul>
  5992. **
  5993. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  5994. ** [database connection] error code and message accessible via
  5995. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  5996. **
  5997. **
  5998. ** ^(If the row that a BLOB handle points to is modified by an
  5999. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  6000. ** then the BLOB handle is marked as "expired".
  6001. ** This is true if any column of the row is changed, even a column
  6002. ** other than the one the BLOB handle is open on.)^
  6003. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  6004. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  6005. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  6006. ** rolled back by the expiration of the BLOB. Such changes will eventually
  6007. ** commit if the transaction continues to completion.)^
  6008. **
  6009. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  6010. ** the opened blob. ^The size of a blob may not be changed by this
  6011. ** interface. Use the [UPDATE] SQL command to change the size of a
  6012. ** blob.
  6013. **
  6014. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  6015. ** and the built-in [zeroblob] SQL function may be used to create a
  6016. ** zero-filled blob to read or write using the incremental-blob interface.
  6017. **
  6018. ** To avoid a resource leak, every open [BLOB handle] should eventually
  6019. ** be released by a call to [sqlite3_blob_close()].
  6020. */
  6021. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  6022. sqlite3*,
  6023. const char *zDb,
  6024. const char *zTable,
  6025. const char *zColumn,
  6026. sqlite3_int64 iRow,
  6027. int flags,
  6028. sqlite3_blob **ppBlob
  6029. );
  6030. /*
  6031. ** CAPI3REF: Move a BLOB Handle to a New Row
  6032. ** METHOD: sqlite3_blob
  6033. **
  6034. ** ^This function is used to move an existing blob handle so that it points
  6035. ** to a different row of the same database table. ^The new row is identified
  6036. ** by the rowid value passed as the second argument. Only the row can be
  6037. ** changed. ^The database, table and column on which the blob handle is open
  6038. ** remain the same. Moving an existing blob handle to a new row can be
  6039. ** faster than closing the existing handle and opening a new one.
  6040. **
  6041. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  6042. ** it must exist and there must be either a blob or text value stored in
  6043. ** the nominated column.)^ ^If the new row is not present in the table, or if
  6044. ** it does not contain a blob or text value, or if another error occurs, an
  6045. ** SQLite error code is returned and the blob handle is considered aborted.
  6046. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  6047. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  6048. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  6049. ** always returns zero.
  6050. **
  6051. ** ^This function sets the database handle error code and message.
  6052. */
  6053. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  6054. /*
  6055. ** CAPI3REF: Close A BLOB Handle
  6056. ** DESTRUCTOR: sqlite3_blob
  6057. **
  6058. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  6059. ** unconditionally. Even if this routine returns an error code, the
  6060. ** handle is still closed.)^
  6061. **
  6062. ** ^If the blob handle being closed was opened for read-write access, and if
  6063. ** the database is in auto-commit mode and there are no other open read-write
  6064. ** blob handles or active write statements, the current transaction is
  6065. ** committed. ^If an error occurs while committing the transaction, an error
  6066. ** code is returned and the transaction rolled back.
  6067. **
  6068. ** Calling this function with an argument that is not a NULL pointer or an
  6069. ** open blob handle results in undefined behaviour. ^Calling this routine
  6070. ** with a null pointer (such as would be returned by a failed call to
  6071. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  6072. ** is passed a valid open blob handle, the values returned by the
  6073. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  6074. */
  6075. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
  6076. /*
  6077. ** CAPI3REF: Return The Size Of An Open BLOB
  6078. ** METHOD: sqlite3_blob
  6079. **
  6080. ** ^Returns the size in bytes of the BLOB accessible via the
  6081. ** successfully opened [BLOB handle] in its only argument. ^The
  6082. ** incremental blob I/O routines can only read or overwriting existing
  6083. ** blob content; they cannot change the size of a blob.
  6084. **
  6085. ** This routine only works on a [BLOB handle] which has been created
  6086. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6087. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6088. ** to this routine results in undefined and probably undesirable behavior.
  6089. */
  6090. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
  6091. /*
  6092. ** CAPI3REF: Read Data From A BLOB Incrementally
  6093. ** METHOD: sqlite3_blob
  6094. **
  6095. ** ^(This function is used to read data from an open [BLOB handle] into a
  6096. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  6097. ** from the open BLOB, starting at offset iOffset.)^
  6098. **
  6099. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6100. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  6101. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  6102. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  6103. ** can be determined using the [sqlite3_blob_bytes()] interface.
  6104. **
  6105. ** ^An attempt to read from an expired [BLOB handle] fails with an
  6106. ** error code of [SQLITE_ABORT].
  6107. **
  6108. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  6109. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6110. **
  6111. ** This routine only works on a [BLOB handle] which has been created
  6112. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6113. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6114. ** to this routine results in undefined and probably undesirable behavior.
  6115. **
  6116. ** See also: [sqlite3_blob_write()].
  6117. */
  6118. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  6119. /*
  6120. ** CAPI3REF: Write Data Into A BLOB Incrementally
  6121. ** METHOD: sqlite3_blob
  6122. **
  6123. ** ^(This function is used to write data into an open [BLOB handle] from a
  6124. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  6125. ** into the open BLOB, starting at offset iOffset.)^
  6126. **
  6127. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  6128. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6129. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  6130. ** [database connection] error code and message accessible via
  6131. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6132. **
  6133. ** ^If the [BLOB handle] passed as the first argument was not opened for
  6134. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  6135. ** this function returns [SQLITE_READONLY].
  6136. **
  6137. ** This function may only modify the contents of the BLOB; it is
  6138. ** not possible to increase the size of a BLOB using this API.
  6139. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6140. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  6141. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  6142. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  6143. ** than zero [SQLITE_ERROR] is returned and no data is written.
  6144. **
  6145. ** ^An attempt to write to an expired [BLOB handle] fails with an
  6146. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  6147. ** before the [BLOB handle] expired are not rolled back by the
  6148. ** expiration of the handle, though of course those changes might
  6149. ** have been overwritten by the statement that expired the BLOB handle
  6150. ** or by other independent statements.
  6151. **
  6152. ** This routine only works on a [BLOB handle] which has been created
  6153. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6154. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6155. ** to this routine results in undefined and probably undesirable behavior.
  6156. **
  6157. ** See also: [sqlite3_blob_read()].
  6158. */
  6159. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6160. /*
  6161. ** CAPI3REF: Virtual File System Objects
  6162. **
  6163. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6164. ** that SQLite uses to interact
  6165. ** with the underlying operating system. Most SQLite builds come with a
  6166. ** single default VFS that is appropriate for the host computer.
  6167. ** New VFSes can be registered and existing VFSes can be unregistered.
  6168. ** The following interfaces are provided.
  6169. **
  6170. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6171. ** ^Names are case sensitive.
  6172. ** ^Names are zero-terminated UTF-8 strings.
  6173. ** ^If there is no match, a NULL pointer is returned.
  6174. ** ^If zVfsName is NULL then the default VFS is returned.
  6175. **
  6176. ** ^New VFSes are registered with sqlite3_vfs_register().
  6177. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  6178. ** ^The same VFS can be registered multiple times without injury.
  6179. ** ^To make an existing VFS into the default VFS, register it again
  6180. ** with the makeDflt flag set. If two different VFSes with the
  6181. ** same name are registered, the behavior is undefined. If a
  6182. ** VFS is registered with a name that is NULL or an empty string,
  6183. ** then the behavior is undefined.
  6184. **
  6185. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6186. ** ^(If the default VFS is unregistered, another VFS is chosen as
  6187. ** the default. The choice for the new VFS is arbitrary.)^
  6188. */
  6189. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
  6190. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6191. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
  6192. /*
  6193. ** CAPI3REF: Mutexes
  6194. **
  6195. ** The SQLite core uses these routines for thread
  6196. ** synchronization. Though they are intended for internal
  6197. ** use by SQLite, code that links against SQLite is
  6198. ** permitted to use any of these routines.
  6199. **
  6200. ** The SQLite source code contains multiple implementations
  6201. ** of these mutex routines. An appropriate implementation
  6202. ** is selected automatically at compile-time. The following
  6203. ** implementations are available in the SQLite core:
  6204. **
  6205. ** <ul>
  6206. ** <li> SQLITE_MUTEX_PTHREADS
  6207. ** <li> SQLITE_MUTEX_W32
  6208. ** <li> SQLITE_MUTEX_NOOP
  6209. ** </ul>
  6210. **
  6211. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  6212. ** that does no real locking and is appropriate for use in
  6213. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  6214. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  6215. ** and Windows.
  6216. **
  6217. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6218. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6219. ** implementation is included with the library. In this case the
  6220. ** application must supply a custom mutex implementation using the
  6221. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6222. ** before calling sqlite3_initialize() or any other public sqlite3_
  6223. ** function that calls sqlite3_initialize().
  6224. **
  6225. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6226. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  6227. ** routine returns NULL if it is unable to allocate the requested
  6228. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  6229. ** integer constants:
  6230. **
  6231. ** <ul>
  6232. ** <li> SQLITE_MUTEX_FAST
  6233. ** <li> SQLITE_MUTEX_RECURSIVE
  6234. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6235. ** <li> SQLITE_MUTEX_STATIC_MEM
  6236. ** <li> SQLITE_MUTEX_STATIC_OPEN
  6237. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6238. ** <li> SQLITE_MUTEX_STATIC_LRU
  6239. ** <li> SQLITE_MUTEX_STATIC_PMEM
  6240. ** <li> SQLITE_MUTEX_STATIC_APP1
  6241. ** <li> SQLITE_MUTEX_STATIC_APP2
  6242. ** <li> SQLITE_MUTEX_STATIC_APP3
  6243. ** <li> SQLITE_MUTEX_STATIC_VFS1
  6244. ** <li> SQLITE_MUTEX_STATIC_VFS2
  6245. ** <li> SQLITE_MUTEX_STATIC_VFS3
  6246. ** </ul>
  6247. **
  6248. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6249. ** cause sqlite3_mutex_alloc() to create
  6250. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6251. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6252. ** The mutex implementation does not need to make a distinction
  6253. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6254. ** not want to. SQLite will only request a recursive mutex in
  6255. ** cases where it really needs one. If a faster non-recursive mutex
  6256. ** implementation is available on the host platform, the mutex subsystem
  6257. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6258. **
  6259. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6260. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6261. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  6262. ** used by the current version of SQLite. Future versions of SQLite
  6263. ** may add additional static mutexes. Static mutexes are for internal
  6264. ** use by SQLite only. Applications that use SQLite mutexes should
  6265. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6266. ** SQLITE_MUTEX_RECURSIVE.
  6267. **
  6268. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6269. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6270. ** returns a different mutex on every call. ^For the static
  6271. ** mutex types, the same mutex is returned on every call that has
  6272. ** the same type number.
  6273. **
  6274. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6275. ** allocated dynamic mutex. Attempting to deallocate a static
  6276. ** mutex results in undefined behavior.
  6277. **
  6278. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6279. ** to enter a mutex. ^If another thread is already within the mutex,
  6280. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6281. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6282. ** upon successful entry. ^(Mutexes created using
  6283. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6284. ** In such cases, the
  6285. ** mutex must be exited an equal number of times before another thread
  6286. ** can enter.)^ If the same thread tries to enter any mutex other
  6287. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  6288. **
  6289. ** ^(Some systems (for example, Windows 95) do not support the operation
  6290. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6291. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6292. ** sqlite3_mutex_try() as an optimization so this is acceptable
  6293. ** behavior.)^
  6294. **
  6295. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6296. ** previously entered by the same thread. The behavior
  6297. ** is undefined if the mutex is not currently entered by the
  6298. ** calling thread or is not currently allocated.
  6299. **
  6300. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6301. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6302. ** behave as no-ops.
  6303. **
  6304. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6305. */
  6306. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
  6307. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
  6308. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
  6309. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
  6310. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
  6311. /*
  6312. ** CAPI3REF: Mutex Methods Object
  6313. **
  6314. ** An instance of this structure defines the low-level routines
  6315. ** used to allocate and use mutexes.
  6316. **
  6317. ** Usually, the default mutex implementations provided by SQLite are
  6318. ** sufficient, however the application has the option of substituting a custom
  6319. ** implementation for specialized deployments or systems for which SQLite
  6320. ** does not provide a suitable implementation. In this case, the application
  6321. ** creates and populates an instance of this structure to pass
  6322. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6323. ** Additionally, an instance of this structure can be used as an
  6324. ** output variable when querying the system for the current mutex
  6325. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6326. **
  6327. ** ^The xMutexInit method defined by this structure is invoked as
  6328. ** part of system initialization by the sqlite3_initialize() function.
  6329. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6330. ** effective call to [sqlite3_initialize()].
  6331. **
  6332. ** ^The xMutexEnd method defined by this structure is invoked as
  6333. ** part of system shutdown by the sqlite3_shutdown() function. The
  6334. ** implementation of this method is expected to release all outstanding
  6335. ** resources obtained by the mutex methods implementation, especially
  6336. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6337. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6338. **
  6339. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6340. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6341. ** xMutexNotheld) implement the following interfaces (respectively):
  6342. **
  6343. ** <ul>
  6344. ** <li> [sqlite3_mutex_alloc()] </li>
  6345. ** <li> [sqlite3_mutex_free()] </li>
  6346. ** <li> [sqlite3_mutex_enter()] </li>
  6347. ** <li> [sqlite3_mutex_try()] </li>
  6348. ** <li> [sqlite3_mutex_leave()] </li>
  6349. ** <li> [sqlite3_mutex_held()] </li>
  6350. ** <li> [sqlite3_mutex_notheld()] </li>
  6351. ** </ul>)^
  6352. **
  6353. ** The only difference is that the public sqlite3_XXX functions enumerated
  6354. ** above silently ignore any invocations that pass a NULL pointer instead
  6355. ** of a valid mutex handle. The implementations of the methods defined
  6356. ** by this structure are not required to handle this case, the results
  6357. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6358. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6359. ** it is passed a NULL pointer).
  6360. **
  6361. ** The xMutexInit() method must be threadsafe. It must be harmless to
  6362. ** invoke xMutexInit() multiple times within the same process and without
  6363. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6364. ** xMutexInit() must be no-ops.
  6365. **
  6366. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6367. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  6368. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6369. ** memory allocation for a fast or recursive mutex.
  6370. **
  6371. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6372. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6373. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6374. ** prior to returning.
  6375. */
  6376. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6377. struct sqlite3_mutex_methods {
  6378. int (*xMutexInit)(void);
  6379. int (*xMutexEnd)(void);
  6380. sqlite3_mutex *(*xMutexAlloc)(int);
  6381. void (*xMutexFree)(sqlite3_mutex *);
  6382. void (*xMutexEnter)(sqlite3_mutex *);
  6383. int (*xMutexTry)(sqlite3_mutex *);
  6384. void (*xMutexLeave)(sqlite3_mutex *);
  6385. int (*xMutexHeld)(sqlite3_mutex *);
  6386. int (*xMutexNotheld)(sqlite3_mutex *);
  6387. };
  6388. /*
  6389. ** CAPI3REF: Mutex Verification Routines
  6390. **
  6391. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6392. ** are intended for use inside assert() statements. The SQLite core
  6393. ** never uses these routines except inside an assert() and applications
  6394. ** are advised to follow the lead of the core. The SQLite core only
  6395. ** provides implementations for these routines when it is compiled
  6396. ** with the SQLITE_DEBUG flag. External mutex implementations
  6397. ** are only required to provide these routines if SQLITE_DEBUG is
  6398. ** defined and if NDEBUG is not defined.
  6399. **
  6400. ** These routines should return true if the mutex in their argument
  6401. ** is held or not held, respectively, by the calling thread.
  6402. **
  6403. ** The implementation is not required to provide versions of these
  6404. ** routines that actually work. If the implementation does not provide working
  6405. ** versions of these routines, it should at least provide stubs that always
  6406. ** return true so that one does not get spurious assertion failures.
  6407. **
  6408. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  6409. ** the routine should return 1. This seems counter-intuitive since
  6410. ** clearly the mutex cannot be held if it does not exist. But
  6411. ** the reason the mutex does not exist is because the build is not
  6412. ** using mutexes. And we do not want the assert() containing the
  6413. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6414. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  6415. ** interface should also return 1 when given a NULL pointer.
  6416. */
  6417. #ifndef NDEBUG
  6418. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
  6419. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
  6420. #endif
  6421. /*
  6422. ** CAPI3REF: Mutex Types
  6423. **
  6424. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6425. ** which is one of these integer constants.
  6426. **
  6427. ** The set of static mutexes may change from one SQLite release to the
  6428. ** next. Applications that override the built-in mutex logic must be
  6429. ** prepared to accommodate additional static mutexes.
  6430. */
  6431. #define SQLITE_MUTEX_FAST 0
  6432. #define SQLITE_MUTEX_RECURSIVE 1
  6433. #define SQLITE_MUTEX_STATIC_MASTER 2
  6434. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6435. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6436. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6437. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6438. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6439. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6440. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6441. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6442. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6443. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6444. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  6445. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  6446. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  6447. /*
  6448. ** CAPI3REF: Retrieve the mutex for a database connection
  6449. ** METHOD: sqlite3
  6450. **
  6451. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6452. ** serializes access to the [database connection] given in the argument
  6453. ** when the [threading mode] is Serialized.
  6454. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6455. ** routine returns a NULL pointer.
  6456. */
  6457. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
  6458. /*
  6459. ** CAPI3REF: Low-Level Control Of Database Files
  6460. ** METHOD: sqlite3
  6461. **
  6462. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6463. ** xFileControl method for the [sqlite3_io_methods] object associated
  6464. ** with a particular database identified by the second argument. ^The
  6465. ** name of the database is "main" for the main database or "temp" for the
  6466. ** TEMP database, or the name that appears after the AS keyword for
  6467. ** databases that are added using the [ATTACH] SQL command.
  6468. ** ^A NULL pointer can be used in place of "main" to refer to the
  6469. ** main database file.
  6470. ** ^The third and fourth parameters to this routine
  6471. ** are passed directly through to the second and third parameters of
  6472. ** the xFileControl method. ^The return value of the xFileControl
  6473. ** method becomes the return value of this routine.
  6474. **
  6475. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6476. ** a pointer to the underlying [sqlite3_file] object to be written into
  6477. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6478. ** case is a short-circuit path which does not actually invoke the
  6479. ** underlying sqlite3_io_methods.xFileControl method.
  6480. **
  6481. ** ^If the second parameter (zDbName) does not match the name of any
  6482. ** open database file, then SQLITE_ERROR is returned. ^This error
  6483. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6484. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6485. ** also return SQLITE_ERROR. There is no way to distinguish between
  6486. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6487. ** xFileControl method.
  6488. **
  6489. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6490. */
  6491. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6492. /*
  6493. ** CAPI3REF: Testing Interface
  6494. **
  6495. ** ^The sqlite3_test_control() interface is used to read out internal
  6496. ** state of SQLite and to inject faults into SQLite for testing
  6497. ** purposes. ^The first parameter is an operation code that determines
  6498. ** the number, meaning, and operation of all subsequent parameters.
  6499. **
  6500. ** This interface is not for use by applications. It exists solely
  6501. ** for verifying the correct operation of the SQLite library. Depending
  6502. ** on how the SQLite library is compiled, this interface might not exist.
  6503. **
  6504. ** The details of the operation codes, their meanings, the parameters
  6505. ** they take, and what they do are all subject to change without notice.
  6506. ** Unlike most of the SQLite API, this function is not guaranteed to
  6507. ** operate consistently from one release to the next.
  6508. */
  6509. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
  6510. /*
  6511. ** CAPI3REF: Testing Interface Operation Codes
  6512. **
  6513. ** These constants are the valid operation code parameters used
  6514. ** as the first argument to [sqlite3_test_control()].
  6515. **
  6516. ** These parameters and their meanings are subject to change
  6517. ** without notice. These values are for testing purposes only.
  6518. ** Applications should not use any of these parameters or the
  6519. ** [sqlite3_test_control()] interface.
  6520. */
  6521. #define SQLITE_TESTCTRL_FIRST 5
  6522. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6523. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6524. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6525. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6526. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6527. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6528. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6529. #define SQLITE_TESTCTRL_ASSERT 12
  6530. #define SQLITE_TESTCTRL_ALWAYS 13
  6531. #define SQLITE_TESTCTRL_RESERVE 14
  6532. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6533. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6534. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6535. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6536. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6537. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6538. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6539. #define SQLITE_TESTCTRL_BYTEORDER 22
  6540. #define SQLITE_TESTCTRL_ISINIT 23
  6541. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6542. #define SQLITE_TESTCTRL_IMPOSTER 25
  6543. #define SQLITE_TESTCTRL_LAST 25
  6544. /*
  6545. ** CAPI3REF: SQLite Runtime Status
  6546. **
  6547. ** ^These interfaces are used to retrieve runtime status information
  6548. ** about the performance of SQLite, and optionally to reset various
  6549. ** highwater marks. ^The first argument is an integer code for
  6550. ** the specific parameter to measure. ^(Recognized integer codes
  6551. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6552. ** ^The current value of the parameter is returned into *pCurrent.
  6553. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6554. ** resetFlag is true, then the highest record value is reset after
  6555. ** *pHighwater is written. ^(Some parameters do not record the highest
  6556. ** value. For those parameters
  6557. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6558. ** ^(Other parameters record only the highwater mark and not the current
  6559. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6560. **
  6561. ** ^The sqlite3_status() and sqlite3_status64() routines return
  6562. ** SQLITE_OK on success and a non-zero [error code] on failure.
  6563. **
  6564. ** If either the current value or the highwater mark is too large to
  6565. ** be represented by a 32-bit integer, then the values returned by
  6566. ** sqlite3_status() are undefined.
  6567. **
  6568. ** See also: [sqlite3_db_status()]
  6569. */
  6570. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6571. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  6572. int op,
  6573. sqlite3_int64 *pCurrent,
  6574. sqlite3_int64 *pHighwater,
  6575. int resetFlag
  6576. );
  6577. /*
  6578. ** CAPI3REF: Status Parameters
  6579. ** KEYWORDS: {status parameters}
  6580. **
  6581. ** These integer constants designate various run-time status parameters
  6582. ** that can be returned by [sqlite3_status()].
  6583. **
  6584. ** <dl>
  6585. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6586. ** <dd>This parameter is the current amount of memory checked out
  6587. ** using [sqlite3_malloc()], either directly or indirectly. The
  6588. ** figure includes calls made to [sqlite3_malloc()] by the application
  6589. ** and internal memory usage by the SQLite library. Scratch memory
  6590. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6591. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6592. ** this parameter. The amount returned is the sum of the allocation
  6593. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6594. **
  6595. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6596. ** <dd>This parameter records the largest memory allocation request
  6597. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6598. ** internal equivalents). Only the value returned in the
  6599. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6600. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6601. **
  6602. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6603. ** <dd>This parameter records the number of separate memory allocations
  6604. ** currently checked out.</dd>)^
  6605. **
  6606. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6607. ** <dd>This parameter returns the number of pages used out of the
  6608. ** [pagecache memory allocator] that was configured using
  6609. ** [SQLITE_CONFIG_PAGECACHE]. The
  6610. ** value returned is in pages, not in bytes.</dd>)^
  6611. **
  6612. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6613. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6614. ** <dd>This parameter returns the number of bytes of page cache
  6615. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6616. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6617. ** returned value includes allocations that overflowed because they
  6618. ** where too large (they were larger than the "sz" parameter to
  6619. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6620. ** no space was left in the page cache.</dd>)^
  6621. **
  6622. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6623. ** <dd>This parameter records the largest memory allocation request
  6624. ** handed to [pagecache memory allocator]. Only the value returned in the
  6625. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6626. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6627. **
  6628. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6629. ** <dd>This parameter returns the number of allocations used out of the
  6630. ** [scratch memory allocator] configured using
  6631. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6632. ** in bytes. Since a single thread may only have one scratch allocation
  6633. ** outstanding at time, this parameter also reports the number of threads
  6634. ** using scratch memory at the same time.</dd>)^
  6635. **
  6636. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6637. ** <dd>This parameter returns the number of bytes of scratch memory
  6638. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6639. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6640. ** returned include overflows because the requested allocation was too
  6641. ** larger (that is, because the requested allocation was larger than the
  6642. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6643. ** slots were available.
  6644. ** </dd>)^
  6645. **
  6646. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6647. ** <dd>This parameter records the largest memory allocation request
  6648. ** handed to [scratch memory allocator]. Only the value returned in the
  6649. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6650. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6651. **
  6652. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6653. ** <dd>The *pHighwater parameter records the deepest parser stack.
  6654. ** The *pCurrent value is undefined. The *pHighwater value is only
  6655. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6656. ** </dl>
  6657. **
  6658. ** New status parameters may be added from time to time.
  6659. */
  6660. #define SQLITE_STATUS_MEMORY_USED 0
  6661. #define SQLITE_STATUS_PAGECACHE_USED 1
  6662. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6663. #define SQLITE_STATUS_SCRATCH_USED 3
  6664. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6665. #define SQLITE_STATUS_MALLOC_SIZE 5
  6666. #define SQLITE_STATUS_PARSER_STACK 6
  6667. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6668. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6669. #define SQLITE_STATUS_MALLOC_COUNT 9
  6670. /*
  6671. ** CAPI3REF: Database Connection Status
  6672. ** METHOD: sqlite3
  6673. **
  6674. ** ^This interface is used to retrieve runtime status information
  6675. ** about a single [database connection]. ^The first argument is the
  6676. ** database connection object to be interrogated. ^The second argument
  6677. ** is an integer constant, taken from the set of
  6678. ** [SQLITE_DBSTATUS options], that
  6679. ** determines the parameter to interrogate. The set of
  6680. ** [SQLITE_DBSTATUS options] is likely
  6681. ** to grow in future releases of SQLite.
  6682. **
  6683. ** ^The current value of the requested parameter is written into *pCur
  6684. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6685. ** the resetFlg is true, then the highest instantaneous value is
  6686. ** reset back down to the current value.
  6687. **
  6688. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6689. ** non-zero [error code] on failure.
  6690. **
  6691. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6692. */
  6693. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6694. /*
  6695. ** CAPI3REF: Status Parameters for database connections
  6696. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6697. **
  6698. ** These constants are the available integer "verbs" that can be passed as
  6699. ** the second argument to the [sqlite3_db_status()] interface.
  6700. **
  6701. ** New verbs may be added in future releases of SQLite. Existing verbs
  6702. ** might be discontinued. Applications should check the return code from
  6703. ** [sqlite3_db_status()] to make sure that the call worked.
  6704. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6705. ** if a discontinued or unsupported verb is invoked.
  6706. **
  6707. ** <dl>
  6708. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6709. ** <dd>This parameter returns the number of lookaside memory slots currently
  6710. ** checked out.</dd>)^
  6711. **
  6712. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6713. ** <dd>This parameter returns the number malloc attempts that were
  6714. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6715. ** the current value is always zero.)^
  6716. **
  6717. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6718. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6719. ** <dd>This parameter returns the number malloc attempts that might have
  6720. ** been satisfied using lookaside memory but failed due to the amount of
  6721. ** memory requested being larger than the lookaside slot size.
  6722. ** Only the high-water value is meaningful;
  6723. ** the current value is always zero.)^
  6724. **
  6725. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6726. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6727. ** <dd>This parameter returns the number malloc attempts that might have
  6728. ** been satisfied using lookaside memory but failed due to all lookaside
  6729. ** memory already being in use.
  6730. ** Only the high-water value is meaningful;
  6731. ** the current value is always zero.)^
  6732. **
  6733. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6734. ** <dd>This parameter returns the approximate number of bytes of heap
  6735. ** memory used by all pager caches associated with the database connection.)^
  6736. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6737. **
  6738. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6739. ** <dd>This parameter returns the approximate number of bytes of heap
  6740. ** memory used to store the schema for all databases associated
  6741. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6742. ** ^The full amount of memory used by the schemas is reported, even if the
  6743. ** schema memory is shared with other database connections due to
  6744. ** [shared cache mode] being enabled.
  6745. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6746. **
  6747. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6748. ** <dd>This parameter returns the approximate number of bytes of heap
  6749. ** and lookaside memory used by all prepared statements associated with
  6750. ** the database connection.)^
  6751. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6752. ** </dd>
  6753. **
  6754. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6755. ** <dd>This parameter returns the number of pager cache hits that have
  6756. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6757. ** is always 0.
  6758. ** </dd>
  6759. **
  6760. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6761. ** <dd>This parameter returns the number of pager cache misses that have
  6762. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6763. ** is always 0.
  6764. ** </dd>
  6765. **
  6766. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6767. ** <dd>This parameter returns the number of dirty cache entries that have
  6768. ** been written to disk. Specifically, the number of pages written to the
  6769. ** wal file in wal mode databases, or the number of pages written to the
  6770. ** database file in rollback mode databases. Any pages written as part of
  6771. ** transaction rollback or database recovery operations are not included.
  6772. ** If an IO or other error occurs while writing a page to disk, the effect
  6773. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6774. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6775. ** </dd>
  6776. **
  6777. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6778. ** <dd>This parameter returns zero for the current value if and only if
  6779. ** all foreign key constraints (deferred or immediate) have been
  6780. ** resolved.)^ ^The highwater mark is always 0.
  6781. ** </dd>
  6782. ** </dl>
  6783. */
  6784. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6785. #define SQLITE_DBSTATUS_CACHE_USED 1
  6786. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6787. #define SQLITE_DBSTATUS_STMT_USED 3
  6788. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6789. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6790. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6791. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6792. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6793. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6794. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6795. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6796. /*
  6797. ** CAPI3REF: Prepared Statement Status
  6798. ** METHOD: sqlite3_stmt
  6799. **
  6800. ** ^(Each prepared statement maintains various
  6801. ** [SQLITE_STMTSTATUS counters] that measure the number
  6802. ** of times it has performed specific operations.)^ These counters can
  6803. ** be used to monitor the performance characteristics of the prepared
  6804. ** statements. For example, if the number of table steps greatly exceeds
  6805. ** the number of table searches or result rows, that would tend to indicate
  6806. ** that the prepared statement is using a full table scan rather than
  6807. ** an index.
  6808. **
  6809. ** ^(This interface is used to retrieve and reset counter values from
  6810. ** a [prepared statement]. The first argument is the prepared statement
  6811. ** object to be interrogated. The second argument
  6812. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6813. ** to be interrogated.)^
  6814. ** ^The current value of the requested counter is returned.
  6815. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6816. ** interface call returns.
  6817. **
  6818. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6819. */
  6820. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6821. /*
  6822. ** CAPI3REF: Status Parameters for prepared statements
  6823. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6824. **
  6825. ** These preprocessor macros define integer codes that name counter
  6826. ** values associated with the [sqlite3_stmt_status()] interface.
  6827. ** The meanings of the various counters are as follows:
  6828. **
  6829. ** <dl>
  6830. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6831. ** <dd>^This is the number of times that SQLite has stepped forward in
  6832. ** a table as part of a full table scan. Large numbers for this counter
  6833. ** may indicate opportunities for performance improvement through
  6834. ** careful use of indices.</dd>
  6835. **
  6836. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6837. ** <dd>^This is the number of sort operations that have occurred.
  6838. ** A non-zero value in this counter may indicate an opportunity to
  6839. ** improvement performance through careful use of indices.</dd>
  6840. **
  6841. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6842. ** <dd>^This is the number of rows inserted into transient indices that
  6843. ** were created automatically in order to help joins run faster.
  6844. ** A non-zero value in this counter may indicate an opportunity to
  6845. ** improvement performance by adding permanent indices that do not
  6846. ** need to be reinitialized each time the statement is run.</dd>
  6847. **
  6848. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6849. ** <dd>^This is the number of virtual machine operations executed
  6850. ** by the prepared statement if that number is less than or equal
  6851. ** to 2147483647. The number of virtual machine operations can be
  6852. ** used as a proxy for the total work done by the prepared statement.
  6853. ** If the number of virtual machine operations exceeds 2147483647
  6854. ** then the value returned by this statement status code is undefined.
  6855. ** </dd>
  6856. ** </dl>
  6857. */
  6858. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6859. #define SQLITE_STMTSTATUS_SORT 2
  6860. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6861. #define SQLITE_STMTSTATUS_VM_STEP 4
  6862. /*
  6863. ** CAPI3REF: Custom Page Cache Object
  6864. **
  6865. ** The sqlite3_pcache type is opaque. It is implemented by
  6866. ** the pluggable module. The SQLite core has no knowledge of
  6867. ** its size or internal structure and never deals with the
  6868. ** sqlite3_pcache object except by holding and passing pointers
  6869. ** to the object.
  6870. **
  6871. ** See [sqlite3_pcache_methods2] for additional information.
  6872. */
  6873. typedef struct sqlite3_pcache sqlite3_pcache;
  6874. /*
  6875. ** CAPI3REF: Custom Page Cache Object
  6876. **
  6877. ** The sqlite3_pcache_page object represents a single page in the
  6878. ** page cache. The page cache will allocate instances of this
  6879. ** object. Various methods of the page cache use pointers to instances
  6880. ** of this object as parameters or as their return value.
  6881. **
  6882. ** See [sqlite3_pcache_methods2] for additional information.
  6883. */
  6884. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6885. struct sqlite3_pcache_page {
  6886. void *pBuf; /* The content of the page */
  6887. void *pExtra; /* Extra information associated with the page */
  6888. };
  6889. /*
  6890. ** CAPI3REF: Application Defined Page Cache.
  6891. ** KEYWORDS: {page cache}
  6892. **
  6893. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6894. ** register an alternative page cache implementation by passing in an
  6895. ** instance of the sqlite3_pcache_methods2 structure.)^
  6896. ** In many applications, most of the heap memory allocated by
  6897. ** SQLite is used for the page cache.
  6898. ** By implementing a
  6899. ** custom page cache using this API, an application can better control
  6900. ** the amount of memory consumed by SQLite, the way in which
  6901. ** that memory is allocated and released, and the policies used to
  6902. ** determine exactly which parts of a database file are cached and for
  6903. ** how long.
  6904. **
  6905. ** The alternative page cache mechanism is an
  6906. ** extreme measure that is only needed by the most demanding applications.
  6907. ** The built-in page cache is recommended for most uses.
  6908. **
  6909. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6910. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6911. ** the application may discard the parameter after the call to
  6912. ** [sqlite3_config()] returns.)^
  6913. **
  6914. ** [[the xInit() page cache method]]
  6915. ** ^(The xInit() method is called once for each effective
  6916. ** call to [sqlite3_initialize()])^
  6917. ** (usually only once during the lifetime of the process). ^(The xInit()
  6918. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6919. ** The intent of the xInit() method is to set up global data structures
  6920. ** required by the custom page cache implementation.
  6921. ** ^(If the xInit() method is NULL, then the
  6922. ** built-in default page cache is used instead of the application defined
  6923. ** page cache.)^
  6924. **
  6925. ** [[the xShutdown() page cache method]]
  6926. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6927. ** It can be used to clean up
  6928. ** any outstanding resources before process shutdown, if required.
  6929. ** ^The xShutdown() method may be NULL.
  6930. **
  6931. ** ^SQLite automatically serializes calls to the xInit method,
  6932. ** so the xInit method need not be threadsafe. ^The
  6933. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6934. ** not need to be threadsafe either. All other methods must be threadsafe
  6935. ** in multithreaded applications.
  6936. **
  6937. ** ^SQLite will never invoke xInit() more than once without an intervening
  6938. ** call to xShutdown().
  6939. **
  6940. ** [[the xCreate() page cache methods]]
  6941. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6942. ** SQLite will typically create one cache instance for each open database file,
  6943. ** though this is not guaranteed. ^The
  6944. ** first parameter, szPage, is the size in bytes of the pages that must
  6945. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6946. ** second parameter szExtra is a number of bytes of extra storage
  6947. ** associated with each page cache entry. ^The szExtra parameter will
  6948. ** a number less than 250. SQLite will use the
  6949. ** extra szExtra bytes on each page to store metadata about the underlying
  6950. ** database page on disk. The value passed into szExtra depends
  6951. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6952. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6953. ** created will be used to cache database pages of a file stored on disk, or
  6954. ** false if it is used for an in-memory database. The cache implementation
  6955. ** does not have to do anything special based with the value of bPurgeable;
  6956. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6957. ** never invoke xUnpin() except to deliberately delete a page.
  6958. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6959. ** false will always have the "discard" flag set to true.
  6960. ** ^Hence, a cache created with bPurgeable false will
  6961. ** never contain any unpinned pages.
  6962. **
  6963. ** [[the xCachesize() page cache method]]
  6964. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6965. ** suggested maximum cache-size (number of pages stored by) the cache
  6966. ** instance passed as the first argument. This is the value configured using
  6967. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6968. ** parameter, the implementation is not required to do anything with this
  6969. ** value; it is advisory only.
  6970. **
  6971. ** [[the xPagecount() page cache methods]]
  6972. ** The xPagecount() method must return the number of pages currently
  6973. ** stored in the cache, both pinned and unpinned.
  6974. **
  6975. ** [[the xFetch() page cache methods]]
  6976. ** The xFetch() method locates a page in the cache and returns a pointer to
  6977. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6978. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6979. ** pointer to a buffer of szPage bytes used to store the content of a
  6980. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6981. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6982. ** for each entry in the page cache.
  6983. **
  6984. ** The page to be fetched is determined by the key. ^The minimum key value
  6985. ** is 1. After it has been retrieved using xFetch, the page is considered
  6986. ** to be "pinned".
  6987. **
  6988. ** If the requested page is already in the page cache, then the page cache
  6989. ** implementation must return a pointer to the page buffer with its content
  6990. ** intact. If the requested page is not already in the cache, then the
  6991. ** cache implementation should use the value of the createFlag
  6992. ** parameter to help it determined what action to take:
  6993. **
  6994. ** <table border=1 width=85% align=center>
  6995. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6996. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6997. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6998. ** Otherwise return NULL.
  6999. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  7000. ** NULL if allocating a new page is effectively impossible.
  7001. ** </table>
  7002. **
  7003. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  7004. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  7005. ** failed.)^ In between the to xFetch() calls, SQLite may
  7006. ** attempt to unpin one or more cache pages by spilling the content of
  7007. ** pinned pages to disk and synching the operating system disk cache.
  7008. **
  7009. ** [[the xUnpin() page cache method]]
  7010. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  7011. ** as its second argument. If the third parameter, discard, is non-zero,
  7012. ** then the page must be evicted from the cache.
  7013. ** ^If the discard parameter is
  7014. ** zero, then the page may be discarded or retained at the discretion of
  7015. ** page cache implementation. ^The page cache implementation
  7016. ** may choose to evict unpinned pages at any time.
  7017. **
  7018. ** The cache must not perform any reference counting. A single
  7019. ** call to xUnpin() unpins the page regardless of the number of prior calls
  7020. ** to xFetch().
  7021. **
  7022. ** [[the xRekey() page cache methods]]
  7023. ** The xRekey() method is used to change the key value associated with the
  7024. ** page passed as the second argument. If the cache
  7025. ** previously contains an entry associated with newKey, it must be
  7026. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  7027. ** to be pinned.
  7028. **
  7029. ** When SQLite calls the xTruncate() method, the cache must discard all
  7030. ** existing cache entries with page numbers (keys) greater than or equal
  7031. ** to the value of the iLimit parameter passed to xTruncate(). If any
  7032. ** of these pages are pinned, they are implicitly unpinned, meaning that
  7033. ** they can be safely discarded.
  7034. **
  7035. ** [[the xDestroy() page cache method]]
  7036. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  7037. ** All resources associated with the specified cache should be freed. ^After
  7038. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  7039. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  7040. ** functions.
  7041. **
  7042. ** [[the xShrink() page cache method]]
  7043. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  7044. ** free up as much of heap memory as possible. The page cache implementation
  7045. ** is not obligated to free any memory, but well-behaved implementations should
  7046. ** do their best.
  7047. */
  7048. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  7049. struct sqlite3_pcache_methods2 {
  7050. int iVersion;
  7051. void *pArg;
  7052. int (*xInit)(void*);
  7053. void (*xShutdown)(void*);
  7054. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  7055. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7056. int (*xPagecount)(sqlite3_pcache*);
  7057. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7058. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  7059. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  7060. unsigned oldKey, unsigned newKey);
  7061. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7062. void (*xDestroy)(sqlite3_pcache*);
  7063. void (*xShrink)(sqlite3_pcache*);
  7064. };
  7065. /*
  7066. ** This is the obsolete pcache_methods object that has now been replaced
  7067. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  7068. ** retained in the header file for backwards compatibility only.
  7069. */
  7070. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  7071. struct sqlite3_pcache_methods {
  7072. void *pArg;
  7073. int (*xInit)(void*);
  7074. void (*xShutdown)(void*);
  7075. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  7076. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7077. int (*xPagecount)(sqlite3_pcache*);
  7078. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7079. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  7080. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  7081. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7082. void (*xDestroy)(sqlite3_pcache*);
  7083. };
  7084. /*
  7085. ** CAPI3REF: Online Backup Object
  7086. **
  7087. ** The sqlite3_backup object records state information about an ongoing
  7088. ** online backup operation. ^The sqlite3_backup object is created by
  7089. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  7090. ** [sqlite3_backup_finish()].
  7091. **
  7092. ** See Also: [Using the SQLite Online Backup API]
  7093. */
  7094. typedef struct sqlite3_backup sqlite3_backup;
  7095. /*
  7096. ** CAPI3REF: Online Backup API.
  7097. **
  7098. ** The backup API copies the content of one database into another.
  7099. ** It is useful either for creating backups of databases or
  7100. ** for copying in-memory databases to or from persistent files.
  7101. **
  7102. ** See Also: [Using the SQLite Online Backup API]
  7103. **
  7104. ** ^SQLite holds a write transaction open on the destination database file
  7105. ** for the duration of the backup operation.
  7106. ** ^The source database is read-locked only while it is being read;
  7107. ** it is not locked continuously for the entire backup operation.
  7108. ** ^Thus, the backup may be performed on a live source database without
  7109. ** preventing other database connections from
  7110. ** reading or writing to the source database while the backup is underway.
  7111. **
  7112. ** ^(To perform a backup operation:
  7113. ** <ol>
  7114. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  7115. ** backup,
  7116. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  7117. ** the data between the two databases, and finally
  7118. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  7119. ** associated with the backup operation.
  7120. ** </ol>)^
  7121. ** There should be exactly one call to sqlite3_backup_finish() for each
  7122. ** successful call to sqlite3_backup_init().
  7123. **
  7124. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  7125. **
  7126. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  7127. ** [database connection] associated with the destination database
  7128. ** and the database name, respectively.
  7129. ** ^The database name is "main" for the main database, "temp" for the
  7130. ** temporary database, or the name specified after the AS keyword in
  7131. ** an [ATTACH] statement for an attached database.
  7132. ** ^The S and M arguments passed to
  7133. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  7134. ** and database name of the source database, respectively.
  7135. ** ^The source and destination [database connections] (parameters S and D)
  7136. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  7137. ** an error.
  7138. **
  7139. ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
  7140. ** there is already a read or read-write transaction open on the
  7141. ** destination database.
  7142. **
  7143. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  7144. ** returned and an error code and error message are stored in the
  7145. ** destination [database connection] D.
  7146. ** ^The error code and message for the failed call to sqlite3_backup_init()
  7147. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  7148. ** [sqlite3_errmsg16()] functions.
  7149. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  7150. ** [sqlite3_backup] object.
  7151. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  7152. ** sqlite3_backup_finish() functions to perform the specified backup
  7153. ** operation.
  7154. **
  7155. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  7156. **
  7157. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  7158. ** the source and destination databases specified by [sqlite3_backup] object B.
  7159. ** ^If N is negative, all remaining source pages are copied.
  7160. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  7161. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  7162. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  7163. ** from source to destination, then it returns [SQLITE_DONE].
  7164. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  7165. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  7166. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  7167. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  7168. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  7169. **
  7170. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  7171. ** <ol>
  7172. ** <li> the destination database was opened read-only, or
  7173. ** <li> the destination database is using write-ahead-log journaling
  7174. ** and the destination and source page sizes differ, or
  7175. ** <li> the destination database is an in-memory database and the
  7176. ** destination and source page sizes differ.
  7177. ** </ol>)^
  7178. **
  7179. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  7180. ** the [sqlite3_busy_handler | busy-handler function]
  7181. ** is invoked (if one is specified). ^If the
  7182. ** busy-handler returns non-zero before the lock is available, then
  7183. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  7184. ** sqlite3_backup_step() can be retried later. ^If the source
  7185. ** [database connection]
  7186. ** is being used to write to the source database when sqlite3_backup_step()
  7187. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  7188. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  7189. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  7190. ** [SQLITE_READONLY] is returned, then
  7191. ** there is no point in retrying the call to sqlite3_backup_step(). These
  7192. ** errors are considered fatal.)^ The application must accept
  7193. ** that the backup operation has failed and pass the backup operation handle
  7194. ** to the sqlite3_backup_finish() to release associated resources.
  7195. **
  7196. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  7197. ** on the destination file. ^The exclusive lock is not released until either
  7198. ** sqlite3_backup_finish() is called or the backup operation is complete
  7199. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  7200. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  7201. ** lasts for the duration of the sqlite3_backup_step() call.
  7202. ** ^Because the source database is not locked between calls to
  7203. ** sqlite3_backup_step(), the source database may be modified mid-way
  7204. ** through the backup process. ^If the source database is modified by an
  7205. ** external process or via a database connection other than the one being
  7206. ** used by the backup operation, then the backup will be automatically
  7207. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  7208. ** database is modified by the using the same database connection as is used
  7209. ** by the backup operation, then the backup database is automatically
  7210. ** updated at the same time.
  7211. **
  7212. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  7213. **
  7214. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  7215. ** application wishes to abandon the backup operation, the application
  7216. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  7217. ** ^The sqlite3_backup_finish() interfaces releases all
  7218. ** resources associated with the [sqlite3_backup] object.
  7219. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  7220. ** active write-transaction on the destination database is rolled back.
  7221. ** The [sqlite3_backup] object is invalid
  7222. ** and may not be used following a call to sqlite3_backup_finish().
  7223. **
  7224. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  7225. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  7226. ** sqlite3_backup_step() completed.
  7227. ** ^If an out-of-memory condition or IO error occurred during any prior
  7228. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  7229. ** sqlite3_backup_finish() returns the corresponding [error code].
  7230. **
  7231. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  7232. ** is not a permanent error and does not affect the return value of
  7233. ** sqlite3_backup_finish().
  7234. **
  7235. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  7236. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  7237. **
  7238. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  7239. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  7240. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  7241. ** in the source database at the conclusion of the most recent
  7242. ** sqlite3_backup_step().
  7243. ** ^(The values returned by these functions are only updated by
  7244. ** sqlite3_backup_step(). If the source database is modified in a way that
  7245. ** changes the size of the source database or the number of pages remaining,
  7246. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  7247. ** and sqlite3_backup_remaining() until after the next
  7248. ** sqlite3_backup_step().)^
  7249. **
  7250. ** <b>Concurrent Usage of Database Handles</b>
  7251. **
  7252. ** ^The source [database connection] may be used by the application for other
  7253. ** purposes while a backup operation is underway or being initialized.
  7254. ** ^If SQLite is compiled and configured to support threadsafe database
  7255. ** connections, then the source database connection may be used concurrently
  7256. ** from within other threads.
  7257. **
  7258. ** However, the application must guarantee that the destination
  7259. ** [database connection] is not passed to any other API (by any thread) after
  7260. ** sqlite3_backup_init() is called and before the corresponding call to
  7261. ** sqlite3_backup_finish(). SQLite does not currently check to see
  7262. ** if the application incorrectly accesses the destination [database connection]
  7263. ** and so no error code is reported, but the operations may malfunction
  7264. ** nevertheless. Use of the destination database connection while a
  7265. ** backup is in progress might also also cause a mutex deadlock.
  7266. **
  7267. ** If running in [shared cache mode], the application must
  7268. ** guarantee that the shared cache used by the destination database
  7269. ** is not accessed while the backup is running. In practice this means
  7270. ** that the application must guarantee that the disk file being
  7271. ** backed up to is not accessed by any connection within the process,
  7272. ** not just the specific connection that was passed to sqlite3_backup_init().
  7273. **
  7274. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7275. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7276. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7277. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7278. ** same time as another thread is invoking sqlite3_backup_step() it is
  7279. ** possible that they return invalid values.
  7280. */
  7281. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  7282. sqlite3 *pDest, /* Destination database handle */
  7283. const char *zDestName, /* Destination database name */
  7284. sqlite3 *pSource, /* Source database handle */
  7285. const char *zSourceName /* Source database name */
  7286. );
  7287. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7288. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
  7289. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
  7290. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
  7291. /*
  7292. ** CAPI3REF: Unlock Notification
  7293. ** METHOD: sqlite3
  7294. **
  7295. ** ^When running in shared-cache mode, a database operation may fail with
  7296. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7297. ** individual tables within the shared-cache cannot be obtained. See
  7298. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7299. ** ^This API may be used to register a callback that SQLite will invoke
  7300. ** when the connection currently holding the required lock relinquishes it.
  7301. ** ^This API is only available if the library was compiled with the
  7302. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7303. **
  7304. ** See Also: [Using the SQLite Unlock Notification Feature].
  7305. **
  7306. ** ^Shared-cache locks are released when a database connection concludes
  7307. ** its current transaction, either by committing it or rolling it back.
  7308. **
  7309. ** ^When a connection (known as the blocked connection) fails to obtain a
  7310. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7311. ** identity of the database connection (the blocking connection) that
  7312. ** has locked the required resource is stored internally. ^After an
  7313. ** application receives an SQLITE_LOCKED error, it may call the
  7314. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7315. ** the first argument to register for a callback that will be invoked
  7316. ** when the blocking connections current transaction is concluded. ^The
  7317. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7318. ** call that concludes the blocking connections transaction.
  7319. **
  7320. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7321. ** there is a chance that the blocking connection will have already
  7322. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7323. ** If this happens, then the specified callback is invoked immediately,
  7324. ** from within the call to sqlite3_unlock_notify().)^
  7325. **
  7326. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7327. ** shared-cache table, and more than one other connection currently holds
  7328. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7329. ** the other connections to use as the blocking connection.
  7330. **
  7331. ** ^(There may be at most one unlock-notify callback registered by a
  7332. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7333. ** blocked connection already has a registered unlock-notify callback,
  7334. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7335. ** called with a NULL pointer as its second argument, then any existing
  7336. ** unlock-notify callback is canceled. ^The blocked connections
  7337. ** unlock-notify callback may also be canceled by closing the blocked
  7338. ** connection using [sqlite3_close()].
  7339. **
  7340. ** The unlock-notify callback is not reentrant. If an application invokes
  7341. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7342. ** crash or deadlock may be the result.
  7343. **
  7344. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7345. ** returns SQLITE_OK.
  7346. **
  7347. ** <b>Callback Invocation Details</b>
  7348. **
  7349. ** When an unlock-notify callback is registered, the application provides a
  7350. ** single void* pointer that is passed to the callback when it is invoked.
  7351. ** However, the signature of the callback function allows SQLite to pass
  7352. ** it an array of void* context pointers. The first argument passed to
  7353. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7354. ** and the second is the number of entries in the array.
  7355. **
  7356. ** When a blocking connections transaction is concluded, there may be
  7357. ** more than one blocked connection that has registered for an unlock-notify
  7358. ** callback. ^If two or more such blocked connections have specified the
  7359. ** same callback function, then instead of invoking the callback function
  7360. ** multiple times, it is invoked once with the set of void* context pointers
  7361. ** specified by the blocked connections bundled together into an array.
  7362. ** This gives the application an opportunity to prioritize any actions
  7363. ** related to the set of unblocked database connections.
  7364. **
  7365. ** <b>Deadlock Detection</b>
  7366. **
  7367. ** Assuming that after registering for an unlock-notify callback a
  7368. ** database waits for the callback to be issued before taking any further
  7369. ** action (a reasonable assumption), then using this API may cause the
  7370. ** application to deadlock. For example, if connection X is waiting for
  7371. ** connection Y's transaction to be concluded, and similarly connection
  7372. ** Y is waiting on connection X's transaction, then neither connection
  7373. ** will proceed and the system may remain deadlocked indefinitely.
  7374. **
  7375. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7376. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7377. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7378. ** unlock-notify callback is registered. The system is said to be in
  7379. ** a deadlocked state if connection A has registered for an unlock-notify
  7380. ** callback on the conclusion of connection B's transaction, and connection
  7381. ** B has itself registered for an unlock-notify callback when connection
  7382. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7383. ** the system is also considered to be deadlocked if connection B has
  7384. ** registered for an unlock-notify callback on the conclusion of connection
  7385. ** C's transaction, where connection C is waiting on connection A. ^Any
  7386. ** number of levels of indirection are allowed.
  7387. **
  7388. ** <b>The "DROP TABLE" Exception</b>
  7389. **
  7390. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7391. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7392. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7393. ** SQLite checks if there are any currently executing SELECT statements
  7394. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7395. ** returned. In this case there is no "blocking connection", so invoking
  7396. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7397. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7398. ** or "DROP INDEX" query, an infinite loop might be the result.
  7399. **
  7400. ** One way around this problem is to check the extended error code returned
  7401. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7402. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7403. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7404. ** SQLITE_LOCKED.)^
  7405. */
  7406. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  7407. sqlite3 *pBlocked, /* Waiting connection */
  7408. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7409. void *pNotifyArg /* Argument to pass to xNotify */
  7410. );
  7411. /*
  7412. ** CAPI3REF: String Comparison
  7413. **
  7414. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7415. ** and extensions to compare the contents of two buffers containing UTF-8
  7416. ** strings in a case-independent fashion, using the same definition of "case
  7417. ** independence" that SQLite uses internally when comparing identifiers.
  7418. */
  7419. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
  7420. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
  7421. /*
  7422. ** CAPI3REF: String Globbing
  7423. *
  7424. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  7425. ** string X matches the [GLOB] pattern P.
  7426. ** ^The definition of [GLOB] pattern matching used in
  7427. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7428. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  7429. ** is case sensitive.
  7430. **
  7431. ** Note that this routine returns zero on a match and non-zero if the strings
  7432. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7433. **
  7434. ** See also: [sqlite3_strlike()].
  7435. */
  7436. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
  7437. /*
  7438. ** CAPI3REF: String LIKE Matching
  7439. *
  7440. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  7441. ** string X matches the [LIKE] pattern P with escape character E.
  7442. ** ^The definition of [LIKE] pattern matching used in
  7443. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  7444. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  7445. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  7446. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  7447. ** insensitive - equivalent upper and lower case ASCII characters match
  7448. ** one another.
  7449. **
  7450. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  7451. ** only ASCII characters are case folded.
  7452. **
  7453. ** Note that this routine returns zero on a match and non-zero if the strings
  7454. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7455. **
  7456. ** See also: [sqlite3_strglob()].
  7457. */
  7458. SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  7459. /*
  7460. ** CAPI3REF: Error Logging Interface
  7461. **
  7462. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7463. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7464. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7465. ** used with [sqlite3_snprintf()] to generate the final output string.
  7466. **
  7467. ** The sqlite3_log() interface is intended for use by extensions such as
  7468. ** virtual tables, collating functions, and SQL functions. While there is
  7469. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7470. ** is considered bad form.
  7471. **
  7472. ** The zFormat string must not be NULL.
  7473. **
  7474. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7475. ** will not use dynamically allocated memory. The log message is stored in
  7476. ** a fixed-length buffer on the stack. If the log message is longer than
  7477. ** a few hundred characters, it will be truncated to the length of the
  7478. ** buffer.
  7479. */
  7480. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
  7481. /*
  7482. ** CAPI3REF: Write-Ahead Log Commit Hook
  7483. ** METHOD: sqlite3
  7484. **
  7485. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7486. ** is invoked each time data is committed to a database in wal mode.
  7487. **
  7488. ** ^(The callback is invoked by SQLite after the commit has taken place and
  7489. ** the associated write-lock on the database released)^, so the implementation
  7490. ** may read, write or [checkpoint] the database as required.
  7491. **
  7492. ** ^The first parameter passed to the callback function when it is invoked
  7493. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7494. ** registering the callback. ^The second is a copy of the database handle.
  7495. ** ^The third parameter is the name of the database that was written to -
  7496. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7497. ** is the number of pages currently in the write-ahead log file,
  7498. ** including those that were just committed.
  7499. **
  7500. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7501. ** code is returned, that error will propagate back up through the
  7502. ** SQLite code base to cause the statement that provoked the callback
  7503. ** to report an error, though the commit will have still occurred. If the
  7504. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7505. ** that does not correspond to any valid SQLite error code, the results
  7506. ** are undefined.
  7507. **
  7508. ** A single database handle may have at most a single write-ahead log callback
  7509. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7510. ** previously registered write-ahead log callback. ^Note that the
  7511. ** [sqlite3_wal_autocheckpoint()] interface and the
  7512. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7513. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  7514. */
  7515. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  7516. sqlite3*,
  7517. int(*)(void *,sqlite3*,const char*,int),
  7518. void*
  7519. );
  7520. /*
  7521. ** CAPI3REF: Configure an auto-checkpoint
  7522. ** METHOD: sqlite3
  7523. **
  7524. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7525. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7526. ** to automatically [checkpoint]
  7527. ** after committing a transaction if there are N or
  7528. ** more frames in the [write-ahead log] file. ^Passing zero or
  7529. ** a negative value as the nFrame parameter disables automatic
  7530. ** checkpoints entirely.
  7531. **
  7532. ** ^The callback registered by this function replaces any existing callback
  7533. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7534. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7535. ** configured by this function.
  7536. **
  7537. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7538. ** from SQL.
  7539. **
  7540. ** ^Checkpoints initiated by this mechanism are
  7541. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7542. **
  7543. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7544. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7545. ** pages. The use of this interface
  7546. ** is only necessary if the default setting is found to be suboptimal
  7547. ** for a particular application.
  7548. */
  7549. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7550. /*
  7551. ** CAPI3REF: Checkpoint a database
  7552. ** METHOD: sqlite3
  7553. **
  7554. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  7555. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  7556. **
  7557. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  7558. ** [write-ahead log] for database X on [database connection] D to be
  7559. ** transferred into the database file and for the write-ahead log to
  7560. ** be reset. See the [checkpointing] documentation for addition
  7561. ** information.
  7562. **
  7563. ** This interface used to be the only way to cause a checkpoint to
  7564. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  7565. ** interface was added. This interface is retained for backwards
  7566. ** compatibility and as a convenience for applications that need to manually
  7567. ** start a callback but which do not need the full power (and corresponding
  7568. ** complication) of [sqlite3_wal_checkpoint_v2()].
  7569. */
  7570. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7571. /*
  7572. ** CAPI3REF: Checkpoint a database
  7573. ** METHOD: sqlite3
  7574. **
  7575. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  7576. ** operation on database X of [database connection] D in mode M. Status
  7577. ** information is written back into integers pointed to by L and C.)^
  7578. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  7579. **
  7580. ** <dl>
  7581. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7582. ** ^Checkpoint as many frames as possible without waiting for any database
  7583. ** readers or writers to finish, then sync the database file if all frames
  7584. ** in the log were checkpointed. ^The [busy-handler callback]
  7585. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  7586. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  7587. ** if there are concurrent readers or writers.
  7588. **
  7589. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7590. ** ^This mode blocks (it invokes the
  7591. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7592. ** database writer and all readers are reading from the most recent database
  7593. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  7594. ** database file. ^This mode blocks new database writers while it is pending,
  7595. ** but new database readers are allowed to continue unimpeded.
  7596. **
  7597. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7598. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  7599. ** that after checkpointing the log file it blocks (calls the
  7600. ** [busy-handler callback])
  7601. ** until all readers are reading from the database file only. ^This ensures
  7602. ** that the next writer will restart the log file from the beginning.
  7603. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  7604. ** database writer attempts while it is pending, but does not impede readers.
  7605. **
  7606. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  7607. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  7608. ** addition that it also truncates the log file to zero bytes just prior
  7609. ** to a successful return.
  7610. ** </dl>
  7611. **
  7612. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7613. ** the log file or to -1 if the checkpoint could not run because
  7614. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  7615. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  7616. ** log file (including any that were already checkpointed before the function
  7617. ** was called) or to -1 if the checkpoint could not run due to an error or
  7618. ** because the database is not in WAL mode. ^Note that upon successful
  7619. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  7620. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  7621. **
  7622. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  7623. ** any other process is running a checkpoint operation at the same time, the
  7624. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  7625. ** busy-handler configured, it will not be invoked in this case.
  7626. **
  7627. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  7628. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  7629. ** obtained immediately, and a busy-handler is configured, it is invoked and
  7630. ** the writer lock retried until either the busy-handler returns 0 or the lock
  7631. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  7632. ** database readers as described above. ^If the busy-handler returns 0 before
  7633. ** the writer lock is obtained or while waiting for database readers, the
  7634. ** checkpoint operation proceeds from that point in the same way as
  7635. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7636. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  7637. **
  7638. ** ^If parameter zDb is NULL or points to a zero length string, then the
  7639. ** specified operation is attempted on all WAL databases [attached] to
  7640. ** [database connection] db. In this case the
  7641. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  7642. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7643. ** attached WAL databases, the operation is still attempted on any remaining
  7644. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  7645. ** error occurs while processing an attached database, processing is abandoned
  7646. ** and the error code is returned to the caller immediately. ^If no error
  7647. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7648. ** databases, SQLITE_OK is returned.
  7649. **
  7650. ** ^If database zDb is the name of an attached database that is not in WAL
  7651. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  7652. ** zDb is not NULL (or a zero length string) and is not the name of any
  7653. ** attached database, SQLITE_ERROR is returned to the caller.
  7654. **
  7655. ** ^Unless it returns SQLITE_MISUSE,
  7656. ** the sqlite3_wal_checkpoint_v2() interface
  7657. ** sets the error information that is queried by
  7658. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  7659. **
  7660. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  7661. ** from SQL.
  7662. */
  7663. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  7664. sqlite3 *db, /* Database handle */
  7665. const char *zDb, /* Name of attached database (or NULL) */
  7666. int eMode, /* SQLITE_CHECKPOINT_* value */
  7667. int *pnLog, /* OUT: Size of WAL log in frames */
  7668. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7669. );
  7670. /*
  7671. ** CAPI3REF: Checkpoint Mode Values
  7672. ** KEYWORDS: {checkpoint mode}
  7673. **
  7674. ** These constants define all valid values for the "checkpoint mode" passed
  7675. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  7676. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  7677. ** meaning of each of these checkpoint modes.
  7678. */
  7679. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  7680. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  7681. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  7682. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  7683. /*
  7684. ** CAPI3REF: Virtual Table Interface Configuration
  7685. **
  7686. ** This function may be called by either the [xConnect] or [xCreate] method
  7687. ** of a [virtual table] implementation to configure
  7688. ** various facets of the virtual table interface.
  7689. **
  7690. ** If this interface is invoked outside the context of an xConnect or
  7691. ** xCreate virtual table method then the behavior is undefined.
  7692. **
  7693. ** At present, there is only one option that may be configured using
  7694. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7695. ** may be added in the future.
  7696. */
  7697. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
  7698. /*
  7699. ** CAPI3REF: Virtual Table Configuration Options
  7700. **
  7701. ** These macros define the various options to the
  7702. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7703. ** can use to customize and optimize their behavior.
  7704. **
  7705. ** <dl>
  7706. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7707. ** <dd>Calls of the form
  7708. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7709. ** where X is an integer. If X is zero, then the [virtual table] whose
  7710. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7711. ** support constraints. In this configuration (which is the default) if
  7712. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7713. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7714. ** specified as part of the users SQL statement, regardless of the actual
  7715. ** ON CONFLICT mode specified.
  7716. **
  7717. ** If X is non-zero, then the virtual table implementation guarantees
  7718. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7719. ** any modifications to internal or persistent data structures have been made.
  7720. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7721. ** is able to roll back a statement or database transaction, and abandon
  7722. ** or continue processing the current SQL statement as appropriate.
  7723. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7724. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7725. ** had been ABORT.
  7726. **
  7727. ** Virtual table implementations that are required to handle OR REPLACE
  7728. ** must do so within the [xUpdate] method. If a call to the
  7729. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7730. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7731. ** silently replace the appropriate rows within the xUpdate callback and
  7732. ** return SQLITE_OK. Or, if this is not possible, it may return
  7733. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7734. ** constraint handling.
  7735. ** </dl>
  7736. */
  7737. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7738. /*
  7739. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7740. **
  7741. ** This function may only be called from within a call to the [xUpdate] method
  7742. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7743. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7744. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7745. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7746. ** [virtual table].
  7747. */
  7748. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
  7749. /*
  7750. ** CAPI3REF: Conflict resolution modes
  7751. ** KEYWORDS: {conflict resolution mode}
  7752. **
  7753. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7754. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7755. ** is for the SQL statement being evaluated.
  7756. **
  7757. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7758. ** return value from the [sqlite3_set_authorizer()] callback and that
  7759. ** [SQLITE_ABORT] is also a [result code].
  7760. */
  7761. #define SQLITE_ROLLBACK 1
  7762. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7763. #define SQLITE_FAIL 3
  7764. /* #define SQLITE_ABORT 4 // Also an error code */
  7765. #define SQLITE_REPLACE 5
  7766. /*
  7767. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  7768. ** KEYWORDS: {scanstatus options}
  7769. **
  7770. ** The following constants can be used for the T parameter to the
  7771. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  7772. ** different metric for sqlite3_stmt_scanstatus() to return.
  7773. **
  7774. ** When the value returned to V is a string, space to hold that string is
  7775. ** managed by the prepared statement S and will be automatically freed when
  7776. ** S is finalized.
  7777. **
  7778. ** <dl>
  7779. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  7780. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  7781. ** set to the total number of times that the X-th loop has run.</dd>
  7782. **
  7783. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  7784. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  7785. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  7786. **
  7787. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  7788. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  7789. ** query planner's estimate for the average number of rows output from each
  7790. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  7791. ** then this value will approximate the quotient NVISIT/NLOOP and the
  7792. ** product of this value for all prior loops with the same SELECTID will
  7793. ** be the NLOOP value for the current loop.
  7794. **
  7795. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  7796. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7797. ** to a zero-terminated UTF-8 string containing the name of the index or table
  7798. ** used for the X-th loop.
  7799. **
  7800. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  7801. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7802. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  7803. ** description for the X-th loop.
  7804. **
  7805. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  7806. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  7807. ** "select-id" for the X-th loop. The select-id identifies which query or
  7808. ** subquery the loop is part of. The main query has a select-id of zero.
  7809. ** The select-id is the same value as is output in the first column
  7810. ** of an [EXPLAIN QUERY PLAN] query.
  7811. ** </dl>
  7812. */
  7813. #define SQLITE_SCANSTAT_NLOOP 0
  7814. #define SQLITE_SCANSTAT_NVISIT 1
  7815. #define SQLITE_SCANSTAT_EST 2
  7816. #define SQLITE_SCANSTAT_NAME 3
  7817. #define SQLITE_SCANSTAT_EXPLAIN 4
  7818. #define SQLITE_SCANSTAT_SELECTID 5
  7819. /*
  7820. ** CAPI3REF: Prepared Statement Scan Status
  7821. ** METHOD: sqlite3_stmt
  7822. **
  7823. ** This interface returns information about the predicted and measured
  7824. ** performance for pStmt. Advanced applications can use this
  7825. ** interface to compare the predicted and the measured performance and
  7826. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  7827. **
  7828. ** Since this interface is expected to be rarely used, it is only
  7829. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  7830. ** compile-time option.
  7831. **
  7832. ** The "iScanStatusOp" parameter determines which status information to return.
  7833. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  7834. ** of this interface is undefined.
  7835. ** ^The requested measurement is written into a variable pointed to by
  7836. ** the "pOut" parameter.
  7837. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  7838. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  7839. ** zero or greater than or equal to the total number of loops used to implement
  7840. ** the statement - a non-zero value is returned and the variable that pOut
  7841. ** points to is unchanged.
  7842. **
  7843. ** ^Statistics might not be available for all loops in all statements. ^In cases
  7844. ** where there exist loops with no available statistics, this function behaves
  7845. ** as if the loop did not exist - it returns non-zero and leave the variable
  7846. ** that pOut points to unchanged.
  7847. **
  7848. ** See also: [sqlite3_stmt_scanstatus_reset()]
  7849. */
  7850. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  7851. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  7852. int idx, /* Index of loop to report on */
  7853. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  7854. void *pOut /* Result written here */
  7855. );
  7856. /*
  7857. ** CAPI3REF: Zero Scan-Status Counters
  7858. ** METHOD: sqlite3_stmt
  7859. **
  7860. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  7861. **
  7862. ** This API is only available if the library is built with pre-processor
  7863. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  7864. */
  7865. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  7866. /*
  7867. ** CAPI3REF: Flush caches to disk mid-transaction
  7868. **
  7869. ** ^If a write-transaction is open on [database connection] D when the
  7870. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  7871. ** pages in the pager-cache that are not currently in use are written out
  7872. ** to disk. A dirty page may be in use if a database cursor created by an
  7873. ** active SQL statement is reading from it, or if it is page 1 of a database
  7874. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  7875. ** interface flushes caches for all schemas - "main", "temp", and
  7876. ** any [attached] databases.
  7877. **
  7878. ** ^If this function needs to obtain extra database locks before dirty pages
  7879. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  7880. ** immediately and there is a busy-handler callback configured, it is invoked
  7881. ** in the usual manner. ^If the required lock still cannot be obtained, then
  7882. ** the database is skipped and an attempt made to flush any dirty pages
  7883. ** belonging to the next (if any) database. ^If any databases are skipped
  7884. ** because locks cannot be obtained, but no other error occurs, this
  7885. ** function returns SQLITE_BUSY.
  7886. **
  7887. ** ^If any other error occurs while flushing dirty pages to disk (for
  7888. ** example an IO error or out-of-memory condition), then processing is
  7889. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  7890. **
  7891. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  7892. **
  7893. ** ^This function does not set the database handle error code or message
  7894. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  7895. */
  7896. SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
  7897. /*
  7898. ** CAPI3REF: Database Snapshot
  7899. ** KEYWORDS: {snapshot}
  7900. ** EXPERIMENTAL
  7901. **
  7902. ** An instance of the snapshot object records the state of a [WAL mode]
  7903. ** database for some specific point in history.
  7904. **
  7905. ** In [WAL mode], multiple [database connections] that are open on the
  7906. ** same database file can each be reading a different historical version
  7907. ** of the database file. When a [database connection] begins a read
  7908. ** transaction, that connection sees an unchanging copy of the database
  7909. ** as it existed for the point in time when the transaction first started.
  7910. ** Subsequent changes to the database from other connections are not seen
  7911. ** by the reader until a new read transaction is started.
  7912. **
  7913. ** The sqlite3_snapshot object records state information about an historical
  7914. ** version of the database file so that it is possible to later open a new read
  7915. ** transaction that sees that historical version of the database rather than
  7916. ** the most recent version.
  7917. **
  7918. ** The constructor for this object is [sqlite3_snapshot_get()]. The
  7919. ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
  7920. ** to an historical snapshot (if possible). The destructor for
  7921. ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
  7922. */
  7923. typedef struct sqlite3_snapshot sqlite3_snapshot;
  7924. /*
  7925. ** CAPI3REF: Record A Database Snapshot
  7926. ** EXPERIMENTAL
  7927. **
  7928. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  7929. ** new [sqlite3_snapshot] object that records the current state of
  7930. ** schema S in database connection D. ^On success, the
  7931. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  7932. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  7933. ** ^If schema S of [database connection] D is not a [WAL mode] database
  7934. ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
  7935. ** leaves the *P value unchanged and returns an appropriate [error code].
  7936. **
  7937. ** The [sqlite3_snapshot] object returned from a successful call to
  7938. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  7939. ** to avoid a memory leak.
  7940. **
  7941. ** The [sqlite3_snapshot_get()] interface is only available when the
  7942. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  7943. */
  7944. SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_get(
  7945. sqlite3 *db,
  7946. const char *zSchema,
  7947. sqlite3_snapshot **ppSnapshot
  7948. );
  7949. /*
  7950. ** CAPI3REF: Start a read transaction on an historical snapshot
  7951. ** EXPERIMENTAL
  7952. **
  7953. ** ^The [sqlite3_snapshot_open(D,S,P)] interface attempts to move the
  7954. ** read transaction that is currently open on schema S of
  7955. ** [database connection] D so that it refers to historical [snapshot] P.
  7956. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  7957. ** or an appropriate [error code] if it fails.
  7958. **
  7959. ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  7960. ** the first operation, apart from other sqlite3_snapshot_open() calls,
  7961. ** following the [BEGIN] that starts a new read transaction.
  7962. ** ^A [snapshot] will fail to open if it has been overwritten by a
  7963. ** [checkpoint].
  7964. **
  7965. ** The [sqlite3_snapshot_open()] interface is only available when the
  7966. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  7967. */
  7968. SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_open(
  7969. sqlite3 *db,
  7970. const char *zSchema,
  7971. sqlite3_snapshot *pSnapshot
  7972. );
  7973. /*
  7974. ** CAPI3REF: Destroy a snapshot
  7975. ** EXPERIMENTAL
  7976. **
  7977. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  7978. ** The application must eventually free every [sqlite3_snapshot] object
  7979. ** using this routine to avoid a memory leak.
  7980. **
  7981. ** The [sqlite3_snapshot_free()] interface is only available when the
  7982. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  7983. */
  7984. SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
  7985. /*
  7986. ** Undo the hack that converts floating point types to integer for
  7987. ** builds on processors without floating point support.
  7988. */
  7989. #ifdef SQLITE_OMIT_FLOATING_POINT
  7990. # undef double
  7991. #endif
  7992. #if 0
  7993. } /* End of the 'extern "C"' block */
  7994. #endif
  7995. #endif /* _SQLITE3_H_ */
  7996. /*
  7997. ** 2010 August 30
  7998. **
  7999. ** The author disclaims copyright to this source code. In place of
  8000. ** a legal notice, here is a blessing:
  8001. **
  8002. ** May you do good and not evil.
  8003. ** May you find forgiveness for yourself and forgive others.
  8004. ** May you share freely, never taking more than you give.
  8005. **
  8006. *************************************************************************
  8007. */
  8008. #ifndef _SQLITE3RTREE_H_
  8009. #define _SQLITE3RTREE_H_
  8010. #if 0
  8011. extern "C" {
  8012. #endif
  8013. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  8014. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  8015. /* The double-precision datatype used by RTree depends on the
  8016. ** SQLITE_RTREE_INT_ONLY compile-time option.
  8017. */
  8018. #ifdef SQLITE_RTREE_INT_ONLY
  8019. typedef sqlite3_int64 sqlite3_rtree_dbl;
  8020. #else
  8021. typedef double sqlite3_rtree_dbl;
  8022. #endif
  8023. /*
  8024. ** Register a geometry callback named zGeom that can be used as part of an
  8025. ** R-Tree geometry query as follows:
  8026. **
  8027. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  8028. */
  8029. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  8030. sqlite3 *db,
  8031. const char *zGeom,
  8032. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  8033. void *pContext
  8034. );
  8035. /*
  8036. ** A pointer to a structure of the following type is passed as the first
  8037. ** argument to callbacks registered using rtree_geometry_callback().
  8038. */
  8039. struct sqlite3_rtree_geometry {
  8040. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  8041. int nParam; /* Size of array aParam[] */
  8042. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  8043. void *pUser; /* Callback implementation user data */
  8044. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  8045. };
  8046. /*
  8047. ** Register a 2nd-generation geometry callback named zScore that can be
  8048. ** used as part of an R-Tree geometry query as follows:
  8049. **
  8050. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  8051. */
  8052. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  8053. sqlite3 *db,
  8054. const char *zQueryFunc,
  8055. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  8056. void *pContext,
  8057. void (*xDestructor)(void*)
  8058. );
  8059. /*
  8060. ** A pointer to a structure of the following type is passed as the
  8061. ** argument to scored geometry callback registered using
  8062. ** sqlite3_rtree_query_callback().
  8063. **
  8064. ** Note that the first 5 fields of this structure are identical to
  8065. ** sqlite3_rtree_geometry. This structure is a subclass of
  8066. ** sqlite3_rtree_geometry.
  8067. */
  8068. struct sqlite3_rtree_query_info {
  8069. void *pContext; /* pContext from when function registered */
  8070. int nParam; /* Number of function parameters */
  8071. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  8072. void *pUser; /* callback can use this, if desired */
  8073. void (*xDelUser)(void*); /* function to free pUser */
  8074. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  8075. unsigned int *anQueue; /* Number of pending entries in the queue */
  8076. int nCoord; /* Number of coordinates */
  8077. int iLevel; /* Level of current node or entry */
  8078. int mxLevel; /* The largest iLevel value in the tree */
  8079. sqlite3_int64 iRowid; /* Rowid for current entry */
  8080. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  8081. int eParentWithin; /* Visibility of parent node */
  8082. int eWithin; /* OUT: Visiblity */
  8083. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  8084. /* The following fields are only available in 3.8.11 and later */
  8085. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  8086. };
  8087. /*
  8088. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  8089. */
  8090. #define NOT_WITHIN 0 /* Object completely outside of query region */
  8091. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  8092. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  8093. #if 0
  8094. } /* end of the 'extern "C"' block */
  8095. #endif
  8096. #endif /* ifndef _SQLITE3RTREE_H_ */
  8097. /*
  8098. ** 2014 May 31
  8099. **
  8100. ** The author disclaims copyright to this source code. In place of
  8101. ** a legal notice, here is a blessing:
  8102. **
  8103. ** May you do good and not evil.
  8104. ** May you find forgiveness for yourself and forgive others.
  8105. ** May you share freely, never taking more than you give.
  8106. **
  8107. ******************************************************************************
  8108. **
  8109. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  8110. ** FTS5 may be extended with:
  8111. **
  8112. ** * custom tokenizers, and
  8113. ** * custom auxiliary functions.
  8114. */
  8115. #ifndef _FTS5_H
  8116. #define _FTS5_H
  8117. #if 0
  8118. extern "C" {
  8119. #endif
  8120. /*************************************************************************
  8121. ** CUSTOM AUXILIARY FUNCTIONS
  8122. **
  8123. ** Virtual table implementations may overload SQL functions by implementing
  8124. ** the sqlite3_module.xFindFunction() method.
  8125. */
  8126. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  8127. typedef struct Fts5Context Fts5Context;
  8128. typedef struct Fts5PhraseIter Fts5PhraseIter;
  8129. typedef void (*fts5_extension_function)(
  8130. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  8131. Fts5Context *pFts, /* First arg to pass to pApi functions */
  8132. sqlite3_context *pCtx, /* Context for returning result/error */
  8133. int nVal, /* Number of values in apVal[] array */
  8134. sqlite3_value **apVal /* Array of trailing arguments */
  8135. );
  8136. struct Fts5PhraseIter {
  8137. const unsigned char *a;
  8138. const unsigned char *b;
  8139. };
  8140. /*
  8141. ** EXTENSION API FUNCTIONS
  8142. **
  8143. ** xUserData(pFts):
  8144. ** Return a copy of the context pointer the extension function was
  8145. ** registered with.
  8146. **
  8147. ** xColumnTotalSize(pFts, iCol, pnToken):
  8148. ** If parameter iCol is less than zero, set output variable *pnToken
  8149. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  8150. ** non-negative but less than the number of columns in the table, return
  8151. ** the total number of tokens in column iCol, considering all rows in
  8152. ** the FTS5 table.
  8153. **
  8154. ** If parameter iCol is greater than or equal to the number of columns
  8155. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  8156. ** an OOM condition or IO error), an appropriate SQLite error code is
  8157. ** returned.
  8158. **
  8159. ** xColumnCount(pFts):
  8160. ** Return the number of columns in the table.
  8161. **
  8162. ** xColumnSize(pFts, iCol, pnToken):
  8163. ** If parameter iCol is less than zero, set output variable *pnToken
  8164. ** to the total number of tokens in the current row. Or, if iCol is
  8165. ** non-negative but less than the number of columns in the table, set
  8166. ** *pnToken to the number of tokens in column iCol of the current row.
  8167. **
  8168. ** If parameter iCol is greater than or equal to the number of columns
  8169. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  8170. ** an OOM condition or IO error), an appropriate SQLite error code is
  8171. ** returned.
  8172. **
  8173. ** xColumnText:
  8174. ** This function attempts to retrieve the text of column iCol of the
  8175. ** current document. If successful, (*pz) is set to point to a buffer
  8176. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  8177. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  8178. ** if an error occurs, an SQLite error code is returned and the final values
  8179. ** of (*pz) and (*pn) are undefined.
  8180. **
  8181. ** xPhraseCount:
  8182. ** Returns the number of phrases in the current query expression.
  8183. **
  8184. ** xPhraseSize:
  8185. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  8186. ** are numbered starting from zero.
  8187. **
  8188. ** xInstCount:
  8189. ** Set *pnInst to the total number of occurrences of all phrases within
  8190. ** the query within the current row. Return SQLITE_OK if successful, or
  8191. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  8192. **
  8193. ** xInst:
  8194. ** Query for the details of phrase match iIdx within the current row.
  8195. ** Phrase matches are numbered starting from zero, so the iIdx argument
  8196. ** should be greater than or equal to zero and smaller than the value
  8197. ** output by xInstCount().
  8198. **
  8199. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  8200. ** if an error occurs.
  8201. **
  8202. ** xRowid:
  8203. ** Returns the rowid of the current row.
  8204. **
  8205. ** xTokenize:
  8206. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  8207. **
  8208. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  8209. ** This API function is used to query the FTS table for phrase iPhrase
  8210. ** of the current query. Specifically, a query equivalent to:
  8211. **
  8212. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  8213. **
  8214. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  8215. ** current query is executed. For each row visited, the callback function
  8216. ** passed as the fourth argument is invoked. The context and API objects
  8217. ** passed to the callback function may be used to access the properties of
  8218. ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
  8219. ** passed as the third argument to pUserData.
  8220. **
  8221. ** If the callback function returns any value other than SQLITE_OK, the
  8222. ** query is abandoned and the xQueryPhrase function returns immediately.
  8223. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  8224. ** Otherwise, the error code is propagated upwards.
  8225. **
  8226. ** If the query runs to completion without incident, SQLITE_OK is returned.
  8227. ** Or, if some error occurs before the query completes or is aborted by
  8228. ** the callback, an SQLite error code is returned.
  8229. **
  8230. **
  8231. ** xSetAuxdata(pFts5, pAux, xDelete)
  8232. **
  8233. ** Save the pointer passed as the second argument as the extension functions
  8234. ** "auxiliary data". The pointer may then be retrieved by the current or any
  8235. ** future invocation of the same fts5 extension function made as part of
  8236. ** of the same MATCH query using the xGetAuxdata() API.
  8237. **
  8238. ** Each extension function is allocated a single auxiliary data slot for
  8239. ** each FTS query (MATCH expression). If the extension function is invoked
  8240. ** more than once for a single FTS query, then all invocations share a
  8241. ** single auxiliary data context.
  8242. **
  8243. ** If there is already an auxiliary data pointer when this function is
  8244. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  8245. ** was specified along with the original pointer, it is invoked at this
  8246. ** point.
  8247. **
  8248. ** The xDelete callback, if one is specified, is also invoked on the
  8249. ** auxiliary data pointer after the FTS5 query has finished.
  8250. **
  8251. ** If an error (e.g. an OOM condition) occurs within this function, an
  8252. ** the auxiliary data is set to NULL and an error code returned. If the
  8253. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  8254. ** pointer before returning.
  8255. **
  8256. **
  8257. ** xGetAuxdata(pFts5, bClear)
  8258. **
  8259. ** Returns the current auxiliary data pointer for the fts5 extension
  8260. ** function. See the xSetAuxdata() method for details.
  8261. **
  8262. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  8263. ** (set to NULL) before this function returns. In this case the xDelete,
  8264. ** if any, is not invoked.
  8265. **
  8266. **
  8267. ** xRowCount(pFts5, pnRow)
  8268. **
  8269. ** This function is used to retrieve the total number of rows in the table.
  8270. ** In other words, the same value that would be returned by:
  8271. **
  8272. ** SELECT count(*) FROM ftstable;
  8273. **
  8274. ** xPhraseFirst()
  8275. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  8276. ** method, to iterate through all instances of a single query phrase within
  8277. ** the current row. This is the same information as is accessible via the
  8278. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  8279. ** to use, this API may be faster under some circumstances. To iterate
  8280. ** through instances of phrase iPhrase, use the following code:
  8281. **
  8282. ** Fts5PhraseIter iter;
  8283. ** int iCol, iOff;
  8284. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  8285. ** iOff>=0;
  8286. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  8287. ** ){
  8288. ** // An instance of phrase iPhrase at offset iOff of column iCol
  8289. ** }
  8290. **
  8291. ** The Fts5PhraseIter structure is defined above. Applications should not
  8292. ** modify this structure directly - it should only be used as shown above
  8293. ** with the xPhraseFirst() and xPhraseNext() API methods.
  8294. **
  8295. ** xPhraseNext()
  8296. ** See xPhraseFirst above.
  8297. */
  8298. struct Fts5ExtensionApi {
  8299. int iVersion; /* Currently always set to 1 */
  8300. void *(*xUserData)(Fts5Context*);
  8301. int (*xColumnCount)(Fts5Context*);
  8302. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  8303. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  8304. int (*xTokenize)(Fts5Context*,
  8305. const char *pText, int nText, /* Text to tokenize */
  8306. void *pCtx, /* Context passed to xToken() */
  8307. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  8308. );
  8309. int (*xPhraseCount)(Fts5Context*);
  8310. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  8311. int (*xInstCount)(Fts5Context*, int *pnInst);
  8312. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  8313. sqlite3_int64 (*xRowid)(Fts5Context*);
  8314. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  8315. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  8316. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  8317. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  8318. );
  8319. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  8320. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  8321. void (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  8322. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  8323. };
  8324. /*
  8325. ** CUSTOM AUXILIARY FUNCTIONS
  8326. *************************************************************************/
  8327. /*************************************************************************
  8328. ** CUSTOM TOKENIZERS
  8329. **
  8330. ** Applications may also register custom tokenizer types. A tokenizer
  8331. ** is registered by providing fts5 with a populated instance of the
  8332. ** following structure. All structure methods must be defined, setting
  8333. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  8334. ** behaviour. The structure methods are expected to function as follows:
  8335. **
  8336. ** xCreate:
  8337. ** This function is used to allocate and inititalize a tokenizer instance.
  8338. ** A tokenizer instance is required to actually tokenize text.
  8339. **
  8340. ** The first argument passed to this function is a copy of the (void*)
  8341. ** pointer provided by the application when the fts5_tokenizer object
  8342. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  8343. ** The second and third arguments are an array of nul-terminated strings
  8344. ** containing the tokenizer arguments, if any, specified following the
  8345. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  8346. ** to create the FTS5 table.
  8347. **
  8348. ** The final argument is an output variable. If successful, (*ppOut)
  8349. ** should be set to point to the new tokenizer handle and SQLITE_OK
  8350. ** returned. If an error occurs, some value other than SQLITE_OK should
  8351. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  8352. ** is undefined.
  8353. **
  8354. ** xDelete:
  8355. ** This function is invoked to delete a tokenizer handle previously
  8356. ** allocated using xCreate(). Fts5 guarantees that this function will
  8357. ** be invoked exactly once for each successful call to xCreate().
  8358. **
  8359. ** xTokenize:
  8360. ** This function is expected to tokenize the nText byte string indicated
  8361. ** by argument pText. pText may or may not be nul-terminated. The first
  8362. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  8363. ** returned by an earlier call to xCreate().
  8364. **
  8365. ** The second argument indicates the reason that FTS5 is requesting
  8366. ** tokenization of the supplied text. This is always one of the following
  8367. ** four values:
  8368. **
  8369. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  8370. ** or removed from the FTS table. The tokenizer is being invoked to
  8371. ** determine the set of tokens to add to (or delete from) the
  8372. ** FTS index.
  8373. **
  8374. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  8375. ** against the FTS index. The tokenizer is being called to tokenize
  8376. ** a bareword or quoted string specified as part of the query.
  8377. **
  8378. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  8379. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  8380. ** followed by a "*" character, indicating that the last token
  8381. ** returned by the tokenizer will be treated as a token prefix.
  8382. **
  8383. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  8384. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  8385. ** function. Or an fts5_api.xColumnSize() request made by the same
  8386. ** on a columnsize=0 database.
  8387. ** </ul>
  8388. **
  8389. ** For each token in the input string, the supplied callback xToken() must
  8390. ** be invoked. The first argument to it should be a copy of the pointer
  8391. ** passed as the second argument to xTokenize(). The third and fourth
  8392. ** arguments are a pointer to a buffer containing the token text, and the
  8393. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  8394. ** of the first byte of and first byte immediately following the text from
  8395. ** which the token is derived within the input.
  8396. **
  8397. ** The second argument passed to the xToken() callback ("tflags") should
  8398. ** normally be set to 0. The exception is if the tokenizer supports
  8399. ** synonyms. In this case see the discussion below for details.
  8400. **
  8401. ** FTS5 assumes the xToken() callback is invoked for each token in the
  8402. ** order that they occur within the input text.
  8403. **
  8404. ** If an xToken() callback returns any value other than SQLITE_OK, then
  8405. ** the tokenization should be abandoned and the xTokenize() method should
  8406. ** immediately return a copy of the xToken() return value. Or, if the
  8407. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  8408. ** if an error occurs with the xTokenize() implementation itself, it
  8409. ** may abandon the tokenization and return any error code other than
  8410. ** SQLITE_OK or SQLITE_DONE.
  8411. **
  8412. ** SYNONYM SUPPORT
  8413. **
  8414. ** Custom tokenizers may also support synonyms. Consider a case in which a
  8415. ** user wishes to query for a phrase such as "first place". Using the
  8416. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  8417. ** of "first place" within the document set, but not alternative forms
  8418. ** such as "1st place". In some applications, it would be better to match
  8419. ** all instances of "first place" or "1st place" regardless of which form
  8420. ** the user specified in the MATCH query text.
  8421. **
  8422. ** There are several ways to approach this in FTS5:
  8423. **
  8424. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  8425. ** In the above example, this means that the tokenizer returns the
  8426. ** same token for inputs "first" and "1st". Say that token is in
  8427. ** fact "first", so that when the user inserts the document "I won
  8428. ** 1st place" entries are added to the index for tokens "i", "won",
  8429. ** "first" and "place". If the user then queries for '1st + place',
  8430. ** the tokenizer substitutes "first" for "1st" and the query works
  8431. ** as expected.
  8432. **
  8433. ** <li> By adding multiple synonyms for a single term to the FTS index.
  8434. ** In this case, when tokenizing query text, the tokenizer may
  8435. ** provide multiple synonyms for a single term within the document.
  8436. ** FTS5 then queries the index for each synonym individually. For
  8437. ** example, faced with the query:
  8438. **
  8439. ** <codeblock>
  8440. ** ... MATCH 'first place'</codeblock>
  8441. **
  8442. ** the tokenizer offers both "1st" and "first" as synonyms for the
  8443. ** first token in the MATCH query and FTS5 effectively runs a query
  8444. ** similar to:
  8445. **
  8446. ** <codeblock>
  8447. ** ... MATCH '(first OR 1st) place'</codeblock>
  8448. **
  8449. ** except that, for the purposes of auxiliary functions, the query
  8450. ** still appears to contain just two phrases - "(first OR 1st)"
  8451. ** being treated as a single phrase.
  8452. **
  8453. ** <li> By adding multiple synonyms for a single term to the FTS index.
  8454. ** Using this method, when tokenizing document text, the tokenizer
  8455. ** provides multiple synonyms for each token. So that when a
  8456. ** document such as "I won first place" is tokenized, entries are
  8457. ** added to the FTS index for "i", "won", "first", "1st" and
  8458. ** "place".
  8459. **
  8460. ** This way, even if the tokenizer does not provide synonyms
  8461. ** when tokenizing query text (it should not - to do would be
  8462. ** inefficient), it doesn't matter if the user queries for
  8463. ** 'first + place' or '1st + place', as there are entires in the
  8464. ** FTS index corresponding to both forms of the first token.
  8465. ** </ol>
  8466. **
  8467. ** Whether it is parsing document or query text, any call to xToken that
  8468. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  8469. ** is considered to supply a synonym for the previous token. For example,
  8470. ** when parsing the document "I won first place", a tokenizer that supports
  8471. ** synonyms would call xToken() 5 times, as follows:
  8472. **
  8473. ** <codeblock>
  8474. ** xToken(pCtx, 0, "i", 1, 0, 1);
  8475. ** xToken(pCtx, 0, "won", 3, 2, 5);
  8476. ** xToken(pCtx, 0, "first", 5, 6, 11);
  8477. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  8478. ** xToken(pCtx, 0, "place", 5, 12, 17);
  8479. **</codeblock>
  8480. **
  8481. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  8482. ** xToken() is called. Multiple synonyms may be specified for a single token
  8483. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  8484. ** There is no limit to the number of synonyms that may be provided for a
  8485. ** single token.
  8486. **
  8487. ** In many cases, method (1) above is the best approach. It does not add
  8488. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  8489. ** so it is efficient in terms of disk space and query speed. However, it
  8490. ** does not support prefix queries very well. If, as suggested above, the
  8491. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  8492. **
  8493. ** <codeblock>
  8494. ** ... MATCH '1s*'</codeblock>
  8495. **
  8496. ** will not match documents that contain the token "1st" (as the tokenizer
  8497. ** will probably not map "1s" to any prefix of "first").
  8498. **
  8499. ** For full prefix support, method (3) may be preferred. In this case,
  8500. ** because the index contains entries for both "first" and "1st", prefix
  8501. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  8502. ** extra entries are added to the FTS index, this method uses more space
  8503. ** within the database.
  8504. **
  8505. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  8506. ** a query such as '1s*' will match documents that contain the literal
  8507. ** token "1st", but not "first" (assuming the tokenizer is not able to
  8508. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  8509. ** will match against "1st" and "first". This method does not require
  8510. ** extra disk space, as no extra entries are added to the FTS index.
  8511. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  8512. ** as separate queries of the FTS index are required for each synonym.
  8513. **
  8514. ** When using methods (2) or (3), it is important that the tokenizer only
  8515. ** provide synonyms when tokenizing document text (method (2)) or query
  8516. ** text (method (3)), not both. Doing so will not cause any errors, but is
  8517. ** inefficient.
  8518. */
  8519. typedef struct Fts5Tokenizer Fts5Tokenizer;
  8520. typedef struct fts5_tokenizer fts5_tokenizer;
  8521. struct fts5_tokenizer {
  8522. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  8523. void (*xDelete)(Fts5Tokenizer*);
  8524. int (*xTokenize)(Fts5Tokenizer*,
  8525. void *pCtx,
  8526. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  8527. const char *pText, int nText,
  8528. int (*xToken)(
  8529. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  8530. int tflags, /* Mask of FTS5_TOKEN_* flags */
  8531. const char *pToken, /* Pointer to buffer containing token */
  8532. int nToken, /* Size of token in bytes */
  8533. int iStart, /* Byte offset of token within input text */
  8534. int iEnd /* Byte offset of end of token within input text */
  8535. )
  8536. );
  8537. };
  8538. /* Flags that may be passed as the third argument to xTokenize() */
  8539. #define FTS5_TOKENIZE_QUERY 0x0001
  8540. #define FTS5_TOKENIZE_PREFIX 0x0002
  8541. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  8542. #define FTS5_TOKENIZE_AUX 0x0008
  8543. /* Flags that may be passed by the tokenizer implementation back to FTS5
  8544. ** as the third argument to the supplied xToken callback. */
  8545. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  8546. /*
  8547. ** END OF CUSTOM TOKENIZERS
  8548. *************************************************************************/
  8549. /*************************************************************************
  8550. ** FTS5 EXTENSION REGISTRATION API
  8551. */
  8552. typedef struct fts5_api fts5_api;
  8553. struct fts5_api {
  8554. int iVersion; /* Currently always set to 2 */
  8555. /* Create a new tokenizer */
  8556. int (*xCreateTokenizer)(
  8557. fts5_api *pApi,
  8558. const char *zName,
  8559. void *pContext,
  8560. fts5_tokenizer *pTokenizer,
  8561. void (*xDestroy)(void*)
  8562. );
  8563. /* Find an existing tokenizer */
  8564. int (*xFindTokenizer)(
  8565. fts5_api *pApi,
  8566. const char *zName,
  8567. void **ppContext,
  8568. fts5_tokenizer *pTokenizer
  8569. );
  8570. /* Create a new auxiliary function */
  8571. int (*xCreateFunction)(
  8572. fts5_api *pApi,
  8573. const char *zName,
  8574. void *pContext,
  8575. fts5_extension_function xFunction,
  8576. void (*xDestroy)(void*)
  8577. );
  8578. };
  8579. /*
  8580. ** END OF REGISTRATION API
  8581. *************************************************************************/
  8582. #if 0
  8583. } /* end of the 'extern "C"' block */
  8584. #endif
  8585. #endif /* _FTS5_H */
  8586. /************** End of sqlite3.h *********************************************/
  8587. /************** Continuing where we left off in sqliteInt.h ******************/
  8588. /*
  8589. ** Include the configuration header output by 'configure' if we're using the
  8590. ** autoconf-based build
  8591. */
  8592. #ifdef _HAVE_SQLITE_CONFIG_H
  8593. #include "config.h"
  8594. #endif
  8595. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  8596. /************** Begin file sqliteLimit.h *************************************/
  8597. /*
  8598. ** 2007 May 7
  8599. **
  8600. ** The author disclaims copyright to this source code. In place of
  8601. ** a legal notice, here is a blessing:
  8602. **
  8603. ** May you do good and not evil.
  8604. ** May you find forgiveness for yourself and forgive others.
  8605. ** May you share freely, never taking more than you give.
  8606. **
  8607. *************************************************************************
  8608. **
  8609. ** This file defines various limits of what SQLite can process.
  8610. */
  8611. /*
  8612. ** The maximum length of a TEXT or BLOB in bytes. This also
  8613. ** limits the size of a row in a table or index.
  8614. **
  8615. ** The hard limit is the ability of a 32-bit signed integer
  8616. ** to count the size: 2^31-1 or 2147483647.
  8617. */
  8618. #ifndef SQLITE_MAX_LENGTH
  8619. # define SQLITE_MAX_LENGTH 1000000000
  8620. #endif
  8621. /*
  8622. ** This is the maximum number of
  8623. **
  8624. ** * Columns in a table
  8625. ** * Columns in an index
  8626. ** * Columns in a view
  8627. ** * Terms in the SET clause of an UPDATE statement
  8628. ** * Terms in the result set of a SELECT statement
  8629. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  8630. ** * Terms in the VALUES clause of an INSERT statement
  8631. **
  8632. ** The hard upper limit here is 32676. Most database people will
  8633. ** tell you that in a well-normalized database, you usually should
  8634. ** not have more than a dozen or so columns in any table. And if
  8635. ** that is the case, there is no point in having more than a few
  8636. ** dozen values in any of the other situations described above.
  8637. */
  8638. #ifndef SQLITE_MAX_COLUMN
  8639. # define SQLITE_MAX_COLUMN 2000
  8640. #endif
  8641. /*
  8642. ** The maximum length of a single SQL statement in bytes.
  8643. **
  8644. ** It used to be the case that setting this value to zero would
  8645. ** turn the limit off. That is no longer true. It is not possible
  8646. ** to turn this limit off.
  8647. */
  8648. #ifndef SQLITE_MAX_SQL_LENGTH
  8649. # define SQLITE_MAX_SQL_LENGTH 1000000000
  8650. #endif
  8651. /*
  8652. ** The maximum depth of an expression tree. This is limited to
  8653. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  8654. ** want to place more severe limits on the complexity of an
  8655. ** expression.
  8656. **
  8657. ** A value of 0 used to mean that the limit was not enforced.
  8658. ** But that is no longer true. The limit is now strictly enforced
  8659. ** at all times.
  8660. */
  8661. #ifndef SQLITE_MAX_EXPR_DEPTH
  8662. # define SQLITE_MAX_EXPR_DEPTH 1000
  8663. #endif
  8664. /*
  8665. ** The maximum number of terms in a compound SELECT statement.
  8666. ** The code generator for compound SELECT statements does one
  8667. ** level of recursion for each term. A stack overflow can result
  8668. ** if the number of terms is too large. In practice, most SQL
  8669. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  8670. ** any limit on the number of terms in a compount SELECT.
  8671. */
  8672. #ifndef SQLITE_MAX_COMPOUND_SELECT
  8673. # define SQLITE_MAX_COMPOUND_SELECT 500
  8674. #endif
  8675. /*
  8676. ** The maximum number of opcodes in a VDBE program.
  8677. ** Not currently enforced.
  8678. */
  8679. #ifndef SQLITE_MAX_VDBE_OP
  8680. # define SQLITE_MAX_VDBE_OP 25000
  8681. #endif
  8682. /*
  8683. ** The maximum number of arguments to an SQL function.
  8684. */
  8685. #ifndef SQLITE_MAX_FUNCTION_ARG
  8686. # define SQLITE_MAX_FUNCTION_ARG 127
  8687. #endif
  8688. /*
  8689. ** The suggested maximum number of in-memory pages to use for
  8690. ** the main database table and for temporary tables.
  8691. **
  8692. ** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
  8693. ** is 2000 pages.
  8694. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  8695. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  8696. */
  8697. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  8698. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  8699. #endif
  8700. /*
  8701. ** The default number of frames to accumulate in the log file before
  8702. ** checkpointing the database in WAL mode.
  8703. */
  8704. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  8705. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  8706. #endif
  8707. /*
  8708. ** The maximum number of attached databases. This must be between 0
  8709. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  8710. ** is used internally to track attached databases.
  8711. */
  8712. #ifndef SQLITE_MAX_ATTACHED
  8713. # define SQLITE_MAX_ATTACHED 10
  8714. #endif
  8715. /*
  8716. ** The maximum value of a ?nnn wildcard that the parser will accept.
  8717. */
  8718. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  8719. # define SQLITE_MAX_VARIABLE_NUMBER 999
  8720. #endif
  8721. /* Maximum page size. The upper bound on this value is 65536. This a limit
  8722. ** imposed by the use of 16-bit offsets within each page.
  8723. **
  8724. ** Earlier versions of SQLite allowed the user to change this value at
  8725. ** compile time. This is no longer permitted, on the grounds that it creates
  8726. ** a library that is technically incompatible with an SQLite library
  8727. ** compiled with a different limit. If a process operating on a database
  8728. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  8729. ** compiled with the default page-size limit will not be able to rollback
  8730. ** the aborted transaction. This could lead to database corruption.
  8731. */
  8732. #ifdef SQLITE_MAX_PAGE_SIZE
  8733. # undef SQLITE_MAX_PAGE_SIZE
  8734. #endif
  8735. #define SQLITE_MAX_PAGE_SIZE 65536
  8736. /*
  8737. ** The default size of a database page.
  8738. */
  8739. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  8740. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  8741. #endif
  8742. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  8743. # undef SQLITE_DEFAULT_PAGE_SIZE
  8744. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  8745. #endif
  8746. /*
  8747. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  8748. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  8749. ** device characteristics (sector-size and atomic write() support),
  8750. ** SQLite may choose a larger value. This constant is the maximum value
  8751. ** SQLite will choose on its own.
  8752. */
  8753. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  8754. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  8755. #endif
  8756. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  8757. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  8758. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  8759. #endif
  8760. /*
  8761. ** Maximum number of pages in one database file.
  8762. **
  8763. ** This is really just the default value for the max_page_count pragma.
  8764. ** This value can be lowered (or raised) at run-time using that the
  8765. ** max_page_count macro.
  8766. */
  8767. #ifndef SQLITE_MAX_PAGE_COUNT
  8768. # define SQLITE_MAX_PAGE_COUNT 1073741823
  8769. #endif
  8770. /*
  8771. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  8772. ** operator.
  8773. */
  8774. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  8775. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  8776. #endif
  8777. /*
  8778. ** Maximum depth of recursion for triggers.
  8779. **
  8780. ** A value of 1 means that a trigger program will not be able to itself
  8781. ** fire any triggers. A value of 0 means that no trigger programs at all
  8782. ** may be executed.
  8783. */
  8784. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  8785. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  8786. #endif
  8787. /************** End of sqliteLimit.h *****************************************/
  8788. /************** Continuing where we left off in sqliteInt.h ******************/
  8789. /* Disable nuisance warnings on Borland compilers */
  8790. #if defined(__BORLANDC__)
  8791. #pragma warn -rch /* unreachable code */
  8792. #pragma warn -ccc /* Condition is always true or false */
  8793. #pragma warn -aus /* Assigned value is never used */
  8794. #pragma warn -csu /* Comparing signed and unsigned */
  8795. #pragma warn -spa /* Suspicious pointer arithmetic */
  8796. #endif
  8797. /*
  8798. ** Include standard header files as necessary
  8799. */
  8800. #ifdef HAVE_STDINT_H
  8801. #include <stdint.h>
  8802. #endif
  8803. #ifdef HAVE_INTTYPES_H
  8804. #include <inttypes.h>
  8805. #endif
  8806. /*
  8807. ** The following macros are used to cast pointers to integers and
  8808. ** integers to pointers. The way you do this varies from one compiler
  8809. ** to the next, so we have developed the following set of #if statements
  8810. ** to generate appropriate macros for a wide range of compilers.
  8811. **
  8812. ** The correct "ANSI" way to do this is to use the intptr_t type.
  8813. ** Unfortunately, that typedef is not available on all compilers, or
  8814. ** if it is available, it requires an #include of specific headers
  8815. ** that vary from one machine to the next.
  8816. **
  8817. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  8818. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  8819. ** So we have to define the macros in different ways depending on the
  8820. ** compiler.
  8821. */
  8822. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  8823. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  8824. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  8825. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  8826. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  8827. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  8828. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  8829. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  8830. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  8831. #else /* Generates a warning - but it always works */
  8832. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  8833. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  8834. #endif
  8835. /*
  8836. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  8837. ** something between S (inclusive) and E (exclusive).
  8838. **
  8839. ** In other words, S is a buffer and E is a pointer to the first byte after
  8840. ** the end of buffer S. This macro returns true if P points to something
  8841. ** contained within the buffer S.
  8842. */
  8843. #if defined(HAVE_STDINT_H)
  8844. # define SQLITE_WITHIN(P,S,E) \
  8845. ((uintptr_t)(P)>=(uintptr_t)(S) && (uintptr_t)(P)<(uintptr_t)(E))
  8846. #else
  8847. # define SQLITE_WITHIN(P,S,E) ((P)>=(S) && (P)<(E))
  8848. #endif
  8849. /*
  8850. ** A macro to hint to the compiler that a function should not be
  8851. ** inlined.
  8852. */
  8853. #if defined(__GNUC__)
  8854. # define SQLITE_NOINLINE __attribute__((noinline))
  8855. #elif defined(_MSC_VER) && _MSC_VER>=1310
  8856. # define SQLITE_NOINLINE __declspec(noinline)
  8857. #else
  8858. # define SQLITE_NOINLINE
  8859. #endif
  8860. /*
  8861. ** Make sure that the compiler intrinsics we desire are enabled when
  8862. ** compiling with an appropriate version of MSVC unless prevented by
  8863. ** the SQLITE_DISABLE_INTRINSIC define.
  8864. */
  8865. #if !defined(SQLITE_DISABLE_INTRINSIC)
  8866. # if defined(_MSC_VER) && _MSC_VER>=1300
  8867. # if !defined(_WIN32_WCE)
  8868. # include <intrin.h>
  8869. # pragma intrinsic(_byteswap_ushort)
  8870. # pragma intrinsic(_byteswap_ulong)
  8871. # pragma intrinsic(_ReadWriteBarrier)
  8872. # else
  8873. # include <cmnintrin.h>
  8874. # endif
  8875. # endif
  8876. #endif
  8877. /*
  8878. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  8879. ** 0 means mutexes are permanently disable and the library is never
  8880. ** threadsafe. 1 means the library is serialized which is the highest
  8881. ** level of threadsafety. 2 means the library is multithreaded - multiple
  8882. ** threads can use SQLite as long as no two threads try to use the same
  8883. ** database connection at the same time.
  8884. **
  8885. ** Older versions of SQLite used an optional THREADSAFE macro.
  8886. ** We support that for legacy.
  8887. */
  8888. #if !defined(SQLITE_THREADSAFE)
  8889. # if defined(THREADSAFE)
  8890. # define SQLITE_THREADSAFE THREADSAFE
  8891. # else
  8892. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  8893. # endif
  8894. #endif
  8895. /*
  8896. ** Powersafe overwrite is on by default. But can be turned off using
  8897. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  8898. */
  8899. #ifndef SQLITE_POWERSAFE_OVERWRITE
  8900. # define SQLITE_POWERSAFE_OVERWRITE 1
  8901. #endif
  8902. /*
  8903. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  8904. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  8905. ** which case memory allocation statistics are disabled by default.
  8906. */
  8907. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  8908. # define SQLITE_DEFAULT_MEMSTATUS 1
  8909. #endif
  8910. /*
  8911. ** Exactly one of the following macros must be defined in order to
  8912. ** specify which memory allocation subsystem to use.
  8913. **
  8914. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  8915. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  8916. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  8917. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  8918. **
  8919. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  8920. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  8921. ** will cause HeapValidate to be called. If heap validation should fail, an
  8922. ** assertion will be triggered.
  8923. **
  8924. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  8925. ** the default.
  8926. */
  8927. #if defined(SQLITE_SYSTEM_MALLOC) \
  8928. + defined(SQLITE_WIN32_MALLOC) \
  8929. + defined(SQLITE_ZERO_MALLOC) \
  8930. + defined(SQLITE_MEMDEBUG)>1
  8931. # error "Two or more of the following compile-time configuration options\
  8932. are defined but at most one is allowed:\
  8933. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  8934. SQLITE_ZERO_MALLOC"
  8935. #endif
  8936. #if defined(SQLITE_SYSTEM_MALLOC) \
  8937. + defined(SQLITE_WIN32_MALLOC) \
  8938. + defined(SQLITE_ZERO_MALLOC) \
  8939. + defined(SQLITE_MEMDEBUG)==0
  8940. # define SQLITE_SYSTEM_MALLOC 1
  8941. #endif
  8942. /*
  8943. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  8944. ** sizes of memory allocations below this value where possible.
  8945. */
  8946. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  8947. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  8948. #endif
  8949. /*
  8950. ** We need to define _XOPEN_SOURCE as follows in order to enable
  8951. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  8952. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  8953. ** it.
  8954. */
  8955. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  8956. # define _XOPEN_SOURCE 600
  8957. #endif
  8958. /*
  8959. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  8960. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  8961. ** make it true by defining or undefining NDEBUG.
  8962. **
  8963. ** Setting NDEBUG makes the code smaller and faster by disabling the
  8964. ** assert() statements in the code. So we want the default action
  8965. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  8966. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  8967. ** feature.
  8968. */
  8969. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  8970. # define NDEBUG 1
  8971. #endif
  8972. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  8973. # undef NDEBUG
  8974. #endif
  8975. /*
  8976. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  8977. */
  8978. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  8979. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  8980. #endif
  8981. /*
  8982. ** The testcase() macro is used to aid in coverage testing. When
  8983. ** doing coverage testing, the condition inside the argument to
  8984. ** testcase() must be evaluated both true and false in order to
  8985. ** get full branch coverage. The testcase() macro is inserted
  8986. ** to help ensure adequate test coverage in places where simple
  8987. ** condition/decision coverage is inadequate. For example, testcase()
  8988. ** can be used to make sure boundary values are tested. For
  8989. ** bitmask tests, testcase() can be used to make sure each bit
  8990. ** is significant and used at least once. On switch statements
  8991. ** where multiple cases go to the same block of code, testcase()
  8992. ** can insure that all cases are evaluated.
  8993. **
  8994. */
  8995. #ifdef SQLITE_COVERAGE_TEST
  8996. SQLITE_PRIVATE void sqlite3Coverage(int);
  8997. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  8998. #else
  8999. # define testcase(X)
  9000. #endif
  9001. /*
  9002. ** The TESTONLY macro is used to enclose variable declarations or
  9003. ** other bits of code that are needed to support the arguments
  9004. ** within testcase() and assert() macros.
  9005. */
  9006. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  9007. # define TESTONLY(X) X
  9008. #else
  9009. # define TESTONLY(X)
  9010. #endif
  9011. /*
  9012. ** Sometimes we need a small amount of code such as a variable initialization
  9013. ** to setup for a later assert() statement. We do not want this code to
  9014. ** appear when assert() is disabled. The following macro is therefore
  9015. ** used to contain that setup code. The "VVA" acronym stands for
  9016. ** "Verification, Validation, and Accreditation". In other words, the
  9017. ** code within VVA_ONLY() will only run during verification processes.
  9018. */
  9019. #ifndef NDEBUG
  9020. # define VVA_ONLY(X) X
  9021. #else
  9022. # define VVA_ONLY(X)
  9023. #endif
  9024. /*
  9025. ** The ALWAYS and NEVER macros surround boolean expressions which
  9026. ** are intended to always be true or false, respectively. Such
  9027. ** expressions could be omitted from the code completely. But they
  9028. ** are included in a few cases in order to enhance the resilience
  9029. ** of SQLite to unexpected behavior - to make the code "self-healing"
  9030. ** or "ductile" rather than being "brittle" and crashing at the first
  9031. ** hint of unplanned behavior.
  9032. **
  9033. ** In other words, ALWAYS and NEVER are added for defensive code.
  9034. **
  9035. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  9036. ** be true and false so that the unreachable code they specify will
  9037. ** not be counted as untested code.
  9038. */
  9039. #if defined(SQLITE_COVERAGE_TEST)
  9040. # define ALWAYS(X) (1)
  9041. # define NEVER(X) (0)
  9042. #elif !defined(NDEBUG)
  9043. # define ALWAYS(X) ((X)?1:(assert(0),0))
  9044. # define NEVER(X) ((X)?(assert(0),1):0)
  9045. #else
  9046. # define ALWAYS(X) (X)
  9047. # define NEVER(X) (X)
  9048. #endif
  9049. /*
  9050. ** Declarations used for tracing the operating system interfaces.
  9051. */
  9052. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  9053. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  9054. extern int sqlite3OSTrace;
  9055. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  9056. # define SQLITE_HAVE_OS_TRACE
  9057. #else
  9058. # define OSTRACE(X)
  9059. # undef SQLITE_HAVE_OS_TRACE
  9060. #endif
  9061. /*
  9062. ** Is the sqlite3ErrName() function needed in the build? Currently,
  9063. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  9064. ** OSTRACE is enabled), and by several "test*.c" files (which are
  9065. ** compiled using SQLITE_TEST).
  9066. */
  9067. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  9068. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  9069. # define SQLITE_NEED_ERR_NAME
  9070. #else
  9071. # undef SQLITE_NEED_ERR_NAME
  9072. #endif
  9073. /*
  9074. ** Return true (non-zero) if the input is an integer that is too large
  9075. ** to fit in 32-bits. This macro is used inside of various testcase()
  9076. ** macros to verify that we have tested SQLite for large-file support.
  9077. */
  9078. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  9079. /*
  9080. ** The macro unlikely() is a hint that surrounds a boolean
  9081. ** expression that is usually false. Macro likely() surrounds
  9082. ** a boolean expression that is usually true. These hints could,
  9083. ** in theory, be used by the compiler to generate better code, but
  9084. ** currently they are just comments for human readers.
  9085. */
  9086. #define likely(X) (X)
  9087. #define unlikely(X) (X)
  9088. /************** Include hash.h in the middle of sqliteInt.h ******************/
  9089. /************** Begin file hash.h ********************************************/
  9090. /*
  9091. ** 2001 September 22
  9092. **
  9093. ** The author disclaims copyright to this source code. In place of
  9094. ** a legal notice, here is a blessing:
  9095. **
  9096. ** May you do good and not evil.
  9097. ** May you find forgiveness for yourself and forgive others.
  9098. ** May you share freely, never taking more than you give.
  9099. **
  9100. *************************************************************************
  9101. ** This is the header file for the generic hash-table implementation
  9102. ** used in SQLite.
  9103. */
  9104. #ifndef _SQLITE_HASH_H_
  9105. #define _SQLITE_HASH_H_
  9106. /* Forward declarations of structures. */
  9107. typedef struct Hash Hash;
  9108. typedef struct HashElem HashElem;
  9109. /* A complete hash table is an instance of the following structure.
  9110. ** The internals of this structure are intended to be opaque -- client
  9111. ** code should not attempt to access or modify the fields of this structure
  9112. ** directly. Change this structure only by using the routines below.
  9113. ** However, some of the "procedures" and "functions" for modifying and
  9114. ** accessing this structure are really macros, so we can't really make
  9115. ** this structure opaque.
  9116. **
  9117. ** All elements of the hash table are on a single doubly-linked list.
  9118. ** Hash.first points to the head of this list.
  9119. **
  9120. ** There are Hash.htsize buckets. Each bucket points to a spot in
  9121. ** the global doubly-linked list. The contents of the bucket are the
  9122. ** element pointed to plus the next _ht.count-1 elements in the list.
  9123. **
  9124. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  9125. ** by a linear search of the global list. For small tables, the
  9126. ** Hash.ht table is never allocated because if there are few elements
  9127. ** in the table, it is faster to do a linear search than to manage
  9128. ** the hash table.
  9129. */
  9130. struct Hash {
  9131. unsigned int htsize; /* Number of buckets in the hash table */
  9132. unsigned int count; /* Number of entries in this table */
  9133. HashElem *first; /* The first element of the array */
  9134. struct _ht { /* the hash table */
  9135. int count; /* Number of entries with this hash */
  9136. HashElem *chain; /* Pointer to first entry with this hash */
  9137. } *ht;
  9138. };
  9139. /* Each element in the hash table is an instance of the following
  9140. ** structure. All elements are stored on a single doubly-linked list.
  9141. **
  9142. ** Again, this structure is intended to be opaque, but it can't really
  9143. ** be opaque because it is used by macros.
  9144. */
  9145. struct HashElem {
  9146. HashElem *next, *prev; /* Next and previous elements in the table */
  9147. void *data; /* Data associated with this element */
  9148. const char *pKey; /* Key associated with this element */
  9149. };
  9150. /*
  9151. ** Access routines. To delete, insert a NULL pointer.
  9152. */
  9153. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  9154. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  9155. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  9156. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  9157. /*
  9158. ** Macros for looping over all elements of a hash table. The idiom is
  9159. ** like this:
  9160. **
  9161. ** Hash h;
  9162. ** HashElem *p;
  9163. ** ...
  9164. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  9165. ** SomeStructure *pData = sqliteHashData(p);
  9166. ** // do something with pData
  9167. ** }
  9168. */
  9169. #define sqliteHashFirst(H) ((H)->first)
  9170. #define sqliteHashNext(E) ((E)->next)
  9171. #define sqliteHashData(E) ((E)->data)
  9172. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  9173. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  9174. /*
  9175. ** Number of entries in a hash table
  9176. */
  9177. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  9178. #endif /* _SQLITE_HASH_H_ */
  9179. /************** End of hash.h ************************************************/
  9180. /************** Continuing where we left off in sqliteInt.h ******************/
  9181. /************** Include parse.h in the middle of sqliteInt.h *****************/
  9182. /************** Begin file parse.h *******************************************/
  9183. #define TK_SEMI 1
  9184. #define TK_EXPLAIN 2
  9185. #define TK_QUERY 3
  9186. #define TK_PLAN 4
  9187. #define TK_BEGIN 5
  9188. #define TK_TRANSACTION 6
  9189. #define TK_DEFERRED 7
  9190. #define TK_IMMEDIATE 8
  9191. #define TK_EXCLUSIVE 9
  9192. #define TK_COMMIT 10
  9193. #define TK_END 11
  9194. #define TK_ROLLBACK 12
  9195. #define TK_SAVEPOINT 13
  9196. #define TK_RELEASE 14
  9197. #define TK_TO 15
  9198. #define TK_TABLE 16
  9199. #define TK_CREATE 17
  9200. #define TK_IF 18
  9201. #define TK_NOT 19
  9202. #define TK_EXISTS 20
  9203. #define TK_TEMP 21
  9204. #define TK_LP 22
  9205. #define TK_RP 23
  9206. #define TK_AS 24
  9207. #define TK_WITHOUT 25
  9208. #define TK_COMMA 26
  9209. #define TK_ID 27
  9210. #define TK_INDEXED 28
  9211. #define TK_ABORT 29
  9212. #define TK_ACTION 30
  9213. #define TK_AFTER 31
  9214. #define TK_ANALYZE 32
  9215. #define TK_ASC 33
  9216. #define TK_ATTACH 34
  9217. #define TK_BEFORE 35
  9218. #define TK_BY 36
  9219. #define TK_CASCADE 37
  9220. #define TK_CAST 38
  9221. #define TK_COLUMNKW 39
  9222. #define TK_CONFLICT 40
  9223. #define TK_DATABASE 41
  9224. #define TK_DESC 42
  9225. #define TK_DETACH 43
  9226. #define TK_EACH 44
  9227. #define TK_FAIL 45
  9228. #define TK_FOR 46
  9229. #define TK_IGNORE 47
  9230. #define TK_INITIALLY 48
  9231. #define TK_INSTEAD 49
  9232. #define TK_LIKE_KW 50
  9233. #define TK_MATCH 51
  9234. #define TK_NO 52
  9235. #define TK_KEY 53
  9236. #define TK_OF 54
  9237. #define TK_OFFSET 55
  9238. #define TK_PRAGMA 56
  9239. #define TK_RAISE 57
  9240. #define TK_RECURSIVE 58
  9241. #define TK_REPLACE 59
  9242. #define TK_RESTRICT 60
  9243. #define TK_ROW 61
  9244. #define TK_TRIGGER 62
  9245. #define TK_VACUUM 63
  9246. #define TK_VIEW 64
  9247. #define TK_VIRTUAL 65
  9248. #define TK_WITH 66
  9249. #define TK_REINDEX 67
  9250. #define TK_RENAME 68
  9251. #define TK_CTIME_KW 69
  9252. #define TK_ANY 70
  9253. #define TK_OR 71
  9254. #define TK_AND 72
  9255. #define TK_IS 73
  9256. #define TK_BETWEEN 74
  9257. #define TK_IN 75
  9258. #define TK_ISNULL 76
  9259. #define TK_NOTNULL 77
  9260. #define TK_NE 78
  9261. #define TK_EQ 79
  9262. #define TK_GT 80
  9263. #define TK_LE 81
  9264. #define TK_LT 82
  9265. #define TK_GE 83
  9266. #define TK_ESCAPE 84
  9267. #define TK_BITAND 85
  9268. #define TK_BITOR 86
  9269. #define TK_LSHIFT 87
  9270. #define TK_RSHIFT 88
  9271. #define TK_PLUS 89
  9272. #define TK_MINUS 90
  9273. #define TK_STAR 91
  9274. #define TK_SLASH 92
  9275. #define TK_REM 93
  9276. #define TK_CONCAT 94
  9277. #define TK_COLLATE 95
  9278. #define TK_BITNOT 96
  9279. #define TK_STRING 97
  9280. #define TK_JOIN_KW 98
  9281. #define TK_CONSTRAINT 99
  9282. #define TK_DEFAULT 100
  9283. #define TK_NULL 101
  9284. #define TK_PRIMARY 102
  9285. #define TK_UNIQUE 103
  9286. #define TK_CHECK 104
  9287. #define TK_REFERENCES 105
  9288. #define TK_AUTOINCR 106
  9289. #define TK_ON 107
  9290. #define TK_INSERT 108
  9291. #define TK_DELETE 109
  9292. #define TK_UPDATE 110
  9293. #define TK_SET 111
  9294. #define TK_DEFERRABLE 112
  9295. #define TK_FOREIGN 113
  9296. #define TK_DROP 114
  9297. #define TK_UNION 115
  9298. #define TK_ALL 116
  9299. #define TK_EXCEPT 117
  9300. #define TK_INTERSECT 118
  9301. #define TK_SELECT 119
  9302. #define TK_VALUES 120
  9303. #define TK_DISTINCT 121
  9304. #define TK_DOT 122
  9305. #define TK_FROM 123
  9306. #define TK_JOIN 124
  9307. #define TK_USING 125
  9308. #define TK_ORDER 126
  9309. #define TK_GROUP 127
  9310. #define TK_HAVING 128
  9311. #define TK_LIMIT 129
  9312. #define TK_WHERE 130
  9313. #define TK_INTO 131
  9314. #define TK_INTEGER 132
  9315. #define TK_FLOAT 133
  9316. #define TK_BLOB 134
  9317. #define TK_VARIABLE 135
  9318. #define TK_CASE 136
  9319. #define TK_WHEN 137
  9320. #define TK_THEN 138
  9321. #define TK_ELSE 139
  9322. #define TK_INDEX 140
  9323. #define TK_ALTER 141
  9324. #define TK_ADD 142
  9325. #define TK_TO_TEXT 143
  9326. #define TK_TO_BLOB 144
  9327. #define TK_TO_NUMERIC 145
  9328. #define TK_TO_INT 146
  9329. #define TK_TO_REAL 147
  9330. #define TK_ISNOT 148
  9331. #define TK_END_OF_FILE 149
  9332. #define TK_UNCLOSED_STRING 150
  9333. #define TK_FUNCTION 151
  9334. #define TK_COLUMN 152
  9335. #define TK_AGG_FUNCTION 153
  9336. #define TK_AGG_COLUMN 154
  9337. #define TK_UMINUS 155
  9338. #define TK_UPLUS 156
  9339. #define TK_REGISTER 157
  9340. #define TK_ASTERISK 158
  9341. #define TK_SPACE 159
  9342. #define TK_ILLEGAL 160
  9343. /* The token codes above must all fit in 8 bits */
  9344. #define TKFLG_MASK 0xff
  9345. /* Flags that can be added to a token code when it is not
  9346. ** being stored in a u8: */
  9347. #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
  9348. /************** End of parse.h ***********************************************/
  9349. /************** Continuing where we left off in sqliteInt.h ******************/
  9350. #include <stdio.h>
  9351. #include <stdlib.h>
  9352. #include <string.h>
  9353. #include <assert.h>
  9354. #include <stddef.h>
  9355. /*
  9356. ** If compiling for a processor that lacks floating point support,
  9357. ** substitute integer for floating-point
  9358. */
  9359. #ifdef SQLITE_OMIT_FLOATING_POINT
  9360. # define double sqlite_int64
  9361. # define float sqlite_int64
  9362. # define LONGDOUBLE_TYPE sqlite_int64
  9363. # ifndef SQLITE_BIG_DBL
  9364. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  9365. # endif
  9366. # define SQLITE_OMIT_DATETIME_FUNCS 1
  9367. # define SQLITE_OMIT_TRACE 1
  9368. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  9369. # undef SQLITE_HAVE_ISNAN
  9370. #endif
  9371. #ifndef SQLITE_BIG_DBL
  9372. # define SQLITE_BIG_DBL (1e99)
  9373. #endif
  9374. /*
  9375. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  9376. ** afterward. Having this macro allows us to cause the C compiler
  9377. ** to omit code used by TEMP tables without messy #ifndef statements.
  9378. */
  9379. #ifdef SQLITE_OMIT_TEMPDB
  9380. #define OMIT_TEMPDB 1
  9381. #else
  9382. #define OMIT_TEMPDB 0
  9383. #endif
  9384. /*
  9385. ** The "file format" number is an integer that is incremented whenever
  9386. ** the VDBE-level file format changes. The following macros define the
  9387. ** the default file format for new databases and the maximum file format
  9388. ** that the library can read.
  9389. */
  9390. #define SQLITE_MAX_FILE_FORMAT 4
  9391. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  9392. # define SQLITE_DEFAULT_FILE_FORMAT 4
  9393. #endif
  9394. /*
  9395. ** Determine whether triggers are recursive by default. This can be
  9396. ** changed at run-time using a pragma.
  9397. */
  9398. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  9399. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  9400. #endif
  9401. /*
  9402. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  9403. ** on the command-line
  9404. */
  9405. #ifndef SQLITE_TEMP_STORE
  9406. # define SQLITE_TEMP_STORE 1
  9407. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  9408. #endif
  9409. /*
  9410. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  9411. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  9412. ** to zero.
  9413. */
  9414. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  9415. # undef SQLITE_MAX_WORKER_THREADS
  9416. # define SQLITE_MAX_WORKER_THREADS 0
  9417. #endif
  9418. #ifndef SQLITE_MAX_WORKER_THREADS
  9419. # define SQLITE_MAX_WORKER_THREADS 8
  9420. #endif
  9421. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  9422. # define SQLITE_DEFAULT_WORKER_THREADS 0
  9423. #endif
  9424. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  9425. # undef SQLITE_MAX_WORKER_THREADS
  9426. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  9427. #endif
  9428. /*
  9429. ** The default initial allocation for the pagecache when using separate
  9430. ** pagecaches for each database connection. A positive number is the
  9431. ** number of pages. A negative number N translations means that a buffer
  9432. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  9433. */
  9434. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  9435. # define SQLITE_DEFAULT_PCACHE_INITSZ 100
  9436. #endif
  9437. /*
  9438. ** GCC does not define the offsetof() macro so we'll have to do it
  9439. ** ourselves.
  9440. */
  9441. #ifndef offsetof
  9442. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  9443. #endif
  9444. /*
  9445. ** Macros to compute minimum and maximum of two numbers.
  9446. */
  9447. #define MIN(A,B) ((A)<(B)?(A):(B))
  9448. #define MAX(A,B) ((A)>(B)?(A):(B))
  9449. /*
  9450. ** Swap two objects of type TYPE.
  9451. */
  9452. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  9453. /*
  9454. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  9455. ** not, there are still machines out there that use EBCDIC.)
  9456. */
  9457. #if 'A' == '\301'
  9458. # define SQLITE_EBCDIC 1
  9459. #else
  9460. # define SQLITE_ASCII 1
  9461. #endif
  9462. /*
  9463. ** Integers of known sizes. These typedefs might change for architectures
  9464. ** where the sizes very. Preprocessor macros are available so that the
  9465. ** types can be conveniently redefined at compile-type. Like this:
  9466. **
  9467. ** cc '-DUINTPTR_TYPE=long long int' ...
  9468. */
  9469. #ifndef UINT32_TYPE
  9470. # ifdef HAVE_UINT32_T
  9471. # define UINT32_TYPE uint32_t
  9472. # else
  9473. # define UINT32_TYPE unsigned int
  9474. # endif
  9475. #endif
  9476. #ifndef UINT16_TYPE
  9477. # ifdef HAVE_UINT16_T
  9478. # define UINT16_TYPE uint16_t
  9479. # else
  9480. # define UINT16_TYPE unsigned short int
  9481. # endif
  9482. #endif
  9483. #ifndef INT16_TYPE
  9484. # ifdef HAVE_INT16_T
  9485. # define INT16_TYPE int16_t
  9486. # else
  9487. # define INT16_TYPE short int
  9488. # endif
  9489. #endif
  9490. #ifndef UINT8_TYPE
  9491. # ifdef HAVE_UINT8_T
  9492. # define UINT8_TYPE uint8_t
  9493. # else
  9494. # define UINT8_TYPE unsigned char
  9495. # endif
  9496. #endif
  9497. #ifndef INT8_TYPE
  9498. # ifdef HAVE_INT8_T
  9499. # define INT8_TYPE int8_t
  9500. # else
  9501. # define INT8_TYPE signed char
  9502. # endif
  9503. #endif
  9504. #ifndef LONGDOUBLE_TYPE
  9505. # define LONGDOUBLE_TYPE long double
  9506. #endif
  9507. typedef sqlite_int64 i64; /* 8-byte signed integer */
  9508. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  9509. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  9510. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  9511. typedef INT16_TYPE i16; /* 2-byte signed integer */
  9512. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  9513. typedef INT8_TYPE i8; /* 1-byte signed integer */
  9514. /*
  9515. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  9516. ** that can be stored in a u32 without loss of data. The value
  9517. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  9518. ** have to specify the value in the less intuitive manner shown:
  9519. */
  9520. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  9521. /*
  9522. ** The datatype used to store estimates of the number of rows in a
  9523. ** table or index. This is an unsigned integer type. For 99.9% of
  9524. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  9525. ** can be used at compile-time if desired.
  9526. */
  9527. #ifdef SQLITE_64BIT_STATS
  9528. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  9529. #else
  9530. typedef u32 tRowcnt; /* 32-bit is the default */
  9531. #endif
  9532. /*
  9533. ** Estimated quantities used for query planning are stored as 16-bit
  9534. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  9535. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  9536. ** But the allowed values are "grainy". Not every value is representable.
  9537. ** For example, quantities 16 and 17 are both represented by a LogEst
  9538. ** of 40. However, since LogEst quantities are suppose to be estimates,
  9539. ** not exact values, this imprecision is not a problem.
  9540. **
  9541. ** "LogEst" is short for "Logarithmic Estimate".
  9542. **
  9543. ** Examples:
  9544. ** 1 -> 0 20 -> 43 10000 -> 132
  9545. ** 2 -> 10 25 -> 46 25000 -> 146
  9546. ** 3 -> 16 100 -> 66 1000000 -> 199
  9547. ** 4 -> 20 1000 -> 99 1048576 -> 200
  9548. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  9549. **
  9550. ** The LogEst can be negative to indicate fractional values.
  9551. ** Examples:
  9552. **
  9553. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  9554. */
  9555. typedef INT16_TYPE LogEst;
  9556. /*
  9557. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  9558. */
  9559. #ifndef SQLITE_PTRSIZE
  9560. # if defined(__SIZEOF_POINTER__)
  9561. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  9562. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  9563. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  9564. # define SQLITE_PTRSIZE 4
  9565. # else
  9566. # define SQLITE_PTRSIZE 8
  9567. # endif
  9568. #endif
  9569. /*
  9570. ** Macros to determine whether the machine is big or little endian,
  9571. ** and whether or not that determination is run-time or compile-time.
  9572. **
  9573. ** For best performance, an attempt is made to guess at the byte-order
  9574. ** using C-preprocessor macros. If that is unsuccessful, or if
  9575. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  9576. ** at run-time.
  9577. */
  9578. #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  9579. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  9580. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  9581. defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
  9582. # define SQLITE_BYTEORDER 1234
  9583. # define SQLITE_BIGENDIAN 0
  9584. # define SQLITE_LITTLEENDIAN 1
  9585. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  9586. #endif
  9587. #if (defined(sparc) || defined(__ppc__)) \
  9588. && !defined(SQLITE_RUNTIME_BYTEORDER)
  9589. # define SQLITE_BYTEORDER 4321
  9590. # define SQLITE_BIGENDIAN 1
  9591. # define SQLITE_LITTLEENDIAN 0
  9592. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  9593. #endif
  9594. #if !defined(SQLITE_BYTEORDER)
  9595. # ifdef SQLITE_AMALGAMATION
  9596. const int sqlite3one = 1;
  9597. # else
  9598. extern const int sqlite3one;
  9599. # endif
  9600. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  9601. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  9602. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  9603. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  9604. #endif
  9605. /*
  9606. ** Constants for the largest and smallest possible 64-bit signed integers.
  9607. ** These macros are designed to work correctly on both 32-bit and 64-bit
  9608. ** compilers.
  9609. */
  9610. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  9611. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  9612. /*
  9613. ** Round up a number to the next larger multiple of 8. This is used
  9614. ** to force 8-byte alignment on 64-bit architectures.
  9615. */
  9616. #define ROUND8(x) (((x)+7)&~7)
  9617. /*
  9618. ** Round down to the nearest multiple of 8
  9619. */
  9620. #define ROUNDDOWN8(x) ((x)&~7)
  9621. /*
  9622. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  9623. ** macro is used only within assert() to verify that the code gets
  9624. ** all alignment restrictions correct.
  9625. **
  9626. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  9627. ** underlying malloc() implementation might return us 4-byte aligned
  9628. ** pointers. In that case, only verify 4-byte alignment.
  9629. */
  9630. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  9631. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  9632. #else
  9633. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  9634. #endif
  9635. /*
  9636. ** Disable MMAP on platforms where it is known to not work
  9637. */
  9638. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  9639. # undef SQLITE_MAX_MMAP_SIZE
  9640. # define SQLITE_MAX_MMAP_SIZE 0
  9641. #endif
  9642. /*
  9643. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  9644. */
  9645. #ifdef __APPLE__
  9646. # include <TargetConditionals.h>
  9647. # if TARGET_OS_IPHONE
  9648. # undef SQLITE_MAX_MMAP_SIZE
  9649. # define SQLITE_MAX_MMAP_SIZE 0
  9650. # endif
  9651. #endif
  9652. #ifndef SQLITE_MAX_MMAP_SIZE
  9653. # if defined(__linux__) \
  9654. || defined(_WIN32) \
  9655. || (defined(__APPLE__) && defined(__MACH__)) \
  9656. || defined(__sun) \
  9657. || defined(__FreeBSD__) \
  9658. || defined(__DragonFly__)
  9659. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  9660. # else
  9661. # define SQLITE_MAX_MMAP_SIZE 0
  9662. # endif
  9663. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  9664. #endif
  9665. /*
  9666. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  9667. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  9668. ** not exceed the maximum mmap size.
  9669. */
  9670. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  9671. # define SQLITE_DEFAULT_MMAP_SIZE 0
  9672. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  9673. #endif
  9674. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  9675. # undef SQLITE_DEFAULT_MMAP_SIZE
  9676. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  9677. #endif
  9678. /*
  9679. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  9680. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  9681. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  9682. */
  9683. #ifdef SQLITE_ENABLE_STAT4
  9684. # undef SQLITE_ENABLE_STAT3
  9685. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  9686. #elif SQLITE_ENABLE_STAT3
  9687. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  9688. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  9689. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  9690. #endif
  9691. /*
  9692. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  9693. ** the Select query generator tracing logic is turned on.
  9694. */
  9695. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  9696. # define SELECTTRACE_ENABLED 1
  9697. #else
  9698. # define SELECTTRACE_ENABLED 0
  9699. #endif
  9700. /*
  9701. ** An instance of the following structure is used to store the busy-handler
  9702. ** callback for a given sqlite handle.
  9703. **
  9704. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  9705. ** callback for the database handle. Each pager opened via the sqlite
  9706. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  9707. ** callback is currently invoked only from within pager.c.
  9708. */
  9709. typedef struct BusyHandler BusyHandler;
  9710. struct BusyHandler {
  9711. int (*xFunc)(void *,int); /* The busy callback */
  9712. void *pArg; /* First arg to busy callback */
  9713. int nBusy; /* Incremented with each busy call */
  9714. };
  9715. /*
  9716. ** Name of the master database table. The master database table
  9717. ** is a special table that holds the names and attributes of all
  9718. ** user tables and indices.
  9719. */
  9720. #define MASTER_NAME "sqlite_master"
  9721. #define TEMP_MASTER_NAME "sqlite_temp_master"
  9722. /*
  9723. ** The root-page of the master database table.
  9724. */
  9725. #define MASTER_ROOT 1
  9726. /*
  9727. ** The name of the schema table.
  9728. */
  9729. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  9730. /*
  9731. ** A convenience macro that returns the number of elements in
  9732. ** an array.
  9733. */
  9734. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  9735. /*
  9736. ** Determine if the argument is a power of two
  9737. */
  9738. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  9739. /*
  9740. ** The following value as a destructor means to use sqlite3DbFree().
  9741. ** The sqlite3DbFree() routine requires two parameters instead of the
  9742. ** one parameter that destructors normally want. So we have to introduce
  9743. ** this magic value that the code knows to handle differently. Any
  9744. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  9745. ** and SQLITE_TRANSIENT.
  9746. */
  9747. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  9748. /*
  9749. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  9750. ** not support Writable Static Data (WSD) such as global and static variables.
  9751. ** All variables must either be on the stack or dynamically allocated from
  9752. ** the heap. When WSD is unsupported, the variable declarations scattered
  9753. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  9754. ** macro is used for this purpose. And instead of referencing the variable
  9755. ** directly, we use its constant as a key to lookup the run-time allocated
  9756. ** buffer that holds real variable. The constant is also the initializer
  9757. ** for the run-time allocated buffer.
  9758. **
  9759. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  9760. ** macros become no-ops and have zero performance impact.
  9761. */
  9762. #ifdef SQLITE_OMIT_WSD
  9763. #define SQLITE_WSD const
  9764. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  9765. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  9766. SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
  9767. SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
  9768. #else
  9769. #define SQLITE_WSD
  9770. #define GLOBAL(t,v) v
  9771. #define sqlite3GlobalConfig sqlite3Config
  9772. #endif
  9773. /*
  9774. ** The following macros are used to suppress compiler warnings and to
  9775. ** make it clear to human readers when a function parameter is deliberately
  9776. ** left unused within the body of a function. This usually happens when
  9777. ** a function is called via a function pointer. For example the
  9778. ** implementation of an SQL aggregate step callback may not use the
  9779. ** parameter indicating the number of arguments passed to the aggregate,
  9780. ** if it knows that this is enforced elsewhere.
  9781. **
  9782. ** When a function parameter is not used at all within the body of a function,
  9783. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  9784. ** However, these macros may also be used to suppress warnings related to
  9785. ** parameters that may or may not be used depending on compilation options.
  9786. ** For example those parameters only used in assert() statements. In these
  9787. ** cases the parameters are named as per the usual conventions.
  9788. */
  9789. #define UNUSED_PARAMETER(x) (void)(x)
  9790. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  9791. /*
  9792. ** Forward references to structures
  9793. */
  9794. typedef struct AggInfo AggInfo;
  9795. typedef struct AuthContext AuthContext;
  9796. typedef struct AutoincInfo AutoincInfo;
  9797. typedef struct Bitvec Bitvec;
  9798. typedef struct CollSeq CollSeq;
  9799. typedef struct Column Column;
  9800. typedef struct Db Db;
  9801. typedef struct Schema Schema;
  9802. typedef struct Expr Expr;
  9803. typedef struct ExprList ExprList;
  9804. typedef struct ExprSpan ExprSpan;
  9805. typedef struct FKey FKey;
  9806. typedef struct FuncDestructor FuncDestructor;
  9807. typedef struct FuncDef FuncDef;
  9808. typedef struct FuncDefHash FuncDefHash;
  9809. typedef struct IdList IdList;
  9810. typedef struct Index Index;
  9811. typedef struct IndexSample IndexSample;
  9812. typedef struct KeyClass KeyClass;
  9813. typedef struct KeyInfo KeyInfo;
  9814. typedef struct Lookaside Lookaside;
  9815. typedef struct LookasideSlot LookasideSlot;
  9816. typedef struct Module Module;
  9817. typedef struct NameContext NameContext;
  9818. typedef struct Parse Parse;
  9819. typedef struct PrintfArguments PrintfArguments;
  9820. typedef struct RowSet RowSet;
  9821. typedef struct Savepoint Savepoint;
  9822. typedef struct Select Select;
  9823. typedef struct SQLiteThread SQLiteThread;
  9824. typedef struct SelectDest SelectDest;
  9825. typedef struct SrcList SrcList;
  9826. typedef struct StrAccum StrAccum;
  9827. typedef struct Table Table;
  9828. typedef struct TableLock TableLock;
  9829. typedef struct Token Token;
  9830. typedef struct TreeView TreeView;
  9831. typedef struct Trigger Trigger;
  9832. typedef struct TriggerPrg TriggerPrg;
  9833. typedef struct TriggerStep TriggerStep;
  9834. typedef struct UnpackedRecord UnpackedRecord;
  9835. typedef struct VTable VTable;
  9836. typedef struct VtabCtx VtabCtx;
  9837. typedef struct Walker Walker;
  9838. typedef struct WhereInfo WhereInfo;
  9839. typedef struct With With;
  9840. /*
  9841. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  9842. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  9843. ** pointer types (i.e. FuncDef) defined above.
  9844. */
  9845. /************** Include btree.h in the middle of sqliteInt.h *****************/
  9846. /************** Begin file btree.h *******************************************/
  9847. /*
  9848. ** 2001 September 15
  9849. **
  9850. ** The author disclaims copyright to this source code. In place of
  9851. ** a legal notice, here is a blessing:
  9852. **
  9853. ** May you do good and not evil.
  9854. ** May you find forgiveness for yourself and forgive others.
  9855. ** May you share freely, never taking more than you give.
  9856. **
  9857. *************************************************************************
  9858. ** This header file defines the interface that the sqlite B-Tree file
  9859. ** subsystem. See comments in the source code for a detailed description
  9860. ** of what each interface routine does.
  9861. */
  9862. #ifndef _BTREE_H_
  9863. #define _BTREE_H_
  9864. /* TODO: This definition is just included so other modules compile. It
  9865. ** needs to be revisited.
  9866. */
  9867. #define SQLITE_N_BTREE_META 16
  9868. /*
  9869. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  9870. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  9871. */
  9872. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  9873. #define SQLITE_DEFAULT_AUTOVACUUM 0
  9874. #endif
  9875. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  9876. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  9877. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  9878. /*
  9879. ** Forward declarations of structure
  9880. */
  9881. typedef struct Btree Btree;
  9882. typedef struct BtCursor BtCursor;
  9883. typedef struct BtShared BtShared;
  9884. SQLITE_PRIVATE int sqlite3BtreeOpen(
  9885. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  9886. const char *zFilename, /* Name of database file to open */
  9887. sqlite3 *db, /* Associated database connection */
  9888. Btree **ppBtree, /* Return open Btree* here */
  9889. int flags, /* Flags */
  9890. int vfsFlags /* Flags passed through to VFS open */
  9891. );
  9892. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  9893. ** following values.
  9894. **
  9895. ** NOTE: These values must match the corresponding PAGER_ values in
  9896. ** pager.h.
  9897. */
  9898. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  9899. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  9900. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  9901. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  9902. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  9903. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  9904. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  9905. #if SQLITE_MAX_MMAP_SIZE>0
  9906. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  9907. #endif
  9908. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  9909. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  9910. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  9911. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  9912. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  9913. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  9914. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  9915. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  9916. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  9917. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  9918. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  9919. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  9920. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  9921. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  9922. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  9923. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  9924. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  9925. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  9926. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  9927. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  9928. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  9929. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  9930. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  9931. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  9932. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  9933. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  9934. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  9935. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  9936. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  9937. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  9938. ** of the flags shown below.
  9939. **
  9940. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  9941. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  9942. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  9943. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  9944. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  9945. ** indices.)
  9946. */
  9947. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  9948. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  9949. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  9950. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  9951. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  9952. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  9953. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  9954. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  9955. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  9956. /*
  9957. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  9958. ** should be one of the following values. The integer values are assigned
  9959. ** to constants so that the offset of the corresponding field in an
  9960. ** SQLite database header may be found using the following formula:
  9961. **
  9962. ** offset = 36 + (idx * 4)
  9963. **
  9964. ** For example, the free-page-count field is located at byte offset 36 of
  9965. ** the database file header. The incr-vacuum-flag field is located at
  9966. ** byte offset 64 (== 36+4*7).
  9967. **
  9968. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  9969. ** It is a read-only number computed by the pager. But we merge it with
  9970. ** the header value access routines since its access pattern is the same.
  9971. ** Call it a "virtual meta value".
  9972. */
  9973. #define BTREE_FREE_PAGE_COUNT 0
  9974. #define BTREE_SCHEMA_VERSION 1
  9975. #define BTREE_FILE_FORMAT 2
  9976. #define BTREE_DEFAULT_CACHE_SIZE 3
  9977. #define BTREE_LARGEST_ROOT_PAGE 4
  9978. #define BTREE_TEXT_ENCODING 5
  9979. #define BTREE_USER_VERSION 6
  9980. #define BTREE_INCR_VACUUM 7
  9981. #define BTREE_APPLICATION_ID 8
  9982. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  9983. /*
  9984. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  9985. ** interface.
  9986. **
  9987. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  9988. **
  9989. ** The first argument is an Expr* (which is guaranteed to be constant for
  9990. ** the lifetime of the cursor) that defines constraints on which rows
  9991. ** might be fetched with this cursor. The Expr* tree may contain
  9992. ** TK_REGISTER nodes that refer to values stored in the array of registers
  9993. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  9994. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  9995. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  9996. ** column of the b-tree of the cursor. The Expr tree will not contain
  9997. ** any function calls nor subqueries nor references to b-trees other than
  9998. ** the cursor being hinted.
  9999. **
  10000. ** The design of the _RANGE hint is aid b-tree implementations that try
  10001. ** to prefetch content from remote machines - to provide those
  10002. ** implementations with limits on what needs to be prefetched and thereby
  10003. ** reduce network bandwidth.
  10004. **
  10005. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  10006. ** standard SQLite. The other hints are provided for extentions that use
  10007. ** the SQLite parser and code generator but substitute their own storage
  10008. ** engine.
  10009. */
  10010. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  10011. /*
  10012. ** Values that may be OR'd together to form the argument to the
  10013. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  10014. **
  10015. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  10016. ** to be filled with content that is already in sorted order.
  10017. **
  10018. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  10019. ** OP_SeekLE opcodes for a range search, but where the range of entries
  10020. ** selected will all have the same key. In other words, the cursor will
  10021. ** be used only for equality key searches.
  10022. **
  10023. */
  10024. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  10025. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  10026. /*
  10027. ** Flags passed as the third argument to sqlite3BtreeCursor().
  10028. **
  10029. ** For read-only cursors the wrFlag argument is always zero. For read-write
  10030. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or
  10031. ** (BTREE_WRCSR). If the BTREE_FORDELETE flag is set, then the cursor will
  10032. ** only be used by SQLite for the following:
  10033. **
  10034. ** * to seek to and delete specific entries, and/or
  10035. **
  10036. ** * to read values that will be used to create keys that other
  10037. ** BTREE_FORDELETE cursors will seek to and delete.
  10038. */
  10039. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  10040. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  10041. SQLITE_PRIVATE int sqlite3BtreeCursor(
  10042. Btree*, /* BTree containing table to open */
  10043. int iTable, /* Index of root page */
  10044. int wrFlag, /* 1 for writing. 0 for read-only */
  10045. struct KeyInfo*, /* First argument to compare function */
  10046. BtCursor *pCursor /* Space to write cursor structure */
  10047. );
  10048. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  10049. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  10050. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  10051. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  10052. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  10053. #endif
  10054. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  10055. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  10056. BtCursor*,
  10057. UnpackedRecord *pUnKey,
  10058. i64 intKey,
  10059. int bias,
  10060. int *pRes
  10061. );
  10062. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  10063. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  10064. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, int);
  10065. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  10066. const void *pData, int nData,
  10067. int nZero, int bias, int seekResult);
  10068. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  10069. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  10070. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  10071. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  10072. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  10073. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  10074. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  10075. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
  10076. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
  10077. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  10078. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  10079. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  10080. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  10081. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  10082. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  10083. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  10084. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  10085. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  10086. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  10087. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  10088. #ifndef NDEBUG
  10089. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  10090. #endif
  10091. #ifndef SQLITE_OMIT_BTREECOUNT
  10092. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  10093. #endif
  10094. #ifdef SQLITE_TEST
  10095. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  10096. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  10097. #endif
  10098. #ifndef SQLITE_OMIT_WAL
  10099. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  10100. #endif
  10101. /*
  10102. ** If we are not using shared cache, then there is no need to
  10103. ** use mutexes to access the BtShared structures. So make the
  10104. ** Enter and Leave procedures no-ops.
  10105. */
  10106. #ifndef SQLITE_OMIT_SHARED_CACHE
  10107. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  10108. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  10109. #else
  10110. # define sqlite3BtreeEnter(X)
  10111. # define sqlite3BtreeEnterAll(X)
  10112. #endif
  10113. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  10114. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  10115. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  10116. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  10117. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  10118. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  10119. #ifndef NDEBUG
  10120. /* These routines are used inside assert() statements only. */
  10121. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  10122. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  10123. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  10124. #endif
  10125. #else
  10126. # define sqlite3BtreeSharable(X) 0
  10127. # define sqlite3BtreeLeave(X)
  10128. # define sqlite3BtreeEnterCursor(X)
  10129. # define sqlite3BtreeLeaveCursor(X)
  10130. # define sqlite3BtreeLeaveAll(X)
  10131. # define sqlite3BtreeHoldsMutex(X) 1
  10132. # define sqlite3BtreeHoldsAllMutexes(X) 1
  10133. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  10134. #endif
  10135. #endif /* _BTREE_H_ */
  10136. /************** End of btree.h ***********************************************/
  10137. /************** Continuing where we left off in sqliteInt.h ******************/
  10138. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  10139. /************** Begin file vdbe.h ********************************************/
  10140. /*
  10141. ** 2001 September 15
  10142. **
  10143. ** The author disclaims copyright to this source code. In place of
  10144. ** a legal notice, here is a blessing:
  10145. **
  10146. ** May you do good and not evil.
  10147. ** May you find forgiveness for yourself and forgive others.
  10148. ** May you share freely, never taking more than you give.
  10149. **
  10150. *************************************************************************
  10151. ** Header file for the Virtual DataBase Engine (VDBE)
  10152. **
  10153. ** This header defines the interface to the virtual database engine
  10154. ** or VDBE. The VDBE implements an abstract machine that runs a
  10155. ** simple program to access and modify the underlying database.
  10156. */
  10157. #ifndef _SQLITE_VDBE_H_
  10158. #define _SQLITE_VDBE_H_
  10159. /* #include <stdio.h> */
  10160. /*
  10161. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  10162. ** in the source file sqliteVdbe.c are allowed to see the insides
  10163. ** of this structure.
  10164. */
  10165. typedef struct Vdbe Vdbe;
  10166. /*
  10167. ** The names of the following types declared in vdbeInt.h are required
  10168. ** for the VdbeOp definition.
  10169. */
  10170. typedef struct Mem Mem;
  10171. typedef struct SubProgram SubProgram;
  10172. /*
  10173. ** A single instruction of the virtual machine has an opcode
  10174. ** and as many as three operands. The instruction is recorded
  10175. ** as an instance of the following structure:
  10176. */
  10177. struct VdbeOp {
  10178. u8 opcode; /* What operation to perform */
  10179. signed char p4type; /* One of the P4_xxx constants for p4 */
  10180. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  10181. u8 p5; /* Fifth parameter is an unsigned character */
  10182. int p1; /* First operand */
  10183. int p2; /* Second parameter (often the jump destination) */
  10184. int p3; /* The third parameter */
  10185. union p4union { /* fourth parameter */
  10186. int i; /* Integer value if p4type==P4_INT32 */
  10187. void *p; /* Generic pointer */
  10188. char *z; /* Pointer to data for string (char array) types */
  10189. i64 *pI64; /* Used when p4type is P4_INT64 */
  10190. double *pReal; /* Used when p4type is P4_REAL */
  10191. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  10192. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  10193. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  10194. Mem *pMem; /* Used when p4type is P4_MEM */
  10195. VTable *pVtab; /* Used when p4type is P4_VTAB */
  10196. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  10197. int *ai; /* Used when p4type is P4_INTARRAY */
  10198. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  10199. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  10200. Expr *pExpr; /* Used when p4type is P4_EXPR */
  10201. #endif
  10202. int (*xAdvance)(BtCursor *, int *);
  10203. } p4;
  10204. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  10205. char *zComment; /* Comment to improve readability */
  10206. #endif
  10207. #ifdef VDBE_PROFILE
  10208. u32 cnt; /* Number of times this instruction was executed */
  10209. u64 cycles; /* Total time spent executing this instruction */
  10210. #endif
  10211. #ifdef SQLITE_VDBE_COVERAGE
  10212. int iSrcLine; /* Source-code line that generated this opcode */
  10213. #endif
  10214. };
  10215. typedef struct VdbeOp VdbeOp;
  10216. /*
  10217. ** A sub-routine used to implement a trigger program.
  10218. */
  10219. struct SubProgram {
  10220. VdbeOp *aOp; /* Array of opcodes for sub-program */
  10221. int nOp; /* Elements in aOp[] */
  10222. int nMem; /* Number of memory cells required */
  10223. int nCsr; /* Number of cursors required */
  10224. int nOnce; /* Number of OP_Once instructions */
  10225. void *token; /* id that may be used to recursive triggers */
  10226. SubProgram *pNext; /* Next sub-program already visited */
  10227. };
  10228. /*
  10229. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  10230. ** it takes up less space.
  10231. */
  10232. struct VdbeOpList {
  10233. u8 opcode; /* What operation to perform */
  10234. signed char p1; /* First operand */
  10235. signed char p2; /* Second parameter (often the jump destination) */
  10236. signed char p3; /* Third parameter */
  10237. };
  10238. typedef struct VdbeOpList VdbeOpList;
  10239. /*
  10240. ** Allowed values of VdbeOp.p4type
  10241. */
  10242. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  10243. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  10244. #define P4_STATIC (-2) /* Pointer to a static string */
  10245. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  10246. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  10247. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  10248. #define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */
  10249. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  10250. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  10251. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  10252. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  10253. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  10254. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  10255. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  10256. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  10257. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  10258. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  10259. #define P4_FUNCCTX (-20) /* P4 is a pointer to an sqlite3_context object */
  10260. /* Error message codes for OP_Halt */
  10261. #define P5_ConstraintNotNull 1
  10262. #define P5_ConstraintUnique 2
  10263. #define P5_ConstraintCheck 3
  10264. #define P5_ConstraintFK 4
  10265. /*
  10266. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  10267. ** number of columns of data returned by the statement.
  10268. */
  10269. #define COLNAME_NAME 0
  10270. #define COLNAME_DECLTYPE 1
  10271. #define COLNAME_DATABASE 2
  10272. #define COLNAME_TABLE 3
  10273. #define COLNAME_COLUMN 4
  10274. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  10275. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  10276. #else
  10277. # ifdef SQLITE_OMIT_DECLTYPE
  10278. # define COLNAME_N 1 /* Store only the name */
  10279. # else
  10280. # define COLNAME_N 2 /* Store the name and decltype */
  10281. # endif
  10282. #endif
  10283. /*
  10284. ** The following macro converts a relative address in the p2 field
  10285. ** of a VdbeOp structure into a negative number so that
  10286. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  10287. ** the macro again restores the address.
  10288. */
  10289. #define ADDR(X) (-1-(X))
  10290. /*
  10291. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  10292. ** header file that defines a number for each opcode used by the VDBE.
  10293. */
  10294. /************** Include opcodes.h in the middle of vdbe.h ********************/
  10295. /************** Begin file opcodes.h *****************************************/
  10296. /* Automatically generated. Do not edit */
  10297. /* See the tool/mkopcodeh.tcl script for details */
  10298. #define OP_Savepoint 1
  10299. #define OP_AutoCommit 2
  10300. #define OP_Transaction 3
  10301. #define OP_SorterNext 4
  10302. #define OP_PrevIfOpen 5
  10303. #define OP_NextIfOpen 6
  10304. #define OP_Prev 7
  10305. #define OP_Next 8
  10306. #define OP_Checkpoint 9
  10307. #define OP_JournalMode 10
  10308. #define OP_Vacuum 11
  10309. #define OP_VFilter 12 /* synopsis: iplan=r[P3] zplan='P4' */
  10310. #define OP_VUpdate 13 /* synopsis: data=r[P3@P2] */
  10311. #define OP_Goto 14
  10312. #define OP_Gosub 15
  10313. #define OP_Return 16
  10314. #define OP_InitCoroutine 17
  10315. #define OP_EndCoroutine 18
  10316. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  10317. #define OP_Yield 20
  10318. #define OP_HaltIfNull 21 /* synopsis: if r[P3]=null halt */
  10319. #define OP_Halt 22
  10320. #define OP_Integer 23 /* synopsis: r[P2]=P1 */
  10321. #define OP_Int64 24 /* synopsis: r[P2]=P4 */
  10322. #define OP_String 25 /* synopsis: r[P2]='P4' (len=P1) */
  10323. #define OP_Null 26 /* synopsis: r[P2..P3]=NULL */
  10324. #define OP_SoftNull 27 /* synopsis: r[P1]=NULL */
  10325. #define OP_Blob 28 /* synopsis: r[P2]=P4 (len=P1) */
  10326. #define OP_Variable 29 /* synopsis: r[P2]=parameter(P1,P4) */
  10327. #define OP_Move 30 /* synopsis: r[P2@P3]=r[P1@P3] */
  10328. #define OP_Copy 31 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  10329. #define OP_SCopy 32 /* synopsis: r[P2]=r[P1] */
  10330. #define OP_IntCopy 33 /* synopsis: r[P2]=r[P1] */
  10331. #define OP_ResultRow 34 /* synopsis: output=r[P1@P2] */
  10332. #define OP_CollSeq 35
  10333. #define OP_Function0 36 /* synopsis: r[P3]=func(r[P2@P5]) */
  10334. #define OP_Function 37 /* synopsis: r[P3]=func(r[P2@P5]) */
  10335. #define OP_AddImm 38 /* synopsis: r[P1]=r[P1]+P2 */
  10336. #define OP_MustBeInt 39
  10337. #define OP_RealAffinity 40
  10338. #define OP_Cast 41 /* synopsis: affinity(r[P1]) */
  10339. #define OP_Permutation 42
  10340. #define OP_Compare 43 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  10341. #define OP_Jump 44
  10342. #define OP_Once 45
  10343. #define OP_If 46
  10344. #define OP_IfNot 47
  10345. #define OP_Column 48 /* synopsis: r[P3]=PX */
  10346. #define OP_Affinity 49 /* synopsis: affinity(r[P1@P2]) */
  10347. #define OP_MakeRecord 50 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  10348. #define OP_Count 51 /* synopsis: r[P2]=count() */
  10349. #define OP_ReadCookie 52
  10350. #define OP_SetCookie 53
  10351. #define OP_ReopenIdx 54 /* synopsis: root=P2 iDb=P3 */
  10352. #define OP_OpenRead 55 /* synopsis: root=P2 iDb=P3 */
  10353. #define OP_OpenWrite 56 /* synopsis: root=P2 iDb=P3 */
  10354. #define OP_OpenAutoindex 57 /* synopsis: nColumn=P2 */
  10355. #define OP_OpenEphemeral 58 /* synopsis: nColumn=P2 */
  10356. #define OP_SorterOpen 59
  10357. #define OP_SequenceTest 60 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  10358. #define OP_OpenPseudo 61 /* synopsis: P3 columns in r[P2] */
  10359. #define OP_Close 62
  10360. #define OP_ColumnsUsed 63
  10361. #define OP_SeekLT 64 /* synopsis: key=r[P3@P4] */
  10362. #define OP_SeekLE 65 /* synopsis: key=r[P3@P4] */
  10363. #define OP_SeekGE 66 /* synopsis: key=r[P3@P4] */
  10364. #define OP_SeekGT 67 /* synopsis: key=r[P3@P4] */
  10365. #define OP_Seek 68 /* synopsis: intkey=r[P2] */
  10366. #define OP_NoConflict 69 /* synopsis: key=r[P3@P4] */
  10367. #define OP_NotFound 70 /* synopsis: key=r[P3@P4] */
  10368. #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  10369. #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  10370. #define OP_Found 73 /* synopsis: key=r[P3@P4] */
  10371. #define OP_NotExists 74 /* synopsis: intkey=r[P3] */
  10372. #define OP_Sequence 75 /* synopsis: r[P2]=cursor[P1].ctr++ */
  10373. #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  10374. #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  10375. #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
  10376. #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
  10377. #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
  10378. #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
  10379. #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
  10380. #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
  10381. #define OP_NewRowid 84 /* synopsis: r[P2]=rowid */
  10382. #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  10383. #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  10384. #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  10385. #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  10386. #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  10387. #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  10388. #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  10389. #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  10390. #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  10391. #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  10392. #define OP_Insert 95 /* synopsis: intkey=r[P3] data=r[P2] */
  10393. #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  10394. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  10395. #define OP_InsertInt 98 /* synopsis: intkey=P3 data=r[P2] */
  10396. #define OP_Delete 99
  10397. #define OP_ResetCount 100
  10398. #define OP_SorterCompare 101 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  10399. #define OP_SorterData 102 /* synopsis: r[P2]=data */
  10400. #define OP_RowKey 103 /* synopsis: r[P2]=key */
  10401. #define OP_RowData 104 /* synopsis: r[P2]=data */
  10402. #define OP_Rowid 105 /* synopsis: r[P2]=rowid */
  10403. #define OP_NullRow 106
  10404. #define OP_Last 107
  10405. #define OP_SorterSort 108
  10406. #define OP_Sort 109
  10407. #define OP_Rewind 110
  10408. #define OP_SorterInsert 111
  10409. #define OP_IdxInsert 112 /* synopsis: key=r[P2] */
  10410. #define OP_IdxDelete 113 /* synopsis: key=r[P2@P3] */
  10411. #define OP_IdxRowid 114 /* synopsis: r[P2]=rowid */
  10412. #define OP_IdxLE 115 /* synopsis: key=r[P3@P4] */
  10413. #define OP_IdxGT 116 /* synopsis: key=r[P3@P4] */
  10414. #define OP_IdxLT 117 /* synopsis: key=r[P3@P4] */
  10415. #define OP_IdxGE 118 /* synopsis: key=r[P3@P4] */
  10416. #define OP_Destroy 119
  10417. #define OP_Clear 120
  10418. #define OP_ResetSorter 121
  10419. #define OP_CreateIndex 122 /* synopsis: r[P2]=root iDb=P1 */
  10420. #define OP_CreateTable 123 /* synopsis: r[P2]=root iDb=P1 */
  10421. #define OP_ParseSchema 124
  10422. #define OP_LoadAnalysis 125
  10423. #define OP_DropTable 126
  10424. #define OP_DropIndex 127
  10425. #define OP_DropTrigger 128
  10426. #define OP_IntegrityCk 129
  10427. #define OP_RowSetAdd 130 /* synopsis: rowset(P1)=r[P2] */
  10428. #define OP_RowSetRead 131 /* synopsis: r[P3]=rowset(P1) */
  10429. #define OP_RowSetTest 132 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  10430. #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  10431. #define OP_Program 134
  10432. #define OP_Param 135
  10433. #define OP_FkCounter 136 /* synopsis: fkctr[P1]+=P2 */
  10434. #define OP_FkIfZero 137 /* synopsis: if fkctr[P1]==0 goto P2 */
  10435. #define OP_MemMax 138 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  10436. #define OP_IfPos 139 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  10437. #define OP_SetIfNotPos 140 /* synopsis: if r[P1]<=0 then r[P2]=P3 */
  10438. #define OP_IfNotZero 141 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
  10439. #define OP_DecrJumpZero 142 /* synopsis: if (--r[P1])==0 goto P2 */
  10440. #define OP_JumpZeroIncr 143 /* synopsis: if (r[P1]++)==0 ) goto P2 */
  10441. #define OP_AggStep0 144 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  10442. #define OP_AggStep 145 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  10443. #define OP_AggFinal 146 /* synopsis: accum=r[P1] N=P2 */
  10444. #define OP_IncrVacuum 147
  10445. #define OP_Expire 148
  10446. #define OP_TableLock 149 /* synopsis: iDb=P1 root=P2 write=P3 */
  10447. #define OP_VBegin 150
  10448. #define OP_VCreate 151
  10449. #define OP_VDestroy 152
  10450. #define OP_VOpen 153
  10451. #define OP_VColumn 154 /* synopsis: r[P3]=vcolumn(P2) */
  10452. #define OP_VNext 155
  10453. #define OP_VRename 156
  10454. #define OP_Pagecount 157
  10455. #define OP_MaxPgcnt 158
  10456. #define OP_Init 159 /* synopsis: Start at P2 */
  10457. #define OP_CursorHint 160
  10458. #define OP_Noop 161
  10459. #define OP_Explain 162
  10460. /* Properties such as "out2" or "jump" that are specified in
  10461. ** comments following the "case" for each opcode in the vdbe.c
  10462. ** are encoded into bitvectors as follows:
  10463. */
  10464. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  10465. #define OPFLG_IN1 0x0002 /* in1: P1 is an input */
  10466. #define OPFLG_IN2 0x0004 /* in2: P2 is an input */
  10467. #define OPFLG_IN3 0x0008 /* in3: P3 is an input */
  10468. #define OPFLG_OUT2 0x0010 /* out2: P2 is an output */
  10469. #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
  10470. #define OPFLG_INITIALIZER {\
  10471. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,\
  10472. /* 8 */ 0x01, 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01,\
  10473. /* 16 */ 0x02, 0x01, 0x02, 0x12, 0x03, 0x08, 0x00, 0x10,\
  10474. /* 24 */ 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00,\
  10475. /* 32 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03,\
  10476. /* 40 */ 0x02, 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03,\
  10477. /* 48 */ 0x00, 0x00, 0x00, 0x10, 0x10, 0x08, 0x00, 0x00,\
  10478. /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  10479. /* 64 */ 0x09, 0x09, 0x09, 0x09, 0x04, 0x09, 0x09, 0x26,\
  10480. /* 72 */ 0x26, 0x09, 0x09, 0x10, 0x03, 0x03, 0x0b, 0x0b,\
  10481. /* 80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x10, 0x26, 0x26, 0x26,\
  10482. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
  10483. /* 96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  10484. /* 104 */ 0x00, 0x10, 0x00, 0x01, 0x01, 0x01, 0x01, 0x04,\
  10485. /* 112 */ 0x04, 0x00, 0x10, 0x01, 0x01, 0x01, 0x01, 0x10,\
  10486. /* 120 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
  10487. /* 128 */ 0x00, 0x00, 0x06, 0x23, 0x0b, 0x10, 0x01, 0x10,\
  10488. /* 136 */ 0x00, 0x01, 0x04, 0x03, 0x06, 0x03, 0x03, 0x03,\
  10489. /* 144 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,\
  10490. /* 152 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x10, 0x01,\
  10491. /* 160 */ 0x00, 0x00, 0x00,}
  10492. /************** End of opcodes.h *********************************************/
  10493. /************** Continuing where we left off in vdbe.h ***********************/
  10494. /*
  10495. ** Prototypes for the VDBE interface. See comments on the implementation
  10496. ** for a description of what each of these routines does.
  10497. */
  10498. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  10499. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  10500. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  10501. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  10502. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  10503. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  10504. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  10505. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  10506. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  10507. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  10508. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  10509. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  10510. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  10511. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  10512. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  10513. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  10514. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  10515. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  10516. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  10517. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  10518. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  10519. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  10520. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  10521. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  10522. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  10523. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  10524. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  10525. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  10526. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  10527. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  10528. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  10529. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  10530. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  10531. #ifdef SQLITE_DEBUG
  10532. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  10533. #endif
  10534. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  10535. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  10536. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  10537. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  10538. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  10539. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  10540. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  10541. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  10542. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  10543. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  10544. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  10545. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  10546. #ifndef SQLITE_OMIT_TRACE
  10547. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  10548. #endif
  10549. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  10550. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  10551. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  10552. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  10553. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  10554. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  10555. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  10556. #ifndef SQLITE_OMIT_TRIGGER
  10557. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  10558. #endif
  10559. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  10560. ** each VDBE opcode.
  10561. **
  10562. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  10563. ** comments in VDBE programs that show key decision points in the code
  10564. ** generator.
  10565. */
  10566. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  10567. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  10568. # define VdbeComment(X) sqlite3VdbeComment X
  10569. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  10570. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  10571. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  10572. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  10573. # else
  10574. # define VdbeModuleComment(X)
  10575. # endif
  10576. #else
  10577. # define VdbeComment(X)
  10578. # define VdbeNoopComment(X)
  10579. # define VdbeModuleComment(X)
  10580. #endif
  10581. /*
  10582. ** The VdbeCoverage macros are used to set a coverage testing point
  10583. ** for VDBE branch instructions. The coverage testing points are line
  10584. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  10585. ** only works with an amalagmation build. That's ok since a VDBE branch
  10586. ** coverage build designed for testing the test suite only. No application
  10587. ** should ever ship with VDBE branch coverage measuring turned on.
  10588. **
  10589. ** VdbeCoverage(v) // Mark the previously coded instruction
  10590. ** // as a branch
  10591. **
  10592. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  10593. **
  10594. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  10595. **
  10596. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  10597. **
  10598. ** Every VDBE branch operation must be tagged with one of the macros above.
  10599. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  10600. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  10601. ** routine in vdbe.c, alerting the developer to the missed tag.
  10602. */
  10603. #ifdef SQLITE_VDBE_COVERAGE
  10604. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  10605. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  10606. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  10607. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  10608. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  10609. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  10610. #else
  10611. # define VdbeCoverage(v)
  10612. # define VdbeCoverageIf(v,x)
  10613. # define VdbeCoverageAlwaysTaken(v)
  10614. # define VdbeCoverageNeverTaken(v)
  10615. # define VDBE_OFFSET_LINENO(x) 0
  10616. #endif
  10617. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  10618. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  10619. #else
  10620. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  10621. #endif
  10622. #endif
  10623. /************** End of vdbe.h ************************************************/
  10624. /************** Continuing where we left off in sqliteInt.h ******************/
  10625. /************** Include pager.h in the middle of sqliteInt.h *****************/
  10626. /************** Begin file pager.h *******************************************/
  10627. /*
  10628. ** 2001 September 15
  10629. **
  10630. ** The author disclaims copyright to this source code. In place of
  10631. ** a legal notice, here is a blessing:
  10632. **
  10633. ** May you do good and not evil.
  10634. ** May you find forgiveness for yourself and forgive others.
  10635. ** May you share freely, never taking more than you give.
  10636. **
  10637. *************************************************************************
  10638. ** This header file defines the interface that the sqlite page cache
  10639. ** subsystem. The page cache subsystem reads and writes a file a page
  10640. ** at a time and provides a journal for rollback.
  10641. */
  10642. #ifndef _PAGER_H_
  10643. #define _PAGER_H_
  10644. /*
  10645. ** Default maximum size for persistent journal files. A negative
  10646. ** value means no limit. This value may be overridden using the
  10647. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  10648. */
  10649. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  10650. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  10651. #endif
  10652. /*
  10653. ** The type used to represent a page number. The first page in a file
  10654. ** is called page 1. 0 is used to represent "not a page".
  10655. */
  10656. typedef u32 Pgno;
  10657. /*
  10658. ** Each open file is managed by a separate instance of the "Pager" structure.
  10659. */
  10660. typedef struct Pager Pager;
  10661. /*
  10662. ** Handle type for pages.
  10663. */
  10664. typedef struct PgHdr DbPage;
  10665. /*
  10666. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  10667. ** reserved for working around a windows/posix incompatibility). It is
  10668. ** used in the journal to signify that the remainder of the journal file
  10669. ** is devoted to storing a master journal name - there are no more pages to
  10670. ** roll back. See comments for function writeMasterJournal() in pager.c
  10671. ** for details.
  10672. */
  10673. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  10674. /*
  10675. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  10676. **
  10677. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  10678. */
  10679. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  10680. #define PAGER_MEMORY 0x0002 /* In-memory database */
  10681. /*
  10682. ** Valid values for the second argument to sqlite3PagerLockingMode().
  10683. */
  10684. #define PAGER_LOCKINGMODE_QUERY -1
  10685. #define PAGER_LOCKINGMODE_NORMAL 0
  10686. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  10687. /*
  10688. ** Numeric constants that encode the journalmode.
  10689. */
  10690. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  10691. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  10692. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  10693. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  10694. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  10695. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  10696. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  10697. /*
  10698. ** Flags that make up the mask passed to sqlite3PagerGet().
  10699. */
  10700. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  10701. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  10702. /*
  10703. ** Flags for sqlite3PagerSetFlags()
  10704. */
  10705. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  10706. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  10707. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  10708. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  10709. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  10710. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  10711. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  10712. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  10713. /*
  10714. ** The remainder of this file contains the declarations of the functions
  10715. ** that make up the Pager sub-system API. See source code comments for
  10716. ** a detailed description of each routine.
  10717. */
  10718. /* Open and close a Pager connection. */
  10719. SQLITE_PRIVATE int sqlite3PagerOpen(
  10720. sqlite3_vfs*,
  10721. Pager **ppPager,
  10722. const char*,
  10723. int,
  10724. int,
  10725. int,
  10726. void(*)(DbPage*)
  10727. );
  10728. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  10729. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  10730. /* Functions used to configure a Pager object. */
  10731. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  10732. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  10733. #ifdef SQLITE_HAS_CODEC
  10734. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  10735. #endif
  10736. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  10737. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  10738. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  10739. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  10740. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  10741. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  10742. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  10743. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  10744. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  10745. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  10746. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  10747. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  10748. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  10749. /* Functions used to obtain and release page references. */
  10750. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  10751. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  10752. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  10753. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  10754. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  10755. /* Operations on page references. */
  10756. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  10757. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  10758. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  10759. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  10760. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  10761. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  10762. /* Functions used to manage pager transactions and savepoints. */
  10763. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  10764. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  10765. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  10766. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  10767. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  10768. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  10769. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  10770. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  10771. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  10772. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  10773. #ifndef SQLITE_OMIT_WAL
  10774. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  10775. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  10776. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  10777. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  10778. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  10779. # ifdef SQLITE_ENABLE_SNAPSHOT
  10780. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  10781. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  10782. # endif
  10783. #endif
  10784. #ifdef SQLITE_ENABLE_ZIPVFS
  10785. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  10786. #endif
  10787. /* Functions used to query pager state and configuration. */
  10788. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  10789. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  10790. #ifdef SQLITE_DEBUG
  10791. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  10792. #endif
  10793. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  10794. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  10795. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  10796. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  10797. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  10798. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  10799. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  10800. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  10801. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  10802. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  10803. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  10804. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  10805. /* Functions used to truncate the database file. */
  10806. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  10807. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  10808. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  10809. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  10810. #endif
  10811. /* Functions to support testing and debugging. */
  10812. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  10813. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  10814. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  10815. #endif
  10816. #ifdef SQLITE_TEST
  10817. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  10818. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  10819. void disable_simulated_io_errors(void);
  10820. void enable_simulated_io_errors(void);
  10821. #else
  10822. # define disable_simulated_io_errors()
  10823. # define enable_simulated_io_errors()
  10824. #endif
  10825. #endif /* _PAGER_H_ */
  10826. /************** End of pager.h ***********************************************/
  10827. /************** Continuing where we left off in sqliteInt.h ******************/
  10828. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  10829. /************** Begin file pcache.h ******************************************/
  10830. /*
  10831. ** 2008 August 05
  10832. **
  10833. ** The author disclaims copyright to this source code. In place of
  10834. ** a legal notice, here is a blessing:
  10835. **
  10836. ** May you do good and not evil.
  10837. ** May you find forgiveness for yourself and forgive others.
  10838. ** May you share freely, never taking more than you give.
  10839. **
  10840. *************************************************************************
  10841. ** This header file defines the interface that the sqlite page cache
  10842. ** subsystem.
  10843. */
  10844. #ifndef _PCACHE_H_
  10845. typedef struct PgHdr PgHdr;
  10846. typedef struct PCache PCache;
  10847. /*
  10848. ** Every page in the cache is controlled by an instance of the following
  10849. ** structure.
  10850. */
  10851. struct PgHdr {
  10852. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  10853. void *pData; /* Page data */
  10854. void *pExtra; /* Extra content */
  10855. PgHdr *pDirty; /* Transient list of dirty pages */
  10856. Pager *pPager; /* The pager this page is part of */
  10857. Pgno pgno; /* Page number for this page */
  10858. #ifdef SQLITE_CHECK_PAGES
  10859. u32 pageHash; /* Hash of page content */
  10860. #endif
  10861. u16 flags; /* PGHDR flags defined below */
  10862. /**********************************************************************
  10863. ** Elements above are public. All that follows is private to pcache.c
  10864. ** and should not be accessed by other modules.
  10865. */
  10866. i16 nRef; /* Number of users of this page */
  10867. PCache *pCache; /* Cache that owns this page */
  10868. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  10869. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  10870. };
  10871. /* Bit values for PgHdr.flags */
  10872. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  10873. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  10874. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  10875. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  10876. ** writing this page to the database */
  10877. #define PGHDR_NEED_READ 0x010 /* Content is unread */
  10878. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  10879. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  10880. /* Initialize and shutdown the page cache subsystem */
  10881. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  10882. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  10883. /* Page cache buffer management:
  10884. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  10885. */
  10886. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  10887. /* Create a new pager cache.
  10888. ** Under memory stress, invoke xStress to try to make pages clean.
  10889. ** Only clean and unpinned pages can be reclaimed.
  10890. */
  10891. SQLITE_PRIVATE int sqlite3PcacheOpen(
  10892. int szPage, /* Size of every page */
  10893. int szExtra, /* Extra space associated with each page */
  10894. int bPurgeable, /* True if pages are on backing store */
  10895. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  10896. void *pStress, /* Argument to xStress */
  10897. PCache *pToInit /* Preallocated space for the PCache */
  10898. );
  10899. /* Modify the page-size after the cache has been created. */
  10900. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  10901. /* Return the size in bytes of a PCache object. Used to preallocate
  10902. ** storage space.
  10903. */
  10904. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  10905. /* One release per successful fetch. Page is pinned until released.
  10906. ** Reference counted.
  10907. */
  10908. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  10909. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  10910. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  10911. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  10912. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  10913. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  10914. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  10915. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  10916. /* Change a page number. Used by incr-vacuum. */
  10917. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  10918. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  10919. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  10920. /* Get a list of all dirty pages in the cache, sorted by page number */
  10921. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  10922. /* Reset and close the cache object */
  10923. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  10924. /* Clear flags from pages of the page cache */
  10925. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  10926. /* Discard the contents of the cache */
  10927. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  10928. /* Return the total number of outstanding page references */
  10929. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  10930. /* Increment the reference count of an existing page */
  10931. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  10932. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  10933. /* Return the total number of pages stored in the cache */
  10934. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  10935. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  10936. /* Iterate through all dirty pages currently stored in the cache. This
  10937. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  10938. ** library is built.
  10939. */
  10940. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  10941. #endif
  10942. /* Set and get the suggested cache-size for the specified pager-cache.
  10943. **
  10944. ** If no global maximum is configured, then the system attempts to limit
  10945. ** the total number of pages cached by purgeable pager-caches to the sum
  10946. ** of the suggested cache-sizes.
  10947. */
  10948. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  10949. #ifdef SQLITE_TEST
  10950. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  10951. #endif
  10952. /* Set or get the suggested spill-size for the specified pager-cache.
  10953. **
  10954. ** The spill-size is the minimum number of pages in cache before the cache
  10955. ** will attempt to spill dirty pages by calling xStress.
  10956. */
  10957. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  10958. /* Free up as much memory as possible from the page cache */
  10959. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  10960. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  10961. /* Try to return memory used by the pcache module to the main memory heap */
  10962. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  10963. #endif
  10964. #ifdef SQLITE_TEST
  10965. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  10966. #endif
  10967. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  10968. /* Return the header size */
  10969. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  10970. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  10971. #endif /* _PCACHE_H_ */
  10972. /************** End of pcache.h **********************************************/
  10973. /************** Continuing where we left off in sqliteInt.h ******************/
  10974. /************** Include os.h in the middle of sqliteInt.h ********************/
  10975. /************** Begin file os.h **********************************************/
  10976. /*
  10977. ** 2001 September 16
  10978. **
  10979. ** The author disclaims copyright to this source code. In place of
  10980. ** a legal notice, here is a blessing:
  10981. **
  10982. ** May you do good and not evil.
  10983. ** May you find forgiveness for yourself and forgive others.
  10984. ** May you share freely, never taking more than you give.
  10985. **
  10986. ******************************************************************************
  10987. **
  10988. ** This header file (together with is companion C source-code file
  10989. ** "os.c") attempt to abstract the underlying operating system so that
  10990. ** the SQLite library will work on both POSIX and windows systems.
  10991. **
  10992. ** This header file is #include-ed by sqliteInt.h and thus ends up
  10993. ** being included by every source file.
  10994. */
  10995. #ifndef _SQLITE_OS_H_
  10996. #define _SQLITE_OS_H_
  10997. /*
  10998. ** Attempt to automatically detect the operating system and setup the
  10999. ** necessary pre-processor macros for it.
  11000. */
  11001. /************** Include os_setup.h in the middle of os.h *********************/
  11002. /************** Begin file os_setup.h ****************************************/
  11003. /*
  11004. ** 2013 November 25
  11005. **
  11006. ** The author disclaims copyright to this source code. In place of
  11007. ** a legal notice, here is a blessing:
  11008. **
  11009. ** May you do good and not evil.
  11010. ** May you find forgiveness for yourself and forgive others.
  11011. ** May you share freely, never taking more than you give.
  11012. **
  11013. ******************************************************************************
  11014. **
  11015. ** This file contains pre-processor directives related to operating system
  11016. ** detection and/or setup.
  11017. */
  11018. #ifndef _OS_SETUP_H_
  11019. #define _OS_SETUP_H_
  11020. /*
  11021. ** Figure out if we are dealing with Unix, Windows, or some other operating
  11022. ** system.
  11023. **
  11024. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  11025. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  11026. ** the three will be 1. The other two will be 0.
  11027. */
  11028. #if defined(SQLITE_OS_OTHER)
  11029. # if SQLITE_OS_OTHER==1
  11030. # undef SQLITE_OS_UNIX
  11031. # define SQLITE_OS_UNIX 0
  11032. # undef SQLITE_OS_WIN
  11033. # define SQLITE_OS_WIN 0
  11034. # else
  11035. # undef SQLITE_OS_OTHER
  11036. # endif
  11037. #endif
  11038. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  11039. # define SQLITE_OS_OTHER 0
  11040. # ifndef SQLITE_OS_WIN
  11041. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  11042. defined(__MINGW32__) || defined(__BORLANDC__)
  11043. # define SQLITE_OS_WIN 1
  11044. # define SQLITE_OS_UNIX 0
  11045. # else
  11046. # define SQLITE_OS_WIN 0
  11047. # define SQLITE_OS_UNIX 1
  11048. # endif
  11049. # else
  11050. # define SQLITE_OS_UNIX 0
  11051. # endif
  11052. #else
  11053. # ifndef SQLITE_OS_WIN
  11054. # define SQLITE_OS_WIN 0
  11055. # endif
  11056. #endif
  11057. #endif /* _OS_SETUP_H_ */
  11058. /************** End of os_setup.h ********************************************/
  11059. /************** Continuing where we left off in os.h *************************/
  11060. /* If the SET_FULLSYNC macro is not defined above, then make it
  11061. ** a no-op
  11062. */
  11063. #ifndef SET_FULLSYNC
  11064. # define SET_FULLSYNC(x,y)
  11065. #endif
  11066. /*
  11067. ** The default size of a disk sector
  11068. */
  11069. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  11070. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  11071. #endif
  11072. /*
  11073. ** Temporary files are named starting with this prefix followed by 16 random
  11074. ** alphanumeric characters, and no file extension. They are stored in the
  11075. ** OS's standard temporary file directory, and are deleted prior to exit.
  11076. ** If sqlite is being embedded in another program, you may wish to change the
  11077. ** prefix to reflect your program's name, so that if your program exits
  11078. ** prematurely, old temporary files can be easily identified. This can be done
  11079. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  11080. **
  11081. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  11082. ** Mcafee started using SQLite in their anti-virus product and it
  11083. ** started putting files with the "sqlite" name in the c:/temp folder.
  11084. ** This annoyed many windows users. Those users would then do a
  11085. ** Google search for "sqlite", find the telephone numbers of the
  11086. ** developers and call to wake them up at night and complain.
  11087. ** For this reason, the default name prefix is changed to be "sqlite"
  11088. ** spelled backwards. So the temp files are still identified, but
  11089. ** anybody smart enough to figure out the code is also likely smart
  11090. ** enough to know that calling the developer will not help get rid
  11091. ** of the file.
  11092. */
  11093. #ifndef SQLITE_TEMP_FILE_PREFIX
  11094. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  11095. #endif
  11096. /*
  11097. ** The following values may be passed as the second argument to
  11098. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  11099. **
  11100. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  11101. ** RESERVED: A single process may hold a RESERVED lock on a file at
  11102. ** any time. Other processes may hold and obtain new SHARED locks.
  11103. ** PENDING: A single process may hold a PENDING lock on a file at
  11104. ** any one time. Existing SHARED locks may persist, but no new
  11105. ** SHARED locks may be obtained by other processes.
  11106. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  11107. **
  11108. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  11109. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  11110. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  11111. ** sqlite3OsLock().
  11112. */
  11113. #define NO_LOCK 0
  11114. #define SHARED_LOCK 1
  11115. #define RESERVED_LOCK 2
  11116. #define PENDING_LOCK 3
  11117. #define EXCLUSIVE_LOCK 4
  11118. /*
  11119. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  11120. **
  11121. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  11122. ** those functions are not available. So we use only LockFile() and
  11123. ** UnlockFile().
  11124. **
  11125. ** LockFile() prevents not just writing but also reading by other processes.
  11126. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  11127. ** byte out of a specific range of bytes. The lock byte is obtained at
  11128. ** random so two separate readers can probably access the file at the
  11129. ** same time, unless they are unlucky and choose the same lock byte.
  11130. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  11131. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  11132. ** a single byte of the file that is designated as the reserved lock byte.
  11133. ** A PENDING_LOCK is obtained by locking a designated byte different from
  11134. ** the RESERVED_LOCK byte.
  11135. **
  11136. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  11137. ** which means we can use reader/writer locks. When reader/writer locks
  11138. ** are used, the lock is placed on the same range of bytes that is used
  11139. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  11140. ** will support two or more Win95 readers or two or more WinNT readers.
  11141. ** But a single Win95 reader will lock out all WinNT readers and a single
  11142. ** WinNT reader will lock out all other Win95 readers.
  11143. **
  11144. ** The following #defines specify the range of bytes used for locking.
  11145. ** SHARED_SIZE is the number of bytes available in the pool from which
  11146. ** a random byte is selected for a shared lock. The pool of bytes for
  11147. ** shared locks begins at SHARED_FIRST.
  11148. **
  11149. ** The same locking strategy and
  11150. ** byte ranges are used for Unix. This leaves open the possibility of having
  11151. ** clients on win95, winNT, and unix all talking to the same shared file
  11152. ** and all locking correctly. To do so would require that samba (or whatever
  11153. ** tool is being used for file sharing) implements locks correctly between
  11154. ** windows and unix. I'm guessing that isn't likely to happen, but by
  11155. ** using the same locking range we are at least open to the possibility.
  11156. **
  11157. ** Locking in windows is manditory. For this reason, we cannot store
  11158. ** actual data in the bytes used for locking. The pager never allocates
  11159. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  11160. ** that all locks will fit on a single page even at the minimum page size.
  11161. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  11162. ** is set high so that we don't have to allocate an unused page except
  11163. ** for very large databases. But one should test the page skipping logic
  11164. ** by setting PENDING_BYTE low and running the entire regression suite.
  11165. **
  11166. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  11167. ** file format. Depending on how it is changed, you might not notice
  11168. ** the incompatibility right away, even running a full regression test.
  11169. ** The default location of PENDING_BYTE is the first byte past the
  11170. ** 1GB boundary.
  11171. **
  11172. */
  11173. #ifdef SQLITE_OMIT_WSD
  11174. # define PENDING_BYTE (0x40000000)
  11175. #else
  11176. # define PENDING_BYTE sqlite3PendingByte
  11177. #endif
  11178. #define RESERVED_BYTE (PENDING_BYTE+1)
  11179. #define SHARED_FIRST (PENDING_BYTE+2)
  11180. #define SHARED_SIZE 510
  11181. /*
  11182. ** Wrapper around OS specific sqlite3_os_init() function.
  11183. */
  11184. SQLITE_PRIVATE int sqlite3OsInit(void);
  11185. /*
  11186. ** Functions for accessing sqlite3_file methods
  11187. */
  11188. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  11189. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  11190. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  11191. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  11192. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  11193. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  11194. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  11195. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  11196. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  11197. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  11198. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  11199. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  11200. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  11201. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  11202. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  11203. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  11204. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  11205. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  11206. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  11207. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  11208. /*
  11209. ** Functions for accessing sqlite3_vfs methods
  11210. */
  11211. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  11212. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  11213. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  11214. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  11215. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11216. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  11217. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  11218. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  11219. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  11220. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  11221. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  11222. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  11223. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  11224. /*
  11225. ** Convenience functions for opening and closing files using
  11226. ** sqlite3_malloc() to obtain space for the file-handle structure.
  11227. */
  11228. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  11229. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  11230. #endif /* _SQLITE_OS_H_ */
  11231. /************** End of os.h **************************************************/
  11232. /************** Continuing where we left off in sqliteInt.h ******************/
  11233. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  11234. /************** Begin file mutex.h *******************************************/
  11235. /*
  11236. ** 2007 August 28
  11237. **
  11238. ** The author disclaims copyright to this source code. In place of
  11239. ** a legal notice, here is a blessing:
  11240. **
  11241. ** May you do good and not evil.
  11242. ** May you find forgiveness for yourself and forgive others.
  11243. ** May you share freely, never taking more than you give.
  11244. **
  11245. *************************************************************************
  11246. **
  11247. ** This file contains the common header for all mutex implementations.
  11248. ** The sqliteInt.h header #includes this file so that it is available
  11249. ** to all source files. We break it out in an effort to keep the code
  11250. ** better organized.
  11251. **
  11252. ** NOTE: source files should *not* #include this header file directly.
  11253. ** Source files should #include the sqliteInt.h file and let that file
  11254. ** include this one indirectly.
  11255. */
  11256. /*
  11257. ** Figure out what version of the code to use. The choices are
  11258. **
  11259. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  11260. ** mutexes implementation cannot be overridden
  11261. ** at start-time.
  11262. **
  11263. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  11264. ** mutual exclusion is provided. But this
  11265. ** implementation can be overridden at
  11266. ** start-time.
  11267. **
  11268. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  11269. **
  11270. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  11271. */
  11272. #if !SQLITE_THREADSAFE
  11273. # define SQLITE_MUTEX_OMIT
  11274. #endif
  11275. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  11276. # if SQLITE_OS_UNIX
  11277. # define SQLITE_MUTEX_PTHREADS
  11278. # elif SQLITE_OS_WIN
  11279. # define SQLITE_MUTEX_W32
  11280. # else
  11281. # define SQLITE_MUTEX_NOOP
  11282. # endif
  11283. #endif
  11284. #ifdef SQLITE_MUTEX_OMIT
  11285. /*
  11286. ** If this is a no-op implementation, implement everything as macros.
  11287. */
  11288. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  11289. #define sqlite3_mutex_free(X)
  11290. #define sqlite3_mutex_enter(X)
  11291. #define sqlite3_mutex_try(X) SQLITE_OK
  11292. #define sqlite3_mutex_leave(X)
  11293. #define sqlite3_mutex_held(X) ((void)(X),1)
  11294. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  11295. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  11296. #define sqlite3MutexInit() SQLITE_OK
  11297. #define sqlite3MutexEnd()
  11298. #define MUTEX_LOGIC(X)
  11299. #else
  11300. #define MUTEX_LOGIC(X) X
  11301. #endif /* defined(SQLITE_MUTEX_OMIT) */
  11302. /************** End of mutex.h ***********************************************/
  11303. /************** Continuing where we left off in sqliteInt.h ******************/
  11304. /*
  11305. ** Each database file to be accessed by the system is an instance
  11306. ** of the following structure. There are normally two of these structures
  11307. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  11308. ** aDb[1] is the database file used to hold temporary tables. Additional
  11309. ** databases may be attached.
  11310. */
  11311. struct Db {
  11312. char *zName; /* Name of this database */
  11313. Btree *pBt; /* The B*Tree structure for this database file */
  11314. u8 safety_level; /* How aggressive at syncing data to disk */
  11315. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  11316. };
  11317. /*
  11318. ** An instance of the following structure stores a database schema.
  11319. **
  11320. ** Most Schema objects are associated with a Btree. The exception is
  11321. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  11322. ** In shared cache mode, a single Schema object can be shared by multiple
  11323. ** Btrees that refer to the same underlying BtShared object.
  11324. **
  11325. ** Schema objects are automatically deallocated when the last Btree that
  11326. ** references them is destroyed. The TEMP Schema is manually freed by
  11327. ** sqlite3_close().
  11328. *
  11329. ** A thread must be holding a mutex on the corresponding Btree in order
  11330. ** to access Schema content. This implies that the thread must also be
  11331. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  11332. ** For a TEMP Schema, only the connection mutex is required.
  11333. */
  11334. struct Schema {
  11335. int schema_cookie; /* Database schema version number for this file */
  11336. int iGeneration; /* Generation counter. Incremented with each change */
  11337. Hash tblHash; /* All tables indexed by name */
  11338. Hash idxHash; /* All (named) indices indexed by name */
  11339. Hash trigHash; /* All triggers indexed by name */
  11340. Hash fkeyHash; /* All foreign keys by referenced table name */
  11341. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  11342. u8 file_format; /* Schema format version for this file */
  11343. u8 enc; /* Text encoding used by this database */
  11344. u16 schemaFlags; /* Flags associated with this schema */
  11345. int cache_size; /* Number of pages to use in the cache */
  11346. };
  11347. /*
  11348. ** These macros can be used to test, set, or clear bits in the
  11349. ** Db.pSchema->flags field.
  11350. */
  11351. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  11352. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  11353. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  11354. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  11355. /*
  11356. ** Allowed values for the DB.pSchema->flags field.
  11357. **
  11358. ** The DB_SchemaLoaded flag is set after the database schema has been
  11359. ** read into internal hash tables.
  11360. **
  11361. ** DB_UnresetViews means that one or more views have column names that
  11362. ** have been filled out. If the schema changes, these column names might
  11363. ** changes and so the view will need to be reset.
  11364. */
  11365. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  11366. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  11367. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  11368. /*
  11369. ** The number of different kinds of things that can be limited
  11370. ** using the sqlite3_limit() interface.
  11371. */
  11372. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  11373. /*
  11374. ** Lookaside malloc is a set of fixed-size buffers that can be used
  11375. ** to satisfy small transient memory allocation requests for objects
  11376. ** associated with a particular database connection. The use of
  11377. ** lookaside malloc provides a significant performance enhancement
  11378. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  11379. ** SQL statements.
  11380. **
  11381. ** The Lookaside structure holds configuration information about the
  11382. ** lookaside malloc subsystem. Each available memory allocation in
  11383. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  11384. ** objects.
  11385. **
  11386. ** Lookaside allocations are only allowed for objects that are associated
  11387. ** with a particular database connection. Hence, schema information cannot
  11388. ** be stored in lookaside because in shared cache mode the schema information
  11389. ** is shared by multiple database connections. Therefore, while parsing
  11390. ** schema information, the Lookaside.bEnabled flag is cleared so that
  11391. ** lookaside allocations are not used to construct the schema objects.
  11392. */
  11393. struct Lookaside {
  11394. u16 sz; /* Size of each buffer in bytes */
  11395. u8 bEnabled; /* False to disable new lookaside allocations */
  11396. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  11397. int nOut; /* Number of buffers currently checked out */
  11398. int mxOut; /* Highwater mark for nOut */
  11399. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  11400. LookasideSlot *pFree; /* List of available buffers */
  11401. void *pStart; /* First byte of available memory space */
  11402. void *pEnd; /* First byte past end of available space */
  11403. };
  11404. struct LookasideSlot {
  11405. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  11406. };
  11407. /*
  11408. ** A hash table for function definitions.
  11409. **
  11410. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  11411. ** Collisions are on the FuncDef.pHash chain.
  11412. */
  11413. struct FuncDefHash {
  11414. FuncDef *a[23]; /* Hash table for functions */
  11415. };
  11416. #ifdef SQLITE_USER_AUTHENTICATION
  11417. /*
  11418. ** Information held in the "sqlite3" database connection object and used
  11419. ** to manage user authentication.
  11420. */
  11421. typedef struct sqlite3_userauth sqlite3_userauth;
  11422. struct sqlite3_userauth {
  11423. u8 authLevel; /* Current authentication level */
  11424. int nAuthPW; /* Size of the zAuthPW in bytes */
  11425. char *zAuthPW; /* Password used to authenticate */
  11426. char *zAuthUser; /* User name used to authenticate */
  11427. };
  11428. /* Allowed values for sqlite3_userauth.authLevel */
  11429. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  11430. #define UAUTH_Fail 1 /* User authentication failed */
  11431. #define UAUTH_User 2 /* Authenticated as a normal user */
  11432. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  11433. /* Functions used only by user authorization logic */
  11434. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  11435. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  11436. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  11437. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  11438. #endif /* SQLITE_USER_AUTHENTICATION */
  11439. /*
  11440. ** typedef for the authorization callback function.
  11441. */
  11442. #ifdef SQLITE_USER_AUTHENTICATION
  11443. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  11444. const char*, const char*);
  11445. #else
  11446. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  11447. const char*);
  11448. #endif
  11449. /*
  11450. ** Each database connection is an instance of the following structure.
  11451. */
  11452. struct sqlite3 {
  11453. sqlite3_vfs *pVfs; /* OS Interface */
  11454. struct Vdbe *pVdbe; /* List of active virtual machines */
  11455. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  11456. sqlite3_mutex *mutex; /* Connection mutex */
  11457. Db *aDb; /* All backends */
  11458. int nDb; /* Number of backends currently in use */
  11459. int flags; /* Miscellaneous flags. See below */
  11460. i64 lastRowid; /* ROWID of most recent insert (see above) */
  11461. i64 szMmap; /* Default mmap_size setting */
  11462. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  11463. int errCode; /* Most recent error code (SQLITE_*) */
  11464. int errMask; /* & result codes with this before returning */
  11465. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  11466. u8 enc; /* Text encoding */
  11467. u8 autoCommit; /* The auto-commit flag. */
  11468. u8 temp_store; /* 1: file 2: memory 0: default */
  11469. u8 mallocFailed; /* True if we have seen a malloc failure */
  11470. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  11471. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  11472. u8 suppressErr; /* Do not issue error messages if true */
  11473. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  11474. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  11475. int nextPagesize; /* Pagesize after VACUUM if >0 */
  11476. u32 magic; /* Magic number for detect library misuse */
  11477. int nChange; /* Value returned by sqlite3_changes() */
  11478. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  11479. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  11480. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  11481. struct sqlite3InitInfo { /* Information used during initialization */
  11482. int newTnum; /* Rootpage of table being initialized */
  11483. u8 iDb; /* Which db file is being initialized */
  11484. u8 busy; /* TRUE if currently initializing */
  11485. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  11486. u8 imposterTable; /* Building an imposter table */
  11487. } init;
  11488. int nVdbeActive; /* Number of VDBEs currently running */
  11489. int nVdbeRead; /* Number of active VDBEs that read or write */
  11490. int nVdbeWrite; /* Number of active VDBEs that read and write */
  11491. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  11492. int nVDestroy; /* Number of active OP_VDestroy operations */
  11493. int nExtension; /* Number of loaded extensions */
  11494. void **aExtension; /* Array of shared library handles */
  11495. void (*xTrace)(void*,const char*); /* Trace function */
  11496. void *pTraceArg; /* Argument to the trace function */
  11497. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  11498. void *pProfileArg; /* Argument to profile function */
  11499. void *pCommitArg; /* Argument to xCommitCallback() */
  11500. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  11501. void *pRollbackArg; /* Argument to xRollbackCallback() */
  11502. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  11503. void *pUpdateArg;
  11504. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  11505. #ifndef SQLITE_OMIT_WAL
  11506. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  11507. void *pWalArg;
  11508. #endif
  11509. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  11510. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  11511. void *pCollNeededArg;
  11512. sqlite3_value *pErr; /* Most recent error message */
  11513. union {
  11514. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  11515. double notUsed1; /* Spacer */
  11516. } u1;
  11517. Lookaside lookaside; /* Lookaside malloc configuration */
  11518. #ifndef SQLITE_OMIT_AUTHORIZATION
  11519. sqlite3_xauth xAuth; /* Access authorization function */
  11520. void *pAuthArg; /* 1st argument to the access auth function */
  11521. #endif
  11522. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  11523. int (*xProgress)(void *); /* The progress callback */
  11524. void *pProgressArg; /* Argument to the progress callback */
  11525. unsigned nProgressOps; /* Number of opcodes for progress callback */
  11526. #endif
  11527. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11528. int nVTrans; /* Allocated size of aVTrans */
  11529. Hash aModule; /* populated by sqlite3_create_module() */
  11530. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  11531. VTable **aVTrans; /* Virtual tables with open transactions */
  11532. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  11533. #endif
  11534. FuncDefHash aFunc; /* Hash table of connection functions */
  11535. Hash aCollSeq; /* All collating sequences */
  11536. BusyHandler busyHandler; /* Busy callback */
  11537. Db aDbStatic[2]; /* Static space for the 2 default backends */
  11538. Savepoint *pSavepoint; /* List of active savepoints */
  11539. int busyTimeout; /* Busy handler timeout, in msec */
  11540. int nSavepoint; /* Number of non-transaction savepoints */
  11541. int nStatement; /* Number of nested statement-transactions */
  11542. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  11543. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  11544. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  11545. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11546. /* The following variables are all protected by the STATIC_MASTER
  11547. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  11548. **
  11549. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  11550. ** unlock so that it can proceed.
  11551. **
  11552. ** When X.pBlockingConnection==Y, that means that something that X tried
  11553. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  11554. ** held by Y.
  11555. */
  11556. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  11557. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  11558. void *pUnlockArg; /* Argument to xUnlockNotify */
  11559. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  11560. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  11561. #endif
  11562. #ifdef SQLITE_USER_AUTHENTICATION
  11563. sqlite3_userauth auth; /* User authentication information */
  11564. #endif
  11565. };
  11566. /*
  11567. ** A macro to discover the encoding of a database.
  11568. */
  11569. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  11570. #define ENC(db) ((db)->enc)
  11571. /*
  11572. ** Possible values for the sqlite3.flags.
  11573. */
  11574. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  11575. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  11576. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  11577. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  11578. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  11579. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  11580. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  11581. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  11582. /* DELETE, or UPDATE and return */
  11583. /* the count using a callback. */
  11584. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  11585. /* result set is empty */
  11586. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  11587. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  11588. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  11589. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  11590. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  11591. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  11592. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  11593. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  11594. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  11595. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  11596. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  11597. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  11598. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  11599. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  11600. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  11601. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  11602. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  11603. #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
  11604. #define SQLITE_Vacuum 0x08000000 /* Currently in a VACUUM */
  11605. #define SQLITE_CellSizeCk 0x10000000 /* Check btree cell sizes on load */
  11606. /*
  11607. ** Bits of the sqlite3.dbOptFlags field that are used by the
  11608. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  11609. ** selectively disable various optimizations.
  11610. */
  11611. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  11612. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  11613. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  11614. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  11615. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  11616. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  11617. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  11618. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  11619. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  11620. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  11621. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  11622. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  11623. #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
  11624. #define SQLITE_AllOpts 0xffff /* All optimizations */
  11625. /*
  11626. ** Macros for testing whether or not optimizations are enabled or disabled.
  11627. */
  11628. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11629. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  11630. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  11631. #else
  11632. #define OptimizationDisabled(db, mask) 0
  11633. #define OptimizationEnabled(db, mask) 1
  11634. #endif
  11635. /*
  11636. ** Return true if it OK to factor constant expressions into the initialization
  11637. ** code. The argument is a Parse object for the code generator.
  11638. */
  11639. #define ConstFactorOk(P) ((P)->okConstFactor)
  11640. /*
  11641. ** Possible values for the sqlite.magic field.
  11642. ** The numbers are obtained at random and have no special meaning, other
  11643. ** than being distinct from one another.
  11644. */
  11645. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  11646. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  11647. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  11648. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  11649. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  11650. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  11651. /*
  11652. ** Each SQL function is defined by an instance of the following
  11653. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  11654. ** hash table. When multiple functions have the same name, the hash table
  11655. ** points to a linked list of these structures.
  11656. */
  11657. struct FuncDef {
  11658. i16 nArg; /* Number of arguments. -1 means unlimited */
  11659. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  11660. void *pUserData; /* User data parameter */
  11661. FuncDef *pNext; /* Next function with same name */
  11662. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  11663. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  11664. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  11665. char *zName; /* SQL name of the function. */
  11666. FuncDef *pHash; /* Next with a different name but the same hash */
  11667. FuncDestructor *pDestructor; /* Reference counted destructor function */
  11668. };
  11669. /*
  11670. ** This structure encapsulates a user-function destructor callback (as
  11671. ** configured using create_function_v2()) and a reference counter. When
  11672. ** create_function_v2() is called to create a function with a destructor,
  11673. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  11674. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  11675. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  11676. ** member of each of the new FuncDef objects is set to point to the allocated
  11677. ** FuncDestructor.
  11678. **
  11679. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  11680. ** count on this object is decremented. When it reaches 0, the destructor
  11681. ** is invoked and the FuncDestructor structure freed.
  11682. */
  11683. struct FuncDestructor {
  11684. int nRef;
  11685. void (*xDestroy)(void *);
  11686. void *pUserData;
  11687. };
  11688. /*
  11689. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  11690. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  11691. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  11692. ** are assert() statements in the code to verify this.
  11693. */
  11694. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  11695. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  11696. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  11697. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  11698. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  11699. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  11700. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  11701. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  11702. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  11703. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  11704. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  11705. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  11706. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  11707. ** single query - might change over time */
  11708. /*
  11709. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  11710. ** used to create the initializers for the FuncDef structures.
  11711. **
  11712. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  11713. ** Used to create a scalar function definition of a function zName
  11714. ** implemented by C function xFunc that accepts nArg arguments. The
  11715. ** value passed as iArg is cast to a (void*) and made available
  11716. ** as the user-data (sqlite3_user_data()) for the function. If
  11717. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  11718. **
  11719. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  11720. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  11721. **
  11722. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  11723. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  11724. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  11725. ** and functions like sqlite_version() that can change, but not during
  11726. ** a single query.
  11727. **
  11728. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  11729. ** Used to create an aggregate function definition implemented by
  11730. ** the C functions xStep and xFinal. The first four parameters
  11731. ** are interpreted in the same way as the first 4 parameters to
  11732. ** FUNCTION().
  11733. **
  11734. ** LIKEFUNC(zName, nArg, pArg, flags)
  11735. ** Used to create a scalar function definition of a function zName
  11736. ** that accepts nArg arguments and is implemented by a call to C
  11737. ** function likeFunc. Argument pArg is cast to a (void *) and made
  11738. ** available as the function user-data (sqlite3_user_data()). The
  11739. ** FuncDef.flags variable is set to the value passed as the flags
  11740. ** parameter.
  11741. */
  11742. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11743. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11744. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  11745. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11746. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11747. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  11748. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  11749. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11750. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  11751. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  11752. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  11753. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  11754. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  11755. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  11756. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  11757. #define LIKEFUNC(zName, nArg, arg, flags) \
  11758. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  11759. (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  11760. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  11761. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  11762. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  11763. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  11764. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  11765. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  11766. /*
  11767. ** All current savepoints are stored in a linked list starting at
  11768. ** sqlite3.pSavepoint. The first element in the list is the most recently
  11769. ** opened savepoint. Savepoints are added to the list by the vdbe
  11770. ** OP_Savepoint instruction.
  11771. */
  11772. struct Savepoint {
  11773. char *zName; /* Savepoint name (nul-terminated) */
  11774. i64 nDeferredCons; /* Number of deferred fk violations */
  11775. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  11776. Savepoint *pNext; /* Parent savepoint (if any) */
  11777. };
  11778. /*
  11779. ** The following are used as the second parameter to sqlite3Savepoint(),
  11780. ** and as the P1 argument to the OP_Savepoint instruction.
  11781. */
  11782. #define SAVEPOINT_BEGIN 0
  11783. #define SAVEPOINT_RELEASE 1
  11784. #define SAVEPOINT_ROLLBACK 2
  11785. /*
  11786. ** Each SQLite module (virtual table definition) is defined by an
  11787. ** instance of the following structure, stored in the sqlite3.aModule
  11788. ** hash table.
  11789. */
  11790. struct Module {
  11791. const sqlite3_module *pModule; /* Callback pointers */
  11792. const char *zName; /* Name passed to create_module() */
  11793. void *pAux; /* pAux passed to create_module() */
  11794. void (*xDestroy)(void *); /* Module destructor function */
  11795. Table *pEpoTab; /* Eponymous table for this module */
  11796. };
  11797. /*
  11798. ** information about each column of an SQL table is held in an instance
  11799. ** of this structure.
  11800. */
  11801. struct Column {
  11802. char *zName; /* Name of this column */
  11803. Expr *pDflt; /* Default value of this column */
  11804. char *zDflt; /* Original text of the default value */
  11805. char *zType; /* Data type for this column */
  11806. char *zColl; /* Collating sequence. If NULL, use the default */
  11807. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  11808. char affinity; /* One of the SQLITE_AFF_... values */
  11809. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  11810. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  11811. };
  11812. /* Allowed values for Column.colFlags:
  11813. */
  11814. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  11815. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  11816. /*
  11817. ** A "Collating Sequence" is defined by an instance of the following
  11818. ** structure. Conceptually, a collating sequence consists of a name and
  11819. ** a comparison routine that defines the order of that sequence.
  11820. **
  11821. ** If CollSeq.xCmp is NULL, it means that the
  11822. ** collating sequence is undefined. Indices built on an undefined
  11823. ** collating sequence may not be read or written.
  11824. */
  11825. struct CollSeq {
  11826. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  11827. u8 enc; /* Text encoding handled by xCmp() */
  11828. void *pUser; /* First argument to xCmp() */
  11829. int (*xCmp)(void*,int, const void*, int, const void*);
  11830. void (*xDel)(void*); /* Destructor for pUser */
  11831. };
  11832. /*
  11833. ** A sort order can be either ASC or DESC.
  11834. */
  11835. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  11836. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  11837. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  11838. /*
  11839. ** Column affinity types.
  11840. **
  11841. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  11842. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  11843. ** the speed a little by numbering the values consecutively.
  11844. **
  11845. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  11846. ** when multiple affinity types are concatenated into a string and
  11847. ** used as the P4 operand, they will be more readable.
  11848. **
  11849. ** Note also that the numeric types are grouped together so that testing
  11850. ** for a numeric type is a single comparison. And the BLOB type is first.
  11851. */
  11852. #define SQLITE_AFF_BLOB 'A'
  11853. #define SQLITE_AFF_TEXT 'B'
  11854. #define SQLITE_AFF_NUMERIC 'C'
  11855. #define SQLITE_AFF_INTEGER 'D'
  11856. #define SQLITE_AFF_REAL 'E'
  11857. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  11858. /*
  11859. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  11860. ** affinity value.
  11861. */
  11862. #define SQLITE_AFF_MASK 0x47
  11863. /*
  11864. ** Additional bit values that can be ORed with an affinity without
  11865. ** changing the affinity.
  11866. **
  11867. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  11868. ** It causes an assert() to fire if either operand to a comparison
  11869. ** operator is NULL. It is added to certain comparison operators to
  11870. ** prove that the operands are always NOT NULL.
  11871. */
  11872. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  11873. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  11874. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  11875. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  11876. /*
  11877. ** An object of this type is created for each virtual table present in
  11878. ** the database schema.
  11879. **
  11880. ** If the database schema is shared, then there is one instance of this
  11881. ** structure for each database connection (sqlite3*) that uses the shared
  11882. ** schema. This is because each database connection requires its own unique
  11883. ** instance of the sqlite3_vtab* handle used to access the virtual table
  11884. ** implementation. sqlite3_vtab* handles can not be shared between
  11885. ** database connections, even when the rest of the in-memory database
  11886. ** schema is shared, as the implementation often stores the database
  11887. ** connection handle passed to it via the xConnect() or xCreate() method
  11888. ** during initialization internally. This database connection handle may
  11889. ** then be used by the virtual table implementation to access real tables
  11890. ** within the database. So that they appear as part of the callers
  11891. ** transaction, these accesses need to be made via the same database
  11892. ** connection as that used to execute SQL operations on the virtual table.
  11893. **
  11894. ** All VTable objects that correspond to a single table in a shared
  11895. ** database schema are initially stored in a linked-list pointed to by
  11896. ** the Table.pVTable member variable of the corresponding Table object.
  11897. ** When an sqlite3_prepare() operation is required to access the virtual
  11898. ** table, it searches the list for the VTable that corresponds to the
  11899. ** database connection doing the preparing so as to use the correct
  11900. ** sqlite3_vtab* handle in the compiled query.
  11901. **
  11902. ** When an in-memory Table object is deleted (for example when the
  11903. ** schema is being reloaded for some reason), the VTable objects are not
  11904. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  11905. ** immediately. Instead, they are moved from the Table.pVTable list to
  11906. ** another linked list headed by the sqlite3.pDisconnect member of the
  11907. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  11908. ** next time a statement is prepared using said sqlite3*. This is done
  11909. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  11910. ** Refer to comments above function sqlite3VtabUnlockList() for an
  11911. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  11912. ** list without holding the corresponding sqlite3.mutex mutex.
  11913. **
  11914. ** The memory for objects of this type is always allocated by
  11915. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  11916. ** the first argument.
  11917. */
  11918. struct VTable {
  11919. sqlite3 *db; /* Database connection associated with this table */
  11920. Module *pMod; /* Pointer to module implementation */
  11921. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  11922. int nRef; /* Number of pointers to this structure */
  11923. u8 bConstraint; /* True if constraints are supported */
  11924. int iSavepoint; /* Depth of the SAVEPOINT stack */
  11925. VTable *pNext; /* Next in linked list (see above) */
  11926. };
  11927. /*
  11928. ** The schema for each SQL table and view is represented in memory
  11929. ** by an instance of the following structure.
  11930. */
  11931. struct Table {
  11932. char *zName; /* Name of the table or view */
  11933. Column *aCol; /* Information about each column */
  11934. Index *pIndex; /* List of SQL indexes on this table. */
  11935. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  11936. FKey *pFKey; /* Linked list of all foreign keys in this table */
  11937. char *zColAff; /* String defining the affinity of each column */
  11938. ExprList *pCheck; /* All CHECK constraints */
  11939. /* ... also used as column name list in a VIEW */
  11940. int tnum; /* Root BTree page for this table */
  11941. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  11942. i16 nCol; /* Number of columns in this table */
  11943. u16 nRef; /* Number of pointers to this Table */
  11944. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  11945. LogEst szTabRow; /* Estimated size of each table row in bytes */
  11946. #ifdef SQLITE_ENABLE_COSTMULT
  11947. LogEst costMult; /* Cost multiplier for using this table */
  11948. #endif
  11949. u8 tabFlags; /* Mask of TF_* values */
  11950. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  11951. #ifndef SQLITE_OMIT_ALTERTABLE
  11952. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  11953. #endif
  11954. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11955. int nModuleArg; /* Number of arguments to the module */
  11956. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  11957. VTable *pVTable; /* List of VTable objects. */
  11958. #endif
  11959. Trigger *pTrigger; /* List of triggers stored in pSchema */
  11960. Schema *pSchema; /* Schema that contains this table */
  11961. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  11962. };
  11963. /*
  11964. ** Allowed values for Table.tabFlags.
  11965. **
  11966. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  11967. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  11968. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  11969. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  11970. ** special handling during INSERT processing.
  11971. */
  11972. #define TF_Readonly 0x01 /* Read-only system table */
  11973. #define TF_Ephemeral 0x02 /* An ephemeral table */
  11974. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  11975. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  11976. #define TF_Virtual 0x10 /* Is a virtual table */
  11977. #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
  11978. #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
  11979. #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
  11980. /*
  11981. ** Test to see whether or not a table is a virtual table. This is
  11982. ** done as a macro so that it will be optimized out when virtual
  11983. ** table support is omitted from the build.
  11984. */
  11985. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11986. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  11987. #else
  11988. # define IsVirtual(X) 0
  11989. #endif
  11990. /*
  11991. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  11992. ** only works for non-virtual tables (ordinary tables and views) and is
  11993. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  11994. ** IsHiddenColumn() macro is general purpose.
  11995. */
  11996. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  11997. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  11998. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  11999. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  12000. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  12001. # define IsOrdinaryHiddenColumn(X) 0
  12002. #else
  12003. # define IsHiddenColumn(X) 0
  12004. # define IsOrdinaryHiddenColumn(X) 0
  12005. #endif
  12006. /* Does the table have a rowid */
  12007. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  12008. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  12009. /*
  12010. ** Each foreign key constraint is an instance of the following structure.
  12011. **
  12012. ** A foreign key is associated with two tables. The "from" table is
  12013. ** the table that contains the REFERENCES clause that creates the foreign
  12014. ** key. The "to" table is the table that is named in the REFERENCES clause.
  12015. ** Consider this example:
  12016. **
  12017. ** CREATE TABLE ex1(
  12018. ** a INTEGER PRIMARY KEY,
  12019. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  12020. ** );
  12021. **
  12022. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  12023. ** Equivalent names:
  12024. **
  12025. ** from-table == child-table
  12026. ** to-table == parent-table
  12027. **
  12028. ** Each REFERENCES clause generates an instance of the following structure
  12029. ** which is attached to the from-table. The to-table need not exist when
  12030. ** the from-table is created. The existence of the to-table is not checked.
  12031. **
  12032. ** The list of all parents for child Table X is held at X.pFKey.
  12033. **
  12034. ** A list of all children for a table named Z (which might not even exist)
  12035. ** is held in Schema.fkeyHash with a hash key of Z.
  12036. */
  12037. struct FKey {
  12038. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  12039. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  12040. char *zTo; /* Name of table that the key points to (aka: Parent) */
  12041. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  12042. FKey *pPrevTo; /* Previous with the same zTo */
  12043. int nCol; /* Number of columns in this key */
  12044. /* EV: R-30323-21917 */
  12045. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  12046. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  12047. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  12048. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  12049. int iFrom; /* Index of column in pFrom */
  12050. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  12051. } aCol[1]; /* One entry for each of nCol columns */
  12052. };
  12053. /*
  12054. ** SQLite supports many different ways to resolve a constraint
  12055. ** error. ROLLBACK processing means that a constraint violation
  12056. ** causes the operation in process to fail and for the current transaction
  12057. ** to be rolled back. ABORT processing means the operation in process
  12058. ** fails and any prior changes from that one operation are backed out,
  12059. ** but the transaction is not rolled back. FAIL processing means that
  12060. ** the operation in progress stops and returns an error code. But prior
  12061. ** changes due to the same operation are not backed out and no rollback
  12062. ** occurs. IGNORE means that the particular row that caused the constraint
  12063. ** error is not inserted or updated. Processing continues and no error
  12064. ** is returned. REPLACE means that preexisting database rows that caused
  12065. ** a UNIQUE constraint violation are removed so that the new insert or
  12066. ** update can proceed. Processing continues and no error is reported.
  12067. **
  12068. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  12069. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  12070. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  12071. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  12072. ** referenced table row is propagated into the row that holds the
  12073. ** foreign key.
  12074. **
  12075. ** The following symbolic values are used to record which type
  12076. ** of action to take.
  12077. */
  12078. #define OE_None 0 /* There is no constraint to check */
  12079. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  12080. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  12081. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  12082. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  12083. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  12084. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  12085. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  12086. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  12087. #define OE_Cascade 9 /* Cascade the changes */
  12088. #define OE_Default 10 /* Do whatever the default action is */
  12089. /*
  12090. ** An instance of the following structure is passed as the first
  12091. ** argument to sqlite3VdbeKeyCompare and is used to control the
  12092. ** comparison of the two index keys.
  12093. **
  12094. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  12095. ** are nField slots for the columns of an index then one extra slot
  12096. ** for the rowid at the end.
  12097. */
  12098. struct KeyInfo {
  12099. u32 nRef; /* Number of references to this KeyInfo object */
  12100. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  12101. u16 nField; /* Number of key columns in the index */
  12102. u16 nXField; /* Number of columns beyond the key columns */
  12103. sqlite3 *db; /* The database connection */
  12104. u8 *aSortOrder; /* Sort order for each column. */
  12105. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  12106. };
  12107. /*
  12108. ** This object holds a record which has been parsed out into individual
  12109. ** fields, for the purposes of doing a comparison.
  12110. **
  12111. ** A record is an object that contains one or more fields of data.
  12112. ** Records are used to store the content of a table row and to store
  12113. ** the key of an index. A blob encoding of a record is created by
  12114. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  12115. ** OP_Column opcode.
  12116. **
  12117. ** An instance of this object serves as a "key" for doing a search on
  12118. ** an index b+tree. The goal of the search is to find the entry that
  12119. ** is closed to the key described by this object. This object might hold
  12120. ** just a prefix of the key. The number of fields is given by
  12121. ** pKeyInfo->nField.
  12122. **
  12123. ** The r1 and r2 fields are the values to return if this key is less than
  12124. ** or greater than a key in the btree, respectively. These are normally
  12125. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  12126. ** is in DESC order.
  12127. **
  12128. ** The key comparison functions actually return default_rc when they find
  12129. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  12130. ** multiple entries in the b-tree with the same key (when only looking
  12131. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  12132. ** cause the search to find the last match, or +1 to cause the search to
  12133. ** find the first match.
  12134. **
  12135. ** The key comparison functions will set eqSeen to true if they ever
  12136. ** get and equal results when comparing this structure to a b-tree record.
  12137. ** When default_rc!=0, the search might end up on the record immediately
  12138. ** before the first match or immediately after the last match. The
  12139. ** eqSeen field will indicate whether or not an exact match exists in the
  12140. ** b-tree.
  12141. */
  12142. struct UnpackedRecord {
  12143. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  12144. Mem *aMem; /* Values */
  12145. u16 nField; /* Number of entries in apMem[] */
  12146. i8 default_rc; /* Comparison result if keys are equal */
  12147. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  12148. i8 r1; /* Value to return if (lhs > rhs) */
  12149. i8 r2; /* Value to return if (rhs < lhs) */
  12150. u8 eqSeen; /* True if an equality comparison has been seen */
  12151. };
  12152. /*
  12153. ** Each SQL index is represented in memory by an
  12154. ** instance of the following structure.
  12155. **
  12156. ** The columns of the table that are to be indexed are described
  12157. ** by the aiColumn[] field of this structure. For example, suppose
  12158. ** we have the following table and index:
  12159. **
  12160. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  12161. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  12162. **
  12163. ** In the Table structure describing Ex1, nCol==3 because there are
  12164. ** three columns in the table. In the Index structure describing
  12165. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  12166. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  12167. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  12168. ** The second column to be indexed (c1) has an index of 0 in
  12169. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  12170. **
  12171. ** The Index.onError field determines whether or not the indexed columns
  12172. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  12173. ** it means this is not a unique index. Otherwise it is a unique index
  12174. ** and the value of Index.onError indicate the which conflict resolution
  12175. ** algorithm to employ whenever an attempt is made to insert a non-unique
  12176. ** element.
  12177. **
  12178. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  12179. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  12180. ** table as part of parsing an existing database schema), transient instances
  12181. ** of this structure may be created. In this case the Index.tnum variable is
  12182. ** used to store the address of a VDBE instruction, not a database page
  12183. ** number (it cannot - the database page is not allocated until the VDBE
  12184. ** program is executed). See convertToWithoutRowidTable() for details.
  12185. */
  12186. struct Index {
  12187. char *zName; /* Name of this index */
  12188. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  12189. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  12190. Table *pTable; /* The SQL table being indexed */
  12191. char *zColAff; /* String defining the affinity of each column */
  12192. Index *pNext; /* The next index associated with the same table */
  12193. Schema *pSchema; /* Schema containing this index */
  12194. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  12195. const char **azColl; /* Array of collation sequence names for index */
  12196. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  12197. ExprList *aColExpr; /* Column expressions */
  12198. int tnum; /* DB Page containing root of this index */
  12199. LogEst szIdxRow; /* Estimated average row size in bytes */
  12200. u16 nKeyCol; /* Number of columns forming the key */
  12201. u16 nColumn; /* Number of columns stored in the index */
  12202. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  12203. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  12204. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  12205. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  12206. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  12207. unsigned isCovering:1; /* True if this is a covering index */
  12208. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  12209. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  12210. int nSample; /* Number of elements in aSample[] */
  12211. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  12212. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  12213. IndexSample *aSample; /* Samples of the left-most key */
  12214. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  12215. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  12216. #endif
  12217. };
  12218. /*
  12219. ** Allowed values for Index.idxType
  12220. */
  12221. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  12222. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  12223. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  12224. /* Return true if index X is a PRIMARY KEY index */
  12225. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  12226. /* Return true if index X is a UNIQUE index */
  12227. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  12228. /* The Index.aiColumn[] values are normally positive integer. But
  12229. ** there are some negative values that have special meaning:
  12230. */
  12231. #define XN_ROWID (-1) /* Indexed column is the rowid */
  12232. #define XN_EXPR (-2) /* Indexed column is an expression */
  12233. /*
  12234. ** Each sample stored in the sqlite_stat3 table is represented in memory
  12235. ** using a structure of this type. See documentation at the top of the
  12236. ** analyze.c source file for additional information.
  12237. */
  12238. struct IndexSample {
  12239. void *p; /* Pointer to sampled record */
  12240. int n; /* Size of record in bytes */
  12241. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  12242. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  12243. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  12244. };
  12245. /*
  12246. ** Each token coming out of the lexer is an instance of
  12247. ** this structure. Tokens are also used as part of an expression.
  12248. **
  12249. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  12250. ** may contain random values. Do not make any assumptions about Token.dyn
  12251. ** and Token.n when Token.z==0.
  12252. */
  12253. struct Token {
  12254. const char *z; /* Text of the token. Not NULL-terminated! */
  12255. unsigned int n; /* Number of characters in this token */
  12256. };
  12257. /*
  12258. ** An instance of this structure contains information needed to generate
  12259. ** code for a SELECT that contains aggregate functions.
  12260. **
  12261. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  12262. ** pointer to this structure. The Expr.iColumn field is the index in
  12263. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  12264. ** code for that node.
  12265. **
  12266. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  12267. ** original Select structure that describes the SELECT statement. These
  12268. ** fields do not need to be freed when deallocating the AggInfo structure.
  12269. */
  12270. struct AggInfo {
  12271. u8 directMode; /* Direct rendering mode means take data directly
  12272. ** from source tables rather than from accumulators */
  12273. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  12274. ** than the source table */
  12275. int sortingIdx; /* Cursor number of the sorting index */
  12276. int sortingIdxPTab; /* Cursor number of pseudo-table */
  12277. int nSortingColumn; /* Number of columns in the sorting index */
  12278. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  12279. ExprList *pGroupBy; /* The group by clause */
  12280. struct AggInfo_col { /* For each column used in source tables */
  12281. Table *pTab; /* Source table */
  12282. int iTable; /* Cursor number of the source table */
  12283. int iColumn; /* Column number within the source table */
  12284. int iSorterColumn; /* Column number in the sorting index */
  12285. int iMem; /* Memory location that acts as accumulator */
  12286. Expr *pExpr; /* The original expression */
  12287. } *aCol;
  12288. int nColumn; /* Number of used entries in aCol[] */
  12289. int nAccumulator; /* Number of columns that show through to the output.
  12290. ** Additional columns are used only as parameters to
  12291. ** aggregate functions */
  12292. struct AggInfo_func { /* For each aggregate function */
  12293. Expr *pExpr; /* Expression encoding the function */
  12294. FuncDef *pFunc; /* The aggregate function implementation */
  12295. int iMem; /* Memory location that acts as accumulator */
  12296. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  12297. } *aFunc;
  12298. int nFunc; /* Number of entries in aFunc[] */
  12299. };
  12300. /*
  12301. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  12302. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  12303. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  12304. ** it uses less memory in the Expr object, which is a big memory user
  12305. ** in systems with lots of prepared statements. And few applications
  12306. ** need more than about 10 or 20 variables. But some extreme users want
  12307. ** to have prepared statements with over 32767 variables, and for them
  12308. ** the option is available (at compile-time).
  12309. */
  12310. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  12311. typedef i16 ynVar;
  12312. #else
  12313. typedef int ynVar;
  12314. #endif
  12315. /*
  12316. ** Each node of an expression in the parse tree is an instance
  12317. ** of this structure.
  12318. **
  12319. ** Expr.op is the opcode. The integer parser token codes are reused
  12320. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  12321. ** code representing the ">=" operator. This same integer code is reused
  12322. ** to represent the greater-than-or-equal-to operator in the expression
  12323. ** tree.
  12324. **
  12325. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  12326. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  12327. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  12328. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  12329. ** then Expr.token contains the name of the function.
  12330. **
  12331. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  12332. ** binary operator. Either or both may be NULL.
  12333. **
  12334. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  12335. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  12336. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  12337. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  12338. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  12339. ** valid.
  12340. **
  12341. ** An expression of the form ID or ID.ID refers to a column in a table.
  12342. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  12343. ** the integer cursor number of a VDBE cursor pointing to that table and
  12344. ** Expr.iColumn is the column number for the specific column. If the
  12345. ** expression is used as a result in an aggregate SELECT, then the
  12346. ** value is also stored in the Expr.iAgg column in the aggregate so that
  12347. ** it can be accessed after all aggregates are computed.
  12348. **
  12349. ** If the expression is an unbound variable marker (a question mark
  12350. ** character '?' in the original SQL) then the Expr.iTable holds the index
  12351. ** number for that variable.
  12352. **
  12353. ** If the expression is a subquery then Expr.iColumn holds an integer
  12354. ** register number containing the result of the subquery. If the
  12355. ** subquery gives a constant result, then iTable is -1. If the subquery
  12356. ** gives a different answer at different times during statement processing
  12357. ** then iTable is the address of a subroutine that computes the subquery.
  12358. **
  12359. ** If the Expr is of type OP_Column, and the table it is selecting from
  12360. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  12361. ** corresponding table definition.
  12362. **
  12363. ** ALLOCATION NOTES:
  12364. **
  12365. ** Expr objects can use a lot of memory space in database schema. To
  12366. ** help reduce memory requirements, sometimes an Expr object will be
  12367. ** truncated. And to reduce the number of memory allocations, sometimes
  12368. ** two or more Expr objects will be stored in a single memory allocation,
  12369. ** together with Expr.zToken strings.
  12370. **
  12371. ** If the EP_Reduced and EP_TokenOnly flags are set when
  12372. ** an Expr object is truncated. When EP_Reduced is set, then all
  12373. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  12374. ** are contained within the same memory allocation. Note, however, that
  12375. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  12376. ** allocated, regardless of whether or not EP_Reduced is set.
  12377. */
  12378. struct Expr {
  12379. u8 op; /* Operation performed by this node */
  12380. char affinity; /* The affinity of the column or 0 if not a column */
  12381. u32 flags; /* Various flags. EP_* See below */
  12382. union {
  12383. char *zToken; /* Token value. Zero terminated and dequoted */
  12384. int iValue; /* Non-negative integer value if EP_IntValue */
  12385. } u;
  12386. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  12387. ** space is allocated for the fields below this point. An attempt to
  12388. ** access them will result in a segfault or malfunction.
  12389. *********************************************************************/
  12390. Expr *pLeft; /* Left subnode */
  12391. Expr *pRight; /* Right subnode */
  12392. union {
  12393. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  12394. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  12395. } x;
  12396. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  12397. ** space is allocated for the fields below this point. An attempt to
  12398. ** access them will result in a segfault or malfunction.
  12399. *********************************************************************/
  12400. #if SQLITE_MAX_EXPR_DEPTH>0
  12401. int nHeight; /* Height of the tree headed by this node */
  12402. #endif
  12403. int iTable; /* TK_COLUMN: cursor number of table holding column
  12404. ** TK_REGISTER: register number
  12405. ** TK_TRIGGER: 1 -> new, 0 -> old
  12406. ** EP_Unlikely: 134217728 times likelihood */
  12407. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  12408. ** TK_VARIABLE: variable number (always >= 1). */
  12409. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  12410. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  12411. u8 op2; /* TK_REGISTER: original value of Expr.op
  12412. ** TK_COLUMN: the value of p5 for OP_Column
  12413. ** TK_AGG_FUNCTION: nesting depth */
  12414. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  12415. Table *pTab; /* Table for TK_COLUMN expressions. */
  12416. };
  12417. /*
  12418. ** The following are the meanings of bits in the Expr.flags field.
  12419. */
  12420. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  12421. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  12422. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  12423. #define EP_Error 0x000008 /* Expression contains one or more errors */
  12424. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  12425. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  12426. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  12427. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  12428. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  12429. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  12430. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  12431. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  12432. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  12433. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  12434. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  12435. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  12436. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  12437. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  12438. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  12439. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  12440. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  12441. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  12442. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  12443. /*
  12444. ** Combinations of two or more EP_* flags
  12445. */
  12446. #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
  12447. /*
  12448. ** These macros can be used to test, set, or clear bits in the
  12449. ** Expr.flags field.
  12450. */
  12451. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  12452. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  12453. #define ExprSetProperty(E,P) (E)->flags|=(P)
  12454. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  12455. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  12456. ** and Accreditation only. It works like ExprSetProperty() during VVA
  12457. ** processes but is a no-op for delivery.
  12458. */
  12459. #ifdef SQLITE_DEBUG
  12460. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  12461. #else
  12462. # define ExprSetVVAProperty(E,P)
  12463. #endif
  12464. /*
  12465. ** Macros to determine the number of bytes required by a normal Expr
  12466. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  12467. ** and an Expr struct with the EP_TokenOnly flag set.
  12468. */
  12469. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  12470. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  12471. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  12472. /*
  12473. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  12474. ** above sqlite3ExprDup() for details.
  12475. */
  12476. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  12477. /*
  12478. ** A list of expressions. Each expression may optionally have a
  12479. ** name. An expr/name combination can be used in several ways, such
  12480. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  12481. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  12482. ** also be used as the argument to a function, in which case the a.zName
  12483. ** field is not used.
  12484. **
  12485. ** By default the Expr.zSpan field holds a human-readable description of
  12486. ** the expression that is used in the generation of error messages and
  12487. ** column labels. In this case, Expr.zSpan is typically the text of a
  12488. ** column expression as it exists in a SELECT statement. However, if
  12489. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  12490. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  12491. ** form is used for name resolution with nested FROM clauses.
  12492. */
  12493. struct ExprList {
  12494. int nExpr; /* Number of expressions on the list */
  12495. struct ExprList_item { /* For each expression in the list */
  12496. Expr *pExpr; /* The list of expressions */
  12497. char *zName; /* Token associated with this expression */
  12498. char *zSpan; /* Original text of the expression */
  12499. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  12500. unsigned done :1; /* A flag to indicate when processing is finished */
  12501. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  12502. unsigned reusable :1; /* Constant expression is reusable */
  12503. union {
  12504. struct {
  12505. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  12506. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  12507. } x;
  12508. int iConstExprReg; /* Register in which Expr value is cached */
  12509. } u;
  12510. } *a; /* Alloc a power of two greater or equal to nExpr */
  12511. };
  12512. /*
  12513. ** An instance of this structure is used by the parser to record both
  12514. ** the parse tree for an expression and the span of input text for an
  12515. ** expression.
  12516. */
  12517. struct ExprSpan {
  12518. Expr *pExpr; /* The expression parse tree */
  12519. const char *zStart; /* First character of input text */
  12520. const char *zEnd; /* One character past the end of input text */
  12521. };
  12522. /*
  12523. ** An instance of this structure can hold a simple list of identifiers,
  12524. ** such as the list "a,b,c" in the following statements:
  12525. **
  12526. ** INSERT INTO t(a,b,c) VALUES ...;
  12527. ** CREATE INDEX idx ON t(a,b,c);
  12528. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  12529. **
  12530. ** The IdList.a.idx field is used when the IdList represents the list of
  12531. ** column names after a table name in an INSERT statement. In the statement
  12532. **
  12533. ** INSERT INTO t(a,b,c) ...
  12534. **
  12535. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  12536. */
  12537. struct IdList {
  12538. struct IdList_item {
  12539. char *zName; /* Name of the identifier */
  12540. int idx; /* Index in some Table.aCol[] of a column named zName */
  12541. } *a;
  12542. int nId; /* Number of identifiers on the list */
  12543. };
  12544. /*
  12545. ** The bitmask datatype defined below is used for various optimizations.
  12546. **
  12547. ** Changing this from a 64-bit to a 32-bit type limits the number of
  12548. ** tables in a join to 32 instead of 64. But it also reduces the size
  12549. ** of the library by 738 bytes on ix86.
  12550. */
  12551. typedef u64 Bitmask;
  12552. /*
  12553. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  12554. */
  12555. #define BMS ((int)(sizeof(Bitmask)*8))
  12556. /*
  12557. ** A bit in a Bitmask
  12558. */
  12559. #define MASKBIT(n) (((Bitmask)1)<<(n))
  12560. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  12561. /*
  12562. ** The following structure describes the FROM clause of a SELECT statement.
  12563. ** Each table or subquery in the FROM clause is a separate element of
  12564. ** the SrcList.a[] array.
  12565. **
  12566. ** With the addition of multiple database support, the following structure
  12567. ** can also be used to describe a particular table such as the table that
  12568. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  12569. ** such a table must be a simple name: ID. But in SQLite, the table can
  12570. ** now be identified by a database name, a dot, then the table name: ID.ID.
  12571. **
  12572. ** The jointype starts out showing the join type between the current table
  12573. ** and the next table on the list. The parser builds the list this way.
  12574. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  12575. ** jointype expresses the join between the table and the previous table.
  12576. **
  12577. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  12578. ** contains more than 63 columns and the 64-th or later column is used.
  12579. */
  12580. struct SrcList {
  12581. int nSrc; /* Number of tables or subqueries in the FROM clause */
  12582. u32 nAlloc; /* Number of entries allocated in a[] below */
  12583. struct SrcList_item {
  12584. Schema *pSchema; /* Schema to which this item is fixed */
  12585. char *zDatabase; /* Name of database holding this table */
  12586. char *zName; /* Name of the table */
  12587. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  12588. Table *pTab; /* An SQL table corresponding to zName */
  12589. Select *pSelect; /* A SELECT statement used in place of a table name */
  12590. int addrFillSub; /* Address of subroutine to manifest a subquery */
  12591. int regReturn; /* Register holding return address of addrFillSub */
  12592. int regResult; /* Registers holding results of a co-routine */
  12593. struct {
  12594. u8 jointype; /* Type of join between this able and the previous */
  12595. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  12596. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  12597. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  12598. unsigned isCorrelated :1; /* True if sub-query is correlated */
  12599. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  12600. unsigned isRecursive :1; /* True for recursive reference in WITH */
  12601. } fg;
  12602. #ifndef SQLITE_OMIT_EXPLAIN
  12603. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  12604. #endif
  12605. int iCursor; /* The VDBE cursor number used to access this table */
  12606. Expr *pOn; /* The ON clause of a join */
  12607. IdList *pUsing; /* The USING clause of a join */
  12608. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  12609. union {
  12610. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  12611. ExprList *pFuncArg; /* Arguments to table-valued-function */
  12612. } u1;
  12613. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  12614. } a[1]; /* One entry for each identifier on the list */
  12615. };
  12616. /*
  12617. ** Permitted values of the SrcList.a.jointype field
  12618. */
  12619. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  12620. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  12621. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  12622. #define JT_LEFT 0x0008 /* Left outer join */
  12623. #define JT_RIGHT 0x0010 /* Right outer join */
  12624. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  12625. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  12626. /*
  12627. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  12628. ** and the WhereInfo.wctrlFlags member.
  12629. */
  12630. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  12631. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  12632. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  12633. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  12634. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  12635. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  12636. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  12637. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  12638. #define WHERE_NO_AUTOINDEX 0x0080 /* Disallow automatic indexes */
  12639. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  12640. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  12641. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  12642. #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
  12643. #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
  12644. #define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
  12645. /* Allowed return values from sqlite3WhereIsDistinct()
  12646. */
  12647. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  12648. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  12649. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  12650. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  12651. /*
  12652. ** A NameContext defines a context in which to resolve table and column
  12653. ** names. The context consists of a list of tables (the pSrcList) field and
  12654. ** a list of named expression (pEList). The named expression list may
  12655. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  12656. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  12657. ** pEList corresponds to the result set of a SELECT and is NULL for
  12658. ** other statements.
  12659. **
  12660. ** NameContexts can be nested. When resolving names, the inner-most
  12661. ** context is searched first. If no match is found, the next outer
  12662. ** context is checked. If there is still no match, the next context
  12663. ** is checked. This process continues until either a match is found
  12664. ** or all contexts are check. When a match is found, the nRef member of
  12665. ** the context containing the match is incremented.
  12666. **
  12667. ** Each subquery gets a new NameContext. The pNext field points to the
  12668. ** NameContext in the parent query. Thus the process of scanning the
  12669. ** NameContext list corresponds to searching through successively outer
  12670. ** subqueries looking for a match.
  12671. */
  12672. struct NameContext {
  12673. Parse *pParse; /* The parser */
  12674. SrcList *pSrcList; /* One or more tables used to resolve names */
  12675. ExprList *pEList; /* Optional list of result-set columns */
  12676. AggInfo *pAggInfo; /* Information about aggregates at this level */
  12677. NameContext *pNext; /* Next outer name context. NULL for outermost */
  12678. int nRef; /* Number of names resolved by this context */
  12679. int nErr; /* Number of errors encountered while resolving names */
  12680. u16 ncFlags; /* Zero or more NC_* flags defined below */
  12681. };
  12682. /*
  12683. ** Allowed values for the NameContext, ncFlags field.
  12684. **
  12685. ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
  12686. ** SQLITE_FUNC_MINMAX.
  12687. **
  12688. */
  12689. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  12690. #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
  12691. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  12692. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  12693. #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
  12694. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  12695. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  12696. /*
  12697. ** An instance of the following structure contains all information
  12698. ** needed to generate code for a single SELECT statement.
  12699. **
  12700. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  12701. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  12702. ** limit and nOffset to the value of the offset (or 0 if there is not
  12703. ** offset). But later on, nLimit and nOffset become the memory locations
  12704. ** in the VDBE that record the limit and offset counters.
  12705. **
  12706. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  12707. ** These addresses must be stored so that we can go back and fill in
  12708. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  12709. ** the number of columns in P2 can be computed at the same time
  12710. ** as the OP_OpenEphm instruction is coded because not
  12711. ** enough information about the compound query is known at that point.
  12712. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  12713. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  12714. ** sequences for the ORDER BY clause.
  12715. */
  12716. struct Select {
  12717. ExprList *pEList; /* The fields of the result */
  12718. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  12719. u16 selFlags; /* Various SF_* values */
  12720. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  12721. #if SELECTTRACE_ENABLED
  12722. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  12723. #endif
  12724. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  12725. u64 nSelectRow; /* Estimated number of result rows */
  12726. SrcList *pSrc; /* The FROM clause */
  12727. Expr *pWhere; /* The WHERE clause */
  12728. ExprList *pGroupBy; /* The GROUP BY clause */
  12729. Expr *pHaving; /* The HAVING clause */
  12730. ExprList *pOrderBy; /* The ORDER BY clause */
  12731. Select *pPrior; /* Prior select in a compound select statement */
  12732. Select *pNext; /* Next select to the left in a compound */
  12733. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  12734. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  12735. With *pWith; /* WITH clause attached to this select. Or NULL. */
  12736. };
  12737. /*
  12738. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  12739. ** "Select Flag".
  12740. */
  12741. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  12742. #define SF_All 0x0002 /* Includes the ALL keyword */
  12743. #define SF_Resolved 0x0004 /* Identifiers have been resolved */
  12744. #define SF_Aggregate 0x0008 /* Contains aggregate functions */
  12745. #define SF_UsesEphemeral 0x0010 /* Uses the OpenEphemeral opcode */
  12746. #define SF_Expanded 0x0020 /* sqlite3SelectExpand() called on this */
  12747. #define SF_HasTypeInfo 0x0040 /* FROM subqueries have Table metadata */
  12748. #define SF_Compound 0x0080 /* Part of a compound query */
  12749. #define SF_Values 0x0100 /* Synthesized from VALUES clause */
  12750. #define SF_MultiValue 0x0200 /* Single VALUES term with multiple rows */
  12751. #define SF_NestedFrom 0x0400 /* Part of a parenthesized FROM clause */
  12752. #define SF_MaybeConvert 0x0800 /* Need convertCompoundSelectToSubquery() */
  12753. #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
  12754. #define SF_Recursive 0x2000 /* The recursive part of a recursive CTE */
  12755. #define SF_Converted 0x4000 /* By convertCompoundSelectToSubquery() */
  12756. #define SF_IncludeHidden 0x8000 /* Include hidden columns in output */
  12757. /*
  12758. ** The results of a SELECT can be distributed in several ways, as defined
  12759. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  12760. ** Type".
  12761. **
  12762. ** SRT_Union Store results as a key in a temporary index
  12763. ** identified by pDest->iSDParm.
  12764. **
  12765. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  12766. **
  12767. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  12768. ** set is not empty.
  12769. **
  12770. ** SRT_Discard Throw the results away. This is used by SELECT
  12771. ** statements within triggers whose only purpose is
  12772. ** the side-effects of functions.
  12773. **
  12774. ** All of the above are free to ignore their ORDER BY clause. Those that
  12775. ** follow must honor the ORDER BY clause.
  12776. **
  12777. ** SRT_Output Generate a row of output (using the OP_ResultRow
  12778. ** opcode) for each row in the result set.
  12779. **
  12780. ** SRT_Mem Only valid if the result is a single column.
  12781. ** Store the first column of the first result row
  12782. ** in register pDest->iSDParm then abandon the rest
  12783. ** of the query. This destination implies "LIMIT 1".
  12784. **
  12785. ** SRT_Set The result must be a single column. Store each
  12786. ** row of result as the key in table pDest->iSDParm.
  12787. ** Apply the affinity pDest->affSdst before storing
  12788. ** results. Used to implement "IN (SELECT ...)".
  12789. **
  12790. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  12791. ** the result there. The cursor is left open after
  12792. ** returning. This is like SRT_Table except that
  12793. ** this destination uses OP_OpenEphemeral to create
  12794. ** the table first.
  12795. **
  12796. ** SRT_Coroutine Generate a co-routine that returns a new row of
  12797. ** results each time it is invoked. The entry point
  12798. ** of the co-routine is stored in register pDest->iSDParm
  12799. ** and the result row is stored in pDest->nDest registers
  12800. ** starting with pDest->iSdst.
  12801. **
  12802. ** SRT_Table Store results in temporary table pDest->iSDParm.
  12803. ** SRT_Fifo This is like SRT_EphemTab except that the table
  12804. ** is assumed to already be open. SRT_Fifo has
  12805. ** the additional property of being able to ignore
  12806. ** the ORDER BY clause.
  12807. **
  12808. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  12809. ** But also use temporary table pDest->iSDParm+1 as
  12810. ** a record of all prior results and ignore any duplicate
  12811. ** rows. Name means: "Distinct Fifo".
  12812. **
  12813. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  12814. ** an index). Append a sequence number so that all entries
  12815. ** are distinct.
  12816. **
  12817. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  12818. ** the same record has never been stored before. The
  12819. ** index at pDest->iSDParm+1 hold all prior stores.
  12820. */
  12821. #define SRT_Union 1 /* Store result as keys in an index */
  12822. #define SRT_Except 2 /* Remove result from a UNION index */
  12823. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  12824. #define SRT_Discard 4 /* Do not save the results anywhere */
  12825. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  12826. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  12827. #define SRT_Queue 7 /* Store result in an queue */
  12828. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  12829. /* The ORDER BY clause is ignored for all of the above */
  12830. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  12831. #define SRT_Output 9 /* Output each row of result */
  12832. #define SRT_Mem 10 /* Store result in a memory cell */
  12833. #define SRT_Set 11 /* Store results as keys in an index */
  12834. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  12835. #define SRT_Coroutine 13 /* Generate a single row of result */
  12836. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  12837. /*
  12838. ** An instance of this object describes where to put of the results of
  12839. ** a SELECT statement.
  12840. */
  12841. struct SelectDest {
  12842. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  12843. char affSdst; /* Affinity used when eDest==SRT_Set */
  12844. int iSDParm; /* A parameter used by the eDest disposal method */
  12845. int iSdst; /* Base register where results are written */
  12846. int nSdst; /* Number of registers allocated */
  12847. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  12848. };
  12849. /*
  12850. ** During code generation of statements that do inserts into AUTOINCREMENT
  12851. ** tables, the following information is attached to the Table.u.autoInc.p
  12852. ** pointer of each autoincrement table to record some side information that
  12853. ** the code generator needs. We have to keep per-table autoincrement
  12854. ** information in case inserts are down within triggers. Triggers do not
  12855. ** normally coordinate their activities, but we do need to coordinate the
  12856. ** loading and saving of autoincrement information.
  12857. */
  12858. struct AutoincInfo {
  12859. AutoincInfo *pNext; /* Next info block in a list of them all */
  12860. Table *pTab; /* Table this info block refers to */
  12861. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  12862. int regCtr; /* Memory register holding the rowid counter */
  12863. };
  12864. /*
  12865. ** Size of the column cache
  12866. */
  12867. #ifndef SQLITE_N_COLCACHE
  12868. # define SQLITE_N_COLCACHE 10
  12869. #endif
  12870. /*
  12871. ** At least one instance of the following structure is created for each
  12872. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  12873. ** statement. All such objects are stored in the linked list headed at
  12874. ** Parse.pTriggerPrg and deleted once statement compilation has been
  12875. ** completed.
  12876. **
  12877. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  12878. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  12879. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  12880. ** The Parse.pTriggerPrg list never contains two entries with the same
  12881. ** values for both pTrigger and orconf.
  12882. **
  12883. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  12884. ** accessed (or set to 0 for triggers fired as a result of INSERT
  12885. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  12886. ** a mask of new.* columns used by the program.
  12887. */
  12888. struct TriggerPrg {
  12889. Trigger *pTrigger; /* Trigger this program was coded from */
  12890. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  12891. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  12892. int orconf; /* Default ON CONFLICT policy */
  12893. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  12894. };
  12895. /*
  12896. ** The yDbMask datatype for the bitmask of all attached databases.
  12897. */
  12898. #if SQLITE_MAX_ATTACHED>30
  12899. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  12900. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  12901. # define DbMaskZero(M) memset((M),0,sizeof(M))
  12902. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  12903. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  12904. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  12905. #else
  12906. typedef unsigned int yDbMask;
  12907. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  12908. # define DbMaskZero(M) (M)=0
  12909. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  12910. # define DbMaskAllZero(M) (M)==0
  12911. # define DbMaskNonZero(M) (M)!=0
  12912. #endif
  12913. /*
  12914. ** An SQL parser context. A copy of this structure is passed through
  12915. ** the parser and down into all the parser action routine in order to
  12916. ** carry around information that is global to the entire parse.
  12917. **
  12918. ** The structure is divided into two parts. When the parser and code
  12919. ** generate call themselves recursively, the first part of the structure
  12920. ** is constant but the second part is reset at the beginning and end of
  12921. ** each recursion.
  12922. **
  12923. ** The nTableLock and aTableLock variables are only used if the shared-cache
  12924. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  12925. ** used to store the set of table-locks required by the statement being
  12926. ** compiled. Function sqlite3TableLock() is used to add entries to the
  12927. ** list.
  12928. */
  12929. struct Parse {
  12930. sqlite3 *db; /* The main database structure */
  12931. char *zErrMsg; /* An error message */
  12932. Vdbe *pVdbe; /* An engine for executing database bytecode */
  12933. int rc; /* Return code from execution */
  12934. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  12935. u8 checkSchema; /* Causes schema cookie check after an error */
  12936. u8 nested; /* Number of nested calls to the parser/code generator */
  12937. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  12938. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  12939. u8 mayAbort; /* True if statement may throw an ABORT exception */
  12940. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  12941. u8 okConstFactor; /* OK to factor out constants */
  12942. int aTempReg[8]; /* Holding area for temporary registers */
  12943. int nRangeReg; /* Size of the temporary register block */
  12944. int iRangeReg; /* First register in temporary register block */
  12945. int nErr; /* Number of errors seen */
  12946. int nTab; /* Number of previously allocated VDBE cursors */
  12947. int nMem; /* Number of memory cells used so far */
  12948. int nSet; /* Number of sets used so far */
  12949. int nOnce; /* Number of OP_Once instructions so far */
  12950. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  12951. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  12952. int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
  12953. int ckBase; /* Base register of data during check constraints */
  12954. int iSelfTab; /* Table of an index whose exprs are being coded */
  12955. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  12956. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  12957. int nLabel; /* Number of labels used */
  12958. int *aLabel; /* Space to hold the labels */
  12959. struct yColCache {
  12960. int iTable; /* Table cursor number */
  12961. i16 iColumn; /* Table column number */
  12962. u8 tempReg; /* iReg is a temp register that needs to be freed */
  12963. int iLevel; /* Nesting level */
  12964. int iReg; /* Reg with value of this column. 0 means none. */
  12965. int lru; /* Least recently used entry has the smallest value */
  12966. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  12967. ExprList *pConstExpr;/* Constant expressions */
  12968. Token constraintName;/* Name of the constraint currently being parsed */
  12969. yDbMask writeMask; /* Start a write transaction on these databases */
  12970. yDbMask cookieMask; /* Bitmask of schema verified databases */
  12971. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  12972. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  12973. int regRoot; /* Register holding root page number for new objects */
  12974. int nMaxArg; /* Max args passed to user function by sub-program */
  12975. #if SELECTTRACE_ENABLED
  12976. int nSelect; /* Number of SELECT statements seen */
  12977. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  12978. #endif
  12979. #ifndef SQLITE_OMIT_SHARED_CACHE
  12980. int nTableLock; /* Number of locks in aTableLock */
  12981. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  12982. #endif
  12983. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  12984. /* Information used while coding trigger programs. */
  12985. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  12986. Table *pTriggerTab; /* Table triggers are being coded for */
  12987. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  12988. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  12989. u32 oldmask; /* Mask of old.* columns referenced */
  12990. u32 newmask; /* Mask of new.* columns referenced */
  12991. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  12992. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  12993. u8 disableTriggers; /* True to disable triggers */
  12994. /************************************************************************
  12995. ** Above is constant between recursions. Below is reset before and after
  12996. ** each recursion. The boundary between these two regions is determined
  12997. ** using offsetof(Parse,nVar) so the nVar field must be the first field
  12998. ** in the recursive region.
  12999. ************************************************************************/
  13000. int nVar; /* Number of '?' variables seen in the SQL so far */
  13001. int nzVar; /* Number of available slots in azVar[] */
  13002. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  13003. u8 explain; /* True if the EXPLAIN flag is found on the query */
  13004. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13005. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  13006. int nVtabLock; /* Number of virtual tables to lock */
  13007. #endif
  13008. int nAlias; /* Number of aliased result set columns */
  13009. int nHeight; /* Expression tree height of current sub-select */
  13010. #ifndef SQLITE_OMIT_EXPLAIN
  13011. int iSelectId; /* ID of current select for EXPLAIN output */
  13012. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  13013. #endif
  13014. char **azVar; /* Pointers to names of parameters */
  13015. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  13016. const char *zTail; /* All SQL text past the last semicolon parsed */
  13017. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  13018. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  13019. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  13020. Token sNameToken; /* Token with unqualified schema object name */
  13021. Token sLastToken; /* The last token parsed */
  13022. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13023. Token sArg; /* Complete text of a module argument */
  13024. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  13025. #endif
  13026. Table *pZombieTab; /* List of Table objects to delete after code gen */
  13027. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  13028. With *pWith; /* Current WITH clause, or NULL */
  13029. With *pWithToFree; /* Free this WITH object at the end of the parse */
  13030. };
  13031. /*
  13032. ** Return true if currently inside an sqlite3_declare_vtab() call.
  13033. */
  13034. #ifdef SQLITE_OMIT_VIRTUALTABLE
  13035. #define IN_DECLARE_VTAB 0
  13036. #else
  13037. #define IN_DECLARE_VTAB (pParse->declareVtab)
  13038. #endif
  13039. /*
  13040. ** An instance of the following structure can be declared on a stack and used
  13041. ** to save the Parse.zAuthContext value so that it can be restored later.
  13042. */
  13043. struct AuthContext {
  13044. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  13045. Parse *pParse; /* The Parse structure */
  13046. };
  13047. /*
  13048. ** Bitfield flags for P5 value in various opcodes.
  13049. */
  13050. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  13051. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  13052. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  13053. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  13054. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  13055. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  13056. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  13057. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  13058. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  13059. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  13060. #define OPFLAG_FORDELETE 0x08 /* OP_Open is opening for-delete csr */
  13061. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  13062. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  13063. /*
  13064. * Each trigger present in the database schema is stored as an instance of
  13065. * struct Trigger.
  13066. *
  13067. * Pointers to instances of struct Trigger are stored in two ways.
  13068. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  13069. * database). This allows Trigger structures to be retrieved by name.
  13070. * 2. All triggers associated with a single table form a linked list, using the
  13071. * pNext member of struct Trigger. A pointer to the first element of the
  13072. * linked list is stored as the "pTrigger" member of the associated
  13073. * struct Table.
  13074. *
  13075. * The "step_list" member points to the first element of a linked list
  13076. * containing the SQL statements specified as the trigger program.
  13077. */
  13078. struct Trigger {
  13079. char *zName; /* The name of the trigger */
  13080. char *table; /* The table or view to which the trigger applies */
  13081. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  13082. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  13083. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  13084. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  13085. the <column-list> is stored here */
  13086. Schema *pSchema; /* Schema containing the trigger */
  13087. Schema *pTabSchema; /* Schema containing the table */
  13088. TriggerStep *step_list; /* Link list of trigger program steps */
  13089. Trigger *pNext; /* Next trigger associated with the table */
  13090. };
  13091. /*
  13092. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  13093. ** determine which.
  13094. **
  13095. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  13096. ** In that cases, the constants below can be ORed together.
  13097. */
  13098. #define TRIGGER_BEFORE 1
  13099. #define TRIGGER_AFTER 2
  13100. /*
  13101. * An instance of struct TriggerStep is used to store a single SQL statement
  13102. * that is a part of a trigger-program.
  13103. *
  13104. * Instances of struct TriggerStep are stored in a singly linked list (linked
  13105. * using the "pNext" member) referenced by the "step_list" member of the
  13106. * associated struct Trigger instance. The first element of the linked list is
  13107. * the first step of the trigger-program.
  13108. *
  13109. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  13110. * "SELECT" statement. The meanings of the other members is determined by the
  13111. * value of "op" as follows:
  13112. *
  13113. * (op == TK_INSERT)
  13114. * orconf -> stores the ON CONFLICT algorithm
  13115. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  13116. * this stores a pointer to the SELECT statement. Otherwise NULL.
  13117. * zTarget -> Dequoted name of the table to insert into.
  13118. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  13119. * this stores values to be inserted. Otherwise NULL.
  13120. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  13121. * statement, then this stores the column-names to be
  13122. * inserted into.
  13123. *
  13124. * (op == TK_DELETE)
  13125. * zTarget -> Dequoted name of the table to delete from.
  13126. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  13127. * Otherwise NULL.
  13128. *
  13129. * (op == TK_UPDATE)
  13130. * zTarget -> Dequoted name of the table to update.
  13131. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  13132. * Otherwise NULL.
  13133. * pExprList -> A list of the columns to update and the expressions to update
  13134. * them to. See sqlite3Update() documentation of "pChanges"
  13135. * argument.
  13136. *
  13137. */
  13138. struct TriggerStep {
  13139. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  13140. u8 orconf; /* OE_Rollback etc. */
  13141. Trigger *pTrig; /* The trigger that this step is a part of */
  13142. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  13143. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  13144. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  13145. ExprList *pExprList; /* SET clause for UPDATE. */
  13146. IdList *pIdList; /* Column names for INSERT */
  13147. TriggerStep *pNext; /* Next in the link-list */
  13148. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  13149. };
  13150. /*
  13151. ** The following structure contains information used by the sqliteFix...
  13152. ** routines as they walk the parse tree to make database references
  13153. ** explicit.
  13154. */
  13155. typedef struct DbFixer DbFixer;
  13156. struct DbFixer {
  13157. Parse *pParse; /* The parsing context. Error messages written here */
  13158. Schema *pSchema; /* Fix items to this schema */
  13159. int bVarOnly; /* Check for variable references only */
  13160. const char *zDb; /* Make sure all objects are contained in this database */
  13161. const char *zType; /* Type of the container - used for error messages */
  13162. const Token *pName; /* Name of the container - used for error messages */
  13163. };
  13164. /*
  13165. ** An objected used to accumulate the text of a string where we
  13166. ** do not necessarily know how big the string will be in the end.
  13167. */
  13168. struct StrAccum {
  13169. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  13170. char *zBase; /* A base allocation. Not from malloc. */
  13171. char *zText; /* The string collected so far */
  13172. u32 nChar; /* Length of the string so far */
  13173. u32 nAlloc; /* Amount of space allocated in zText */
  13174. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  13175. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  13176. u8 bMalloced; /* zText points to allocated space */
  13177. };
  13178. #define STRACCUM_NOMEM 1
  13179. #define STRACCUM_TOOBIG 2
  13180. /*
  13181. ** A pointer to this structure is used to communicate information
  13182. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  13183. */
  13184. typedef struct {
  13185. sqlite3 *db; /* The database being initialized */
  13186. char **pzErrMsg; /* Error message stored here */
  13187. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  13188. int rc; /* Result code stored here */
  13189. } InitData;
  13190. /*
  13191. ** Structure containing global configuration data for the SQLite library.
  13192. **
  13193. ** This structure also contains some state information.
  13194. */
  13195. struct Sqlite3Config {
  13196. int bMemstat; /* True to enable memory status */
  13197. int bCoreMutex; /* True to enable core mutexing */
  13198. int bFullMutex; /* True to enable full mutexing */
  13199. int bOpenUri; /* True to interpret filenames as URIs */
  13200. int bUseCis; /* Use covering indices for full-scans */
  13201. int mxStrlen; /* Maximum string length */
  13202. int neverCorrupt; /* Database is always well-formed */
  13203. int szLookaside; /* Default lookaside buffer size */
  13204. int nLookaside; /* Default lookaside buffer count */
  13205. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  13206. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  13207. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  13208. void *pHeap; /* Heap storage space */
  13209. int nHeap; /* Size of pHeap[] */
  13210. int mnReq, mxReq; /* Min and max heap requests sizes */
  13211. sqlite3_int64 szMmap; /* mmap() space per open file */
  13212. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  13213. void *pScratch; /* Scratch memory */
  13214. int szScratch; /* Size of each scratch buffer */
  13215. int nScratch; /* Number of scratch buffers */
  13216. void *pPage; /* Page cache memory */
  13217. int szPage; /* Size of each page in pPage[] */
  13218. int nPage; /* Number of pages in pPage[] */
  13219. int mxParserStack; /* maximum depth of the parser stack */
  13220. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  13221. u32 szPma; /* Maximum Sorter PMA size */
  13222. /* The above might be initialized to non-zero. The following need to always
  13223. ** initially be zero, however. */
  13224. int isInit; /* True after initialization has finished */
  13225. int inProgress; /* True while initialization in progress */
  13226. int isMutexInit; /* True after mutexes are initialized */
  13227. int isMallocInit; /* True after malloc is initialized */
  13228. int isPCacheInit; /* True after malloc is initialized */
  13229. int nRefInitMutex; /* Number of users of pInitMutex */
  13230. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  13231. void (*xLog)(void*,int,const char*); /* Function for logging */
  13232. void *pLogArg; /* First argument to xLog() */
  13233. #ifdef SQLITE_ENABLE_SQLLOG
  13234. void(*xSqllog)(void*,sqlite3*,const char*, int);
  13235. void *pSqllogArg;
  13236. #endif
  13237. #ifdef SQLITE_VDBE_COVERAGE
  13238. /* The following callback (if not NULL) is invoked on every VDBE branch
  13239. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  13240. */
  13241. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  13242. void *pVdbeBranchArg; /* 1st argument */
  13243. #endif
  13244. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13245. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  13246. #endif
  13247. int bLocaltimeFault; /* True to fail localtime() calls */
  13248. };
  13249. /*
  13250. ** This macro is used inside of assert() statements to indicate that
  13251. ** the assert is only valid on a well-formed database. Instead of:
  13252. **
  13253. ** assert( X );
  13254. **
  13255. ** One writes:
  13256. **
  13257. ** assert( X || CORRUPT_DB );
  13258. **
  13259. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  13260. ** that the database is definitely corrupt, only that it might be corrupt.
  13261. ** For most test cases, CORRUPT_DB is set to false using a special
  13262. ** sqlite3_test_control(). This enables assert() statements to prove
  13263. ** things that are always true for well-formed databases.
  13264. */
  13265. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  13266. /*
  13267. ** Context pointer passed down through the tree-walk.
  13268. */
  13269. struct Walker {
  13270. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  13271. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  13272. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  13273. Parse *pParse; /* Parser context. */
  13274. int walkerDepth; /* Number of subqueries */
  13275. u8 eCode; /* A small processing code */
  13276. union { /* Extra data for callback */
  13277. NameContext *pNC; /* Naming context */
  13278. int n; /* A counter */
  13279. int iCur; /* A cursor number */
  13280. SrcList *pSrcList; /* FROM clause */
  13281. struct SrcCount *pSrcCount; /* Counting column references */
  13282. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  13283. } u;
  13284. };
  13285. /* Forward declarations */
  13286. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  13287. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  13288. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  13289. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  13290. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  13291. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  13292. /*
  13293. ** Return code from the parse-tree walking primitives and their
  13294. ** callbacks.
  13295. */
  13296. #define WRC_Continue 0 /* Continue down into children */
  13297. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  13298. #define WRC_Abort 2 /* Abandon the tree walk */
  13299. /*
  13300. ** An instance of this structure represents a set of one or more CTEs
  13301. ** (common table expressions) created by a single WITH clause.
  13302. */
  13303. struct With {
  13304. int nCte; /* Number of CTEs in the WITH clause */
  13305. With *pOuter; /* Containing WITH clause, or NULL */
  13306. struct Cte { /* For each CTE in the WITH clause.... */
  13307. char *zName; /* Name of this CTE */
  13308. ExprList *pCols; /* List of explicit column names, or NULL */
  13309. Select *pSelect; /* The definition of this CTE */
  13310. const char *zCteErr; /* Error message for circular references */
  13311. } a[1];
  13312. };
  13313. #ifdef SQLITE_DEBUG
  13314. /*
  13315. ** An instance of the TreeView object is used for printing the content of
  13316. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  13317. */
  13318. struct TreeView {
  13319. int iLevel; /* Which level of the tree we are on */
  13320. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  13321. };
  13322. #endif /* SQLITE_DEBUG */
  13323. /*
  13324. ** Assuming zIn points to the first byte of a UTF-8 character,
  13325. ** advance zIn to point to the first byte of the next UTF-8 character.
  13326. */
  13327. #define SQLITE_SKIP_UTF8(zIn) { \
  13328. if( (*(zIn++))>=0xc0 ){ \
  13329. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  13330. } \
  13331. }
  13332. /*
  13333. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  13334. ** the same name but without the _BKPT suffix. These macros invoke
  13335. ** routines that report the line-number on which the error originated
  13336. ** using sqlite3_log(). The routines also provide a convenient place
  13337. ** to set a debugger breakpoint.
  13338. */
  13339. SQLITE_PRIVATE int sqlite3CorruptError(int);
  13340. SQLITE_PRIVATE int sqlite3MisuseError(int);
  13341. SQLITE_PRIVATE int sqlite3CantopenError(int);
  13342. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  13343. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  13344. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  13345. /*
  13346. ** FTS4 is really an extension for FTS3. It is enabled using the
  13347. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  13348. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  13349. */
  13350. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  13351. # define SQLITE_ENABLE_FTS3 1
  13352. #endif
  13353. /*
  13354. ** The ctype.h header is needed for non-ASCII systems. It is also
  13355. ** needed by FTS3 when FTS3 is included in the amalgamation.
  13356. */
  13357. #if !defined(SQLITE_ASCII) || \
  13358. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  13359. # include <ctype.h>
  13360. #endif
  13361. /*
  13362. ** The following macros mimic the standard library functions toupper(),
  13363. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  13364. ** sqlite versions only work for ASCII characters, regardless of locale.
  13365. */
  13366. #ifdef SQLITE_ASCII
  13367. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  13368. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  13369. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  13370. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  13371. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  13372. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  13373. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  13374. #else
  13375. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  13376. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  13377. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  13378. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  13379. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  13380. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  13381. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  13382. #endif
  13383. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  13384. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  13385. #endif
  13386. /*
  13387. ** Internal function prototypes
  13388. */
  13389. #define sqlite3StrICmp sqlite3_stricmp
  13390. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  13391. #define sqlite3StrNICmp sqlite3_strnicmp
  13392. SQLITE_PRIVATE int sqlite3MallocInit(void);
  13393. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  13394. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  13395. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  13396. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  13397. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  13398. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  13399. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  13400. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  13401. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  13402. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  13403. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  13404. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  13405. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  13406. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  13407. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  13408. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  13409. SQLITE_PRIVATE void sqlite3PageFree(void*);
  13410. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  13411. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13412. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  13413. #endif
  13414. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  13415. /*
  13416. ** On systems with ample stack space and that support alloca(), make
  13417. ** use of alloca() to obtain space for large automatic objects. By default,
  13418. ** obtain space from malloc().
  13419. **
  13420. ** The alloca() routine never returns NULL. This will cause code paths
  13421. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  13422. */
  13423. #ifdef SQLITE_USE_ALLOCA
  13424. # define sqlite3StackAllocRaw(D,N) alloca(N)
  13425. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  13426. # define sqlite3StackFree(D,P)
  13427. #else
  13428. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  13429. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  13430. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  13431. #endif
  13432. #ifdef SQLITE_ENABLE_MEMSYS3
  13433. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  13434. #endif
  13435. #ifdef SQLITE_ENABLE_MEMSYS5
  13436. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  13437. #endif
  13438. #ifndef SQLITE_MUTEX_OMIT
  13439. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  13440. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  13441. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  13442. SQLITE_PRIVATE int sqlite3MutexInit(void);
  13443. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  13444. #endif
  13445. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  13446. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  13447. #else
  13448. # define sqlite3MemoryBarrier()
  13449. #endif
  13450. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  13451. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  13452. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  13453. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  13454. /* Access to mutexes used by sqlite3_status() */
  13455. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  13456. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  13457. #ifndef SQLITE_OMIT_FLOATING_POINT
  13458. SQLITE_PRIVATE int sqlite3IsNaN(double);
  13459. #else
  13460. # define sqlite3IsNaN(X) 0
  13461. #endif
  13462. /*
  13463. ** An instance of the following structure holds information about SQL
  13464. ** functions arguments that are the parameters to the printf() function.
  13465. */
  13466. struct PrintfArguments {
  13467. int nArg; /* Total number of arguments */
  13468. int nUsed; /* Number of arguments used so far */
  13469. sqlite3_value **apArg; /* The argument values */
  13470. };
  13471. #define SQLITE_PRINTF_INTERNAL 0x01
  13472. #define SQLITE_PRINTF_SQLFUNC 0x02
  13473. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
  13474. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
  13475. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  13476. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  13477. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  13478. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  13479. #endif
  13480. #if defined(SQLITE_TEST)
  13481. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  13482. #endif
  13483. #if defined(SQLITE_DEBUG)
  13484. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  13485. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  13486. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  13487. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  13488. #endif
  13489. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  13490. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  13491. SQLITE_PRIVATE int sqlite3Dequote(char*);
  13492. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  13493. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  13494. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  13495. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  13496. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  13497. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  13498. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  13499. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  13500. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  13501. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  13502. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  13503. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  13504. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  13505. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  13506. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  13507. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  13508. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  13509. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  13510. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  13511. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  13512. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  13513. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  13514. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  13515. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  13516. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  13517. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  13518. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  13519. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  13520. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  13521. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  13522. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  13523. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  13524. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  13525. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  13526. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  13527. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  13528. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  13529. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  13530. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  13531. #else
  13532. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  13533. #endif
  13534. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  13535. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  13536. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  13537. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  13538. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  13539. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  13540. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  13541. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  13542. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  13543. sqlite3_vfs**,char**,char **);
  13544. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  13545. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  13546. #ifdef SQLITE_OMIT_BUILTIN_TEST
  13547. # define sqlite3FaultSim(X) SQLITE_OK
  13548. #else
  13549. SQLITE_PRIVATE int sqlite3FaultSim(int);
  13550. #endif
  13551. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  13552. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  13553. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  13554. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  13555. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  13556. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  13557. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  13558. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13559. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  13560. #endif
  13561. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  13562. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  13563. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  13564. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  13565. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  13566. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  13567. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  13568. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  13569. #else
  13570. # define sqlite3ViewGetColumnNames(A,B) 0
  13571. #endif
  13572. #if SQLITE_MAX_ATTACHED>30
  13573. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  13574. #endif
  13575. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  13576. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  13577. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  13578. #ifndef SQLITE_OMIT_AUTOINCREMENT
  13579. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  13580. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  13581. #else
  13582. # define sqlite3AutoincrementBegin(X)
  13583. # define sqlite3AutoincrementEnd(X)
  13584. #endif
  13585. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  13586. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  13587. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  13588. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  13589. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  13590. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  13591. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  13592. Token*, Select*, Expr*, IdList*);
  13593. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  13594. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  13595. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  13596. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  13597. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  13598. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  13599. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  13600. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  13601. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  13602. Expr*, int, int);
  13603. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  13604. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  13605. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  13606. Expr*,ExprList*,u16,Expr*,Expr*);
  13607. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  13608. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  13609. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  13610. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  13611. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  13612. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  13613. #endif
  13614. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  13615. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  13616. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  13617. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  13618. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  13619. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  13620. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  13621. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  13622. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  13623. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  13624. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  13625. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  13626. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  13627. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  13628. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  13629. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  13630. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
  13631. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  13632. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  13633. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  13634. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  13635. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  13636. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  13637. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  13638. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  13639. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  13640. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  13641. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  13642. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
  13643. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  13644. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  13645. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  13646. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  13647. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  13648. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  13649. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  13650. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  13651. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  13652. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  13653. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  13654. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  13655. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  13656. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  13657. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  13658. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  13659. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  13660. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  13661. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  13662. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  13663. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  13664. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  13665. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  13666. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  13667. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  13668. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  13669. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13670. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  13671. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  13672. #endif
  13673. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  13674. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  13675. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  13676. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  13677. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  13678. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  13679. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  13680. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  13681. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  13682. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  13683. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  13684. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  13685. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  13686. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  13687. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  13688. #endif
  13689. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  13690. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  13691. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  13692. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  13693. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  13694. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  13695. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  13696. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  13697. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  13698. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  13699. u8,u8,int,int*);
  13700. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  13701. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  13702. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  13703. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  13704. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  13705. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  13706. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  13707. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  13708. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  13709. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  13710. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  13711. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  13712. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  13713. #if SELECTTRACE_ENABLED
  13714. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  13715. #else
  13716. # define sqlite3SelectSetName(A,B)
  13717. #endif
  13718. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  13719. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  13720. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  13721. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  13722. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  13723. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  13724. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  13725. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  13726. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  13727. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  13728. #endif
  13729. #ifndef SQLITE_OMIT_TRIGGER
  13730. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  13731. Expr*,int, int);
  13732. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  13733. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  13734. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  13735. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  13736. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  13737. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  13738. int, int, int);
  13739. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  13740. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  13741. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  13742. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  13743. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  13744. Select*,u8);
  13745. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  13746. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  13747. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  13748. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  13749. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  13750. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  13751. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  13752. #else
  13753. # define sqlite3TriggersExist(B,C,D,E,F) 0
  13754. # define sqlite3DeleteTrigger(A,B)
  13755. # define sqlite3DropTriggerPtr(A,B)
  13756. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  13757. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  13758. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  13759. # define sqlite3TriggerList(X, Y) 0
  13760. # define sqlite3ParseToplevel(p) p
  13761. # define sqlite3IsToplevel(p) 1
  13762. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  13763. #endif
  13764. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  13765. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  13766. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  13767. #ifndef SQLITE_OMIT_AUTHORIZATION
  13768. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  13769. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  13770. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  13771. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  13772. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  13773. #else
  13774. # define sqlite3AuthRead(a,b,c,d)
  13775. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  13776. # define sqlite3AuthContextPush(a,b,c)
  13777. # define sqlite3AuthContextPop(a) ((void)(a))
  13778. #endif
  13779. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  13780. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  13781. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  13782. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  13783. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  13784. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  13785. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  13786. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  13787. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  13788. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  13789. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  13790. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  13791. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  13792. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  13793. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  13794. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  13795. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13796. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  13797. #endif
  13798. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  13799. /*
  13800. ** Routines to read and write variable-length integers. These used to
  13801. ** be defined locally, but now we use the varint routines in the util.c
  13802. ** file.
  13803. */
  13804. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  13805. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  13806. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  13807. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  13808. /*
  13809. ** The common case is for a varint to be a single byte. They following
  13810. ** macros handle the common case without a procedure call, but then call
  13811. ** the procedure for larger varints.
  13812. */
  13813. #define getVarint32(A,B) \
  13814. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  13815. #define putVarint32(A,B) \
  13816. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  13817. sqlite3PutVarint((A),(B)))
  13818. #define getVarint sqlite3GetVarint
  13819. #define putVarint sqlite3PutVarint
  13820. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  13821. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  13822. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  13823. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  13824. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  13825. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  13826. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  13827. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  13828. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  13829. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  13830. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  13831. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  13832. #if defined(SQLITE_NEED_ERR_NAME)
  13833. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  13834. #endif
  13835. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  13836. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  13837. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  13838. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  13839. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  13840. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  13841. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  13842. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  13843. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  13844. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  13845. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  13846. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  13847. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  13848. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  13849. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  13850. #ifdef SQLITE_ENABLE_8_3_NAMES
  13851. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  13852. #else
  13853. # define sqlite3FileSuffix3(X,Y)
  13854. #endif
  13855. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  13856. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  13857. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  13858. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  13859. void(*)(void*));
  13860. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  13861. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  13862. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  13863. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  13864. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  13865. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  13866. #ifndef SQLITE_AMALGAMATION
  13867. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  13868. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  13869. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  13870. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  13871. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  13872. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  13873. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  13874. #ifndef SQLITE_OMIT_WSD
  13875. SQLITE_PRIVATE int sqlite3PendingByte;
  13876. #endif
  13877. #endif
  13878. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  13879. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  13880. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  13881. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  13882. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  13883. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  13884. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  13885. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  13886. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  13887. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  13888. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  13889. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  13890. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  13891. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  13892. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  13893. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  13894. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  13895. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  13896. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  13897. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  13898. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  13899. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  13900. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  13901. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  13902. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  13903. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  13904. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  13905. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  13906. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  13907. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  13908. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  13909. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  13910. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  13911. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  13912. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  13913. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  13914. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  13915. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  13916. #ifdef SQLITE_DEBUG
  13917. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  13918. #endif
  13919. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  13920. void (*)(sqlite3_context*,int,sqlite3_value **),
  13921. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  13922. FuncDestructor *pDestructor
  13923. );
  13924. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  13925. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  13926. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  13927. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  13928. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  13929. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  13930. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  13931. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  13932. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  13933. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  13934. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  13935. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  13936. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  13937. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  13938. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  13939. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  13940. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  13941. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  13942. #endif
  13943. /*
  13944. ** The interface to the LEMON-generated parser
  13945. */
  13946. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  13947. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  13948. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  13949. #ifdef YYTRACKMAXSTACKDEPTH
  13950. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  13951. #endif
  13952. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  13953. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  13954. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  13955. #else
  13956. # define sqlite3CloseExtensions(X)
  13957. #endif
  13958. #ifndef SQLITE_OMIT_SHARED_CACHE
  13959. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  13960. #else
  13961. #define sqlite3TableLock(v,w,x,y,z)
  13962. #endif
  13963. #ifdef SQLITE_TEST
  13964. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  13965. #endif
  13966. #ifdef SQLITE_OMIT_VIRTUALTABLE
  13967. # define sqlite3VtabClear(Y)
  13968. # define sqlite3VtabSync(X,Y) SQLITE_OK
  13969. # define sqlite3VtabRollback(X)
  13970. # define sqlite3VtabCommit(X)
  13971. # define sqlite3VtabInSync(db) 0
  13972. # define sqlite3VtabLock(X)
  13973. # define sqlite3VtabUnlock(X)
  13974. # define sqlite3VtabUnlockList(X)
  13975. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  13976. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  13977. #else
  13978. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  13979. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  13980. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  13981. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  13982. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  13983. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  13984. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  13985. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  13986. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  13987. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  13988. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  13989. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  13990. #endif
  13991. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  13992. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  13993. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  13994. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  13995. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  13996. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  13997. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  13998. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  13999. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  14000. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  14001. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  14002. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  14003. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  14004. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  14005. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  14006. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  14007. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  14008. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  14009. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  14010. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  14011. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  14012. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  14013. #ifndef SQLITE_OMIT_WAL
  14014. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  14015. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  14016. #endif
  14017. #ifndef SQLITE_OMIT_CTE
  14018. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  14019. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  14020. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  14021. #else
  14022. #define sqlite3WithPush(x,y,z)
  14023. #define sqlite3WithDelete(x,y)
  14024. #endif
  14025. /* Declarations for functions in fkey.c. All of these are replaced by
  14026. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  14027. ** key functionality is available. If OMIT_TRIGGER is defined but
  14028. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  14029. ** this case foreign keys are parsed, but no other functionality is
  14030. ** provided (enforcement of FK constraints requires the triggers sub-system).
  14031. */
  14032. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  14033. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  14034. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  14035. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  14036. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  14037. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  14038. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  14039. #else
  14040. #define sqlite3FkActions(a,b,c,d,e,f)
  14041. #define sqlite3FkCheck(a,b,c,d,e,f)
  14042. #define sqlite3FkDropTable(a,b,c)
  14043. #define sqlite3FkOldmask(a,b) 0
  14044. #define sqlite3FkRequired(a,b,c,d) 0
  14045. #endif
  14046. #ifndef SQLITE_OMIT_FOREIGN_KEY
  14047. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  14048. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  14049. #else
  14050. #define sqlite3FkDelete(a,b)
  14051. #define sqlite3FkLocateIndex(a,b,c,d,e)
  14052. #endif
  14053. /*
  14054. ** Available fault injectors. Should be numbered beginning with 0.
  14055. */
  14056. #define SQLITE_FAULTINJECTOR_MALLOC 0
  14057. #define SQLITE_FAULTINJECTOR_COUNT 1
  14058. /*
  14059. ** The interface to the code in fault.c used for identifying "benign"
  14060. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  14061. ** is not defined.
  14062. */
  14063. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14064. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  14065. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  14066. #else
  14067. #define sqlite3BeginBenignMalloc()
  14068. #define sqlite3EndBenignMalloc()
  14069. #endif
  14070. /*
  14071. ** Allowed return values from sqlite3FindInIndex()
  14072. */
  14073. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  14074. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  14075. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  14076. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  14077. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  14078. /*
  14079. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  14080. */
  14081. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  14082. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  14083. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  14084. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
  14085. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  14086. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  14087. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  14088. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  14089. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  14090. #else
  14091. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  14092. #define sqlite3JournalExists(p) 1
  14093. #endif
  14094. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  14095. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  14096. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  14097. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  14098. #if SQLITE_MAX_EXPR_DEPTH>0
  14099. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  14100. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  14101. #else
  14102. #define sqlite3SelectExprHeight(x) 0
  14103. #define sqlite3ExprCheckHeight(x,y)
  14104. #endif
  14105. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  14106. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  14107. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  14108. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  14109. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  14110. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  14111. #else
  14112. #define sqlite3ConnectionBlocked(x,y)
  14113. #define sqlite3ConnectionUnlocked(x)
  14114. #define sqlite3ConnectionClosed(x)
  14115. #endif
  14116. #ifdef SQLITE_DEBUG
  14117. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  14118. #endif
  14119. /*
  14120. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  14121. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  14122. ** print I/O tracing messages.
  14123. */
  14124. #ifdef SQLITE_ENABLE_IOTRACE
  14125. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  14126. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  14127. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  14128. #else
  14129. # define IOTRACE(A)
  14130. # define sqlite3VdbeIOTraceSql(X)
  14131. #endif
  14132. /*
  14133. ** These routines are available for the mem2.c debugging memory allocator
  14134. ** only. They are used to verify that different "types" of memory
  14135. ** allocations are properly tracked by the system.
  14136. **
  14137. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  14138. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  14139. ** a single bit set.
  14140. **
  14141. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  14142. ** argument match the type set by the previous sqlite3MemdebugSetType().
  14143. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  14144. **
  14145. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  14146. ** argument match the type set by the previous sqlite3MemdebugSetType().
  14147. **
  14148. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  14149. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  14150. ** it might have been allocated by lookaside, except the allocation was
  14151. ** too large or lookaside was already full. It is important to verify
  14152. ** that allocations that might have been satisfied by lookaside are not
  14153. ** passed back to non-lookaside free() routines. Asserts such as the
  14154. ** example above are placed on the non-lookaside free() routines to verify
  14155. ** this constraint.
  14156. **
  14157. ** All of this is no-op for a production build. It only comes into
  14158. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  14159. */
  14160. #ifdef SQLITE_MEMDEBUG
  14161. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  14162. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  14163. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  14164. #else
  14165. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  14166. # define sqlite3MemdebugHasType(X,Y) 1
  14167. # define sqlite3MemdebugNoType(X,Y) 1
  14168. #endif
  14169. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  14170. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  14171. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  14172. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  14173. /*
  14174. ** Threading interface
  14175. */
  14176. #if SQLITE_MAX_WORKER_THREADS>0
  14177. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  14178. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  14179. #endif
  14180. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  14181. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  14182. #endif
  14183. #endif /* _SQLITEINT_H_ */
  14184. /************** End of sqliteInt.h *******************************************/
  14185. /************** Begin file global.c ******************************************/
  14186. /*
  14187. ** 2008 June 13
  14188. **
  14189. ** The author disclaims copyright to this source code. In place of
  14190. ** a legal notice, here is a blessing:
  14191. **
  14192. ** May you do good and not evil.
  14193. ** May you find forgiveness for yourself and forgive others.
  14194. ** May you share freely, never taking more than you give.
  14195. **
  14196. *************************************************************************
  14197. **
  14198. ** This file contains definitions of global variables and constants.
  14199. */
  14200. /* #include "sqliteInt.h" */
  14201. /* An array to map all upper-case characters into their corresponding
  14202. ** lower-case character.
  14203. **
  14204. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  14205. ** handle case conversions for the UTF character set since the tables
  14206. ** involved are nearly as big or bigger than SQLite itself.
  14207. */
  14208. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  14209. #ifdef SQLITE_ASCII
  14210. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  14211. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  14212. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  14213. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  14214. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  14215. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  14216. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  14217. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  14218. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  14219. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  14220. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  14221. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  14222. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  14223. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  14224. 252,253,254,255
  14225. #endif
  14226. #ifdef SQLITE_EBCDIC
  14227. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  14228. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  14229. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  14230. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  14231. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  14232. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  14233. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  14234. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  14235. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  14236. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  14237. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  14238. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  14239. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  14240. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  14241. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  14242. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  14243. #endif
  14244. };
  14245. /*
  14246. ** The following 256 byte lookup table is used to support SQLites built-in
  14247. ** equivalents to the following standard library functions:
  14248. **
  14249. ** isspace() 0x01
  14250. ** isalpha() 0x02
  14251. ** isdigit() 0x04
  14252. ** isalnum() 0x06
  14253. ** isxdigit() 0x08
  14254. ** toupper() 0x20
  14255. ** SQLite identifier character 0x40
  14256. **
  14257. ** Bit 0x20 is set if the mapped character requires translation to upper
  14258. ** case. i.e. if the character is a lower-case ASCII character.
  14259. ** If x is a lower-case ASCII character, then its upper-case equivalent
  14260. ** is (x - 0x20). Therefore toupper() can be implemented as:
  14261. **
  14262. ** (x & ~(map[x]&0x20))
  14263. **
  14264. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  14265. ** array. tolower() is used more often than toupper() by SQLite.
  14266. **
  14267. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  14268. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  14269. ** non-ASCII UTF character. Hence the test for whether or not a character is
  14270. ** part of an identifier is 0x46.
  14271. **
  14272. ** SQLite's versions are identical to the standard versions assuming a
  14273. ** locale of "C". They are implemented as macros in sqliteInt.h.
  14274. */
  14275. #ifdef SQLITE_ASCII
  14276. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  14277. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  14278. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  14279. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  14280. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  14281. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  14282. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  14283. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  14284. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  14285. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  14286. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  14287. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  14288. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  14289. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  14290. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  14291. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  14292. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  14293. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  14294. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  14295. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  14296. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  14297. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  14298. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  14299. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  14300. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  14301. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  14302. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  14303. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  14304. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  14305. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  14306. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  14307. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  14308. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  14309. };
  14310. #endif
  14311. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  14312. ** compatibility for legacy applications, the URI filename capability is
  14313. ** disabled by default.
  14314. **
  14315. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  14316. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  14317. **
  14318. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  14319. ** disabled. The default value may be changed by compiling with the
  14320. ** SQLITE_USE_URI symbol defined.
  14321. */
  14322. #ifndef SQLITE_USE_URI
  14323. # define SQLITE_USE_URI 0
  14324. #endif
  14325. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  14326. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  14327. ** that compile-time option is omitted.
  14328. */
  14329. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  14330. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  14331. #endif
  14332. /* The minimum PMA size is set to this value multiplied by the database
  14333. ** page size in bytes.
  14334. */
  14335. #ifndef SQLITE_SORTER_PMASZ
  14336. # define SQLITE_SORTER_PMASZ 250
  14337. #endif
  14338. /*
  14339. ** The following singleton contains the global configuration for
  14340. ** the SQLite library.
  14341. */
  14342. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  14343. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  14344. 1, /* bCoreMutex */
  14345. SQLITE_THREADSAFE==1, /* bFullMutex */
  14346. SQLITE_USE_URI, /* bOpenUri */
  14347. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  14348. 0x7ffffffe, /* mxStrlen */
  14349. 0, /* neverCorrupt */
  14350. 128, /* szLookaside */
  14351. 500, /* nLookaside */
  14352. {0,0,0,0,0,0,0,0}, /* m */
  14353. {0,0,0,0,0,0,0,0,0}, /* mutex */
  14354. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  14355. (void*)0, /* pHeap */
  14356. 0, /* nHeap */
  14357. 0, 0, /* mnHeap, mxHeap */
  14358. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  14359. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  14360. (void*)0, /* pScratch */
  14361. 0, /* szScratch */
  14362. 0, /* nScratch */
  14363. (void*)0, /* pPage */
  14364. 0, /* szPage */
  14365. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  14366. 0, /* mxParserStack */
  14367. 0, /* sharedCacheEnabled */
  14368. SQLITE_SORTER_PMASZ, /* szPma */
  14369. /* All the rest should always be initialized to zero */
  14370. 0, /* isInit */
  14371. 0, /* inProgress */
  14372. 0, /* isMutexInit */
  14373. 0, /* isMallocInit */
  14374. 0, /* isPCacheInit */
  14375. 0, /* nRefInitMutex */
  14376. 0, /* pInitMutex */
  14377. 0, /* xLog */
  14378. 0, /* pLogArg */
  14379. #ifdef SQLITE_ENABLE_SQLLOG
  14380. 0, /* xSqllog */
  14381. 0, /* pSqllogArg */
  14382. #endif
  14383. #ifdef SQLITE_VDBE_COVERAGE
  14384. 0, /* xVdbeBranch */
  14385. 0, /* pVbeBranchArg */
  14386. #endif
  14387. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14388. 0, /* xTestCallback */
  14389. #endif
  14390. 0 /* bLocaltimeFault */
  14391. };
  14392. /*
  14393. ** Hash table for global functions - functions common to all
  14394. ** database connections. After initialization, this table is
  14395. ** read-only.
  14396. */
  14397. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  14398. /*
  14399. ** Constant tokens for values 0 and 1.
  14400. */
  14401. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  14402. { "0", 1 },
  14403. { "1", 1 }
  14404. };
  14405. /*
  14406. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  14407. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  14408. ** the database page that contains the pending byte. It never attempts
  14409. ** to read or write that page. The pending byte page is set assign
  14410. ** for use by the VFS layers as space for managing file locks.
  14411. **
  14412. ** During testing, it is often desirable to move the pending byte to
  14413. ** a different position in the file. This allows code that has to
  14414. ** deal with the pending byte to run on files that are much smaller
  14415. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  14416. ** move the pending byte.
  14417. **
  14418. ** IMPORTANT: Changing the pending byte to any value other than
  14419. ** 0x40000000 results in an incompatible database file format!
  14420. ** Changing the pending byte during operation will result in undefined
  14421. ** and incorrect behavior.
  14422. */
  14423. #ifndef SQLITE_OMIT_WSD
  14424. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  14425. #endif
  14426. /* #include "opcodes.h" */
  14427. /*
  14428. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  14429. ** created by mkopcodeh.awk during compilation. Data is obtained
  14430. ** from the comments following the "case OP_xxxx:" statements in
  14431. ** the vdbe.c file.
  14432. */
  14433. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  14434. /*
  14435. ** Name of the default collating sequence
  14436. */
  14437. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  14438. /************** End of global.c **********************************************/
  14439. /************** Begin file ctime.c *******************************************/
  14440. /*
  14441. ** 2010 February 23
  14442. **
  14443. ** The author disclaims copyright to this source code. In place of
  14444. ** a legal notice, here is a blessing:
  14445. **
  14446. ** May you do good and not evil.
  14447. ** May you find forgiveness for yourself and forgive others.
  14448. ** May you share freely, never taking more than you give.
  14449. **
  14450. *************************************************************************
  14451. **
  14452. ** This file implements routines used to report what compile-time options
  14453. ** SQLite was built with.
  14454. */
  14455. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  14456. /* #include "sqliteInt.h" */
  14457. /*
  14458. ** An array of names of all compile-time options. This array should
  14459. ** be sorted A-Z.
  14460. **
  14461. ** This array looks large, but in a typical installation actually uses
  14462. ** only a handful of compile-time options, so most times this array is usually
  14463. ** rather short and uses little memory space.
  14464. */
  14465. static const char * const azCompileOpt[] = {
  14466. /* These macros are provided to "stringify" the value of the define
  14467. ** for those options in which the value is meaningful. */
  14468. #define CTIMEOPT_VAL_(opt) #opt
  14469. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  14470. #if SQLITE_32BIT_ROWID
  14471. "32BIT_ROWID",
  14472. #endif
  14473. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  14474. "4_BYTE_ALIGNED_MALLOC",
  14475. #endif
  14476. #if SQLITE_CASE_SENSITIVE_LIKE
  14477. "CASE_SENSITIVE_LIKE",
  14478. #endif
  14479. #if SQLITE_CHECK_PAGES
  14480. "CHECK_PAGES",
  14481. #endif
  14482. #if SQLITE_COVERAGE_TEST
  14483. "COVERAGE_TEST",
  14484. #endif
  14485. #if SQLITE_DEBUG
  14486. "DEBUG",
  14487. #endif
  14488. #if SQLITE_DEFAULT_LOCKING_MODE
  14489. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  14490. #endif
  14491. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  14492. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  14493. #endif
  14494. #if SQLITE_DISABLE_DIRSYNC
  14495. "DISABLE_DIRSYNC",
  14496. #endif
  14497. #if SQLITE_DISABLE_LFS
  14498. "DISABLE_LFS",
  14499. #endif
  14500. #if SQLITE_ENABLE_8_3_NAMES
  14501. "ENABLE_8_3_NAMES",
  14502. #endif
  14503. #if SQLITE_ENABLE_API_ARMOR
  14504. "ENABLE_API_ARMOR",
  14505. #endif
  14506. #if SQLITE_ENABLE_ATOMIC_WRITE
  14507. "ENABLE_ATOMIC_WRITE",
  14508. #endif
  14509. #if SQLITE_ENABLE_CEROD
  14510. "ENABLE_CEROD",
  14511. #endif
  14512. #if SQLITE_ENABLE_COLUMN_METADATA
  14513. "ENABLE_COLUMN_METADATA",
  14514. #endif
  14515. #if SQLITE_ENABLE_DBSTAT_VTAB
  14516. "ENABLE_DBSTAT_VTAB",
  14517. #endif
  14518. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  14519. "ENABLE_EXPENSIVE_ASSERT",
  14520. #endif
  14521. #if SQLITE_ENABLE_FTS1
  14522. "ENABLE_FTS1",
  14523. #endif
  14524. #if SQLITE_ENABLE_FTS2
  14525. "ENABLE_FTS2",
  14526. #endif
  14527. #if SQLITE_ENABLE_FTS3
  14528. "ENABLE_FTS3",
  14529. #endif
  14530. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  14531. "ENABLE_FTS3_PARENTHESIS",
  14532. #endif
  14533. #if SQLITE_ENABLE_FTS4
  14534. "ENABLE_FTS4",
  14535. #endif
  14536. #if SQLITE_ENABLE_FTS5
  14537. "ENABLE_FTS5",
  14538. #endif
  14539. #if SQLITE_ENABLE_ICU
  14540. "ENABLE_ICU",
  14541. #endif
  14542. #if SQLITE_ENABLE_IOTRACE
  14543. "ENABLE_IOTRACE",
  14544. #endif
  14545. #if SQLITE_ENABLE_JSON1
  14546. "ENABLE_JSON1",
  14547. #endif
  14548. #if SQLITE_ENABLE_LOAD_EXTENSION
  14549. "ENABLE_LOAD_EXTENSION",
  14550. #endif
  14551. #if SQLITE_ENABLE_LOCKING_STYLE
  14552. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  14553. #endif
  14554. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  14555. "ENABLE_MEMORY_MANAGEMENT",
  14556. #endif
  14557. #if SQLITE_ENABLE_MEMSYS3
  14558. "ENABLE_MEMSYS3",
  14559. #endif
  14560. #if SQLITE_ENABLE_MEMSYS5
  14561. "ENABLE_MEMSYS5",
  14562. #endif
  14563. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  14564. "ENABLE_OVERSIZE_CELL_CHECK",
  14565. #endif
  14566. #if SQLITE_ENABLE_RTREE
  14567. "ENABLE_RTREE",
  14568. #endif
  14569. #if defined(SQLITE_ENABLE_STAT4)
  14570. "ENABLE_STAT4",
  14571. #elif defined(SQLITE_ENABLE_STAT3)
  14572. "ENABLE_STAT3",
  14573. #endif
  14574. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  14575. "ENABLE_UNLOCK_NOTIFY",
  14576. #endif
  14577. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  14578. "ENABLE_UPDATE_DELETE_LIMIT",
  14579. #endif
  14580. #if SQLITE_HAS_CODEC
  14581. "HAS_CODEC",
  14582. #endif
  14583. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  14584. "HAVE_ISNAN",
  14585. #endif
  14586. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  14587. "HOMEGROWN_RECURSIVE_MUTEX",
  14588. #endif
  14589. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  14590. "IGNORE_AFP_LOCK_ERRORS",
  14591. #endif
  14592. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  14593. "IGNORE_FLOCK_LOCK_ERRORS",
  14594. #endif
  14595. #ifdef SQLITE_INT64_TYPE
  14596. "INT64_TYPE",
  14597. #endif
  14598. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  14599. "LIKE_DOESNT_MATCH_BLOBS",
  14600. #endif
  14601. #if SQLITE_LOCK_TRACE
  14602. "LOCK_TRACE",
  14603. #endif
  14604. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  14605. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  14606. #endif
  14607. #ifdef SQLITE_MAX_SCHEMA_RETRY
  14608. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  14609. #endif
  14610. #if SQLITE_MEMDEBUG
  14611. "MEMDEBUG",
  14612. #endif
  14613. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  14614. "MIXED_ENDIAN_64BIT_FLOAT",
  14615. #endif
  14616. #if SQLITE_NO_SYNC
  14617. "NO_SYNC",
  14618. #endif
  14619. #if SQLITE_OMIT_ALTERTABLE
  14620. "OMIT_ALTERTABLE",
  14621. #endif
  14622. #if SQLITE_OMIT_ANALYZE
  14623. "OMIT_ANALYZE",
  14624. #endif
  14625. #if SQLITE_OMIT_ATTACH
  14626. "OMIT_ATTACH",
  14627. #endif
  14628. #if SQLITE_OMIT_AUTHORIZATION
  14629. "OMIT_AUTHORIZATION",
  14630. #endif
  14631. #if SQLITE_OMIT_AUTOINCREMENT
  14632. "OMIT_AUTOINCREMENT",
  14633. #endif
  14634. #if SQLITE_OMIT_AUTOINIT
  14635. "OMIT_AUTOINIT",
  14636. #endif
  14637. #if SQLITE_OMIT_AUTOMATIC_INDEX
  14638. "OMIT_AUTOMATIC_INDEX",
  14639. #endif
  14640. #if SQLITE_OMIT_AUTORESET
  14641. "OMIT_AUTORESET",
  14642. #endif
  14643. #if SQLITE_OMIT_AUTOVACUUM
  14644. "OMIT_AUTOVACUUM",
  14645. #endif
  14646. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  14647. "OMIT_BETWEEN_OPTIMIZATION",
  14648. #endif
  14649. #if SQLITE_OMIT_BLOB_LITERAL
  14650. "OMIT_BLOB_LITERAL",
  14651. #endif
  14652. #if SQLITE_OMIT_BTREECOUNT
  14653. "OMIT_BTREECOUNT",
  14654. #endif
  14655. #if SQLITE_OMIT_BUILTIN_TEST
  14656. "OMIT_BUILTIN_TEST",
  14657. #endif
  14658. #if SQLITE_OMIT_CAST
  14659. "OMIT_CAST",
  14660. #endif
  14661. #if SQLITE_OMIT_CHECK
  14662. "OMIT_CHECK",
  14663. #endif
  14664. #if SQLITE_OMIT_COMPLETE
  14665. "OMIT_COMPLETE",
  14666. #endif
  14667. #if SQLITE_OMIT_COMPOUND_SELECT
  14668. "OMIT_COMPOUND_SELECT",
  14669. #endif
  14670. #if SQLITE_OMIT_CTE
  14671. "OMIT_CTE",
  14672. #endif
  14673. #if SQLITE_OMIT_DATETIME_FUNCS
  14674. "OMIT_DATETIME_FUNCS",
  14675. #endif
  14676. #if SQLITE_OMIT_DECLTYPE
  14677. "OMIT_DECLTYPE",
  14678. #endif
  14679. #if SQLITE_OMIT_DEPRECATED
  14680. "OMIT_DEPRECATED",
  14681. #endif
  14682. #if SQLITE_OMIT_DISKIO
  14683. "OMIT_DISKIO",
  14684. #endif
  14685. #if SQLITE_OMIT_EXPLAIN
  14686. "OMIT_EXPLAIN",
  14687. #endif
  14688. #if SQLITE_OMIT_FLAG_PRAGMAS
  14689. "OMIT_FLAG_PRAGMAS",
  14690. #endif
  14691. #if SQLITE_OMIT_FLOATING_POINT
  14692. "OMIT_FLOATING_POINT",
  14693. #endif
  14694. #if SQLITE_OMIT_FOREIGN_KEY
  14695. "OMIT_FOREIGN_KEY",
  14696. #endif
  14697. #if SQLITE_OMIT_GET_TABLE
  14698. "OMIT_GET_TABLE",
  14699. #endif
  14700. #if SQLITE_OMIT_INCRBLOB
  14701. "OMIT_INCRBLOB",
  14702. #endif
  14703. #if SQLITE_OMIT_INTEGRITY_CHECK
  14704. "OMIT_INTEGRITY_CHECK",
  14705. #endif
  14706. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  14707. "OMIT_LIKE_OPTIMIZATION",
  14708. #endif
  14709. #if SQLITE_OMIT_LOAD_EXTENSION
  14710. "OMIT_LOAD_EXTENSION",
  14711. #endif
  14712. #if SQLITE_OMIT_LOCALTIME
  14713. "OMIT_LOCALTIME",
  14714. #endif
  14715. #if SQLITE_OMIT_LOOKASIDE
  14716. "OMIT_LOOKASIDE",
  14717. #endif
  14718. #if SQLITE_OMIT_MEMORYDB
  14719. "OMIT_MEMORYDB",
  14720. #endif
  14721. #if SQLITE_OMIT_OR_OPTIMIZATION
  14722. "OMIT_OR_OPTIMIZATION",
  14723. #endif
  14724. #if SQLITE_OMIT_PAGER_PRAGMAS
  14725. "OMIT_PAGER_PRAGMAS",
  14726. #endif
  14727. #if SQLITE_OMIT_PRAGMA
  14728. "OMIT_PRAGMA",
  14729. #endif
  14730. #if SQLITE_OMIT_PROGRESS_CALLBACK
  14731. "OMIT_PROGRESS_CALLBACK",
  14732. #endif
  14733. #if SQLITE_OMIT_QUICKBALANCE
  14734. "OMIT_QUICKBALANCE",
  14735. #endif
  14736. #if SQLITE_OMIT_REINDEX
  14737. "OMIT_REINDEX",
  14738. #endif
  14739. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  14740. "OMIT_SCHEMA_PRAGMAS",
  14741. #endif
  14742. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  14743. "OMIT_SCHEMA_VERSION_PRAGMAS",
  14744. #endif
  14745. #if SQLITE_OMIT_SHARED_CACHE
  14746. "OMIT_SHARED_CACHE",
  14747. #endif
  14748. #if SQLITE_OMIT_SUBQUERY
  14749. "OMIT_SUBQUERY",
  14750. #endif
  14751. #if SQLITE_OMIT_TCL_VARIABLE
  14752. "OMIT_TCL_VARIABLE",
  14753. #endif
  14754. #if SQLITE_OMIT_TEMPDB
  14755. "OMIT_TEMPDB",
  14756. #endif
  14757. #if SQLITE_OMIT_TRACE
  14758. "OMIT_TRACE",
  14759. #endif
  14760. #if SQLITE_OMIT_TRIGGER
  14761. "OMIT_TRIGGER",
  14762. #endif
  14763. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  14764. "OMIT_TRUNCATE_OPTIMIZATION",
  14765. #endif
  14766. #if SQLITE_OMIT_UTF16
  14767. "OMIT_UTF16",
  14768. #endif
  14769. #if SQLITE_OMIT_VACUUM
  14770. "OMIT_VACUUM",
  14771. #endif
  14772. #if SQLITE_OMIT_VIEW
  14773. "OMIT_VIEW",
  14774. #endif
  14775. #if SQLITE_OMIT_VIRTUALTABLE
  14776. "OMIT_VIRTUALTABLE",
  14777. #endif
  14778. #if SQLITE_OMIT_WAL
  14779. "OMIT_WAL",
  14780. #endif
  14781. #if SQLITE_OMIT_WSD
  14782. "OMIT_WSD",
  14783. #endif
  14784. #if SQLITE_OMIT_XFER_OPT
  14785. "OMIT_XFER_OPT",
  14786. #endif
  14787. #if SQLITE_PERFORMANCE_TRACE
  14788. "PERFORMANCE_TRACE",
  14789. #endif
  14790. #if SQLITE_PROXY_DEBUG
  14791. "PROXY_DEBUG",
  14792. #endif
  14793. #if SQLITE_RTREE_INT_ONLY
  14794. "RTREE_INT_ONLY",
  14795. #endif
  14796. #if SQLITE_SECURE_DELETE
  14797. "SECURE_DELETE",
  14798. #endif
  14799. #if SQLITE_SMALL_STACK
  14800. "SMALL_STACK",
  14801. #endif
  14802. #if SQLITE_SOUNDEX
  14803. "SOUNDEX",
  14804. #endif
  14805. #if SQLITE_SYSTEM_MALLOC
  14806. "SYSTEM_MALLOC",
  14807. #endif
  14808. #if SQLITE_TCL
  14809. "TCL",
  14810. #endif
  14811. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  14812. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  14813. #endif
  14814. #if SQLITE_TEST
  14815. "TEST",
  14816. #endif
  14817. #if defined(SQLITE_THREADSAFE)
  14818. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  14819. #endif
  14820. #if SQLITE_USE_ALLOCA
  14821. "USE_ALLOCA",
  14822. #endif
  14823. #if SQLITE_USER_AUTHENTICATION
  14824. "USER_AUTHENTICATION",
  14825. #endif
  14826. #if SQLITE_WIN32_MALLOC
  14827. "WIN32_MALLOC",
  14828. #endif
  14829. #if SQLITE_ZERO_MALLOC
  14830. "ZERO_MALLOC"
  14831. #endif
  14832. };
  14833. /*
  14834. ** Given the name of a compile-time option, return true if that option
  14835. ** was used and false if not.
  14836. **
  14837. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  14838. ** is not required for a match.
  14839. */
  14840. SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
  14841. int i, n;
  14842. #if SQLITE_ENABLE_API_ARMOR
  14843. if( zOptName==0 ){
  14844. (void)SQLITE_MISUSE_BKPT;
  14845. return 0;
  14846. }
  14847. #endif
  14848. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  14849. n = sqlite3Strlen30(zOptName);
  14850. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  14851. ** linear search is adequate. No need for a binary search. */
  14852. for(i=0; i<ArraySize(azCompileOpt); i++){
  14853. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  14854. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  14855. ){
  14856. return 1;
  14857. }
  14858. }
  14859. return 0;
  14860. }
  14861. /*
  14862. ** Return the N-th compile-time option string. If N is out of range,
  14863. ** return a NULL pointer.
  14864. */
  14865. SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
  14866. if( N>=0 && N<ArraySize(azCompileOpt) ){
  14867. return azCompileOpt[N];
  14868. }
  14869. return 0;
  14870. }
  14871. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  14872. /************** End of ctime.c ***********************************************/
  14873. /************** Begin file status.c ******************************************/
  14874. /*
  14875. ** 2008 June 18
  14876. **
  14877. ** The author disclaims copyright to this source code. In place of
  14878. ** a legal notice, here is a blessing:
  14879. **
  14880. ** May you do good and not evil.
  14881. ** May you find forgiveness for yourself and forgive others.
  14882. ** May you share freely, never taking more than you give.
  14883. **
  14884. *************************************************************************
  14885. **
  14886. ** This module implements the sqlite3_status() interface and related
  14887. ** functionality.
  14888. */
  14889. /* #include "sqliteInt.h" */
  14890. /************** Include vdbeInt.h in the middle of status.c ******************/
  14891. /************** Begin file vdbeInt.h *****************************************/
  14892. /*
  14893. ** 2003 September 6
  14894. **
  14895. ** The author disclaims copyright to this source code. In place of
  14896. ** a legal notice, here is a blessing:
  14897. **
  14898. ** May you do good and not evil.
  14899. ** May you find forgiveness for yourself and forgive others.
  14900. ** May you share freely, never taking more than you give.
  14901. **
  14902. *************************************************************************
  14903. ** This is the header file for information that is private to the
  14904. ** VDBE. This information used to all be at the top of the single
  14905. ** source code file "vdbe.c". When that file became too big (over
  14906. ** 6000 lines long) it was split up into several smaller files and
  14907. ** this header information was factored out.
  14908. */
  14909. #ifndef _VDBEINT_H_
  14910. #define _VDBEINT_H_
  14911. /*
  14912. ** The maximum number of times that a statement will try to reparse
  14913. ** itself before giving up and returning SQLITE_SCHEMA.
  14914. */
  14915. #ifndef SQLITE_MAX_SCHEMA_RETRY
  14916. # define SQLITE_MAX_SCHEMA_RETRY 50
  14917. #endif
  14918. /*
  14919. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  14920. ** "explain" P4 display logic is enabled.
  14921. */
  14922. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  14923. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  14924. # define VDBE_DISPLAY_P4 1
  14925. #else
  14926. # define VDBE_DISPLAY_P4 0
  14927. #endif
  14928. /*
  14929. ** SQL is translated into a sequence of instructions to be
  14930. ** executed by a virtual machine. Each instruction is an instance
  14931. ** of the following structure.
  14932. */
  14933. typedef struct VdbeOp Op;
  14934. /*
  14935. ** Boolean values
  14936. */
  14937. typedef unsigned Bool;
  14938. /* Opaque type used by code in vdbesort.c */
  14939. typedef struct VdbeSorter VdbeSorter;
  14940. /* Opaque type used by the explainer */
  14941. typedef struct Explain Explain;
  14942. /* Elements of the linked list at Vdbe.pAuxData */
  14943. typedef struct AuxData AuxData;
  14944. /* Types of VDBE cursors */
  14945. #define CURTYPE_BTREE 0
  14946. #define CURTYPE_SORTER 1
  14947. #define CURTYPE_VTAB 2
  14948. #define CURTYPE_PSEUDO 3
  14949. /*
  14950. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  14951. **
  14952. ** * A b-tree cursor
  14953. ** - In the main database or in an ephemeral database
  14954. ** - On either an index or a table
  14955. ** * A sorter
  14956. ** * A virtual table
  14957. ** * A one-row "pseudotable" stored in a single register
  14958. */
  14959. struct VdbeCursor {
  14960. u8 eCurType; /* One of the CURTYPE_* values above */
  14961. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  14962. u8 nullRow; /* True if pointing to a row with no data */
  14963. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  14964. u8 isTable; /* True for rowid tables. False for indexes */
  14965. #ifdef SQLITE_DEBUG
  14966. u8 seekOp; /* Most recent seek operation on this cursor */
  14967. #endif
  14968. Bool isEphemeral:1; /* True for an ephemeral table */
  14969. Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
  14970. Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
  14971. Pgno pgnoRoot; /* Root page of the open btree cursor */
  14972. i16 nField; /* Number of fields in the header */
  14973. u16 nHdrParsed; /* Number of header fields parsed so far */
  14974. union {
  14975. BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
  14976. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  14977. int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
  14978. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  14979. } uc;
  14980. Btree *pBt; /* Separate file holding temporary table */
  14981. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  14982. int seekResult; /* Result of previous sqlite3BtreeMoveto() */
  14983. i64 seqCount; /* Sequence counter */
  14984. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  14985. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  14986. u64 maskUsed; /* Mask of columns used by this cursor */
  14987. #endif
  14988. /* Cached information about the header for the data record that the
  14989. ** cursor is currently pointing to. Only valid if cacheStatus matches
  14990. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  14991. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  14992. ** the cache is out of date.
  14993. **
  14994. ** aRow might point to (ephemeral) data for the current row, or it might
  14995. ** be NULL.
  14996. */
  14997. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  14998. u32 payloadSize; /* Total number of bytes in the record */
  14999. u32 szRow; /* Byte available in aRow */
  15000. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  15001. const u8 *aRow; /* Data for the current row, if all on one page */
  15002. u32 *aOffset; /* Pointer to aType[nField] */
  15003. u32 aType[1]; /* Type values for all entries in the record */
  15004. /* 2*nField extra array elements allocated for aType[], beyond the one
  15005. ** static element declared in the structure. nField total array slots for
  15006. ** aType[] and nField+1 array slots for aOffset[] */
  15007. };
  15008. typedef struct VdbeCursor VdbeCursor;
  15009. /*
  15010. ** When a sub-program is executed (OP_Program), a structure of this type
  15011. ** is allocated to store the current value of the program counter, as
  15012. ** well as the current memory cell array and various other frame specific
  15013. ** values stored in the Vdbe struct. When the sub-program is finished,
  15014. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  15015. ** restoring the state of the VM to as it was before the sub-program
  15016. ** began executing.
  15017. **
  15018. ** The memory for a VdbeFrame object is allocated and managed by a memory
  15019. ** cell in the parent (calling) frame. When the memory cell is deleted or
  15020. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  15021. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  15022. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  15023. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  15024. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  15025. ** child frame are released.
  15026. **
  15027. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  15028. ** set to NULL if the currently executing frame is the main program.
  15029. */
  15030. typedef struct VdbeFrame VdbeFrame;
  15031. struct VdbeFrame {
  15032. Vdbe *v; /* VM this frame belongs to */
  15033. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  15034. Op *aOp; /* Program instructions for parent frame */
  15035. i64 *anExec; /* Event counters from parent frame */
  15036. Mem *aMem; /* Array of memory cells for parent frame */
  15037. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  15038. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  15039. void *token; /* Copy of SubProgram.token */
  15040. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  15041. int nCursor; /* Number of entries in apCsr */
  15042. int pc; /* Program Counter in parent (calling) frame */
  15043. int nOp; /* Size of aOp array */
  15044. int nMem; /* Number of entries in aMem */
  15045. int nOnceFlag; /* Number of entries in aOnceFlag */
  15046. int nChildMem; /* Number of memory cells for child frame */
  15047. int nChildCsr; /* Number of cursors for child frame */
  15048. int nChange; /* Statement changes (Vdbe.nChange) */
  15049. int nDbChange; /* Value of db->nChange */
  15050. };
  15051. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  15052. /*
  15053. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  15054. */
  15055. #define CACHE_STALE 0
  15056. /*
  15057. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  15058. ** structures. Each Mem struct may cache multiple representations (string,
  15059. ** integer etc.) of the same value.
  15060. */
  15061. struct Mem {
  15062. union MemValue {
  15063. double r; /* Real value used when MEM_Real is set in flags */
  15064. i64 i; /* Integer value used when MEM_Int is set in flags */
  15065. int nZero; /* Used when bit MEM_Zero is set in flags */
  15066. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  15067. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  15068. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  15069. } u;
  15070. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  15071. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  15072. u8 eSubtype; /* Subtype for this value */
  15073. int n; /* Number of characters in string value, excluding '\0' */
  15074. char *z; /* String or BLOB value */
  15075. /* ShallowCopy only needs to copy the information above */
  15076. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  15077. int szMalloc; /* Size of the zMalloc allocation */
  15078. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  15079. sqlite3 *db; /* The associated database connection */
  15080. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  15081. #ifdef SQLITE_DEBUG
  15082. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  15083. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  15084. #endif
  15085. };
  15086. /*
  15087. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  15088. ** follows.
  15089. */
  15090. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  15091. /* One or more of the following flags are set to indicate the validOK
  15092. ** representations of the value stored in the Mem struct.
  15093. **
  15094. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  15095. ** No other flags may be set in this case.
  15096. **
  15097. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  15098. ** Usually this is encoded in the same unicode encoding as the main
  15099. ** database (see below for exceptions). If the MEM_Term flag is also
  15100. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  15101. ** flags may coexist with the MEM_Str flag.
  15102. */
  15103. #define MEM_Null 0x0001 /* Value is NULL */
  15104. #define MEM_Str 0x0002 /* Value is a string */
  15105. #define MEM_Int 0x0004 /* Value is an integer */
  15106. #define MEM_Real 0x0008 /* Value is a real number */
  15107. #define MEM_Blob 0x0010 /* Value is a BLOB */
  15108. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  15109. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  15110. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  15111. #define MEM_Undefined 0x0080 /* Value is undefined */
  15112. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  15113. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  15114. /* Whenever Mem contains a valid string or blob representation, one of
  15115. ** the following flags must be set to determine the memory management
  15116. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  15117. ** string is \000 or \u0000 terminated
  15118. */
  15119. #define MEM_Term 0x0200 /* String rep is nul terminated */
  15120. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  15121. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  15122. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  15123. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  15124. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  15125. #ifdef SQLITE_OMIT_INCRBLOB
  15126. #undef MEM_Zero
  15127. #define MEM_Zero 0x0000
  15128. #endif
  15129. /*
  15130. ** Clear any existing type flags from a Mem and replace them with f
  15131. */
  15132. #define MemSetTypeFlag(p, f) \
  15133. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  15134. /*
  15135. ** Return true if a memory cell is not marked as invalid. This macro
  15136. ** is for use inside assert() statements only.
  15137. */
  15138. #ifdef SQLITE_DEBUG
  15139. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  15140. #endif
  15141. /*
  15142. ** Each auxiliary data pointer stored by a user defined function
  15143. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  15144. ** of this structure. All such structures associated with a single VM
  15145. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  15146. ** when the VM is halted (if not before).
  15147. */
  15148. struct AuxData {
  15149. int iOp; /* Instruction number of OP_Function opcode */
  15150. int iArg; /* Index of function argument. */
  15151. void *pAux; /* Aux data pointer */
  15152. void (*xDelete)(void *); /* Destructor for the aux data */
  15153. AuxData *pNext; /* Next element in list */
  15154. };
  15155. /*
  15156. ** The "context" argument for an installable function. A pointer to an
  15157. ** instance of this structure is the first argument to the routines used
  15158. ** implement the SQL functions.
  15159. **
  15160. ** There is a typedef for this structure in sqlite.h. So all routines,
  15161. ** even the public interface to SQLite, can use a pointer to this structure.
  15162. ** But this file is the only place where the internal details of this
  15163. ** structure are known.
  15164. **
  15165. ** This structure is defined inside of vdbeInt.h because it uses substructures
  15166. ** (Mem) which are only defined there.
  15167. */
  15168. struct sqlite3_context {
  15169. Mem *pOut; /* The return value is stored here */
  15170. FuncDef *pFunc; /* Pointer to function information */
  15171. Mem *pMem; /* Memory cell used to store aggregate context */
  15172. Vdbe *pVdbe; /* The VM that owns this context */
  15173. int iOp; /* Instruction number of OP_Function */
  15174. int isError; /* Error code returned by the function. */
  15175. u8 skipFlag; /* Skip accumulator loading if true */
  15176. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  15177. u8 argc; /* Number of arguments */
  15178. sqlite3_value *argv[1]; /* Argument set */
  15179. };
  15180. /*
  15181. ** An Explain object accumulates indented output which is helpful
  15182. ** in describing recursive data structures.
  15183. */
  15184. struct Explain {
  15185. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  15186. StrAccum str; /* The string being accumulated */
  15187. int nIndent; /* Number of elements in aIndent */
  15188. u16 aIndent[100]; /* Levels of indentation */
  15189. char zBase[100]; /* Initial space */
  15190. };
  15191. /* A bitfield type for use inside of structures. Always follow with :N where
  15192. ** N is the number of bits.
  15193. */
  15194. typedef unsigned bft; /* Bit Field Type */
  15195. typedef struct ScanStatus ScanStatus;
  15196. struct ScanStatus {
  15197. int addrExplain; /* OP_Explain for loop */
  15198. int addrLoop; /* Address of "loops" counter */
  15199. int addrVisit; /* Address of "rows visited" counter */
  15200. int iSelectID; /* The "Select-ID" for this loop */
  15201. LogEst nEst; /* Estimated output rows per loop */
  15202. char *zName; /* Name of table or index */
  15203. };
  15204. /*
  15205. ** An instance of the virtual machine. This structure contains the complete
  15206. ** state of the virtual machine.
  15207. **
  15208. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  15209. ** is really a pointer to an instance of this structure.
  15210. */
  15211. struct Vdbe {
  15212. sqlite3 *db; /* The database connection that owns this statement */
  15213. Op *aOp; /* Space to hold the virtual machine's program */
  15214. Mem *aMem; /* The memory locations */
  15215. Mem **apArg; /* Arguments to currently executing user function */
  15216. Mem *aColName; /* Column names to return */
  15217. Mem *pResultSet; /* Pointer to an array of results */
  15218. Parse *pParse; /* Parsing context used to create this Vdbe */
  15219. int nMem; /* Number of memory locations currently allocated */
  15220. int nOp; /* Number of instructions in the program */
  15221. int nCursor; /* Number of slots in apCsr[] */
  15222. u32 magic; /* Magic number for sanity checking */
  15223. char *zErrMsg; /* Error message written here */
  15224. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  15225. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  15226. Mem *aVar; /* Values for the OP_Variable opcode. */
  15227. char **azVar; /* Name of variables */
  15228. ynVar nVar; /* Number of entries in aVar[] */
  15229. ynVar nzVar; /* Number of entries in azVar[] */
  15230. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  15231. int pc; /* The program counter */
  15232. int rc; /* Value to return */
  15233. #ifdef SQLITE_DEBUG
  15234. int rcApp; /* errcode set by sqlite3_result_error_code() */
  15235. #endif
  15236. u16 nResColumn; /* Number of columns in one row of the result set */
  15237. u8 errorAction; /* Recovery action to do in case of an error */
  15238. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  15239. bft explain:2; /* True if EXPLAIN present on SQL command */
  15240. bft changeCntOn:1; /* True to update the change-counter */
  15241. bft expired:1; /* True if the VM needs to be recompiled */
  15242. bft runOnlyOnce:1; /* Automatically expire on reset */
  15243. bft usesStmtJournal:1; /* True if uses a statement journal */
  15244. bft readOnly:1; /* True for statements that do not write */
  15245. bft bIsReader:1; /* True for statements that read */
  15246. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  15247. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  15248. int nChange; /* Number of db changes made since last reset */
  15249. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  15250. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  15251. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  15252. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  15253. #ifndef SQLITE_OMIT_TRACE
  15254. i64 startTime; /* Time when query started - used for profiling */
  15255. #endif
  15256. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  15257. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  15258. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  15259. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  15260. char *zSql; /* Text of the SQL statement that generated this */
  15261. void *pFree; /* Free this when deleting the vdbe */
  15262. VdbeFrame *pFrame; /* Parent frame */
  15263. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  15264. int nFrame; /* Number of frames in pFrame list */
  15265. u32 expmask; /* Binding to these vars invalidates VM */
  15266. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  15267. int nOnceFlag; /* Size of array aOnceFlag[] */
  15268. u8 *aOnceFlag; /* Flags for OP_Once */
  15269. AuxData *pAuxData; /* Linked list of auxdata allocations */
  15270. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  15271. i64 *anExec; /* Number of times each op has been executed */
  15272. int nScan; /* Entries in aScan[] */
  15273. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  15274. #endif
  15275. };
  15276. /*
  15277. ** The following are allowed values for Vdbe.magic
  15278. */
  15279. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  15280. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  15281. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  15282. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  15283. /*
  15284. ** Function prototypes
  15285. */
  15286. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  15287. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  15288. void sqliteVdbePopStack(Vdbe*,int);
  15289. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  15290. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  15291. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  15292. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  15293. #endif
  15294. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  15295. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  15296. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  15297. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  15298. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  15299. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  15300. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  15301. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  15302. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  15303. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  15304. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  15305. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  15306. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  15307. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  15308. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  15309. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  15310. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  15311. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  15312. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  15313. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  15314. #ifdef SQLITE_OMIT_FLOATING_POINT
  15315. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  15316. #else
  15317. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  15318. #endif
  15319. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  15320. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  15321. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  15322. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  15323. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  15324. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  15325. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  15326. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  15327. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  15328. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  15329. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  15330. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  15331. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  15332. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
  15333. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  15334. #define VdbeMemDynamic(X) \
  15335. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  15336. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  15337. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  15338. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  15339. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  15340. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  15341. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  15342. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  15343. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  15344. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  15345. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  15346. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  15347. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  15348. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  15349. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  15350. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  15351. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  15352. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  15353. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  15354. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  15355. #else
  15356. # define sqlite3VdbeEnter(X)
  15357. # define sqlite3VdbeLeave(X)
  15358. #endif
  15359. #ifdef SQLITE_DEBUG
  15360. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  15361. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  15362. #endif
  15363. #ifndef SQLITE_OMIT_FOREIGN_KEY
  15364. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  15365. #else
  15366. # define sqlite3VdbeCheckFk(p,i) 0
  15367. #endif
  15368. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  15369. #ifdef SQLITE_DEBUG
  15370. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  15371. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  15372. #endif
  15373. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  15374. #ifndef SQLITE_OMIT_INCRBLOB
  15375. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  15376. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  15377. #else
  15378. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  15379. #define ExpandBlob(P) SQLITE_OK
  15380. #endif
  15381. #endif /* !defined(_VDBEINT_H_) */
  15382. /************** End of vdbeInt.h *********************************************/
  15383. /************** Continuing where we left off in status.c *********************/
  15384. /*
  15385. ** Variables in which to record status information.
  15386. */
  15387. #if SQLITE_PTRSIZE>4
  15388. typedef sqlite3_int64 sqlite3StatValueType;
  15389. #else
  15390. typedef u32 sqlite3StatValueType;
  15391. #endif
  15392. typedef struct sqlite3StatType sqlite3StatType;
  15393. static SQLITE_WSD struct sqlite3StatType {
  15394. sqlite3StatValueType nowValue[10]; /* Current value */
  15395. sqlite3StatValueType mxValue[10]; /* Maximum value */
  15396. } sqlite3Stat = { {0,}, {0,} };
  15397. /*
  15398. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  15399. ** mutex, or by the pcache1 mutex. The following array determines which.
  15400. */
  15401. static const char statMutex[] = {
  15402. 0, /* SQLITE_STATUS_MEMORY_USED */
  15403. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  15404. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  15405. 0, /* SQLITE_STATUS_SCRATCH_USED */
  15406. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  15407. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  15408. 0, /* SQLITE_STATUS_PARSER_STACK */
  15409. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  15410. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  15411. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  15412. };
  15413. /* The "wsdStat" macro will resolve to the status information
  15414. ** state vector. If writable static data is unsupported on the target,
  15415. ** we have to locate the state vector at run-time. In the more common
  15416. ** case where writable static data is supported, wsdStat can refer directly
  15417. ** to the "sqlite3Stat" state vector declared above.
  15418. */
  15419. #ifdef SQLITE_OMIT_WSD
  15420. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  15421. # define wsdStat x[0]
  15422. #else
  15423. # define wsdStatInit
  15424. # define wsdStat sqlite3Stat
  15425. #endif
  15426. /*
  15427. ** Return the current value of a status parameter. The caller must
  15428. ** be holding the appropriate mutex.
  15429. */
  15430. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  15431. wsdStatInit;
  15432. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15433. assert( op>=0 && op<ArraySize(statMutex) );
  15434. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15435. : sqlite3MallocMutex()) );
  15436. return wsdStat.nowValue[op];
  15437. }
  15438. /*
  15439. ** Add N to the value of a status record. The caller must hold the
  15440. ** appropriate mutex. (Locking is checked by assert()).
  15441. **
  15442. ** The StatusUp() routine can accept positive or negative values for N.
  15443. ** The value of N is added to the current status value and the high-water
  15444. ** mark is adjusted if necessary.
  15445. **
  15446. ** The StatusDown() routine lowers the current value by N. The highwater
  15447. ** mark is unchanged. N must be non-negative for StatusDown().
  15448. */
  15449. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  15450. wsdStatInit;
  15451. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15452. assert( op>=0 && op<ArraySize(statMutex) );
  15453. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15454. : sqlite3MallocMutex()) );
  15455. wsdStat.nowValue[op] += N;
  15456. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  15457. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  15458. }
  15459. }
  15460. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  15461. wsdStatInit;
  15462. assert( N>=0 );
  15463. assert( op>=0 && op<ArraySize(statMutex) );
  15464. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15465. : sqlite3MallocMutex()) );
  15466. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15467. wsdStat.nowValue[op] -= N;
  15468. }
  15469. /*
  15470. ** Adjust the highwater mark if necessary.
  15471. ** The caller must hold the appropriate mutex.
  15472. */
  15473. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  15474. sqlite3StatValueType newValue;
  15475. wsdStatInit;
  15476. assert( X>=0 );
  15477. newValue = (sqlite3StatValueType)X;
  15478. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  15479. assert( op>=0 && op<ArraySize(statMutex) );
  15480. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  15481. : sqlite3MallocMutex()) );
  15482. assert( op==SQLITE_STATUS_MALLOC_SIZE
  15483. || op==SQLITE_STATUS_PAGECACHE_SIZE
  15484. || op==SQLITE_STATUS_SCRATCH_SIZE
  15485. || op==SQLITE_STATUS_PARSER_STACK );
  15486. if( newValue>wsdStat.mxValue[op] ){
  15487. wsdStat.mxValue[op] = newValue;
  15488. }
  15489. }
  15490. /*
  15491. ** Query status information.
  15492. */
  15493. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  15494. int op,
  15495. sqlite3_int64 *pCurrent,
  15496. sqlite3_int64 *pHighwater,
  15497. int resetFlag
  15498. ){
  15499. sqlite3_mutex *pMutex;
  15500. wsdStatInit;
  15501. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  15502. return SQLITE_MISUSE_BKPT;
  15503. }
  15504. #ifdef SQLITE_ENABLE_API_ARMOR
  15505. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  15506. #endif
  15507. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  15508. sqlite3_mutex_enter(pMutex);
  15509. *pCurrent = wsdStat.nowValue[op];
  15510. *pHighwater = wsdStat.mxValue[op];
  15511. if( resetFlag ){
  15512. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  15513. }
  15514. sqlite3_mutex_leave(pMutex);
  15515. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  15516. return SQLITE_OK;
  15517. }
  15518. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  15519. sqlite3_int64 iCur, iHwtr;
  15520. int rc;
  15521. #ifdef SQLITE_ENABLE_API_ARMOR
  15522. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  15523. #endif
  15524. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  15525. if( rc==0 ){
  15526. *pCurrent = (int)iCur;
  15527. *pHighwater = (int)iHwtr;
  15528. }
  15529. return rc;
  15530. }
  15531. /*
  15532. ** Query status information for a single database connection
  15533. */
  15534. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
  15535. sqlite3 *db, /* The database connection whose status is desired */
  15536. int op, /* Status verb */
  15537. int *pCurrent, /* Write current value here */
  15538. int *pHighwater, /* Write high-water mark here */
  15539. int resetFlag /* Reset high-water mark if true */
  15540. ){
  15541. int rc = SQLITE_OK; /* Return code */
  15542. #ifdef SQLITE_ENABLE_API_ARMOR
  15543. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  15544. return SQLITE_MISUSE_BKPT;
  15545. }
  15546. #endif
  15547. sqlite3_mutex_enter(db->mutex);
  15548. switch( op ){
  15549. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  15550. *pCurrent = db->lookaside.nOut;
  15551. *pHighwater = db->lookaside.mxOut;
  15552. if( resetFlag ){
  15553. db->lookaside.mxOut = db->lookaside.nOut;
  15554. }
  15555. break;
  15556. }
  15557. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  15558. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  15559. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  15560. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  15561. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  15562. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  15563. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  15564. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  15565. *pCurrent = 0;
  15566. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  15567. if( resetFlag ){
  15568. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  15569. }
  15570. break;
  15571. }
  15572. /*
  15573. ** Return an approximation for the amount of memory currently used
  15574. ** by all pagers associated with the given database connection. The
  15575. ** highwater mark is meaningless and is returned as zero.
  15576. */
  15577. case SQLITE_DBSTATUS_CACHE_USED: {
  15578. int totalUsed = 0;
  15579. int i;
  15580. sqlite3BtreeEnterAll(db);
  15581. for(i=0; i<db->nDb; i++){
  15582. Btree *pBt = db->aDb[i].pBt;
  15583. if( pBt ){
  15584. Pager *pPager = sqlite3BtreePager(pBt);
  15585. totalUsed += sqlite3PagerMemUsed(pPager);
  15586. }
  15587. }
  15588. sqlite3BtreeLeaveAll(db);
  15589. *pCurrent = totalUsed;
  15590. *pHighwater = 0;
  15591. break;
  15592. }
  15593. /*
  15594. ** *pCurrent gets an accurate estimate of the amount of memory used
  15595. ** to store the schema for all databases (main, temp, and any ATTACHed
  15596. ** databases. *pHighwater is set to zero.
  15597. */
  15598. case SQLITE_DBSTATUS_SCHEMA_USED: {
  15599. int i; /* Used to iterate through schemas */
  15600. int nByte = 0; /* Used to accumulate return value */
  15601. sqlite3BtreeEnterAll(db);
  15602. db->pnBytesFreed = &nByte;
  15603. for(i=0; i<db->nDb; i++){
  15604. Schema *pSchema = db->aDb[i].pSchema;
  15605. if( ALWAYS(pSchema!=0) ){
  15606. HashElem *p;
  15607. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  15608. pSchema->tblHash.count
  15609. + pSchema->trigHash.count
  15610. + pSchema->idxHash.count
  15611. + pSchema->fkeyHash.count
  15612. );
  15613. nByte += sqlite3_msize(pSchema->tblHash.ht);
  15614. nByte += sqlite3_msize(pSchema->trigHash.ht);
  15615. nByte += sqlite3_msize(pSchema->idxHash.ht);
  15616. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  15617. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  15618. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  15619. }
  15620. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  15621. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  15622. }
  15623. }
  15624. }
  15625. db->pnBytesFreed = 0;
  15626. sqlite3BtreeLeaveAll(db);
  15627. *pHighwater = 0;
  15628. *pCurrent = nByte;
  15629. break;
  15630. }
  15631. /*
  15632. ** *pCurrent gets an accurate estimate of the amount of memory used
  15633. ** to store all prepared statements.
  15634. ** *pHighwater is set to zero.
  15635. */
  15636. case SQLITE_DBSTATUS_STMT_USED: {
  15637. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  15638. int nByte = 0; /* Used to accumulate return value */
  15639. db->pnBytesFreed = &nByte;
  15640. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  15641. sqlite3VdbeClearObject(db, pVdbe);
  15642. sqlite3DbFree(db, pVdbe);
  15643. }
  15644. db->pnBytesFreed = 0;
  15645. *pHighwater = 0; /* IMP: R-64479-57858 */
  15646. *pCurrent = nByte;
  15647. break;
  15648. }
  15649. /*
  15650. ** Set *pCurrent to the total cache hits or misses encountered by all
  15651. ** pagers the database handle is connected to. *pHighwater is always set
  15652. ** to zero.
  15653. */
  15654. case SQLITE_DBSTATUS_CACHE_HIT:
  15655. case SQLITE_DBSTATUS_CACHE_MISS:
  15656. case SQLITE_DBSTATUS_CACHE_WRITE:{
  15657. int i;
  15658. int nRet = 0;
  15659. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  15660. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  15661. for(i=0; i<db->nDb; i++){
  15662. if( db->aDb[i].pBt ){
  15663. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  15664. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  15665. }
  15666. }
  15667. *pHighwater = 0; /* IMP: R-42420-56072 */
  15668. /* IMP: R-54100-20147 */
  15669. /* IMP: R-29431-39229 */
  15670. *pCurrent = nRet;
  15671. break;
  15672. }
  15673. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  15674. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  15675. ** have been satisfied. The *pHighwater is always set to zero.
  15676. */
  15677. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  15678. *pHighwater = 0; /* IMP: R-11967-56545 */
  15679. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  15680. break;
  15681. }
  15682. default: {
  15683. rc = SQLITE_ERROR;
  15684. }
  15685. }
  15686. sqlite3_mutex_leave(db->mutex);
  15687. return rc;
  15688. }
  15689. /************** End of status.c **********************************************/
  15690. /************** Begin file date.c ********************************************/
  15691. /*
  15692. ** 2003 October 31
  15693. **
  15694. ** The author disclaims copyright to this source code. In place of
  15695. ** a legal notice, here is a blessing:
  15696. **
  15697. ** May you do good and not evil.
  15698. ** May you find forgiveness for yourself and forgive others.
  15699. ** May you share freely, never taking more than you give.
  15700. **
  15701. *************************************************************************
  15702. ** This file contains the C functions that implement date and time
  15703. ** functions for SQLite.
  15704. **
  15705. ** There is only one exported symbol in this file - the function
  15706. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  15707. ** All other code has file scope.
  15708. **
  15709. ** SQLite processes all times and dates as julian day numbers. The
  15710. ** dates and times are stored as the number of days since noon
  15711. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  15712. ** calendar system.
  15713. **
  15714. ** 1970-01-01 00:00:00 is JD 2440587.5
  15715. ** 2000-01-01 00:00:00 is JD 2451544.5
  15716. **
  15717. ** This implementation requires years to be expressed as a 4-digit number
  15718. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  15719. ** be represented, even though julian day numbers allow a much wider
  15720. ** range of dates.
  15721. **
  15722. ** The Gregorian calendar system is used for all dates and times,
  15723. ** even those that predate the Gregorian calendar. Historians usually
  15724. ** use the julian calendar for dates prior to 1582-10-15 and for some
  15725. ** dates afterwards, depending on locale. Beware of this difference.
  15726. **
  15727. ** The conversion algorithms are implemented based on descriptions
  15728. ** in the following text:
  15729. **
  15730. ** Jean Meeus
  15731. ** Astronomical Algorithms, 2nd Edition, 1998
  15732. ** ISBM 0-943396-61-1
  15733. ** Willmann-Bell, Inc
  15734. ** Richmond, Virginia (USA)
  15735. */
  15736. /* #include "sqliteInt.h" */
  15737. /* #include <stdlib.h> */
  15738. /* #include <assert.h> */
  15739. #include <time.h>
  15740. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  15741. /*
  15742. ** A structure for holding a single date and time.
  15743. */
  15744. typedef struct DateTime DateTime;
  15745. struct DateTime {
  15746. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  15747. int Y, M, D; /* Year, month, and day */
  15748. int h, m; /* Hour and minutes */
  15749. int tz; /* Timezone offset in minutes */
  15750. double s; /* Seconds */
  15751. char validYMD; /* True (1) if Y,M,D are valid */
  15752. char validHMS; /* True (1) if h,m,s are valid */
  15753. char validJD; /* True (1) if iJD is valid */
  15754. char validTZ; /* True (1) if tz is valid */
  15755. char tzSet; /* Timezone was set explicitly */
  15756. };
  15757. /*
  15758. ** Convert zDate into one or more integers. Additional arguments
  15759. ** come in groups of 5 as follows:
  15760. **
  15761. ** N number of digits in the integer
  15762. ** min minimum allowed value of the integer
  15763. ** max maximum allowed value of the integer
  15764. ** nextC first character after the integer
  15765. ** pVal where to write the integers value.
  15766. **
  15767. ** Conversions continue until one with nextC==0 is encountered.
  15768. ** The function returns the number of successful conversions.
  15769. */
  15770. static int getDigits(const char *zDate, ...){
  15771. va_list ap;
  15772. int val;
  15773. int N;
  15774. int min;
  15775. int max;
  15776. int nextC;
  15777. int *pVal;
  15778. int cnt = 0;
  15779. va_start(ap, zDate);
  15780. do{
  15781. N = va_arg(ap, int);
  15782. min = va_arg(ap, int);
  15783. max = va_arg(ap, int);
  15784. nextC = va_arg(ap, int);
  15785. pVal = va_arg(ap, int*);
  15786. val = 0;
  15787. while( N-- ){
  15788. if( !sqlite3Isdigit(*zDate) ){
  15789. goto end_getDigits;
  15790. }
  15791. val = val*10 + *zDate - '0';
  15792. zDate++;
  15793. }
  15794. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  15795. goto end_getDigits;
  15796. }
  15797. *pVal = val;
  15798. zDate++;
  15799. cnt++;
  15800. }while( nextC );
  15801. end_getDigits:
  15802. va_end(ap);
  15803. return cnt;
  15804. }
  15805. /*
  15806. ** Parse a timezone extension on the end of a date-time.
  15807. ** The extension is of the form:
  15808. **
  15809. ** (+/-)HH:MM
  15810. **
  15811. ** Or the "zulu" notation:
  15812. **
  15813. ** Z
  15814. **
  15815. ** If the parse is successful, write the number of minutes
  15816. ** of change in p->tz and return 0. If a parser error occurs,
  15817. ** return non-zero.
  15818. **
  15819. ** A missing specifier is not considered an error.
  15820. */
  15821. static int parseTimezone(const char *zDate, DateTime *p){
  15822. int sgn = 0;
  15823. int nHr, nMn;
  15824. int c;
  15825. while( sqlite3Isspace(*zDate) ){ zDate++; }
  15826. p->tz = 0;
  15827. c = *zDate;
  15828. if( c=='-' ){
  15829. sgn = -1;
  15830. }else if( c=='+' ){
  15831. sgn = +1;
  15832. }else if( c=='Z' || c=='z' ){
  15833. zDate++;
  15834. goto zulu_time;
  15835. }else{
  15836. return c!=0;
  15837. }
  15838. zDate++;
  15839. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  15840. return 1;
  15841. }
  15842. zDate += 5;
  15843. p->tz = sgn*(nMn + nHr*60);
  15844. zulu_time:
  15845. while( sqlite3Isspace(*zDate) ){ zDate++; }
  15846. p->tzSet = 1;
  15847. return *zDate!=0;
  15848. }
  15849. /*
  15850. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  15851. ** The HH, MM, and SS must each be exactly 2 digits. The
  15852. ** fractional seconds FFFF can be one or more digits.
  15853. **
  15854. ** Return 1 if there is a parsing error and 0 on success.
  15855. */
  15856. static int parseHhMmSs(const char *zDate, DateTime *p){
  15857. int h, m, s;
  15858. double ms = 0.0;
  15859. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  15860. return 1;
  15861. }
  15862. zDate += 5;
  15863. if( *zDate==':' ){
  15864. zDate++;
  15865. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  15866. return 1;
  15867. }
  15868. zDate += 2;
  15869. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  15870. double rScale = 1.0;
  15871. zDate++;
  15872. while( sqlite3Isdigit(*zDate) ){
  15873. ms = ms*10.0 + *zDate - '0';
  15874. rScale *= 10.0;
  15875. zDate++;
  15876. }
  15877. ms /= rScale;
  15878. }
  15879. }else{
  15880. s = 0;
  15881. }
  15882. p->validJD = 0;
  15883. p->validHMS = 1;
  15884. p->h = h;
  15885. p->m = m;
  15886. p->s = s + ms;
  15887. if( parseTimezone(zDate, p) ) return 1;
  15888. p->validTZ = (p->tz!=0)?1:0;
  15889. return 0;
  15890. }
  15891. /*
  15892. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  15893. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  15894. **
  15895. ** Reference: Meeus page 61
  15896. */
  15897. static void computeJD(DateTime *p){
  15898. int Y, M, D, A, B, X1, X2;
  15899. if( p->validJD ) return;
  15900. if( p->validYMD ){
  15901. Y = p->Y;
  15902. M = p->M;
  15903. D = p->D;
  15904. }else{
  15905. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  15906. M = 1;
  15907. D = 1;
  15908. }
  15909. if( M<=2 ){
  15910. Y--;
  15911. M += 12;
  15912. }
  15913. A = Y/100;
  15914. B = 2 - A + (A/4);
  15915. X1 = 36525*(Y+4716)/100;
  15916. X2 = 306001*(M+1)/10000;
  15917. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  15918. p->validJD = 1;
  15919. if( p->validHMS ){
  15920. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  15921. if( p->validTZ ){
  15922. p->iJD -= p->tz*60000;
  15923. p->validYMD = 0;
  15924. p->validHMS = 0;
  15925. p->validTZ = 0;
  15926. }
  15927. }
  15928. }
  15929. /*
  15930. ** Parse dates of the form
  15931. **
  15932. ** YYYY-MM-DD HH:MM:SS.FFF
  15933. ** YYYY-MM-DD HH:MM:SS
  15934. ** YYYY-MM-DD HH:MM
  15935. ** YYYY-MM-DD
  15936. **
  15937. ** Write the result into the DateTime structure and return 0
  15938. ** on success and 1 if the input string is not a well-formed
  15939. ** date.
  15940. */
  15941. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  15942. int Y, M, D, neg;
  15943. if( zDate[0]=='-' ){
  15944. zDate++;
  15945. neg = 1;
  15946. }else{
  15947. neg = 0;
  15948. }
  15949. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  15950. return 1;
  15951. }
  15952. zDate += 10;
  15953. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  15954. if( parseHhMmSs(zDate, p)==0 ){
  15955. /* We got the time */
  15956. }else if( *zDate==0 ){
  15957. p->validHMS = 0;
  15958. }else{
  15959. return 1;
  15960. }
  15961. p->validJD = 0;
  15962. p->validYMD = 1;
  15963. p->Y = neg ? -Y : Y;
  15964. p->M = M;
  15965. p->D = D;
  15966. if( p->validTZ ){
  15967. computeJD(p);
  15968. }
  15969. return 0;
  15970. }
  15971. /*
  15972. ** Set the time to the current time reported by the VFS.
  15973. **
  15974. ** Return the number of errors.
  15975. */
  15976. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  15977. p->iJD = sqlite3StmtCurrentTime(context);
  15978. if( p->iJD>0 ){
  15979. p->validJD = 1;
  15980. return 0;
  15981. }else{
  15982. return 1;
  15983. }
  15984. }
  15985. /*
  15986. ** Attempt to parse the given string into a julian day number. Return
  15987. ** the number of errors.
  15988. **
  15989. ** The following are acceptable forms for the input string:
  15990. **
  15991. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  15992. ** DDDD.DD
  15993. ** now
  15994. **
  15995. ** In the first form, the +/-HH:MM is always optional. The fractional
  15996. ** seconds extension (the ".FFF") is optional. The seconds portion
  15997. ** (":SS.FFF") is option. The year and date can be omitted as long
  15998. ** as there is a time string. The time string can be omitted as long
  15999. ** as there is a year and date.
  16000. */
  16001. static int parseDateOrTime(
  16002. sqlite3_context *context,
  16003. const char *zDate,
  16004. DateTime *p
  16005. ){
  16006. double r;
  16007. if( parseYyyyMmDd(zDate,p)==0 ){
  16008. return 0;
  16009. }else if( parseHhMmSs(zDate, p)==0 ){
  16010. return 0;
  16011. }else if( sqlite3StrICmp(zDate,"now")==0){
  16012. return setDateTimeToCurrent(context, p);
  16013. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  16014. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  16015. p->validJD = 1;
  16016. return 0;
  16017. }
  16018. return 1;
  16019. }
  16020. /*
  16021. ** Compute the Year, Month, and Day from the julian day number.
  16022. */
  16023. static void computeYMD(DateTime *p){
  16024. int Z, A, B, C, D, E, X1;
  16025. if( p->validYMD ) return;
  16026. if( !p->validJD ){
  16027. p->Y = 2000;
  16028. p->M = 1;
  16029. p->D = 1;
  16030. }else{
  16031. Z = (int)((p->iJD + 43200000)/86400000);
  16032. A = (int)((Z - 1867216.25)/36524.25);
  16033. A = Z + 1 + A - (A/4);
  16034. B = A + 1524;
  16035. C = (int)((B - 122.1)/365.25);
  16036. D = (36525*(C&32767))/100;
  16037. E = (int)((B-D)/30.6001);
  16038. X1 = (int)(30.6001*E);
  16039. p->D = B - D - X1;
  16040. p->M = E<14 ? E-1 : E-13;
  16041. p->Y = p->M>2 ? C - 4716 : C - 4715;
  16042. }
  16043. p->validYMD = 1;
  16044. }
  16045. /*
  16046. ** Compute the Hour, Minute, and Seconds from the julian day number.
  16047. */
  16048. static void computeHMS(DateTime *p){
  16049. int s;
  16050. if( p->validHMS ) return;
  16051. computeJD(p);
  16052. s = (int)((p->iJD + 43200000) % 86400000);
  16053. p->s = s/1000.0;
  16054. s = (int)p->s;
  16055. p->s -= s;
  16056. p->h = s/3600;
  16057. s -= p->h*3600;
  16058. p->m = s/60;
  16059. p->s += s - p->m*60;
  16060. p->validHMS = 1;
  16061. }
  16062. /*
  16063. ** Compute both YMD and HMS
  16064. */
  16065. static void computeYMD_HMS(DateTime *p){
  16066. computeYMD(p);
  16067. computeHMS(p);
  16068. }
  16069. /*
  16070. ** Clear the YMD and HMS and the TZ
  16071. */
  16072. static void clearYMD_HMS_TZ(DateTime *p){
  16073. p->validYMD = 0;
  16074. p->validHMS = 0;
  16075. p->validTZ = 0;
  16076. }
  16077. /*
  16078. ** On recent Windows platforms, the localtime_s() function is available
  16079. ** as part of the "Secure CRT". It is essentially equivalent to
  16080. ** localtime_r() available under most POSIX platforms, except that the
  16081. ** order of the parameters is reversed.
  16082. **
  16083. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  16084. **
  16085. ** If the user has not indicated to use localtime_r() or localtime_s()
  16086. ** already, check for an MSVC build environment that provides
  16087. ** localtime_s().
  16088. */
  16089. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  16090. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  16091. #undef HAVE_LOCALTIME_S
  16092. #define HAVE_LOCALTIME_S 1
  16093. #endif
  16094. #ifndef SQLITE_OMIT_LOCALTIME
  16095. /*
  16096. ** The following routine implements the rough equivalent of localtime_r()
  16097. ** using whatever operating-system specific localtime facility that
  16098. ** is available. This routine returns 0 on success and
  16099. ** non-zero on any kind of error.
  16100. **
  16101. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  16102. ** routine will always fail.
  16103. **
  16104. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  16105. ** library function localtime_r() is used to assist in the calculation of
  16106. ** local time.
  16107. */
  16108. static int osLocaltime(time_t *t, struct tm *pTm){
  16109. int rc;
  16110. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  16111. struct tm *pX;
  16112. #if SQLITE_THREADSAFE>0
  16113. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  16114. #endif
  16115. sqlite3_mutex_enter(mutex);
  16116. pX = localtime(t);
  16117. #ifndef SQLITE_OMIT_BUILTIN_TEST
  16118. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  16119. #endif
  16120. if( pX ) *pTm = *pX;
  16121. sqlite3_mutex_leave(mutex);
  16122. rc = pX==0;
  16123. #else
  16124. #ifndef SQLITE_OMIT_BUILTIN_TEST
  16125. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  16126. #endif
  16127. #if HAVE_LOCALTIME_R
  16128. rc = localtime_r(t, pTm)==0;
  16129. #else
  16130. rc = localtime_s(pTm, t);
  16131. #endif /* HAVE_LOCALTIME_R */
  16132. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  16133. return rc;
  16134. }
  16135. #endif /* SQLITE_OMIT_LOCALTIME */
  16136. #ifndef SQLITE_OMIT_LOCALTIME
  16137. /*
  16138. ** Compute the difference (in milliseconds) between localtime and UTC
  16139. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  16140. ** return this value and set *pRc to SQLITE_OK.
  16141. **
  16142. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  16143. ** is undefined in this case.
  16144. */
  16145. static sqlite3_int64 localtimeOffset(
  16146. DateTime *p, /* Date at which to calculate offset */
  16147. sqlite3_context *pCtx, /* Write error here if one occurs */
  16148. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  16149. ){
  16150. DateTime x, y;
  16151. time_t t;
  16152. struct tm sLocal;
  16153. /* Initialize the contents of sLocal to avoid a compiler warning. */
  16154. memset(&sLocal, 0, sizeof(sLocal));
  16155. x = *p;
  16156. computeYMD_HMS(&x);
  16157. if( x.Y<1971 || x.Y>=2038 ){
  16158. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  16159. ** works for years between 1970 and 2037. For dates outside this range,
  16160. ** SQLite attempts to map the year into an equivalent year within this
  16161. ** range, do the calculation, then map the year back.
  16162. */
  16163. x.Y = 2000;
  16164. x.M = 1;
  16165. x.D = 1;
  16166. x.h = 0;
  16167. x.m = 0;
  16168. x.s = 0.0;
  16169. } else {
  16170. int s = (int)(x.s + 0.5);
  16171. x.s = s;
  16172. }
  16173. x.tz = 0;
  16174. x.validJD = 0;
  16175. computeJD(&x);
  16176. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  16177. if( osLocaltime(&t, &sLocal) ){
  16178. sqlite3_result_error(pCtx, "local time unavailable", -1);
  16179. *pRc = SQLITE_ERROR;
  16180. return 0;
  16181. }
  16182. y.Y = sLocal.tm_year + 1900;
  16183. y.M = sLocal.tm_mon + 1;
  16184. y.D = sLocal.tm_mday;
  16185. y.h = sLocal.tm_hour;
  16186. y.m = sLocal.tm_min;
  16187. y.s = sLocal.tm_sec;
  16188. y.validYMD = 1;
  16189. y.validHMS = 1;
  16190. y.validJD = 0;
  16191. y.validTZ = 0;
  16192. computeJD(&y);
  16193. *pRc = SQLITE_OK;
  16194. return y.iJD - x.iJD;
  16195. }
  16196. #endif /* SQLITE_OMIT_LOCALTIME */
  16197. /*
  16198. ** Process a modifier to a date-time stamp. The modifiers are
  16199. ** as follows:
  16200. **
  16201. ** NNN days
  16202. ** NNN hours
  16203. ** NNN minutes
  16204. ** NNN.NNNN seconds
  16205. ** NNN months
  16206. ** NNN years
  16207. ** start of month
  16208. ** start of year
  16209. ** start of week
  16210. ** start of day
  16211. ** weekday N
  16212. ** unixepoch
  16213. ** localtime
  16214. ** utc
  16215. **
  16216. ** Return 0 on success and 1 if there is any kind of error. If the error
  16217. ** is in a system call (i.e. localtime()), then an error message is written
  16218. ** to context pCtx. If the error is an unrecognized modifier, no error is
  16219. ** written to pCtx.
  16220. */
  16221. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  16222. int rc = 1;
  16223. int n;
  16224. double r;
  16225. char *z, zBuf[30];
  16226. z = zBuf;
  16227. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  16228. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  16229. }
  16230. z[n] = 0;
  16231. switch( z[0] ){
  16232. #ifndef SQLITE_OMIT_LOCALTIME
  16233. case 'l': {
  16234. /* localtime
  16235. **
  16236. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  16237. ** show local time.
  16238. */
  16239. if( strcmp(z, "localtime")==0 ){
  16240. computeJD(p);
  16241. p->iJD += localtimeOffset(p, pCtx, &rc);
  16242. clearYMD_HMS_TZ(p);
  16243. }
  16244. break;
  16245. }
  16246. #endif
  16247. case 'u': {
  16248. /*
  16249. ** unixepoch
  16250. **
  16251. ** Treat the current value of p->iJD as the number of
  16252. ** seconds since 1970. Convert to a real julian day number.
  16253. */
  16254. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  16255. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  16256. clearYMD_HMS_TZ(p);
  16257. rc = 0;
  16258. }
  16259. #ifndef SQLITE_OMIT_LOCALTIME
  16260. else if( strcmp(z, "utc")==0 ){
  16261. if( p->tzSet==0 ){
  16262. sqlite3_int64 c1;
  16263. computeJD(p);
  16264. c1 = localtimeOffset(p, pCtx, &rc);
  16265. if( rc==SQLITE_OK ){
  16266. p->iJD -= c1;
  16267. clearYMD_HMS_TZ(p);
  16268. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  16269. }
  16270. p->tzSet = 1;
  16271. }else{
  16272. rc = SQLITE_OK;
  16273. }
  16274. }
  16275. #endif
  16276. break;
  16277. }
  16278. case 'w': {
  16279. /*
  16280. ** weekday N
  16281. **
  16282. ** Move the date to the same time on the next occurrence of
  16283. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  16284. ** date is already on the appropriate weekday, this is a no-op.
  16285. */
  16286. if( strncmp(z, "weekday ", 8)==0
  16287. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  16288. && (n=(int)r)==r && n>=0 && r<7 ){
  16289. sqlite3_int64 Z;
  16290. computeYMD_HMS(p);
  16291. p->validTZ = 0;
  16292. p->validJD = 0;
  16293. computeJD(p);
  16294. Z = ((p->iJD + 129600000)/86400000) % 7;
  16295. if( Z>n ) Z -= 7;
  16296. p->iJD += (n - Z)*86400000;
  16297. clearYMD_HMS_TZ(p);
  16298. rc = 0;
  16299. }
  16300. break;
  16301. }
  16302. case 's': {
  16303. /*
  16304. ** start of TTTTT
  16305. **
  16306. ** Move the date backwards to the beginning of the current day,
  16307. ** or month or year.
  16308. */
  16309. if( strncmp(z, "start of ", 9)!=0 ) break;
  16310. z += 9;
  16311. computeYMD(p);
  16312. p->validHMS = 1;
  16313. p->h = p->m = 0;
  16314. p->s = 0.0;
  16315. p->validTZ = 0;
  16316. p->validJD = 0;
  16317. if( strcmp(z,"month")==0 ){
  16318. p->D = 1;
  16319. rc = 0;
  16320. }else if( strcmp(z,"year")==0 ){
  16321. computeYMD(p);
  16322. p->M = 1;
  16323. p->D = 1;
  16324. rc = 0;
  16325. }else if( strcmp(z,"day")==0 ){
  16326. rc = 0;
  16327. }
  16328. break;
  16329. }
  16330. case '+':
  16331. case '-':
  16332. case '0':
  16333. case '1':
  16334. case '2':
  16335. case '3':
  16336. case '4':
  16337. case '5':
  16338. case '6':
  16339. case '7':
  16340. case '8':
  16341. case '9': {
  16342. double rRounder;
  16343. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  16344. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  16345. rc = 1;
  16346. break;
  16347. }
  16348. if( z[n]==':' ){
  16349. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  16350. ** specified number of hours, minutes, seconds, and fractional seconds
  16351. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  16352. ** omitted.
  16353. */
  16354. const char *z2 = z;
  16355. DateTime tx;
  16356. sqlite3_int64 day;
  16357. if( !sqlite3Isdigit(*z2) ) z2++;
  16358. memset(&tx, 0, sizeof(tx));
  16359. if( parseHhMmSs(z2, &tx) ) break;
  16360. computeJD(&tx);
  16361. tx.iJD -= 43200000;
  16362. day = tx.iJD/86400000;
  16363. tx.iJD -= day*86400000;
  16364. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  16365. computeJD(p);
  16366. clearYMD_HMS_TZ(p);
  16367. p->iJD += tx.iJD;
  16368. rc = 0;
  16369. break;
  16370. }
  16371. z += n;
  16372. while( sqlite3Isspace(*z) ) z++;
  16373. n = sqlite3Strlen30(z);
  16374. if( n>10 || n<3 ) break;
  16375. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  16376. computeJD(p);
  16377. rc = 0;
  16378. rRounder = r<0 ? -0.5 : +0.5;
  16379. if( n==3 && strcmp(z,"day")==0 ){
  16380. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  16381. }else if( n==4 && strcmp(z,"hour")==0 ){
  16382. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  16383. }else if( n==6 && strcmp(z,"minute")==0 ){
  16384. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  16385. }else if( n==6 && strcmp(z,"second")==0 ){
  16386. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  16387. }else if( n==5 && strcmp(z,"month")==0 ){
  16388. int x, y;
  16389. computeYMD_HMS(p);
  16390. p->M += (int)r;
  16391. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  16392. p->Y += x;
  16393. p->M -= x*12;
  16394. p->validJD = 0;
  16395. computeJD(p);
  16396. y = (int)r;
  16397. if( y!=r ){
  16398. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  16399. }
  16400. }else if( n==4 && strcmp(z,"year")==0 ){
  16401. int y = (int)r;
  16402. computeYMD_HMS(p);
  16403. p->Y += y;
  16404. p->validJD = 0;
  16405. computeJD(p);
  16406. if( y!=r ){
  16407. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  16408. }
  16409. }else{
  16410. rc = 1;
  16411. }
  16412. clearYMD_HMS_TZ(p);
  16413. break;
  16414. }
  16415. default: {
  16416. break;
  16417. }
  16418. }
  16419. return rc;
  16420. }
  16421. /*
  16422. ** Process time function arguments. argv[0] is a date-time stamp.
  16423. ** argv[1] and following are modifiers. Parse them all and write
  16424. ** the resulting time into the DateTime structure p. Return 0
  16425. ** on success and 1 if there are any errors.
  16426. **
  16427. ** If there are zero parameters (if even argv[0] is undefined)
  16428. ** then assume a default value of "now" for argv[0].
  16429. */
  16430. static int isDate(
  16431. sqlite3_context *context,
  16432. int argc,
  16433. sqlite3_value **argv,
  16434. DateTime *p
  16435. ){
  16436. int i;
  16437. const unsigned char *z;
  16438. int eType;
  16439. memset(p, 0, sizeof(*p));
  16440. if( argc==0 ){
  16441. return setDateTimeToCurrent(context, p);
  16442. }
  16443. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  16444. || eType==SQLITE_INTEGER ){
  16445. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  16446. p->validJD = 1;
  16447. }else{
  16448. z = sqlite3_value_text(argv[0]);
  16449. if( !z || parseDateOrTime(context, (char*)z, p) ){
  16450. return 1;
  16451. }
  16452. }
  16453. for(i=1; i<argc; i++){
  16454. z = sqlite3_value_text(argv[i]);
  16455. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  16456. }
  16457. return 0;
  16458. }
  16459. /*
  16460. ** The following routines implement the various date and time functions
  16461. ** of SQLite.
  16462. */
  16463. /*
  16464. ** julianday( TIMESTRING, MOD, MOD, ...)
  16465. **
  16466. ** Return the julian day number of the date specified in the arguments
  16467. */
  16468. static void juliandayFunc(
  16469. sqlite3_context *context,
  16470. int argc,
  16471. sqlite3_value **argv
  16472. ){
  16473. DateTime x;
  16474. if( isDate(context, argc, argv, &x)==0 ){
  16475. computeJD(&x);
  16476. sqlite3_result_double(context, x.iJD/86400000.0);
  16477. }
  16478. }
  16479. /*
  16480. ** datetime( TIMESTRING, MOD, MOD, ...)
  16481. **
  16482. ** Return YYYY-MM-DD HH:MM:SS
  16483. */
  16484. static void datetimeFunc(
  16485. sqlite3_context *context,
  16486. int argc,
  16487. sqlite3_value **argv
  16488. ){
  16489. DateTime x;
  16490. if( isDate(context, argc, argv, &x)==0 ){
  16491. char zBuf[100];
  16492. computeYMD_HMS(&x);
  16493. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  16494. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  16495. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16496. }
  16497. }
  16498. /*
  16499. ** time( TIMESTRING, MOD, MOD, ...)
  16500. **
  16501. ** Return HH:MM:SS
  16502. */
  16503. static void timeFunc(
  16504. sqlite3_context *context,
  16505. int argc,
  16506. sqlite3_value **argv
  16507. ){
  16508. DateTime x;
  16509. if( isDate(context, argc, argv, &x)==0 ){
  16510. char zBuf[100];
  16511. computeHMS(&x);
  16512. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  16513. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16514. }
  16515. }
  16516. /*
  16517. ** date( TIMESTRING, MOD, MOD, ...)
  16518. **
  16519. ** Return YYYY-MM-DD
  16520. */
  16521. static void dateFunc(
  16522. sqlite3_context *context,
  16523. int argc,
  16524. sqlite3_value **argv
  16525. ){
  16526. DateTime x;
  16527. if( isDate(context, argc, argv, &x)==0 ){
  16528. char zBuf[100];
  16529. computeYMD(&x);
  16530. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  16531. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16532. }
  16533. }
  16534. /*
  16535. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  16536. **
  16537. ** Return a string described by FORMAT. Conversions as follows:
  16538. **
  16539. ** %d day of month
  16540. ** %f ** fractional seconds SS.SSS
  16541. ** %H hour 00-24
  16542. ** %j day of year 000-366
  16543. ** %J ** julian day number
  16544. ** %m month 01-12
  16545. ** %M minute 00-59
  16546. ** %s seconds since 1970-01-01
  16547. ** %S seconds 00-59
  16548. ** %w day of week 0-6 sunday==0
  16549. ** %W week of year 00-53
  16550. ** %Y year 0000-9999
  16551. ** %% %
  16552. */
  16553. static void strftimeFunc(
  16554. sqlite3_context *context,
  16555. int argc,
  16556. sqlite3_value **argv
  16557. ){
  16558. DateTime x;
  16559. u64 n;
  16560. size_t i,j;
  16561. char *z;
  16562. sqlite3 *db;
  16563. const char *zFmt;
  16564. char zBuf[100];
  16565. if( argc==0 ) return;
  16566. zFmt = (const char*)sqlite3_value_text(argv[0]);
  16567. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  16568. db = sqlite3_context_db_handle(context);
  16569. for(i=0, n=1; zFmt[i]; i++, n++){
  16570. if( zFmt[i]=='%' ){
  16571. switch( zFmt[i+1] ){
  16572. case 'd':
  16573. case 'H':
  16574. case 'm':
  16575. case 'M':
  16576. case 'S':
  16577. case 'W':
  16578. n++;
  16579. /* fall thru */
  16580. case 'w':
  16581. case '%':
  16582. break;
  16583. case 'f':
  16584. n += 8;
  16585. break;
  16586. case 'j':
  16587. n += 3;
  16588. break;
  16589. case 'Y':
  16590. n += 8;
  16591. break;
  16592. case 's':
  16593. case 'J':
  16594. n += 50;
  16595. break;
  16596. default:
  16597. return; /* ERROR. return a NULL */
  16598. }
  16599. i++;
  16600. }
  16601. }
  16602. testcase( n==sizeof(zBuf)-1 );
  16603. testcase( n==sizeof(zBuf) );
  16604. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  16605. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  16606. if( n<sizeof(zBuf) ){
  16607. z = zBuf;
  16608. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  16609. sqlite3_result_error_toobig(context);
  16610. return;
  16611. }else{
  16612. z = sqlite3DbMallocRaw(db, (int)n);
  16613. if( z==0 ){
  16614. sqlite3_result_error_nomem(context);
  16615. return;
  16616. }
  16617. }
  16618. computeJD(&x);
  16619. computeYMD_HMS(&x);
  16620. for(i=j=0; zFmt[i]; i++){
  16621. if( zFmt[i]!='%' ){
  16622. z[j++] = zFmt[i];
  16623. }else{
  16624. i++;
  16625. switch( zFmt[i] ){
  16626. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  16627. case 'f': {
  16628. double s = x.s;
  16629. if( s>59.999 ) s = 59.999;
  16630. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  16631. j += sqlite3Strlen30(&z[j]);
  16632. break;
  16633. }
  16634. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  16635. case 'W': /* Fall thru */
  16636. case 'j': {
  16637. int nDay; /* Number of days since 1st day of year */
  16638. DateTime y = x;
  16639. y.validJD = 0;
  16640. y.M = 1;
  16641. y.D = 1;
  16642. computeJD(&y);
  16643. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  16644. if( zFmt[i]=='W' ){
  16645. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  16646. wd = (int)(((x.iJD+43200000)/86400000)%7);
  16647. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  16648. j += 2;
  16649. }else{
  16650. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  16651. j += 3;
  16652. }
  16653. break;
  16654. }
  16655. case 'J': {
  16656. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  16657. j+=sqlite3Strlen30(&z[j]);
  16658. break;
  16659. }
  16660. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  16661. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  16662. case 's': {
  16663. sqlite3_snprintf(30,&z[j],"%lld",
  16664. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  16665. j += sqlite3Strlen30(&z[j]);
  16666. break;
  16667. }
  16668. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  16669. case 'w': {
  16670. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  16671. break;
  16672. }
  16673. case 'Y': {
  16674. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  16675. break;
  16676. }
  16677. default: z[j++] = '%'; break;
  16678. }
  16679. }
  16680. }
  16681. z[j] = 0;
  16682. sqlite3_result_text(context, z, -1,
  16683. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  16684. }
  16685. /*
  16686. ** current_time()
  16687. **
  16688. ** This function returns the same value as time('now').
  16689. */
  16690. static void ctimeFunc(
  16691. sqlite3_context *context,
  16692. int NotUsed,
  16693. sqlite3_value **NotUsed2
  16694. ){
  16695. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16696. timeFunc(context, 0, 0);
  16697. }
  16698. /*
  16699. ** current_date()
  16700. **
  16701. ** This function returns the same value as date('now').
  16702. */
  16703. static void cdateFunc(
  16704. sqlite3_context *context,
  16705. int NotUsed,
  16706. sqlite3_value **NotUsed2
  16707. ){
  16708. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16709. dateFunc(context, 0, 0);
  16710. }
  16711. /*
  16712. ** current_timestamp()
  16713. **
  16714. ** This function returns the same value as datetime('now').
  16715. */
  16716. static void ctimestampFunc(
  16717. sqlite3_context *context,
  16718. int NotUsed,
  16719. sqlite3_value **NotUsed2
  16720. ){
  16721. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16722. datetimeFunc(context, 0, 0);
  16723. }
  16724. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  16725. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  16726. /*
  16727. ** If the library is compiled to omit the full-scale date and time
  16728. ** handling (to get a smaller binary), the following minimal version
  16729. ** of the functions current_time(), current_date() and current_timestamp()
  16730. ** are included instead. This is to support column declarations that
  16731. ** include "DEFAULT CURRENT_TIME" etc.
  16732. **
  16733. ** This function uses the C-library functions time(), gmtime()
  16734. ** and strftime(). The format string to pass to strftime() is supplied
  16735. ** as the user-data for the function.
  16736. */
  16737. static void currentTimeFunc(
  16738. sqlite3_context *context,
  16739. int argc,
  16740. sqlite3_value **argv
  16741. ){
  16742. time_t t;
  16743. char *zFormat = (char *)sqlite3_user_data(context);
  16744. sqlite3 *db;
  16745. sqlite3_int64 iT;
  16746. struct tm *pTm;
  16747. struct tm sNow;
  16748. char zBuf[20];
  16749. UNUSED_PARAMETER(argc);
  16750. UNUSED_PARAMETER(argv);
  16751. iT = sqlite3StmtCurrentTime(context);
  16752. if( iT<=0 ) return;
  16753. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  16754. #if HAVE_GMTIME_R
  16755. pTm = gmtime_r(&t, &sNow);
  16756. #else
  16757. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  16758. pTm = gmtime(&t);
  16759. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  16760. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  16761. #endif
  16762. if( pTm ){
  16763. strftime(zBuf, 20, zFormat, &sNow);
  16764. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  16765. }
  16766. }
  16767. #endif
  16768. /*
  16769. ** This function registered all of the above C functions as SQL
  16770. ** functions. This should be the only routine in this file with
  16771. ** external linkage.
  16772. */
  16773. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  16774. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  16775. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  16776. DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  16777. DFUNCTION(date, -1, 0, 0, dateFunc ),
  16778. DFUNCTION(time, -1, 0, 0, timeFunc ),
  16779. DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  16780. DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  16781. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  16782. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  16783. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  16784. #else
  16785. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  16786. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  16787. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  16788. #endif
  16789. };
  16790. int i;
  16791. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  16792. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  16793. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  16794. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  16795. }
  16796. }
  16797. /************** End of date.c ************************************************/
  16798. /************** Begin file os.c **********************************************/
  16799. /*
  16800. ** 2005 November 29
  16801. **
  16802. ** The author disclaims copyright to this source code. In place of
  16803. ** a legal notice, here is a blessing:
  16804. **
  16805. ** May you do good and not evil.
  16806. ** May you find forgiveness for yourself and forgive others.
  16807. ** May you share freely, never taking more than you give.
  16808. **
  16809. ******************************************************************************
  16810. **
  16811. ** This file contains OS interface code that is common to all
  16812. ** architectures.
  16813. */
  16814. #define _SQLITE_OS_C_ 1
  16815. /* #include "sqliteInt.h" */
  16816. #undef _SQLITE_OS_C_
  16817. /*
  16818. ** The default SQLite sqlite3_vfs implementations do not allocate
  16819. ** memory (actually, os_unix.c allocates a small amount of memory
  16820. ** from within OsOpen()), but some third-party implementations may.
  16821. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  16822. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  16823. **
  16824. ** The following functions are instrumented for malloc() failure
  16825. ** testing:
  16826. **
  16827. ** sqlite3OsRead()
  16828. ** sqlite3OsWrite()
  16829. ** sqlite3OsSync()
  16830. ** sqlite3OsFileSize()
  16831. ** sqlite3OsLock()
  16832. ** sqlite3OsCheckReservedLock()
  16833. ** sqlite3OsFileControl()
  16834. ** sqlite3OsShmMap()
  16835. ** sqlite3OsOpen()
  16836. ** sqlite3OsDelete()
  16837. ** sqlite3OsAccess()
  16838. ** sqlite3OsFullPathname()
  16839. **
  16840. */
  16841. #if defined(SQLITE_TEST)
  16842. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  16843. #define DO_OS_MALLOC_TEST(x) \
  16844. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  16845. void *pTstAlloc = sqlite3Malloc(10); \
  16846. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  16847. sqlite3_free(pTstAlloc); \
  16848. }
  16849. #else
  16850. #define DO_OS_MALLOC_TEST(x)
  16851. #endif
  16852. /*
  16853. ** The following routines are convenience wrappers around methods
  16854. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  16855. ** of this would be completely automatic if SQLite were coded using
  16856. ** C++ instead of plain old C.
  16857. */
  16858. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  16859. int rc = SQLITE_OK;
  16860. if( pId->pMethods ){
  16861. rc = pId->pMethods->xClose(pId);
  16862. pId->pMethods = 0;
  16863. }
  16864. return rc;
  16865. }
  16866. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  16867. DO_OS_MALLOC_TEST(id);
  16868. return id->pMethods->xRead(id, pBuf, amt, offset);
  16869. }
  16870. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  16871. DO_OS_MALLOC_TEST(id);
  16872. return id->pMethods->xWrite(id, pBuf, amt, offset);
  16873. }
  16874. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  16875. return id->pMethods->xTruncate(id, size);
  16876. }
  16877. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  16878. DO_OS_MALLOC_TEST(id);
  16879. return id->pMethods->xSync(id, flags);
  16880. }
  16881. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  16882. DO_OS_MALLOC_TEST(id);
  16883. return id->pMethods->xFileSize(id, pSize);
  16884. }
  16885. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  16886. DO_OS_MALLOC_TEST(id);
  16887. return id->pMethods->xLock(id, lockType);
  16888. }
  16889. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  16890. return id->pMethods->xUnlock(id, lockType);
  16891. }
  16892. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  16893. DO_OS_MALLOC_TEST(id);
  16894. return id->pMethods->xCheckReservedLock(id, pResOut);
  16895. }
  16896. /*
  16897. ** Use sqlite3OsFileControl() when we are doing something that might fail
  16898. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  16899. ** when simply tossing information over the wall to the VFS and we do not
  16900. ** really care if the VFS receives and understands the information since it
  16901. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  16902. ** routine has no return value since the return value would be meaningless.
  16903. */
  16904. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  16905. #ifdef SQLITE_TEST
  16906. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  16907. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  16908. ** is using a regular VFS, it is called after the corresponding
  16909. ** transaction has been committed. Injecting a fault at this point
  16910. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  16911. ** but the transaction is committed anyway.
  16912. **
  16913. ** The core must call OsFileControl() though, not OsFileControlHint(),
  16914. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  16915. ** means the commit really has failed and an error should be returned
  16916. ** to the user. */
  16917. DO_OS_MALLOC_TEST(id);
  16918. }
  16919. #endif
  16920. return id->pMethods->xFileControl(id, op, pArg);
  16921. }
  16922. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  16923. (void)id->pMethods->xFileControl(id, op, pArg);
  16924. }
  16925. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  16926. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  16927. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  16928. }
  16929. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  16930. return id->pMethods->xDeviceCharacteristics(id);
  16931. }
  16932. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  16933. return id->pMethods->xShmLock(id, offset, n, flags);
  16934. }
  16935. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  16936. id->pMethods->xShmBarrier(id);
  16937. }
  16938. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  16939. return id->pMethods->xShmUnmap(id, deleteFlag);
  16940. }
  16941. SQLITE_PRIVATE int sqlite3OsShmMap(
  16942. sqlite3_file *id, /* Database file handle */
  16943. int iPage,
  16944. int pgsz,
  16945. int bExtend, /* True to extend file if necessary */
  16946. void volatile **pp /* OUT: Pointer to mapping */
  16947. ){
  16948. DO_OS_MALLOC_TEST(id);
  16949. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  16950. }
  16951. #if SQLITE_MAX_MMAP_SIZE>0
  16952. /* The real implementation of xFetch and xUnfetch */
  16953. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  16954. DO_OS_MALLOC_TEST(id);
  16955. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  16956. }
  16957. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  16958. return id->pMethods->xUnfetch(id, iOff, p);
  16959. }
  16960. #else
  16961. /* No-op stubs to use when memory-mapped I/O is disabled */
  16962. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  16963. *pp = 0;
  16964. return SQLITE_OK;
  16965. }
  16966. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  16967. return SQLITE_OK;
  16968. }
  16969. #endif
  16970. /*
  16971. ** The next group of routines are convenience wrappers around the
  16972. ** VFS methods.
  16973. */
  16974. SQLITE_PRIVATE int sqlite3OsOpen(
  16975. sqlite3_vfs *pVfs,
  16976. const char *zPath,
  16977. sqlite3_file *pFile,
  16978. int flags,
  16979. int *pFlagsOut
  16980. ){
  16981. int rc;
  16982. DO_OS_MALLOC_TEST(0);
  16983. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  16984. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  16985. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  16986. ** reaching the VFS. */
  16987. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  16988. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  16989. return rc;
  16990. }
  16991. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  16992. DO_OS_MALLOC_TEST(0);
  16993. assert( dirSync==0 || dirSync==1 );
  16994. return pVfs->xDelete(pVfs, zPath, dirSync);
  16995. }
  16996. SQLITE_PRIVATE int sqlite3OsAccess(
  16997. sqlite3_vfs *pVfs,
  16998. const char *zPath,
  16999. int flags,
  17000. int *pResOut
  17001. ){
  17002. DO_OS_MALLOC_TEST(0);
  17003. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  17004. }
  17005. SQLITE_PRIVATE int sqlite3OsFullPathname(
  17006. sqlite3_vfs *pVfs,
  17007. const char *zPath,
  17008. int nPathOut,
  17009. char *zPathOut
  17010. ){
  17011. DO_OS_MALLOC_TEST(0);
  17012. zPathOut[0] = 0;
  17013. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  17014. }
  17015. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  17016. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  17017. return pVfs->xDlOpen(pVfs, zPath);
  17018. }
  17019. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  17020. pVfs->xDlError(pVfs, nByte, zBufOut);
  17021. }
  17022. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  17023. return pVfs->xDlSym(pVfs, pHdle, zSym);
  17024. }
  17025. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  17026. pVfs->xDlClose(pVfs, pHandle);
  17027. }
  17028. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  17029. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  17030. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  17031. }
  17032. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  17033. return pVfs->xSleep(pVfs, nMicro);
  17034. }
  17035. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  17036. int rc;
  17037. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  17038. ** method to get the current date and time if that method is available
  17039. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  17040. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  17041. ** unavailable.
  17042. */
  17043. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  17044. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  17045. }else{
  17046. double r;
  17047. rc = pVfs->xCurrentTime(pVfs, &r);
  17048. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  17049. }
  17050. return rc;
  17051. }
  17052. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  17053. sqlite3_vfs *pVfs,
  17054. const char *zFile,
  17055. sqlite3_file **ppFile,
  17056. int flags,
  17057. int *pOutFlags
  17058. ){
  17059. int rc = SQLITE_NOMEM;
  17060. sqlite3_file *pFile;
  17061. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  17062. if( pFile ){
  17063. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  17064. if( rc!=SQLITE_OK ){
  17065. sqlite3_free(pFile);
  17066. }else{
  17067. *ppFile = pFile;
  17068. }
  17069. }
  17070. return rc;
  17071. }
  17072. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  17073. int rc = SQLITE_OK;
  17074. assert( pFile );
  17075. rc = sqlite3OsClose(pFile);
  17076. sqlite3_free(pFile);
  17077. return rc;
  17078. }
  17079. /*
  17080. ** This function is a wrapper around the OS specific implementation of
  17081. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  17082. ** ability to simulate a malloc failure, so that the handling of an
  17083. ** error in sqlite3_os_init() by the upper layers can be tested.
  17084. */
  17085. SQLITE_PRIVATE int sqlite3OsInit(void){
  17086. void *p = sqlite3_malloc(10);
  17087. if( p==0 ) return SQLITE_NOMEM;
  17088. sqlite3_free(p);
  17089. return sqlite3_os_init();
  17090. }
  17091. /*
  17092. ** The list of all registered VFS implementations.
  17093. */
  17094. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  17095. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  17096. /*
  17097. ** Locate a VFS by name. If no name is given, simply return the
  17098. ** first VFS on the list.
  17099. */
  17100. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
  17101. sqlite3_vfs *pVfs = 0;
  17102. #if SQLITE_THREADSAFE
  17103. sqlite3_mutex *mutex;
  17104. #endif
  17105. #ifndef SQLITE_OMIT_AUTOINIT
  17106. int rc = sqlite3_initialize();
  17107. if( rc ) return 0;
  17108. #endif
  17109. #if SQLITE_THREADSAFE
  17110. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  17111. #endif
  17112. sqlite3_mutex_enter(mutex);
  17113. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  17114. if( zVfs==0 ) break;
  17115. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  17116. }
  17117. sqlite3_mutex_leave(mutex);
  17118. return pVfs;
  17119. }
  17120. /*
  17121. ** Unlink a VFS from the linked list
  17122. */
  17123. static void vfsUnlink(sqlite3_vfs *pVfs){
  17124. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  17125. if( pVfs==0 ){
  17126. /* No-op */
  17127. }else if( vfsList==pVfs ){
  17128. vfsList = pVfs->pNext;
  17129. }else if( vfsList ){
  17130. sqlite3_vfs *p = vfsList;
  17131. while( p->pNext && p->pNext!=pVfs ){
  17132. p = p->pNext;
  17133. }
  17134. if( p->pNext==pVfs ){
  17135. p->pNext = pVfs->pNext;
  17136. }
  17137. }
  17138. }
  17139. /*
  17140. ** Register a VFS with the system. It is harmless to register the same
  17141. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  17142. ** true.
  17143. */
  17144. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  17145. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  17146. #ifndef SQLITE_OMIT_AUTOINIT
  17147. int rc = sqlite3_initialize();
  17148. if( rc ) return rc;
  17149. #endif
  17150. #ifdef SQLITE_ENABLE_API_ARMOR
  17151. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  17152. #endif
  17153. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  17154. sqlite3_mutex_enter(mutex);
  17155. vfsUnlink(pVfs);
  17156. if( makeDflt || vfsList==0 ){
  17157. pVfs->pNext = vfsList;
  17158. vfsList = pVfs;
  17159. }else{
  17160. pVfs->pNext = vfsList->pNext;
  17161. vfsList->pNext = pVfs;
  17162. }
  17163. assert(vfsList);
  17164. sqlite3_mutex_leave(mutex);
  17165. return SQLITE_OK;
  17166. }
  17167. /*
  17168. ** Unregister a VFS so that it is no longer accessible.
  17169. */
  17170. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  17171. #if SQLITE_THREADSAFE
  17172. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  17173. #endif
  17174. sqlite3_mutex_enter(mutex);
  17175. vfsUnlink(pVfs);
  17176. sqlite3_mutex_leave(mutex);
  17177. return SQLITE_OK;
  17178. }
  17179. /************** End of os.c **************************************************/
  17180. /************** Begin file fault.c *******************************************/
  17181. /*
  17182. ** 2008 Jan 22
  17183. **
  17184. ** The author disclaims copyright to this source code. In place of
  17185. ** a legal notice, here is a blessing:
  17186. **
  17187. ** May you do good and not evil.
  17188. ** May you find forgiveness for yourself and forgive others.
  17189. ** May you share freely, never taking more than you give.
  17190. **
  17191. *************************************************************************
  17192. **
  17193. ** This file contains code to support the concept of "benign"
  17194. ** malloc failures (when the xMalloc() or xRealloc() method of the
  17195. ** sqlite3_mem_methods structure fails to allocate a block of memory
  17196. ** and returns 0).
  17197. **
  17198. ** Most malloc failures are non-benign. After they occur, SQLite
  17199. ** abandons the current operation and returns an error code (usually
  17200. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  17201. ** fatal. For example, if a malloc fails while resizing a hash table, this
  17202. ** is completely recoverable simply by not carrying out the resize. The
  17203. ** hash table will continue to function normally. So a malloc failure
  17204. ** during a hash table resize is a benign fault.
  17205. */
  17206. /* #include "sqliteInt.h" */
  17207. #ifndef SQLITE_OMIT_BUILTIN_TEST
  17208. /*
  17209. ** Global variables.
  17210. */
  17211. typedef struct BenignMallocHooks BenignMallocHooks;
  17212. static SQLITE_WSD struct BenignMallocHooks {
  17213. void (*xBenignBegin)(void);
  17214. void (*xBenignEnd)(void);
  17215. } sqlite3Hooks = { 0, 0 };
  17216. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  17217. ** structure. If writable static data is unsupported on the target,
  17218. ** we have to locate the state vector at run-time. In the more common
  17219. ** case where writable static data is supported, wsdHooks can refer directly
  17220. ** to the "sqlite3Hooks" state vector declared above.
  17221. */
  17222. #ifdef SQLITE_OMIT_WSD
  17223. # define wsdHooksInit \
  17224. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  17225. # define wsdHooks x[0]
  17226. #else
  17227. # define wsdHooksInit
  17228. # define wsdHooks sqlite3Hooks
  17229. #endif
  17230. /*
  17231. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  17232. ** sqlite3EndBenignMalloc() are called, respectively.
  17233. */
  17234. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  17235. void (*xBenignBegin)(void),
  17236. void (*xBenignEnd)(void)
  17237. ){
  17238. wsdHooksInit;
  17239. wsdHooks.xBenignBegin = xBenignBegin;
  17240. wsdHooks.xBenignEnd = xBenignEnd;
  17241. }
  17242. /*
  17243. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  17244. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  17245. ** indicates that subsequent malloc failures are non-benign.
  17246. */
  17247. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  17248. wsdHooksInit;
  17249. if( wsdHooks.xBenignBegin ){
  17250. wsdHooks.xBenignBegin();
  17251. }
  17252. }
  17253. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  17254. wsdHooksInit;
  17255. if( wsdHooks.xBenignEnd ){
  17256. wsdHooks.xBenignEnd();
  17257. }
  17258. }
  17259. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  17260. /************** End of fault.c ***********************************************/
  17261. /************** Begin file mem0.c ********************************************/
  17262. /*
  17263. ** 2008 October 28
  17264. **
  17265. ** The author disclaims copyright to this source code. In place of
  17266. ** a legal notice, here is a blessing:
  17267. **
  17268. ** May you do good and not evil.
  17269. ** May you find forgiveness for yourself and forgive others.
  17270. ** May you share freely, never taking more than you give.
  17271. **
  17272. *************************************************************************
  17273. **
  17274. ** This file contains a no-op memory allocation drivers for use when
  17275. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  17276. ** here always fail. SQLite will not operate with these drivers. These
  17277. ** are merely placeholders. Real drivers must be substituted using
  17278. ** sqlite3_config() before SQLite will operate.
  17279. */
  17280. /* #include "sqliteInt.h" */
  17281. /*
  17282. ** This version of the memory allocator is the default. It is
  17283. ** used when no other memory allocator is specified using compile-time
  17284. ** macros.
  17285. */
  17286. #ifdef SQLITE_ZERO_MALLOC
  17287. /*
  17288. ** No-op versions of all memory allocation routines
  17289. */
  17290. static void *sqlite3MemMalloc(int nByte){ return 0; }
  17291. static void sqlite3MemFree(void *pPrior){ return; }
  17292. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  17293. static int sqlite3MemSize(void *pPrior){ return 0; }
  17294. static int sqlite3MemRoundup(int n){ return n; }
  17295. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  17296. static void sqlite3MemShutdown(void *NotUsed){ return; }
  17297. /*
  17298. ** This routine is the only routine in this file with external linkage.
  17299. **
  17300. ** Populate the low-level memory allocation function pointers in
  17301. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  17302. */
  17303. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  17304. static const sqlite3_mem_methods defaultMethods = {
  17305. sqlite3MemMalloc,
  17306. sqlite3MemFree,
  17307. sqlite3MemRealloc,
  17308. sqlite3MemSize,
  17309. sqlite3MemRoundup,
  17310. sqlite3MemInit,
  17311. sqlite3MemShutdown,
  17312. 0
  17313. };
  17314. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  17315. }
  17316. #endif /* SQLITE_ZERO_MALLOC */
  17317. /************** End of mem0.c ************************************************/
  17318. /************** Begin file mem1.c ********************************************/
  17319. /*
  17320. ** 2007 August 14
  17321. **
  17322. ** The author disclaims copyright to this source code. In place of
  17323. ** a legal notice, here is a blessing:
  17324. **
  17325. ** May you do good and not evil.
  17326. ** May you find forgiveness for yourself and forgive others.
  17327. ** May you share freely, never taking more than you give.
  17328. **
  17329. *************************************************************************
  17330. **
  17331. ** This file contains low-level memory allocation drivers for when
  17332. ** SQLite will use the standard C-library malloc/realloc/free interface
  17333. ** to obtain the memory it needs.
  17334. **
  17335. ** This file contains implementations of the low-level memory allocation
  17336. ** routines specified in the sqlite3_mem_methods object. The content of
  17337. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  17338. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  17339. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  17340. ** default configuration is to use memory allocation routines in this
  17341. ** file.
  17342. **
  17343. ** C-preprocessor macro summary:
  17344. **
  17345. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  17346. ** the malloc_usable_size() interface exists
  17347. ** on the target platform. Or, this symbol
  17348. ** can be set manually, if desired.
  17349. ** If an equivalent interface exists by
  17350. ** a different name, using a separate -D
  17351. ** option to rename it.
  17352. **
  17353. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  17354. ** memory allocator. Set this symbol to enable
  17355. ** building on older macs.
  17356. **
  17357. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  17358. ** _msize() on windows systems. This might
  17359. ** be necessary when compiling for Delphi,
  17360. ** for example.
  17361. */
  17362. /* #include "sqliteInt.h" */
  17363. /*
  17364. ** This version of the memory allocator is the default. It is
  17365. ** used when no other memory allocator is specified using compile-time
  17366. ** macros.
  17367. */
  17368. #ifdef SQLITE_SYSTEM_MALLOC
  17369. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  17370. /*
  17371. ** Use the zone allocator available on apple products unless the
  17372. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  17373. */
  17374. #include <sys/sysctl.h>
  17375. #include <malloc/malloc.h>
  17376. #include <libkern/OSAtomic.h>
  17377. static malloc_zone_t* _sqliteZone_;
  17378. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  17379. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  17380. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  17381. #define SQLITE_MALLOCSIZE(x) \
  17382. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  17383. #else /* if not __APPLE__ */
  17384. /*
  17385. ** Use standard C library malloc and free on non-Apple systems.
  17386. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  17387. */
  17388. #define SQLITE_MALLOC(x) malloc(x)
  17389. #define SQLITE_FREE(x) free(x)
  17390. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  17391. /*
  17392. ** The malloc.h header file is needed for malloc_usable_size() function
  17393. ** on some systems (e.g. Linux).
  17394. */
  17395. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  17396. # define SQLITE_USE_MALLOC_H 1
  17397. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  17398. /*
  17399. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  17400. ** use of _msize() is automatic, but can be disabled by compiling with
  17401. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  17402. ** the malloc.h header file.
  17403. */
  17404. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  17405. # define SQLITE_USE_MALLOC_H
  17406. # define SQLITE_USE_MSIZE
  17407. #endif
  17408. /*
  17409. ** Include the malloc.h header file, if necessary. Also set define macro
  17410. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  17411. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  17412. ** The memory size function can always be overridden manually by defining
  17413. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  17414. */
  17415. #if defined(SQLITE_USE_MALLOC_H)
  17416. # include <malloc.h>
  17417. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  17418. # if !defined(SQLITE_MALLOCSIZE)
  17419. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  17420. # endif
  17421. # elif defined(SQLITE_USE_MSIZE)
  17422. # if !defined(SQLITE_MALLOCSIZE)
  17423. # define SQLITE_MALLOCSIZE _msize
  17424. # endif
  17425. # endif
  17426. #endif /* defined(SQLITE_USE_MALLOC_H) */
  17427. #endif /* __APPLE__ or not __APPLE__ */
  17428. /*
  17429. ** Like malloc(), but remember the size of the allocation
  17430. ** so that we can find it later using sqlite3MemSize().
  17431. **
  17432. ** For this low-level routine, we are guaranteed that nByte>0 because
  17433. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  17434. ** routines.
  17435. */
  17436. static void *sqlite3MemMalloc(int nByte){
  17437. #ifdef SQLITE_MALLOCSIZE
  17438. void *p = SQLITE_MALLOC( nByte );
  17439. if( p==0 ){
  17440. testcase( sqlite3GlobalConfig.xLog!=0 );
  17441. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  17442. }
  17443. return p;
  17444. #else
  17445. sqlite3_int64 *p;
  17446. assert( nByte>0 );
  17447. nByte = ROUND8(nByte);
  17448. p = SQLITE_MALLOC( nByte+8 );
  17449. if( p ){
  17450. p[0] = nByte;
  17451. p++;
  17452. }else{
  17453. testcase( sqlite3GlobalConfig.xLog!=0 );
  17454. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  17455. }
  17456. return (void *)p;
  17457. #endif
  17458. }
  17459. /*
  17460. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  17461. ** or sqlite3MemRealloc().
  17462. **
  17463. ** For this low-level routine, we already know that pPrior!=0 since
  17464. ** cases where pPrior==0 will have been intecepted and dealt with
  17465. ** by higher-level routines.
  17466. */
  17467. static void sqlite3MemFree(void *pPrior){
  17468. #ifdef SQLITE_MALLOCSIZE
  17469. SQLITE_FREE(pPrior);
  17470. #else
  17471. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  17472. assert( pPrior!=0 );
  17473. p--;
  17474. SQLITE_FREE(p);
  17475. #endif
  17476. }
  17477. /*
  17478. ** Report the allocated size of a prior return from xMalloc()
  17479. ** or xRealloc().
  17480. */
  17481. static int sqlite3MemSize(void *pPrior){
  17482. #ifdef SQLITE_MALLOCSIZE
  17483. assert( pPrior!=0 );
  17484. return (int)SQLITE_MALLOCSIZE(pPrior);
  17485. #else
  17486. sqlite3_int64 *p;
  17487. assert( pPrior!=0 );
  17488. p = (sqlite3_int64*)pPrior;
  17489. p--;
  17490. return (int)p[0];
  17491. #endif
  17492. }
  17493. /*
  17494. ** Like realloc(). Resize an allocation previously obtained from
  17495. ** sqlite3MemMalloc().
  17496. **
  17497. ** For this low-level interface, we know that pPrior!=0. Cases where
  17498. ** pPrior==0 while have been intercepted by higher-level routine and
  17499. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  17500. ** cases where nByte<=0 will have been intercepted by higher-level
  17501. ** routines and redirected to xFree.
  17502. */
  17503. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  17504. #ifdef SQLITE_MALLOCSIZE
  17505. void *p = SQLITE_REALLOC(pPrior, nByte);
  17506. if( p==0 ){
  17507. testcase( sqlite3GlobalConfig.xLog!=0 );
  17508. sqlite3_log(SQLITE_NOMEM,
  17509. "failed memory resize %u to %u bytes",
  17510. SQLITE_MALLOCSIZE(pPrior), nByte);
  17511. }
  17512. return p;
  17513. #else
  17514. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  17515. assert( pPrior!=0 && nByte>0 );
  17516. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  17517. p--;
  17518. p = SQLITE_REALLOC(p, nByte+8 );
  17519. if( p ){
  17520. p[0] = nByte;
  17521. p++;
  17522. }else{
  17523. testcase( sqlite3GlobalConfig.xLog!=0 );
  17524. sqlite3_log(SQLITE_NOMEM,
  17525. "failed memory resize %u to %u bytes",
  17526. sqlite3MemSize(pPrior), nByte);
  17527. }
  17528. return (void*)p;
  17529. #endif
  17530. }
  17531. /*
  17532. ** Round up a request size to the next valid allocation size.
  17533. */
  17534. static int sqlite3MemRoundup(int n){
  17535. return ROUND8(n);
  17536. }
  17537. /*
  17538. ** Initialize this module.
  17539. */
  17540. static int sqlite3MemInit(void *NotUsed){
  17541. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  17542. int cpuCount;
  17543. size_t len;
  17544. if( _sqliteZone_ ){
  17545. return SQLITE_OK;
  17546. }
  17547. len = sizeof(cpuCount);
  17548. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  17549. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  17550. if( cpuCount>1 ){
  17551. /* defer MT decisions to system malloc */
  17552. _sqliteZone_ = malloc_default_zone();
  17553. }else{
  17554. /* only 1 core, use our own zone to contention over global locks,
  17555. ** e.g. we have our own dedicated locks */
  17556. bool success;
  17557. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  17558. malloc_set_zone_name(newzone, "Sqlite_Heap");
  17559. do{
  17560. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  17561. (void * volatile *)&_sqliteZone_);
  17562. }while(!_sqliteZone_);
  17563. if( !success ){
  17564. /* somebody registered a zone first */
  17565. malloc_destroy_zone(newzone);
  17566. }
  17567. }
  17568. #endif
  17569. UNUSED_PARAMETER(NotUsed);
  17570. return SQLITE_OK;
  17571. }
  17572. /*
  17573. ** Deinitialize this module.
  17574. */
  17575. static void sqlite3MemShutdown(void *NotUsed){
  17576. UNUSED_PARAMETER(NotUsed);
  17577. return;
  17578. }
  17579. /*
  17580. ** This routine is the only routine in this file with external linkage.
  17581. **
  17582. ** Populate the low-level memory allocation function pointers in
  17583. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  17584. */
  17585. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  17586. static const sqlite3_mem_methods defaultMethods = {
  17587. sqlite3MemMalloc,
  17588. sqlite3MemFree,
  17589. sqlite3MemRealloc,
  17590. sqlite3MemSize,
  17591. sqlite3MemRoundup,
  17592. sqlite3MemInit,
  17593. sqlite3MemShutdown,
  17594. 0
  17595. };
  17596. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  17597. }
  17598. #endif /* SQLITE_SYSTEM_MALLOC */
  17599. /************** End of mem1.c ************************************************/
  17600. /************** Begin file mem2.c ********************************************/
  17601. /*
  17602. ** 2007 August 15
  17603. **
  17604. ** The author disclaims copyright to this source code. In place of
  17605. ** a legal notice, here is a blessing:
  17606. **
  17607. ** May you do good and not evil.
  17608. ** May you find forgiveness for yourself and forgive others.
  17609. ** May you share freely, never taking more than you give.
  17610. **
  17611. *************************************************************************
  17612. **
  17613. ** This file contains low-level memory allocation drivers for when
  17614. ** SQLite will use the standard C-library malloc/realloc/free interface
  17615. ** to obtain the memory it needs while adding lots of additional debugging
  17616. ** information to each allocation in order to help detect and fix memory
  17617. ** leaks and memory usage errors.
  17618. **
  17619. ** This file contains implementations of the low-level memory allocation
  17620. ** routines specified in the sqlite3_mem_methods object.
  17621. */
  17622. /* #include "sqliteInt.h" */
  17623. /*
  17624. ** This version of the memory allocator is used only if the
  17625. ** SQLITE_MEMDEBUG macro is defined
  17626. */
  17627. #ifdef SQLITE_MEMDEBUG
  17628. /*
  17629. ** The backtrace functionality is only available with GLIBC
  17630. */
  17631. #ifdef __GLIBC__
  17632. extern int backtrace(void**,int);
  17633. extern void backtrace_symbols_fd(void*const*,int,int);
  17634. #else
  17635. # define backtrace(A,B) 1
  17636. # define backtrace_symbols_fd(A,B,C)
  17637. #endif
  17638. /* #include <stdio.h> */
  17639. /*
  17640. ** Each memory allocation looks like this:
  17641. **
  17642. ** ------------------------------------------------------------------------
  17643. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  17644. ** ------------------------------------------------------------------------
  17645. **
  17646. ** The application code sees only a pointer to the allocation. We have
  17647. ** to back up from the allocation pointer to find the MemBlockHdr. The
  17648. ** MemBlockHdr tells us the size of the allocation and the number of
  17649. ** backtrace pointers. There is also a guard word at the end of the
  17650. ** MemBlockHdr.
  17651. */
  17652. struct MemBlockHdr {
  17653. i64 iSize; /* Size of this allocation */
  17654. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  17655. char nBacktrace; /* Number of backtraces on this alloc */
  17656. char nBacktraceSlots; /* Available backtrace slots */
  17657. u8 nTitle; /* Bytes of title; includes '\0' */
  17658. u8 eType; /* Allocation type code */
  17659. int iForeGuard; /* Guard word for sanity */
  17660. };
  17661. /*
  17662. ** Guard words
  17663. */
  17664. #define FOREGUARD 0x80F5E153
  17665. #define REARGUARD 0xE4676B53
  17666. /*
  17667. ** Number of malloc size increments to track.
  17668. */
  17669. #define NCSIZE 1000
  17670. /*
  17671. ** All of the static variables used by this module are collected
  17672. ** into a single structure named "mem". This is to keep the
  17673. ** static variables organized and to reduce namespace pollution
  17674. ** when this module is combined with other in the amalgamation.
  17675. */
  17676. static struct {
  17677. /*
  17678. ** Mutex to control access to the memory allocation subsystem.
  17679. */
  17680. sqlite3_mutex *mutex;
  17681. /*
  17682. ** Head and tail of a linked list of all outstanding allocations
  17683. */
  17684. struct MemBlockHdr *pFirst;
  17685. struct MemBlockHdr *pLast;
  17686. /*
  17687. ** The number of levels of backtrace to save in new allocations.
  17688. */
  17689. int nBacktrace;
  17690. void (*xBacktrace)(int, int, void **);
  17691. /*
  17692. ** Title text to insert in front of each block
  17693. */
  17694. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  17695. char zTitle[100]; /* The title text */
  17696. /*
  17697. ** sqlite3MallocDisallow() increments the following counter.
  17698. ** sqlite3MallocAllow() decrements it.
  17699. */
  17700. int disallow; /* Do not allow memory allocation */
  17701. /*
  17702. ** Gather statistics on the sizes of memory allocations.
  17703. ** nAlloc[i] is the number of allocation attempts of i*8
  17704. ** bytes. i==NCSIZE is the number of allocation attempts for
  17705. ** sizes more than NCSIZE*8 bytes.
  17706. */
  17707. int nAlloc[NCSIZE]; /* Total number of allocations */
  17708. int nCurrent[NCSIZE]; /* Current number of allocations */
  17709. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  17710. } mem;
  17711. /*
  17712. ** Adjust memory usage statistics
  17713. */
  17714. static void adjustStats(int iSize, int increment){
  17715. int i = ROUND8(iSize)/8;
  17716. if( i>NCSIZE-1 ){
  17717. i = NCSIZE - 1;
  17718. }
  17719. if( increment>0 ){
  17720. mem.nAlloc[i]++;
  17721. mem.nCurrent[i]++;
  17722. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  17723. mem.mxCurrent[i] = mem.nCurrent[i];
  17724. }
  17725. }else{
  17726. mem.nCurrent[i]--;
  17727. assert( mem.nCurrent[i]>=0 );
  17728. }
  17729. }
  17730. /*
  17731. ** Given an allocation, find the MemBlockHdr for that allocation.
  17732. **
  17733. ** This routine checks the guards at either end of the allocation and
  17734. ** if they are incorrect it asserts.
  17735. */
  17736. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  17737. struct MemBlockHdr *p;
  17738. int *pInt;
  17739. u8 *pU8;
  17740. int nReserve;
  17741. p = (struct MemBlockHdr*)pAllocation;
  17742. p--;
  17743. assert( p->iForeGuard==(int)FOREGUARD );
  17744. nReserve = ROUND8(p->iSize);
  17745. pInt = (int*)pAllocation;
  17746. pU8 = (u8*)pAllocation;
  17747. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  17748. /* This checks any of the "extra" bytes allocated due
  17749. ** to rounding up to an 8 byte boundary to ensure
  17750. ** they haven't been overwritten.
  17751. */
  17752. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  17753. return p;
  17754. }
  17755. /*
  17756. ** Return the number of bytes currently allocated at address p.
  17757. */
  17758. static int sqlite3MemSize(void *p){
  17759. struct MemBlockHdr *pHdr;
  17760. if( !p ){
  17761. return 0;
  17762. }
  17763. pHdr = sqlite3MemsysGetHeader(p);
  17764. return (int)pHdr->iSize;
  17765. }
  17766. /*
  17767. ** Initialize the memory allocation subsystem.
  17768. */
  17769. static int sqlite3MemInit(void *NotUsed){
  17770. UNUSED_PARAMETER(NotUsed);
  17771. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  17772. if( !sqlite3GlobalConfig.bMemstat ){
  17773. /* If memory status is enabled, then the malloc.c wrapper will already
  17774. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  17775. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17776. }
  17777. return SQLITE_OK;
  17778. }
  17779. /*
  17780. ** Deinitialize the memory allocation subsystem.
  17781. */
  17782. static void sqlite3MemShutdown(void *NotUsed){
  17783. UNUSED_PARAMETER(NotUsed);
  17784. mem.mutex = 0;
  17785. }
  17786. /*
  17787. ** Round up a request size to the next valid allocation size.
  17788. */
  17789. static int sqlite3MemRoundup(int n){
  17790. return ROUND8(n);
  17791. }
  17792. /*
  17793. ** Fill a buffer with pseudo-random bytes. This is used to preset
  17794. ** the content of a new memory allocation to unpredictable values and
  17795. ** to clear the content of a freed allocation to unpredictable values.
  17796. */
  17797. static void randomFill(char *pBuf, int nByte){
  17798. unsigned int x, y, r;
  17799. x = SQLITE_PTR_TO_INT(pBuf);
  17800. y = nByte | 1;
  17801. while( nByte >= 4 ){
  17802. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  17803. y = y*1103515245 + 12345;
  17804. r = x ^ y;
  17805. *(int*)pBuf = r;
  17806. pBuf += 4;
  17807. nByte -= 4;
  17808. }
  17809. while( nByte-- > 0 ){
  17810. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  17811. y = y*1103515245 + 12345;
  17812. r = x ^ y;
  17813. *(pBuf++) = r & 0xff;
  17814. }
  17815. }
  17816. /*
  17817. ** Allocate nByte bytes of memory.
  17818. */
  17819. static void *sqlite3MemMalloc(int nByte){
  17820. struct MemBlockHdr *pHdr;
  17821. void **pBt;
  17822. char *z;
  17823. int *pInt;
  17824. void *p = 0;
  17825. int totalSize;
  17826. int nReserve;
  17827. sqlite3_mutex_enter(mem.mutex);
  17828. assert( mem.disallow==0 );
  17829. nReserve = ROUND8(nByte);
  17830. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  17831. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  17832. p = malloc(totalSize);
  17833. if( p ){
  17834. z = p;
  17835. pBt = (void**)&z[mem.nTitle];
  17836. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  17837. pHdr->pNext = 0;
  17838. pHdr->pPrev = mem.pLast;
  17839. if( mem.pLast ){
  17840. mem.pLast->pNext = pHdr;
  17841. }else{
  17842. mem.pFirst = pHdr;
  17843. }
  17844. mem.pLast = pHdr;
  17845. pHdr->iForeGuard = FOREGUARD;
  17846. pHdr->eType = MEMTYPE_HEAP;
  17847. pHdr->nBacktraceSlots = mem.nBacktrace;
  17848. pHdr->nTitle = mem.nTitle;
  17849. if( mem.nBacktrace ){
  17850. void *aAddr[40];
  17851. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  17852. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  17853. assert(pBt[0]);
  17854. if( mem.xBacktrace ){
  17855. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  17856. }
  17857. }else{
  17858. pHdr->nBacktrace = 0;
  17859. }
  17860. if( mem.nTitle ){
  17861. memcpy(z, mem.zTitle, mem.nTitle);
  17862. }
  17863. pHdr->iSize = nByte;
  17864. adjustStats(nByte, +1);
  17865. pInt = (int*)&pHdr[1];
  17866. pInt[nReserve/sizeof(int)] = REARGUARD;
  17867. randomFill((char*)pInt, nByte);
  17868. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  17869. p = (void*)pInt;
  17870. }
  17871. sqlite3_mutex_leave(mem.mutex);
  17872. return p;
  17873. }
  17874. /*
  17875. ** Free memory.
  17876. */
  17877. static void sqlite3MemFree(void *pPrior){
  17878. struct MemBlockHdr *pHdr;
  17879. void **pBt;
  17880. char *z;
  17881. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  17882. || mem.mutex!=0 );
  17883. pHdr = sqlite3MemsysGetHeader(pPrior);
  17884. pBt = (void**)pHdr;
  17885. pBt -= pHdr->nBacktraceSlots;
  17886. sqlite3_mutex_enter(mem.mutex);
  17887. if( pHdr->pPrev ){
  17888. assert( pHdr->pPrev->pNext==pHdr );
  17889. pHdr->pPrev->pNext = pHdr->pNext;
  17890. }else{
  17891. assert( mem.pFirst==pHdr );
  17892. mem.pFirst = pHdr->pNext;
  17893. }
  17894. if( pHdr->pNext ){
  17895. assert( pHdr->pNext->pPrev==pHdr );
  17896. pHdr->pNext->pPrev = pHdr->pPrev;
  17897. }else{
  17898. assert( mem.pLast==pHdr );
  17899. mem.pLast = pHdr->pPrev;
  17900. }
  17901. z = (char*)pBt;
  17902. z -= pHdr->nTitle;
  17903. adjustStats((int)pHdr->iSize, -1);
  17904. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  17905. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  17906. free(z);
  17907. sqlite3_mutex_leave(mem.mutex);
  17908. }
  17909. /*
  17910. ** Change the size of an existing memory allocation.
  17911. **
  17912. ** For this debugging implementation, we *always* make a copy of the
  17913. ** allocation into a new place in memory. In this way, if the
  17914. ** higher level code is using pointer to the old allocation, it is
  17915. ** much more likely to break and we are much more liking to find
  17916. ** the error.
  17917. */
  17918. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  17919. struct MemBlockHdr *pOldHdr;
  17920. void *pNew;
  17921. assert( mem.disallow==0 );
  17922. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  17923. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  17924. pNew = sqlite3MemMalloc(nByte);
  17925. if( pNew ){
  17926. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  17927. if( nByte>pOldHdr->iSize ){
  17928. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  17929. }
  17930. sqlite3MemFree(pPrior);
  17931. }
  17932. return pNew;
  17933. }
  17934. /*
  17935. ** Populate the low-level memory allocation function pointers in
  17936. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  17937. */
  17938. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  17939. static const sqlite3_mem_methods defaultMethods = {
  17940. sqlite3MemMalloc,
  17941. sqlite3MemFree,
  17942. sqlite3MemRealloc,
  17943. sqlite3MemSize,
  17944. sqlite3MemRoundup,
  17945. sqlite3MemInit,
  17946. sqlite3MemShutdown,
  17947. 0
  17948. };
  17949. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  17950. }
  17951. /*
  17952. ** Set the "type" of an allocation.
  17953. */
  17954. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  17955. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  17956. struct MemBlockHdr *pHdr;
  17957. pHdr = sqlite3MemsysGetHeader(p);
  17958. assert( pHdr->iForeGuard==FOREGUARD );
  17959. pHdr->eType = eType;
  17960. }
  17961. }
  17962. /*
  17963. ** Return TRUE if the mask of type in eType matches the type of the
  17964. ** allocation p. Also return true if p==NULL.
  17965. **
  17966. ** This routine is designed for use within an assert() statement, to
  17967. ** verify the type of an allocation. For example:
  17968. **
  17969. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  17970. */
  17971. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  17972. int rc = 1;
  17973. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  17974. struct MemBlockHdr *pHdr;
  17975. pHdr = sqlite3MemsysGetHeader(p);
  17976. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  17977. if( (pHdr->eType&eType)==0 ){
  17978. rc = 0;
  17979. }
  17980. }
  17981. return rc;
  17982. }
  17983. /*
  17984. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  17985. ** allocation p. Also return true if p==NULL.
  17986. **
  17987. ** This routine is designed for use within an assert() statement, to
  17988. ** verify the type of an allocation. For example:
  17989. **
  17990. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  17991. */
  17992. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  17993. int rc = 1;
  17994. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  17995. struct MemBlockHdr *pHdr;
  17996. pHdr = sqlite3MemsysGetHeader(p);
  17997. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  17998. if( (pHdr->eType&eType)!=0 ){
  17999. rc = 0;
  18000. }
  18001. }
  18002. return rc;
  18003. }
  18004. /*
  18005. ** Set the number of backtrace levels kept for each allocation.
  18006. ** A value of zero turns off backtracing. The number is always rounded
  18007. ** up to a multiple of 2.
  18008. */
  18009. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  18010. if( depth<0 ){ depth = 0; }
  18011. if( depth>20 ){ depth = 20; }
  18012. depth = (depth+1)&0xfe;
  18013. mem.nBacktrace = depth;
  18014. }
  18015. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  18016. mem.xBacktrace = xBacktrace;
  18017. }
  18018. /*
  18019. ** Set the title string for subsequent allocations.
  18020. */
  18021. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  18022. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  18023. sqlite3_mutex_enter(mem.mutex);
  18024. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  18025. memcpy(mem.zTitle, zTitle, n);
  18026. mem.zTitle[n] = 0;
  18027. mem.nTitle = ROUND8(n);
  18028. sqlite3_mutex_leave(mem.mutex);
  18029. }
  18030. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  18031. struct MemBlockHdr *pHdr;
  18032. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  18033. void **pBt = (void**)pHdr;
  18034. pBt -= pHdr->nBacktraceSlots;
  18035. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  18036. }
  18037. }
  18038. /*
  18039. ** Open the file indicated and write a log of all unfreed memory
  18040. ** allocations into that log.
  18041. */
  18042. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  18043. FILE *out;
  18044. struct MemBlockHdr *pHdr;
  18045. void **pBt;
  18046. int i;
  18047. out = fopen(zFilename, "w");
  18048. if( out==0 ){
  18049. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  18050. zFilename);
  18051. return;
  18052. }
  18053. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  18054. char *z = (char*)pHdr;
  18055. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  18056. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  18057. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  18058. if( pHdr->nBacktrace ){
  18059. fflush(out);
  18060. pBt = (void**)pHdr;
  18061. pBt -= pHdr->nBacktraceSlots;
  18062. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  18063. fprintf(out, "\n");
  18064. }
  18065. }
  18066. fprintf(out, "COUNTS:\n");
  18067. for(i=0; i<NCSIZE-1; i++){
  18068. if( mem.nAlloc[i] ){
  18069. fprintf(out, " %5d: %10d %10d %10d\n",
  18070. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  18071. }
  18072. }
  18073. if( mem.nAlloc[NCSIZE-1] ){
  18074. fprintf(out, " %5d: %10d %10d %10d\n",
  18075. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  18076. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  18077. }
  18078. fclose(out);
  18079. }
  18080. /*
  18081. ** Return the number of times sqlite3MemMalloc() has been called.
  18082. */
  18083. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  18084. int i;
  18085. int nTotal = 0;
  18086. for(i=0; i<NCSIZE; i++){
  18087. nTotal += mem.nAlloc[i];
  18088. }
  18089. return nTotal;
  18090. }
  18091. #endif /* SQLITE_MEMDEBUG */
  18092. /************** End of mem2.c ************************************************/
  18093. /************** Begin file mem3.c ********************************************/
  18094. /*
  18095. ** 2007 October 14
  18096. **
  18097. ** The author disclaims copyright to this source code. In place of
  18098. ** a legal notice, here is a blessing:
  18099. **
  18100. ** May you do good and not evil.
  18101. ** May you find forgiveness for yourself and forgive others.
  18102. ** May you share freely, never taking more than you give.
  18103. **
  18104. *************************************************************************
  18105. ** This file contains the C functions that implement a memory
  18106. ** allocation subsystem for use by SQLite.
  18107. **
  18108. ** This version of the memory allocation subsystem omits all
  18109. ** use of malloc(). The SQLite user supplies a block of memory
  18110. ** before calling sqlite3_initialize() from which allocations
  18111. ** are made and returned by the xMalloc() and xRealloc()
  18112. ** implementations. Once sqlite3_initialize() has been called,
  18113. ** the amount of memory available to SQLite is fixed and cannot
  18114. ** be changed.
  18115. **
  18116. ** This version of the memory allocation subsystem is included
  18117. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  18118. */
  18119. /* #include "sqliteInt.h" */
  18120. /*
  18121. ** This version of the memory allocator is only built into the library
  18122. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  18123. ** mean that the library will use a memory-pool by default, just that
  18124. ** it is available. The mempool allocator is activated by calling
  18125. ** sqlite3_config().
  18126. */
  18127. #ifdef SQLITE_ENABLE_MEMSYS3
  18128. /*
  18129. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  18130. */
  18131. #define MX_SMALL 10
  18132. /*
  18133. ** Number of freelist hash slots
  18134. */
  18135. #define N_HASH 61
  18136. /*
  18137. ** A memory allocation (also called a "chunk") consists of two or
  18138. ** more blocks where each block is 8 bytes. The first 8 bytes are
  18139. ** a header that is not returned to the user.
  18140. **
  18141. ** A chunk is two or more blocks that is either checked out or
  18142. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  18143. ** size of the allocation in blocks if the allocation is free.
  18144. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  18145. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  18146. ** is true if the previous chunk is checked out and false if the
  18147. ** previous chunk is free. The u.hdr.prevSize field is the size of
  18148. ** the previous chunk in blocks if the previous chunk is on the
  18149. ** freelist. If the previous chunk is checked out, then
  18150. ** u.hdr.prevSize can be part of the data for that chunk and should
  18151. ** not be read or written.
  18152. **
  18153. ** We often identify a chunk by its index in mem3.aPool[]. When
  18154. ** this is done, the chunk index refers to the second block of
  18155. ** the chunk. In this way, the first chunk has an index of 1.
  18156. ** A chunk index of 0 means "no such chunk" and is the equivalent
  18157. ** of a NULL pointer.
  18158. **
  18159. ** The second block of free chunks is of the form u.list. The
  18160. ** two fields form a double-linked list of chunks of related sizes.
  18161. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  18162. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  18163. **
  18164. ** The second block of a chunk is user data if the chunk is checked
  18165. ** out. If a chunk is checked out, the user data may extend into
  18166. ** the u.hdr.prevSize value of the following chunk.
  18167. */
  18168. typedef struct Mem3Block Mem3Block;
  18169. struct Mem3Block {
  18170. union {
  18171. struct {
  18172. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  18173. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  18174. } hdr;
  18175. struct {
  18176. u32 next; /* Index in mem3.aPool[] of next free chunk */
  18177. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  18178. } list;
  18179. } u;
  18180. };
  18181. /*
  18182. ** All of the static variables used by this module are collected
  18183. ** into a single structure named "mem3". This is to keep the
  18184. ** static variables organized and to reduce namespace pollution
  18185. ** when this module is combined with other in the amalgamation.
  18186. */
  18187. static SQLITE_WSD struct Mem3Global {
  18188. /*
  18189. ** Memory available for allocation. nPool is the size of the array
  18190. ** (in Mem3Blocks) pointed to by aPool less 2.
  18191. */
  18192. u32 nPool;
  18193. Mem3Block *aPool;
  18194. /*
  18195. ** True if we are evaluating an out-of-memory callback.
  18196. */
  18197. int alarmBusy;
  18198. /*
  18199. ** Mutex to control access to the memory allocation subsystem.
  18200. */
  18201. sqlite3_mutex *mutex;
  18202. /*
  18203. ** The minimum amount of free space that we have seen.
  18204. */
  18205. u32 mnMaster;
  18206. /*
  18207. ** iMaster is the index of the master chunk. Most new allocations
  18208. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  18209. ** of the current master. iMaster is 0 if there is not master chunk.
  18210. ** The master chunk is not in either the aiHash[] or aiSmall[].
  18211. */
  18212. u32 iMaster;
  18213. u32 szMaster;
  18214. /*
  18215. ** Array of lists of free blocks according to the block size
  18216. ** for smaller chunks, or a hash on the block size for larger
  18217. ** chunks.
  18218. */
  18219. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  18220. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  18221. } mem3 = { 97535575 };
  18222. #define mem3 GLOBAL(struct Mem3Global, mem3)
  18223. /*
  18224. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  18225. ** on. *pRoot is the list that i is a member of.
  18226. */
  18227. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  18228. u32 next = mem3.aPool[i].u.list.next;
  18229. u32 prev = mem3.aPool[i].u.list.prev;
  18230. assert( sqlite3_mutex_held(mem3.mutex) );
  18231. if( prev==0 ){
  18232. *pRoot = next;
  18233. }else{
  18234. mem3.aPool[prev].u.list.next = next;
  18235. }
  18236. if( next ){
  18237. mem3.aPool[next].u.list.prev = prev;
  18238. }
  18239. mem3.aPool[i].u.list.next = 0;
  18240. mem3.aPool[i].u.list.prev = 0;
  18241. }
  18242. /*
  18243. ** Unlink the chunk at index i from
  18244. ** whatever list is currently a member of.
  18245. */
  18246. static void memsys3Unlink(u32 i){
  18247. u32 size, hash;
  18248. assert( sqlite3_mutex_held(mem3.mutex) );
  18249. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  18250. assert( i>=1 );
  18251. size = mem3.aPool[i-1].u.hdr.size4x/4;
  18252. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  18253. assert( size>=2 );
  18254. if( size <= MX_SMALL ){
  18255. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  18256. }else{
  18257. hash = size % N_HASH;
  18258. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  18259. }
  18260. }
  18261. /*
  18262. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  18263. ** at *pRoot.
  18264. */
  18265. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  18266. assert( sqlite3_mutex_held(mem3.mutex) );
  18267. mem3.aPool[i].u.list.next = *pRoot;
  18268. mem3.aPool[i].u.list.prev = 0;
  18269. if( *pRoot ){
  18270. mem3.aPool[*pRoot].u.list.prev = i;
  18271. }
  18272. *pRoot = i;
  18273. }
  18274. /*
  18275. ** Link the chunk at index i into either the appropriate
  18276. ** small chunk list, or into the large chunk hash table.
  18277. */
  18278. static void memsys3Link(u32 i){
  18279. u32 size, hash;
  18280. assert( sqlite3_mutex_held(mem3.mutex) );
  18281. assert( i>=1 );
  18282. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  18283. size = mem3.aPool[i-1].u.hdr.size4x/4;
  18284. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  18285. assert( size>=2 );
  18286. if( size <= MX_SMALL ){
  18287. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  18288. }else{
  18289. hash = size % N_HASH;
  18290. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  18291. }
  18292. }
  18293. /*
  18294. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  18295. ** will already be held (obtained by code in malloc.c) if
  18296. ** sqlite3GlobalConfig.bMemStat is true.
  18297. */
  18298. static void memsys3Enter(void){
  18299. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  18300. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18301. }
  18302. sqlite3_mutex_enter(mem3.mutex);
  18303. }
  18304. static void memsys3Leave(void){
  18305. sqlite3_mutex_leave(mem3.mutex);
  18306. }
  18307. /*
  18308. ** Called when we are unable to satisfy an allocation of nBytes.
  18309. */
  18310. static void memsys3OutOfMemory(int nByte){
  18311. if( !mem3.alarmBusy ){
  18312. mem3.alarmBusy = 1;
  18313. assert( sqlite3_mutex_held(mem3.mutex) );
  18314. sqlite3_mutex_leave(mem3.mutex);
  18315. sqlite3_release_memory(nByte);
  18316. sqlite3_mutex_enter(mem3.mutex);
  18317. mem3.alarmBusy = 0;
  18318. }
  18319. }
  18320. /*
  18321. ** Chunk i is a free chunk that has been unlinked. Adjust its
  18322. ** size parameters for check-out and return a pointer to the
  18323. ** user portion of the chunk.
  18324. */
  18325. static void *memsys3Checkout(u32 i, u32 nBlock){
  18326. u32 x;
  18327. assert( sqlite3_mutex_held(mem3.mutex) );
  18328. assert( i>=1 );
  18329. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  18330. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  18331. x = mem3.aPool[i-1].u.hdr.size4x;
  18332. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  18333. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  18334. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  18335. return &mem3.aPool[i];
  18336. }
  18337. /*
  18338. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  18339. ** Return a pointer to the new allocation. Or, if the master chunk
  18340. ** is not large enough, return 0.
  18341. */
  18342. static void *memsys3FromMaster(u32 nBlock){
  18343. assert( sqlite3_mutex_held(mem3.mutex) );
  18344. assert( mem3.szMaster>=nBlock );
  18345. if( nBlock>=mem3.szMaster-1 ){
  18346. /* Use the entire master */
  18347. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  18348. mem3.iMaster = 0;
  18349. mem3.szMaster = 0;
  18350. mem3.mnMaster = 0;
  18351. return p;
  18352. }else{
  18353. /* Split the master block. Return the tail. */
  18354. u32 newi, x;
  18355. newi = mem3.iMaster + mem3.szMaster - nBlock;
  18356. assert( newi > mem3.iMaster+1 );
  18357. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  18358. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  18359. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  18360. mem3.szMaster -= nBlock;
  18361. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  18362. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18363. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18364. if( mem3.szMaster < mem3.mnMaster ){
  18365. mem3.mnMaster = mem3.szMaster;
  18366. }
  18367. return (void*)&mem3.aPool[newi];
  18368. }
  18369. }
  18370. /*
  18371. ** *pRoot is the head of a list of free chunks of the same size
  18372. ** or same size hash. In other words, *pRoot is an entry in either
  18373. ** mem3.aiSmall[] or mem3.aiHash[].
  18374. **
  18375. ** This routine examines all entries on the given list and tries
  18376. ** to coalesce each entries with adjacent free chunks.
  18377. **
  18378. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  18379. ** the current mem3.iMaster with the new larger chunk. In order for
  18380. ** this mem3.iMaster replacement to work, the master chunk must be
  18381. ** linked into the hash tables. That is not the normal state of
  18382. ** affairs, of course. The calling routine must link the master
  18383. ** chunk before invoking this routine, then must unlink the (possibly
  18384. ** changed) master chunk once this routine has finished.
  18385. */
  18386. static void memsys3Merge(u32 *pRoot){
  18387. u32 iNext, prev, size, i, x;
  18388. assert( sqlite3_mutex_held(mem3.mutex) );
  18389. for(i=*pRoot; i>0; i=iNext){
  18390. iNext = mem3.aPool[i].u.list.next;
  18391. size = mem3.aPool[i-1].u.hdr.size4x;
  18392. assert( (size&1)==0 );
  18393. if( (size&2)==0 ){
  18394. memsys3UnlinkFromList(i, pRoot);
  18395. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  18396. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  18397. if( prev==iNext ){
  18398. iNext = mem3.aPool[prev].u.list.next;
  18399. }
  18400. memsys3Unlink(prev);
  18401. size = i + size/4 - prev;
  18402. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  18403. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  18404. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  18405. memsys3Link(prev);
  18406. i = prev;
  18407. }else{
  18408. size /= 4;
  18409. }
  18410. if( size>mem3.szMaster ){
  18411. mem3.iMaster = i;
  18412. mem3.szMaster = size;
  18413. }
  18414. }
  18415. }
  18416. /*
  18417. ** Return a block of memory of at least nBytes in size.
  18418. ** Return NULL if unable.
  18419. **
  18420. ** This function assumes that the necessary mutexes, if any, are
  18421. ** already held by the caller. Hence "Unsafe".
  18422. */
  18423. static void *memsys3MallocUnsafe(int nByte){
  18424. u32 i;
  18425. u32 nBlock;
  18426. u32 toFree;
  18427. assert( sqlite3_mutex_held(mem3.mutex) );
  18428. assert( sizeof(Mem3Block)==8 );
  18429. if( nByte<=12 ){
  18430. nBlock = 2;
  18431. }else{
  18432. nBlock = (nByte + 11)/8;
  18433. }
  18434. assert( nBlock>=2 );
  18435. /* STEP 1:
  18436. ** Look for an entry of the correct size in either the small
  18437. ** chunk table or in the large chunk hash table. This is
  18438. ** successful most of the time (about 9 times out of 10).
  18439. */
  18440. if( nBlock <= MX_SMALL ){
  18441. i = mem3.aiSmall[nBlock-2];
  18442. if( i>0 ){
  18443. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  18444. return memsys3Checkout(i, nBlock);
  18445. }
  18446. }else{
  18447. int hash = nBlock % N_HASH;
  18448. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  18449. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  18450. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  18451. return memsys3Checkout(i, nBlock);
  18452. }
  18453. }
  18454. }
  18455. /* STEP 2:
  18456. ** Try to satisfy the allocation by carving a piece off of the end
  18457. ** of the master chunk. This step usually works if step 1 fails.
  18458. */
  18459. if( mem3.szMaster>=nBlock ){
  18460. return memsys3FromMaster(nBlock);
  18461. }
  18462. /* STEP 3:
  18463. ** Loop through the entire memory pool. Coalesce adjacent free
  18464. ** chunks. Recompute the master chunk as the largest free chunk.
  18465. ** Then try again to satisfy the allocation by carving a piece off
  18466. ** of the end of the master chunk. This step happens very
  18467. ** rarely (we hope!)
  18468. */
  18469. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  18470. memsys3OutOfMemory(toFree);
  18471. if( mem3.iMaster ){
  18472. memsys3Link(mem3.iMaster);
  18473. mem3.iMaster = 0;
  18474. mem3.szMaster = 0;
  18475. }
  18476. for(i=0; i<N_HASH; i++){
  18477. memsys3Merge(&mem3.aiHash[i]);
  18478. }
  18479. for(i=0; i<MX_SMALL-1; i++){
  18480. memsys3Merge(&mem3.aiSmall[i]);
  18481. }
  18482. if( mem3.szMaster ){
  18483. memsys3Unlink(mem3.iMaster);
  18484. if( mem3.szMaster>=nBlock ){
  18485. return memsys3FromMaster(nBlock);
  18486. }
  18487. }
  18488. }
  18489. /* If none of the above worked, then we fail. */
  18490. return 0;
  18491. }
  18492. /*
  18493. ** Free an outstanding memory allocation.
  18494. **
  18495. ** This function assumes that the necessary mutexes, if any, are
  18496. ** already held by the caller. Hence "Unsafe".
  18497. */
  18498. static void memsys3FreeUnsafe(void *pOld){
  18499. Mem3Block *p = (Mem3Block*)pOld;
  18500. int i;
  18501. u32 size, x;
  18502. assert( sqlite3_mutex_held(mem3.mutex) );
  18503. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  18504. i = p - mem3.aPool;
  18505. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  18506. size = mem3.aPool[i-1].u.hdr.size4x/4;
  18507. assert( i+size<=mem3.nPool+1 );
  18508. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  18509. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  18510. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  18511. memsys3Link(i);
  18512. /* Try to expand the master using the newly freed chunk */
  18513. if( mem3.iMaster ){
  18514. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  18515. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  18516. mem3.iMaster -= size;
  18517. mem3.szMaster += size;
  18518. memsys3Unlink(mem3.iMaster);
  18519. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18520. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18521. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  18522. }
  18523. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  18524. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  18525. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  18526. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  18527. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  18528. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  18529. }
  18530. }
  18531. }
  18532. /*
  18533. ** Return the size of an outstanding allocation, in bytes. The
  18534. ** size returned omits the 8-byte header overhead. This only
  18535. ** works for chunks that are currently checked out.
  18536. */
  18537. static int memsys3Size(void *p){
  18538. Mem3Block *pBlock;
  18539. assert( p!=0 );
  18540. pBlock = (Mem3Block*)p;
  18541. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  18542. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  18543. }
  18544. /*
  18545. ** Round up a request size to the next valid allocation size.
  18546. */
  18547. static int memsys3Roundup(int n){
  18548. if( n<=12 ){
  18549. return 12;
  18550. }else{
  18551. return ((n+11)&~7) - 4;
  18552. }
  18553. }
  18554. /*
  18555. ** Allocate nBytes of memory.
  18556. */
  18557. static void *memsys3Malloc(int nBytes){
  18558. sqlite3_int64 *p;
  18559. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  18560. memsys3Enter();
  18561. p = memsys3MallocUnsafe(nBytes);
  18562. memsys3Leave();
  18563. return (void*)p;
  18564. }
  18565. /*
  18566. ** Free memory.
  18567. */
  18568. static void memsys3Free(void *pPrior){
  18569. assert( pPrior );
  18570. memsys3Enter();
  18571. memsys3FreeUnsafe(pPrior);
  18572. memsys3Leave();
  18573. }
  18574. /*
  18575. ** Change the size of an existing memory allocation
  18576. */
  18577. static void *memsys3Realloc(void *pPrior, int nBytes){
  18578. int nOld;
  18579. void *p;
  18580. if( pPrior==0 ){
  18581. return sqlite3_malloc(nBytes);
  18582. }
  18583. if( nBytes<=0 ){
  18584. sqlite3_free(pPrior);
  18585. return 0;
  18586. }
  18587. nOld = memsys3Size(pPrior);
  18588. if( nBytes<=nOld && nBytes>=nOld-128 ){
  18589. return pPrior;
  18590. }
  18591. memsys3Enter();
  18592. p = memsys3MallocUnsafe(nBytes);
  18593. if( p ){
  18594. if( nOld<nBytes ){
  18595. memcpy(p, pPrior, nOld);
  18596. }else{
  18597. memcpy(p, pPrior, nBytes);
  18598. }
  18599. memsys3FreeUnsafe(pPrior);
  18600. }
  18601. memsys3Leave();
  18602. return p;
  18603. }
  18604. /*
  18605. ** Initialize this module.
  18606. */
  18607. static int memsys3Init(void *NotUsed){
  18608. UNUSED_PARAMETER(NotUsed);
  18609. if( !sqlite3GlobalConfig.pHeap ){
  18610. return SQLITE_ERROR;
  18611. }
  18612. /* Store a pointer to the memory block in global structure mem3. */
  18613. assert( sizeof(Mem3Block)==8 );
  18614. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  18615. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  18616. /* Initialize the master block. */
  18617. mem3.szMaster = mem3.nPool;
  18618. mem3.mnMaster = mem3.szMaster;
  18619. mem3.iMaster = 1;
  18620. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  18621. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  18622. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  18623. return SQLITE_OK;
  18624. }
  18625. /*
  18626. ** Deinitialize this module.
  18627. */
  18628. static void memsys3Shutdown(void *NotUsed){
  18629. UNUSED_PARAMETER(NotUsed);
  18630. mem3.mutex = 0;
  18631. return;
  18632. }
  18633. /*
  18634. ** Open the file indicated and write a log of all unfreed memory
  18635. ** allocations into that log.
  18636. */
  18637. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  18638. #ifdef SQLITE_DEBUG
  18639. FILE *out;
  18640. u32 i, j;
  18641. u32 size;
  18642. if( zFilename==0 || zFilename[0]==0 ){
  18643. out = stdout;
  18644. }else{
  18645. out = fopen(zFilename, "w");
  18646. if( out==0 ){
  18647. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  18648. zFilename);
  18649. return;
  18650. }
  18651. }
  18652. memsys3Enter();
  18653. fprintf(out, "CHUNKS:\n");
  18654. for(i=1; i<=mem3.nPool; i+=size/4){
  18655. size = mem3.aPool[i-1].u.hdr.size4x;
  18656. if( size/4<=1 ){
  18657. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  18658. assert( 0 );
  18659. break;
  18660. }
  18661. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  18662. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  18663. assert( 0 );
  18664. break;
  18665. }
  18666. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  18667. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  18668. assert( 0 );
  18669. break;
  18670. }
  18671. if( size&1 ){
  18672. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  18673. }else{
  18674. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  18675. i==mem3.iMaster ? " **master**" : "");
  18676. }
  18677. }
  18678. for(i=0; i<MX_SMALL-1; i++){
  18679. if( mem3.aiSmall[i]==0 ) continue;
  18680. fprintf(out, "small(%2d):", i);
  18681. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  18682. fprintf(out, " %p(%d)", &mem3.aPool[j],
  18683. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  18684. }
  18685. fprintf(out, "\n");
  18686. }
  18687. for(i=0; i<N_HASH; i++){
  18688. if( mem3.aiHash[i]==0 ) continue;
  18689. fprintf(out, "hash(%2d):", i);
  18690. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  18691. fprintf(out, " %p(%d)", &mem3.aPool[j],
  18692. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  18693. }
  18694. fprintf(out, "\n");
  18695. }
  18696. fprintf(out, "master=%d\n", mem3.iMaster);
  18697. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  18698. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  18699. sqlite3_mutex_leave(mem3.mutex);
  18700. if( out==stdout ){
  18701. fflush(stdout);
  18702. }else{
  18703. fclose(out);
  18704. }
  18705. #else
  18706. UNUSED_PARAMETER(zFilename);
  18707. #endif
  18708. }
  18709. /*
  18710. ** This routine is the only routine in this file with external
  18711. ** linkage.
  18712. **
  18713. ** Populate the low-level memory allocation function pointers in
  18714. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  18715. ** arguments specify the block of memory to manage.
  18716. **
  18717. ** This routine is only called by sqlite3_config(), and therefore
  18718. ** is not required to be threadsafe (it is not).
  18719. */
  18720. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  18721. static const sqlite3_mem_methods mempoolMethods = {
  18722. memsys3Malloc,
  18723. memsys3Free,
  18724. memsys3Realloc,
  18725. memsys3Size,
  18726. memsys3Roundup,
  18727. memsys3Init,
  18728. memsys3Shutdown,
  18729. 0
  18730. };
  18731. return &mempoolMethods;
  18732. }
  18733. #endif /* SQLITE_ENABLE_MEMSYS3 */
  18734. /************** End of mem3.c ************************************************/
  18735. /************** Begin file mem5.c ********************************************/
  18736. /*
  18737. ** 2007 October 14
  18738. **
  18739. ** The author disclaims copyright to this source code. In place of
  18740. ** a legal notice, here is a blessing:
  18741. **
  18742. ** May you do good and not evil.
  18743. ** May you find forgiveness for yourself and forgive others.
  18744. ** May you share freely, never taking more than you give.
  18745. **
  18746. *************************************************************************
  18747. ** This file contains the C functions that implement a memory
  18748. ** allocation subsystem for use by SQLite.
  18749. **
  18750. ** This version of the memory allocation subsystem omits all
  18751. ** use of malloc(). The application gives SQLite a block of memory
  18752. ** before calling sqlite3_initialize() from which allocations
  18753. ** are made and returned by the xMalloc() and xRealloc()
  18754. ** implementations. Once sqlite3_initialize() has been called,
  18755. ** the amount of memory available to SQLite is fixed and cannot
  18756. ** be changed.
  18757. **
  18758. ** This version of the memory allocation subsystem is included
  18759. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  18760. **
  18761. ** This memory allocator uses the following algorithm:
  18762. **
  18763. ** 1. All memory allocation sizes are rounded up to a power of 2.
  18764. **
  18765. ** 2. If two adjacent free blocks are the halves of a larger block,
  18766. ** then the two blocks are coalesced into the single larger block.
  18767. **
  18768. ** 3. New memory is allocated from the first available free block.
  18769. **
  18770. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  18771. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  18772. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  18773. **
  18774. ** Let n be the size of the largest allocation divided by the minimum
  18775. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  18776. ** be the maximum amount of memory ever outstanding at one time. Let
  18777. ** N be the total amount of memory available for allocation. Robson
  18778. ** proved that this memory allocator will never breakdown due to
  18779. ** fragmentation as long as the following constraint holds:
  18780. **
  18781. ** N >= M*(1 + log2(n)/2) - n + 1
  18782. **
  18783. ** The sqlite3_status() logic tracks the maximum values of n and M so
  18784. ** that an application can, at any time, verify this constraint.
  18785. */
  18786. /* #include "sqliteInt.h" */
  18787. /*
  18788. ** This version of the memory allocator is used only when
  18789. ** SQLITE_ENABLE_MEMSYS5 is defined.
  18790. */
  18791. #ifdef SQLITE_ENABLE_MEMSYS5
  18792. /*
  18793. ** A minimum allocation is an instance of the following structure.
  18794. ** Larger allocations are an array of these structures where the
  18795. ** size of the array is a power of 2.
  18796. **
  18797. ** The size of this object must be a power of two. That fact is
  18798. ** verified in memsys5Init().
  18799. */
  18800. typedef struct Mem5Link Mem5Link;
  18801. struct Mem5Link {
  18802. int next; /* Index of next free chunk */
  18803. int prev; /* Index of previous free chunk */
  18804. };
  18805. /*
  18806. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  18807. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  18808. ** it is not actually possible to reach this limit.
  18809. */
  18810. #define LOGMAX 30
  18811. /*
  18812. ** Masks used for mem5.aCtrl[] elements.
  18813. */
  18814. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  18815. #define CTRL_FREE 0x20 /* True if not checked out */
  18816. /*
  18817. ** All of the static variables used by this module are collected
  18818. ** into a single structure named "mem5". This is to keep the
  18819. ** static variables organized and to reduce namespace pollution
  18820. ** when this module is combined with other in the amalgamation.
  18821. */
  18822. static SQLITE_WSD struct Mem5Global {
  18823. /*
  18824. ** Memory available for allocation
  18825. */
  18826. int szAtom; /* Smallest possible allocation in bytes */
  18827. int nBlock; /* Number of szAtom sized blocks in zPool */
  18828. u8 *zPool; /* Memory available to be allocated */
  18829. /*
  18830. ** Mutex to control access to the memory allocation subsystem.
  18831. */
  18832. sqlite3_mutex *mutex;
  18833. /*
  18834. ** Performance statistics
  18835. */
  18836. u64 nAlloc; /* Total number of calls to malloc */
  18837. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  18838. u64 totalExcess; /* Total internal fragmentation */
  18839. u32 currentOut; /* Current checkout, including internal fragmentation */
  18840. u32 currentCount; /* Current number of distinct checkouts */
  18841. u32 maxOut; /* Maximum instantaneous currentOut */
  18842. u32 maxCount; /* Maximum instantaneous currentCount */
  18843. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  18844. /*
  18845. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  18846. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  18847. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  18848. */
  18849. int aiFreelist[LOGMAX+1];
  18850. /*
  18851. ** Space for tracking which blocks are checked out and the size
  18852. ** of each block. One byte per block.
  18853. */
  18854. u8 *aCtrl;
  18855. } mem5;
  18856. /*
  18857. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  18858. */
  18859. #define mem5 GLOBAL(struct Mem5Global, mem5)
  18860. /*
  18861. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  18862. ** structures, return a pointer to the idx-th such link.
  18863. */
  18864. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  18865. /*
  18866. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  18867. ** on. It should be found on mem5.aiFreelist[iLogsize].
  18868. */
  18869. static void memsys5Unlink(int i, int iLogsize){
  18870. int next, prev;
  18871. assert( i>=0 && i<mem5.nBlock );
  18872. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  18873. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  18874. next = MEM5LINK(i)->next;
  18875. prev = MEM5LINK(i)->prev;
  18876. if( prev<0 ){
  18877. mem5.aiFreelist[iLogsize] = next;
  18878. }else{
  18879. MEM5LINK(prev)->next = next;
  18880. }
  18881. if( next>=0 ){
  18882. MEM5LINK(next)->prev = prev;
  18883. }
  18884. }
  18885. /*
  18886. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  18887. ** free list.
  18888. */
  18889. static void memsys5Link(int i, int iLogsize){
  18890. int x;
  18891. assert( sqlite3_mutex_held(mem5.mutex) );
  18892. assert( i>=0 && i<mem5.nBlock );
  18893. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  18894. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  18895. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  18896. MEM5LINK(i)->prev = -1;
  18897. if( x>=0 ){
  18898. assert( x<mem5.nBlock );
  18899. MEM5LINK(x)->prev = i;
  18900. }
  18901. mem5.aiFreelist[iLogsize] = i;
  18902. }
  18903. /*
  18904. ** Obtain or release the mutex needed to access global data structures.
  18905. */
  18906. static void memsys5Enter(void){
  18907. sqlite3_mutex_enter(mem5.mutex);
  18908. }
  18909. static void memsys5Leave(void){
  18910. sqlite3_mutex_leave(mem5.mutex);
  18911. }
  18912. /*
  18913. ** Return the size of an outstanding allocation, in bytes.
  18914. ** This only works for chunks that are currently checked out.
  18915. */
  18916. static int memsys5Size(void *p){
  18917. int iSize, i;
  18918. assert( p!=0 );
  18919. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  18920. assert( i>=0 && i<mem5.nBlock );
  18921. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  18922. return iSize;
  18923. }
  18924. /*
  18925. ** Return a block of memory of at least nBytes in size.
  18926. ** Return NULL if unable. Return NULL if nBytes==0.
  18927. **
  18928. ** The caller guarantees that nByte is positive.
  18929. **
  18930. ** The caller has obtained a mutex prior to invoking this
  18931. ** routine so there is never any chance that two or more
  18932. ** threads can be in this routine at the same time.
  18933. */
  18934. static void *memsys5MallocUnsafe(int nByte){
  18935. int i; /* Index of a mem5.aPool[] slot */
  18936. int iBin; /* Index into mem5.aiFreelist[] */
  18937. int iFullSz; /* Size of allocation rounded up to power of 2 */
  18938. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  18939. /* nByte must be a positive */
  18940. assert( nByte>0 );
  18941. /* Keep track of the maximum allocation request. Even unfulfilled
  18942. ** requests are counted */
  18943. if( (u32)nByte>mem5.maxRequest ){
  18944. /* Abort if the requested allocation size is larger than the largest
  18945. ** power of two that we can represent using 32-bit signed integers. */
  18946. if( nByte > 0x40000000 ) return 0;
  18947. mem5.maxRequest = nByte;
  18948. }
  18949. /* Round nByte up to the next valid power of two */
  18950. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  18951. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  18952. ** block. If not, then split a block of the next larger power of
  18953. ** two in order to create a new free block of size iLogsize.
  18954. */
  18955. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  18956. if( iBin>LOGMAX ){
  18957. testcase( sqlite3GlobalConfig.xLog!=0 );
  18958. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  18959. return 0;
  18960. }
  18961. i = mem5.aiFreelist[iBin];
  18962. memsys5Unlink(i, iBin);
  18963. while( iBin>iLogsize ){
  18964. int newSize;
  18965. iBin--;
  18966. newSize = 1 << iBin;
  18967. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  18968. memsys5Link(i+newSize, iBin);
  18969. }
  18970. mem5.aCtrl[i] = iLogsize;
  18971. /* Update allocator performance statistics. */
  18972. mem5.nAlloc++;
  18973. mem5.totalAlloc += iFullSz;
  18974. mem5.totalExcess += iFullSz - nByte;
  18975. mem5.currentCount++;
  18976. mem5.currentOut += iFullSz;
  18977. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  18978. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  18979. #ifdef SQLITE_DEBUG
  18980. /* Make sure the allocated memory does not assume that it is set to zero
  18981. ** or retains a value from a previous allocation */
  18982. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  18983. #endif
  18984. /* Return a pointer to the allocated memory. */
  18985. return (void*)&mem5.zPool[i*mem5.szAtom];
  18986. }
  18987. /*
  18988. ** Free an outstanding memory allocation.
  18989. */
  18990. static void memsys5FreeUnsafe(void *pOld){
  18991. u32 size, iLogsize;
  18992. int iBlock;
  18993. /* Set iBlock to the index of the block pointed to by pOld in
  18994. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  18995. */
  18996. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  18997. /* Check that the pointer pOld points to a valid, non-free block. */
  18998. assert( iBlock>=0 && iBlock<mem5.nBlock );
  18999. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  19000. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  19001. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  19002. size = 1<<iLogsize;
  19003. assert( iBlock+size-1<(u32)mem5.nBlock );
  19004. mem5.aCtrl[iBlock] |= CTRL_FREE;
  19005. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  19006. assert( mem5.currentCount>0 );
  19007. assert( mem5.currentOut>=(size*mem5.szAtom) );
  19008. mem5.currentCount--;
  19009. mem5.currentOut -= size*mem5.szAtom;
  19010. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  19011. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  19012. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  19013. while( ALWAYS(iLogsize<LOGMAX) ){
  19014. int iBuddy;
  19015. if( (iBlock>>iLogsize) & 1 ){
  19016. iBuddy = iBlock - size;
  19017. }else{
  19018. iBuddy = iBlock + size;
  19019. }
  19020. assert( iBuddy>=0 );
  19021. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  19022. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  19023. memsys5Unlink(iBuddy, iLogsize);
  19024. iLogsize++;
  19025. if( iBuddy<iBlock ){
  19026. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  19027. mem5.aCtrl[iBlock] = 0;
  19028. iBlock = iBuddy;
  19029. }else{
  19030. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  19031. mem5.aCtrl[iBuddy] = 0;
  19032. }
  19033. size *= 2;
  19034. }
  19035. #ifdef SQLITE_DEBUG
  19036. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  19037. ** not used after being freed */
  19038. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  19039. #endif
  19040. memsys5Link(iBlock, iLogsize);
  19041. }
  19042. /*
  19043. ** Allocate nBytes of memory.
  19044. */
  19045. static void *memsys5Malloc(int nBytes){
  19046. sqlite3_int64 *p = 0;
  19047. if( nBytes>0 ){
  19048. memsys5Enter();
  19049. p = memsys5MallocUnsafe(nBytes);
  19050. memsys5Leave();
  19051. }
  19052. return (void*)p;
  19053. }
  19054. /*
  19055. ** Free memory.
  19056. **
  19057. ** The outer layer memory allocator prevents this routine from
  19058. ** being called with pPrior==0.
  19059. */
  19060. static void memsys5Free(void *pPrior){
  19061. assert( pPrior!=0 );
  19062. memsys5Enter();
  19063. memsys5FreeUnsafe(pPrior);
  19064. memsys5Leave();
  19065. }
  19066. /*
  19067. ** Change the size of an existing memory allocation.
  19068. **
  19069. ** The outer layer memory allocator prevents this routine from
  19070. ** being called with pPrior==0.
  19071. **
  19072. ** nBytes is always a value obtained from a prior call to
  19073. ** memsys5Round(). Hence nBytes is always a non-negative power
  19074. ** of two. If nBytes==0 that means that an oversize allocation
  19075. ** (an allocation larger than 0x40000000) was requested and this
  19076. ** routine should return 0 without freeing pPrior.
  19077. */
  19078. static void *memsys5Realloc(void *pPrior, int nBytes){
  19079. int nOld;
  19080. void *p;
  19081. assert( pPrior!=0 );
  19082. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  19083. assert( nBytes>=0 );
  19084. if( nBytes==0 ){
  19085. return 0;
  19086. }
  19087. nOld = memsys5Size(pPrior);
  19088. if( nBytes<=nOld ){
  19089. return pPrior;
  19090. }
  19091. p = memsys5Malloc(nBytes);
  19092. if( p ){
  19093. memcpy(p, pPrior, nOld);
  19094. memsys5Free(pPrior);
  19095. }
  19096. return p;
  19097. }
  19098. /*
  19099. ** Round up a request size to the next valid allocation size. If
  19100. ** the allocation is too large to be handled by this allocation system,
  19101. ** return 0.
  19102. **
  19103. ** All allocations must be a power of two and must be expressed by a
  19104. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  19105. ** or 1073741824 bytes.
  19106. */
  19107. static int memsys5Roundup(int n){
  19108. int iFullSz;
  19109. if( n > 0x40000000 ) return 0;
  19110. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  19111. return iFullSz;
  19112. }
  19113. /*
  19114. ** Return the ceiling of the logarithm base 2 of iValue.
  19115. **
  19116. ** Examples: memsys5Log(1) -> 0
  19117. ** memsys5Log(2) -> 1
  19118. ** memsys5Log(4) -> 2
  19119. ** memsys5Log(5) -> 3
  19120. ** memsys5Log(8) -> 3
  19121. ** memsys5Log(9) -> 4
  19122. */
  19123. static int memsys5Log(int iValue){
  19124. int iLog;
  19125. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  19126. return iLog;
  19127. }
  19128. /*
  19129. ** Initialize the memory allocator.
  19130. **
  19131. ** This routine is not threadsafe. The caller must be holding a mutex
  19132. ** to prevent multiple threads from entering at the same time.
  19133. */
  19134. static int memsys5Init(void *NotUsed){
  19135. int ii; /* Loop counter */
  19136. int nByte; /* Number of bytes of memory available to this allocator */
  19137. u8 *zByte; /* Memory usable by this allocator */
  19138. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  19139. int iOffset; /* An offset into mem5.aCtrl[] */
  19140. UNUSED_PARAMETER(NotUsed);
  19141. /* For the purposes of this routine, disable the mutex */
  19142. mem5.mutex = 0;
  19143. /* The size of a Mem5Link object must be a power of two. Verify that
  19144. ** this is case.
  19145. */
  19146. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  19147. nByte = sqlite3GlobalConfig.nHeap;
  19148. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  19149. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  19150. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  19151. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  19152. mem5.szAtom = (1<<nMinLog);
  19153. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  19154. mem5.szAtom = mem5.szAtom << 1;
  19155. }
  19156. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  19157. mem5.zPool = zByte;
  19158. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  19159. for(ii=0; ii<=LOGMAX; ii++){
  19160. mem5.aiFreelist[ii] = -1;
  19161. }
  19162. iOffset = 0;
  19163. for(ii=LOGMAX; ii>=0; ii--){
  19164. int nAlloc = (1<<ii);
  19165. if( (iOffset+nAlloc)<=mem5.nBlock ){
  19166. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  19167. memsys5Link(iOffset, ii);
  19168. iOffset += nAlloc;
  19169. }
  19170. assert((iOffset+nAlloc)>mem5.nBlock);
  19171. }
  19172. /* If a mutex is required for normal operation, allocate one */
  19173. if( sqlite3GlobalConfig.bMemstat==0 ){
  19174. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  19175. }
  19176. return SQLITE_OK;
  19177. }
  19178. /*
  19179. ** Deinitialize this module.
  19180. */
  19181. static void memsys5Shutdown(void *NotUsed){
  19182. UNUSED_PARAMETER(NotUsed);
  19183. mem5.mutex = 0;
  19184. return;
  19185. }
  19186. #ifdef SQLITE_TEST
  19187. /*
  19188. ** Open the file indicated and write a log of all unfreed memory
  19189. ** allocations into that log.
  19190. */
  19191. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  19192. FILE *out;
  19193. int i, j, n;
  19194. int nMinLog;
  19195. if( zFilename==0 || zFilename[0]==0 ){
  19196. out = stdout;
  19197. }else{
  19198. out = fopen(zFilename, "w");
  19199. if( out==0 ){
  19200. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  19201. zFilename);
  19202. return;
  19203. }
  19204. }
  19205. memsys5Enter();
  19206. nMinLog = memsys5Log(mem5.szAtom);
  19207. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  19208. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  19209. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  19210. }
  19211. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  19212. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  19213. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  19214. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  19215. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  19216. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  19217. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  19218. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  19219. memsys5Leave();
  19220. if( out==stdout ){
  19221. fflush(stdout);
  19222. }else{
  19223. fclose(out);
  19224. }
  19225. }
  19226. #endif
  19227. /*
  19228. ** This routine is the only routine in this file with external
  19229. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  19230. ** struct populated with the memsys5 methods.
  19231. */
  19232. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  19233. static const sqlite3_mem_methods memsys5Methods = {
  19234. memsys5Malloc,
  19235. memsys5Free,
  19236. memsys5Realloc,
  19237. memsys5Size,
  19238. memsys5Roundup,
  19239. memsys5Init,
  19240. memsys5Shutdown,
  19241. 0
  19242. };
  19243. return &memsys5Methods;
  19244. }
  19245. #endif /* SQLITE_ENABLE_MEMSYS5 */
  19246. /************** End of mem5.c ************************************************/
  19247. /************** Begin file mutex.c *******************************************/
  19248. /*
  19249. ** 2007 August 14
  19250. **
  19251. ** The author disclaims copyright to this source code. In place of
  19252. ** a legal notice, here is a blessing:
  19253. **
  19254. ** May you do good and not evil.
  19255. ** May you find forgiveness for yourself and forgive others.
  19256. ** May you share freely, never taking more than you give.
  19257. **
  19258. *************************************************************************
  19259. ** This file contains the C functions that implement mutexes.
  19260. **
  19261. ** This file contains code that is common across all mutex implementations.
  19262. */
  19263. /* #include "sqliteInt.h" */
  19264. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  19265. /*
  19266. ** For debugging purposes, record when the mutex subsystem is initialized
  19267. ** and uninitialized so that we can assert() if there is an attempt to
  19268. ** allocate a mutex while the system is uninitialized.
  19269. */
  19270. static SQLITE_WSD int mutexIsInit = 0;
  19271. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  19272. #ifndef SQLITE_MUTEX_OMIT
  19273. /*
  19274. ** Initialize the mutex system.
  19275. */
  19276. SQLITE_PRIVATE int sqlite3MutexInit(void){
  19277. int rc = SQLITE_OK;
  19278. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  19279. /* If the xMutexAlloc method has not been set, then the user did not
  19280. ** install a mutex implementation via sqlite3_config() prior to
  19281. ** sqlite3_initialize() being called. This block copies pointers to
  19282. ** the default implementation into the sqlite3GlobalConfig structure.
  19283. */
  19284. sqlite3_mutex_methods const *pFrom;
  19285. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  19286. if( sqlite3GlobalConfig.bCoreMutex ){
  19287. pFrom = sqlite3DefaultMutex();
  19288. }else{
  19289. pFrom = sqlite3NoopMutex();
  19290. }
  19291. pTo->xMutexInit = pFrom->xMutexInit;
  19292. pTo->xMutexEnd = pFrom->xMutexEnd;
  19293. pTo->xMutexFree = pFrom->xMutexFree;
  19294. pTo->xMutexEnter = pFrom->xMutexEnter;
  19295. pTo->xMutexTry = pFrom->xMutexTry;
  19296. pTo->xMutexLeave = pFrom->xMutexLeave;
  19297. pTo->xMutexHeld = pFrom->xMutexHeld;
  19298. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  19299. sqlite3MemoryBarrier();
  19300. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  19301. }
  19302. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  19303. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  19304. #ifdef SQLITE_DEBUG
  19305. GLOBAL(int, mutexIsInit) = 1;
  19306. #endif
  19307. return rc;
  19308. }
  19309. /*
  19310. ** Shutdown the mutex system. This call frees resources allocated by
  19311. ** sqlite3MutexInit().
  19312. */
  19313. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  19314. int rc = SQLITE_OK;
  19315. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  19316. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  19317. }
  19318. #ifdef SQLITE_DEBUG
  19319. GLOBAL(int, mutexIsInit) = 0;
  19320. #endif
  19321. return rc;
  19322. }
  19323. /*
  19324. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  19325. */
  19326. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
  19327. #ifndef SQLITE_OMIT_AUTOINIT
  19328. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  19329. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  19330. #endif
  19331. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  19332. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  19333. }
  19334. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  19335. if( !sqlite3GlobalConfig.bCoreMutex ){
  19336. return 0;
  19337. }
  19338. assert( GLOBAL(int, mutexIsInit) );
  19339. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  19340. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  19341. }
  19342. /*
  19343. ** Free a dynamic mutex.
  19344. */
  19345. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
  19346. if( p ){
  19347. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  19348. sqlite3GlobalConfig.mutex.xMutexFree(p);
  19349. }
  19350. }
  19351. /*
  19352. ** Obtain the mutex p. If some other thread already has the mutex, block
  19353. ** until it can be obtained.
  19354. */
  19355. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
  19356. if( p ){
  19357. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  19358. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  19359. }
  19360. }
  19361. /*
  19362. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  19363. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  19364. */
  19365. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
  19366. int rc = SQLITE_OK;
  19367. if( p ){
  19368. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  19369. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  19370. }
  19371. return rc;
  19372. }
  19373. /*
  19374. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  19375. ** entered by the same thread. The behavior is undefined if the mutex
  19376. ** is not currently entered. If a NULL pointer is passed as an argument
  19377. ** this function is a no-op.
  19378. */
  19379. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
  19380. if( p ){
  19381. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  19382. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  19383. }
  19384. }
  19385. #ifndef NDEBUG
  19386. /*
  19387. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19388. ** intended for use inside assert() statements.
  19389. */
  19390. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
  19391. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  19392. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  19393. }
  19394. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
  19395. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  19396. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  19397. }
  19398. #endif
  19399. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  19400. /************** End of mutex.c ***********************************************/
  19401. /************** Begin file mutex_noop.c **************************************/
  19402. /*
  19403. ** 2008 October 07
  19404. **
  19405. ** The author disclaims copyright to this source code. In place of
  19406. ** a legal notice, here is a blessing:
  19407. **
  19408. ** May you do good and not evil.
  19409. ** May you find forgiveness for yourself and forgive others.
  19410. ** May you share freely, never taking more than you give.
  19411. **
  19412. *************************************************************************
  19413. ** This file contains the C functions that implement mutexes.
  19414. **
  19415. ** This implementation in this file does not provide any mutual
  19416. ** exclusion and is thus suitable for use only in applications
  19417. ** that use SQLite in a single thread. The routines defined
  19418. ** here are place-holders. Applications can substitute working
  19419. ** mutex routines at start-time using the
  19420. **
  19421. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  19422. **
  19423. ** interface.
  19424. **
  19425. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  19426. ** that does error checking on mutexes to make sure they are being
  19427. ** called correctly.
  19428. */
  19429. /* #include "sqliteInt.h" */
  19430. #ifndef SQLITE_MUTEX_OMIT
  19431. #ifndef SQLITE_DEBUG
  19432. /*
  19433. ** Stub routines for all mutex methods.
  19434. **
  19435. ** This routines provide no mutual exclusion or error checking.
  19436. */
  19437. static int noopMutexInit(void){ return SQLITE_OK; }
  19438. static int noopMutexEnd(void){ return SQLITE_OK; }
  19439. static sqlite3_mutex *noopMutexAlloc(int id){
  19440. UNUSED_PARAMETER(id);
  19441. return (sqlite3_mutex*)8;
  19442. }
  19443. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19444. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19445. static int noopMutexTry(sqlite3_mutex *p){
  19446. UNUSED_PARAMETER(p);
  19447. return SQLITE_OK;
  19448. }
  19449. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  19450. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  19451. static const sqlite3_mutex_methods sMutex = {
  19452. noopMutexInit,
  19453. noopMutexEnd,
  19454. noopMutexAlloc,
  19455. noopMutexFree,
  19456. noopMutexEnter,
  19457. noopMutexTry,
  19458. noopMutexLeave,
  19459. 0,
  19460. 0,
  19461. };
  19462. return &sMutex;
  19463. }
  19464. #endif /* !SQLITE_DEBUG */
  19465. #ifdef SQLITE_DEBUG
  19466. /*
  19467. ** In this implementation, error checking is provided for testing
  19468. ** and debugging purposes. The mutexes still do not provide any
  19469. ** mutual exclusion.
  19470. */
  19471. /*
  19472. ** The mutex object
  19473. */
  19474. typedef struct sqlite3_debug_mutex {
  19475. int id; /* The mutex type */
  19476. int cnt; /* Number of entries without a matching leave */
  19477. } sqlite3_debug_mutex;
  19478. /*
  19479. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19480. ** intended for use inside assert() statements.
  19481. */
  19482. static int debugMutexHeld(sqlite3_mutex *pX){
  19483. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19484. return p==0 || p->cnt>0;
  19485. }
  19486. static int debugMutexNotheld(sqlite3_mutex *pX){
  19487. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19488. return p==0 || p->cnt==0;
  19489. }
  19490. /*
  19491. ** Initialize and deinitialize the mutex subsystem.
  19492. */
  19493. static int debugMutexInit(void){ return SQLITE_OK; }
  19494. static int debugMutexEnd(void){ return SQLITE_OK; }
  19495. /*
  19496. ** The sqlite3_mutex_alloc() routine allocates a new
  19497. ** mutex and returns a pointer to it. If it returns NULL
  19498. ** that means that a mutex could not be allocated.
  19499. */
  19500. static sqlite3_mutex *debugMutexAlloc(int id){
  19501. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  19502. sqlite3_debug_mutex *pNew = 0;
  19503. switch( id ){
  19504. case SQLITE_MUTEX_FAST:
  19505. case SQLITE_MUTEX_RECURSIVE: {
  19506. pNew = sqlite3Malloc(sizeof(*pNew));
  19507. if( pNew ){
  19508. pNew->id = id;
  19509. pNew->cnt = 0;
  19510. }
  19511. break;
  19512. }
  19513. default: {
  19514. #ifdef SQLITE_ENABLE_API_ARMOR
  19515. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  19516. (void)SQLITE_MISUSE_BKPT;
  19517. return 0;
  19518. }
  19519. #endif
  19520. pNew = &aStatic[id-2];
  19521. pNew->id = id;
  19522. break;
  19523. }
  19524. }
  19525. return (sqlite3_mutex*)pNew;
  19526. }
  19527. /*
  19528. ** This routine deallocates a previously allocated mutex.
  19529. */
  19530. static void debugMutexFree(sqlite3_mutex *pX){
  19531. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19532. assert( p->cnt==0 );
  19533. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  19534. sqlite3_free(p);
  19535. }else{
  19536. #ifdef SQLITE_ENABLE_API_ARMOR
  19537. (void)SQLITE_MISUSE_BKPT;
  19538. #endif
  19539. }
  19540. }
  19541. /*
  19542. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  19543. ** to enter a mutex. If another thread is already within the mutex,
  19544. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  19545. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  19546. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  19547. ** be entered multiple times by the same thread. In such cases the,
  19548. ** mutex must be exited an equal number of times before another thread
  19549. ** can enter. If the same thread tries to enter any other kind of mutex
  19550. ** more than once, the behavior is undefined.
  19551. */
  19552. static void debugMutexEnter(sqlite3_mutex *pX){
  19553. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19554. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19555. p->cnt++;
  19556. }
  19557. static int debugMutexTry(sqlite3_mutex *pX){
  19558. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19559. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19560. p->cnt++;
  19561. return SQLITE_OK;
  19562. }
  19563. /*
  19564. ** The sqlite3_mutex_leave() routine exits a mutex that was
  19565. ** previously entered by the same thread. The behavior
  19566. ** is undefined if the mutex is not currently entered or
  19567. ** is not currently allocated. SQLite will never do either.
  19568. */
  19569. static void debugMutexLeave(sqlite3_mutex *pX){
  19570. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  19571. assert( debugMutexHeld(pX) );
  19572. p->cnt--;
  19573. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  19574. }
  19575. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  19576. static const sqlite3_mutex_methods sMutex = {
  19577. debugMutexInit,
  19578. debugMutexEnd,
  19579. debugMutexAlloc,
  19580. debugMutexFree,
  19581. debugMutexEnter,
  19582. debugMutexTry,
  19583. debugMutexLeave,
  19584. debugMutexHeld,
  19585. debugMutexNotheld
  19586. };
  19587. return &sMutex;
  19588. }
  19589. #endif /* SQLITE_DEBUG */
  19590. /*
  19591. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  19592. ** is used regardless of the run-time threadsafety setting.
  19593. */
  19594. #ifdef SQLITE_MUTEX_NOOP
  19595. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  19596. return sqlite3NoopMutex();
  19597. }
  19598. #endif /* defined(SQLITE_MUTEX_NOOP) */
  19599. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  19600. /************** End of mutex_noop.c ******************************************/
  19601. /************** Begin file mutex_unix.c **************************************/
  19602. /*
  19603. ** 2007 August 28
  19604. **
  19605. ** The author disclaims copyright to this source code. In place of
  19606. ** a legal notice, here is a blessing:
  19607. **
  19608. ** May you do good and not evil.
  19609. ** May you find forgiveness for yourself and forgive others.
  19610. ** May you share freely, never taking more than you give.
  19611. **
  19612. *************************************************************************
  19613. ** This file contains the C functions that implement mutexes for pthreads
  19614. */
  19615. /* #include "sqliteInt.h" */
  19616. /*
  19617. ** The code in this file is only used if we are compiling threadsafe
  19618. ** under unix with pthreads.
  19619. **
  19620. ** Note that this implementation requires a version of pthreads that
  19621. ** supports recursive mutexes.
  19622. */
  19623. #ifdef SQLITE_MUTEX_PTHREADS
  19624. #include <pthread.h>
  19625. /*
  19626. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  19627. ** are necessary under two condidtions: (1) Debug builds and (2) using
  19628. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  19629. */
  19630. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  19631. # define SQLITE_MUTEX_NREF 1
  19632. #else
  19633. # define SQLITE_MUTEX_NREF 0
  19634. #endif
  19635. /*
  19636. ** Each recursive mutex is an instance of the following structure.
  19637. */
  19638. struct sqlite3_mutex {
  19639. pthread_mutex_t mutex; /* Mutex controlling the lock */
  19640. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  19641. int id; /* Mutex type */
  19642. #endif
  19643. #if SQLITE_MUTEX_NREF
  19644. volatile int nRef; /* Number of entrances */
  19645. volatile pthread_t owner; /* Thread that is within this mutex */
  19646. int trace; /* True to trace changes */
  19647. #endif
  19648. };
  19649. #if SQLITE_MUTEX_NREF
  19650. #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
  19651. #elif defined(SQLITE_ENABLE_API_ARMOR)
  19652. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
  19653. #else
  19654. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  19655. #endif
  19656. /*
  19657. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19658. ** intended for use only inside assert() statements. On some platforms,
  19659. ** there might be race conditions that can cause these routines to
  19660. ** deliver incorrect results. In particular, if pthread_equal() is
  19661. ** not an atomic operation, then these routines might delivery
  19662. ** incorrect results. On most platforms, pthread_equal() is a
  19663. ** comparison of two integers and is therefore atomic. But we are
  19664. ** told that HPUX is not such a platform. If so, then these routines
  19665. ** will not always work correctly on HPUX.
  19666. **
  19667. ** On those platforms where pthread_equal() is not atomic, SQLite
  19668. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  19669. ** make sure no assert() statements are evaluated and hence these
  19670. ** routines are never called.
  19671. */
  19672. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  19673. static int pthreadMutexHeld(sqlite3_mutex *p){
  19674. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  19675. }
  19676. static int pthreadMutexNotheld(sqlite3_mutex *p){
  19677. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  19678. }
  19679. #endif
  19680. /*
  19681. ** Try to provide a memory barrier operation, needed for initialization
  19682. ** and also for the implementation of xShmBarrier in the VFS in cases
  19683. ** where SQLite is compiled without mutexes.
  19684. */
  19685. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  19686. #if defined(SQLITE_MEMORY_BARRIER)
  19687. SQLITE_MEMORY_BARRIER;
  19688. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  19689. __sync_synchronize();
  19690. #endif
  19691. }
  19692. /*
  19693. ** Initialize and deinitialize the mutex subsystem.
  19694. */
  19695. static int pthreadMutexInit(void){ return SQLITE_OK; }
  19696. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  19697. /*
  19698. ** The sqlite3_mutex_alloc() routine allocates a new
  19699. ** mutex and returns a pointer to it. If it returns NULL
  19700. ** that means that a mutex could not be allocated. SQLite
  19701. ** will unwind its stack and return an error. The argument
  19702. ** to sqlite3_mutex_alloc() is one of these integer constants:
  19703. **
  19704. ** <ul>
  19705. ** <li> SQLITE_MUTEX_FAST
  19706. ** <li> SQLITE_MUTEX_RECURSIVE
  19707. ** <li> SQLITE_MUTEX_STATIC_MASTER
  19708. ** <li> SQLITE_MUTEX_STATIC_MEM
  19709. ** <li> SQLITE_MUTEX_STATIC_OPEN
  19710. ** <li> SQLITE_MUTEX_STATIC_PRNG
  19711. ** <li> SQLITE_MUTEX_STATIC_LRU
  19712. ** <li> SQLITE_MUTEX_STATIC_PMEM
  19713. ** <li> SQLITE_MUTEX_STATIC_APP1
  19714. ** <li> SQLITE_MUTEX_STATIC_APP2
  19715. ** <li> SQLITE_MUTEX_STATIC_APP3
  19716. ** <li> SQLITE_MUTEX_STATIC_VFS1
  19717. ** <li> SQLITE_MUTEX_STATIC_VFS2
  19718. ** <li> SQLITE_MUTEX_STATIC_VFS3
  19719. ** </ul>
  19720. **
  19721. ** The first two constants cause sqlite3_mutex_alloc() to create
  19722. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  19723. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  19724. ** The mutex implementation does not need to make a distinction
  19725. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  19726. ** not want to. But SQLite will only request a recursive mutex in
  19727. ** cases where it really needs one. If a faster non-recursive mutex
  19728. ** implementation is available on the host platform, the mutex subsystem
  19729. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  19730. **
  19731. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  19732. ** a pointer to a static preexisting mutex. Six static mutexes are
  19733. ** used by the current version of SQLite. Future versions of SQLite
  19734. ** may add additional static mutexes. Static mutexes are for internal
  19735. ** use by SQLite only. Applications that use SQLite mutexes should
  19736. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  19737. ** SQLITE_MUTEX_RECURSIVE.
  19738. **
  19739. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  19740. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  19741. ** returns a different mutex on every call. But for the static
  19742. ** mutex types, the same mutex is returned on every call that has
  19743. ** the same type number.
  19744. */
  19745. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  19746. static sqlite3_mutex staticMutexes[] = {
  19747. SQLITE3_MUTEX_INITIALIZER,
  19748. SQLITE3_MUTEX_INITIALIZER,
  19749. SQLITE3_MUTEX_INITIALIZER,
  19750. SQLITE3_MUTEX_INITIALIZER,
  19751. SQLITE3_MUTEX_INITIALIZER,
  19752. SQLITE3_MUTEX_INITIALIZER,
  19753. SQLITE3_MUTEX_INITIALIZER,
  19754. SQLITE3_MUTEX_INITIALIZER,
  19755. SQLITE3_MUTEX_INITIALIZER,
  19756. SQLITE3_MUTEX_INITIALIZER,
  19757. SQLITE3_MUTEX_INITIALIZER,
  19758. SQLITE3_MUTEX_INITIALIZER
  19759. };
  19760. sqlite3_mutex *p;
  19761. switch( iType ){
  19762. case SQLITE_MUTEX_RECURSIVE: {
  19763. p = sqlite3MallocZero( sizeof(*p) );
  19764. if( p ){
  19765. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  19766. /* If recursive mutexes are not available, we will have to
  19767. ** build our own. See below. */
  19768. pthread_mutex_init(&p->mutex, 0);
  19769. #else
  19770. /* Use a recursive mutex if it is available */
  19771. pthread_mutexattr_t recursiveAttr;
  19772. pthread_mutexattr_init(&recursiveAttr);
  19773. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  19774. pthread_mutex_init(&p->mutex, &recursiveAttr);
  19775. pthread_mutexattr_destroy(&recursiveAttr);
  19776. #endif
  19777. }
  19778. break;
  19779. }
  19780. case SQLITE_MUTEX_FAST: {
  19781. p = sqlite3MallocZero( sizeof(*p) );
  19782. if( p ){
  19783. pthread_mutex_init(&p->mutex, 0);
  19784. }
  19785. break;
  19786. }
  19787. default: {
  19788. #ifdef SQLITE_ENABLE_API_ARMOR
  19789. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  19790. (void)SQLITE_MISUSE_BKPT;
  19791. return 0;
  19792. }
  19793. #endif
  19794. p = &staticMutexes[iType-2];
  19795. break;
  19796. }
  19797. }
  19798. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  19799. if( p ) p->id = iType;
  19800. #endif
  19801. return p;
  19802. }
  19803. /*
  19804. ** This routine deallocates a previously
  19805. ** allocated mutex. SQLite is careful to deallocate every
  19806. ** mutex that it allocates.
  19807. */
  19808. static void pthreadMutexFree(sqlite3_mutex *p){
  19809. assert( p->nRef==0 );
  19810. #if SQLITE_ENABLE_API_ARMOR
  19811. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  19812. #endif
  19813. {
  19814. pthread_mutex_destroy(&p->mutex);
  19815. sqlite3_free(p);
  19816. }
  19817. #ifdef SQLITE_ENABLE_API_ARMOR
  19818. else{
  19819. (void)SQLITE_MISUSE_BKPT;
  19820. }
  19821. #endif
  19822. }
  19823. /*
  19824. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  19825. ** to enter a mutex. If another thread is already within the mutex,
  19826. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  19827. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  19828. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  19829. ** be entered multiple times by the same thread. In such cases the,
  19830. ** mutex must be exited an equal number of times before another thread
  19831. ** can enter. If the same thread tries to enter any other kind of mutex
  19832. ** more than once, the behavior is undefined.
  19833. */
  19834. static void pthreadMutexEnter(sqlite3_mutex *p){
  19835. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  19836. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  19837. /* If recursive mutexes are not available, then we have to grow
  19838. ** our own. This implementation assumes that pthread_equal()
  19839. ** is atomic - that it cannot be deceived into thinking self
  19840. ** and p->owner are equal if p->owner changes between two values
  19841. ** that are not equal to self while the comparison is taking place.
  19842. ** This implementation also assumes a coherent cache - that
  19843. ** separate processes cannot read different values from the same
  19844. ** address at the same time. If either of these two conditions
  19845. ** are not met, then the mutexes will fail and problems will result.
  19846. */
  19847. {
  19848. pthread_t self = pthread_self();
  19849. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  19850. p->nRef++;
  19851. }else{
  19852. pthread_mutex_lock(&p->mutex);
  19853. assert( p->nRef==0 );
  19854. p->owner = self;
  19855. p->nRef = 1;
  19856. }
  19857. }
  19858. #else
  19859. /* Use the built-in recursive mutexes if they are available.
  19860. */
  19861. pthread_mutex_lock(&p->mutex);
  19862. #if SQLITE_MUTEX_NREF
  19863. assert( p->nRef>0 || p->owner==0 );
  19864. p->owner = pthread_self();
  19865. p->nRef++;
  19866. #endif
  19867. #endif
  19868. #ifdef SQLITE_DEBUG
  19869. if( p->trace ){
  19870. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  19871. }
  19872. #endif
  19873. }
  19874. static int pthreadMutexTry(sqlite3_mutex *p){
  19875. int rc;
  19876. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  19877. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  19878. /* If recursive mutexes are not available, then we have to grow
  19879. ** our own. This implementation assumes that pthread_equal()
  19880. ** is atomic - that it cannot be deceived into thinking self
  19881. ** and p->owner are equal if p->owner changes between two values
  19882. ** that are not equal to self while the comparison is taking place.
  19883. ** This implementation also assumes a coherent cache - that
  19884. ** separate processes cannot read different values from the same
  19885. ** address at the same time. If either of these two conditions
  19886. ** are not met, then the mutexes will fail and problems will result.
  19887. */
  19888. {
  19889. pthread_t self = pthread_self();
  19890. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  19891. p->nRef++;
  19892. rc = SQLITE_OK;
  19893. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  19894. assert( p->nRef==0 );
  19895. p->owner = self;
  19896. p->nRef = 1;
  19897. rc = SQLITE_OK;
  19898. }else{
  19899. rc = SQLITE_BUSY;
  19900. }
  19901. }
  19902. #else
  19903. /* Use the built-in recursive mutexes if they are available.
  19904. */
  19905. if( pthread_mutex_trylock(&p->mutex)==0 ){
  19906. #if SQLITE_MUTEX_NREF
  19907. p->owner = pthread_self();
  19908. p->nRef++;
  19909. #endif
  19910. rc = SQLITE_OK;
  19911. }else{
  19912. rc = SQLITE_BUSY;
  19913. }
  19914. #endif
  19915. #ifdef SQLITE_DEBUG
  19916. if( rc==SQLITE_OK && p->trace ){
  19917. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  19918. }
  19919. #endif
  19920. return rc;
  19921. }
  19922. /*
  19923. ** The sqlite3_mutex_leave() routine exits a mutex that was
  19924. ** previously entered by the same thread. The behavior
  19925. ** is undefined if the mutex is not currently entered or
  19926. ** is not currently allocated. SQLite will never do either.
  19927. */
  19928. static void pthreadMutexLeave(sqlite3_mutex *p){
  19929. assert( pthreadMutexHeld(p) );
  19930. #if SQLITE_MUTEX_NREF
  19931. p->nRef--;
  19932. if( p->nRef==0 ) p->owner = 0;
  19933. #endif
  19934. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  19935. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  19936. if( p->nRef==0 ){
  19937. pthread_mutex_unlock(&p->mutex);
  19938. }
  19939. #else
  19940. pthread_mutex_unlock(&p->mutex);
  19941. #endif
  19942. #ifdef SQLITE_DEBUG
  19943. if( p->trace ){
  19944. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  19945. }
  19946. #endif
  19947. }
  19948. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  19949. static const sqlite3_mutex_methods sMutex = {
  19950. pthreadMutexInit,
  19951. pthreadMutexEnd,
  19952. pthreadMutexAlloc,
  19953. pthreadMutexFree,
  19954. pthreadMutexEnter,
  19955. pthreadMutexTry,
  19956. pthreadMutexLeave,
  19957. #ifdef SQLITE_DEBUG
  19958. pthreadMutexHeld,
  19959. pthreadMutexNotheld
  19960. #else
  19961. 0,
  19962. 0
  19963. #endif
  19964. };
  19965. return &sMutex;
  19966. }
  19967. #endif /* SQLITE_MUTEX_PTHREADS */
  19968. /************** End of mutex_unix.c ******************************************/
  19969. /************** Begin file mutex_w32.c ***************************************/
  19970. /*
  19971. ** 2007 August 14
  19972. **
  19973. ** The author disclaims copyright to this source code. In place of
  19974. ** a legal notice, here is a blessing:
  19975. **
  19976. ** May you do good and not evil.
  19977. ** May you find forgiveness for yourself and forgive others.
  19978. ** May you share freely, never taking more than you give.
  19979. **
  19980. *************************************************************************
  19981. ** This file contains the C functions that implement mutexes for Win32.
  19982. */
  19983. /* #include "sqliteInt.h" */
  19984. #if SQLITE_OS_WIN
  19985. /*
  19986. ** Include code that is common to all os_*.c files
  19987. */
  19988. /************** Include os_common.h in the middle of mutex_w32.c *************/
  19989. /************** Begin file os_common.h ***************************************/
  19990. /*
  19991. ** 2004 May 22
  19992. **
  19993. ** The author disclaims copyright to this source code. In place of
  19994. ** a legal notice, here is a blessing:
  19995. **
  19996. ** May you do good and not evil.
  19997. ** May you find forgiveness for yourself and forgive others.
  19998. ** May you share freely, never taking more than you give.
  19999. **
  20000. ******************************************************************************
  20001. **
  20002. ** This file contains macros and a little bit of code that is common to
  20003. ** all of the platform-specific files (os_*.c) and is #included into those
  20004. ** files.
  20005. **
  20006. ** This file should be #included by the os_*.c files only. It is not a
  20007. ** general purpose header file.
  20008. */
  20009. #ifndef _OS_COMMON_H_
  20010. #define _OS_COMMON_H_
  20011. /*
  20012. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  20013. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  20014. ** switch. The following code should catch this problem at compile-time.
  20015. */
  20016. #ifdef MEMORY_DEBUG
  20017. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  20018. #endif
  20019. /*
  20020. ** Macros for performance tracing. Normally turned off. Only works
  20021. ** on i486 hardware.
  20022. */
  20023. #ifdef SQLITE_PERFORMANCE_TRACE
  20024. /*
  20025. ** hwtime.h contains inline assembler code for implementing
  20026. ** high-performance timing routines.
  20027. */
  20028. /************** Include hwtime.h in the middle of os_common.h ****************/
  20029. /************** Begin file hwtime.h ******************************************/
  20030. /*
  20031. ** 2008 May 27
  20032. **
  20033. ** The author disclaims copyright to this source code. In place of
  20034. ** a legal notice, here is a blessing:
  20035. **
  20036. ** May you do good and not evil.
  20037. ** May you find forgiveness for yourself and forgive others.
  20038. ** May you share freely, never taking more than you give.
  20039. **
  20040. ******************************************************************************
  20041. **
  20042. ** This file contains inline asm code for retrieving "high-performance"
  20043. ** counters for x86 class CPUs.
  20044. */
  20045. #ifndef _HWTIME_H_
  20046. #define _HWTIME_H_
  20047. /*
  20048. ** The following routine only works on pentium-class (or newer) processors.
  20049. ** It uses the RDTSC opcode to read the cycle count value out of the
  20050. ** processor and returns that value. This can be used for high-res
  20051. ** profiling.
  20052. */
  20053. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  20054. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  20055. #if defined(__GNUC__)
  20056. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20057. unsigned int lo, hi;
  20058. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  20059. return (sqlite_uint64)hi << 32 | lo;
  20060. }
  20061. #elif defined(_MSC_VER)
  20062. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  20063. __asm {
  20064. rdtsc
  20065. ret ; return value at EDX:EAX
  20066. }
  20067. }
  20068. #endif
  20069. #elif (defined(__GNUC__) && defined(__x86_64__))
  20070. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20071. unsigned long val;
  20072. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  20073. return val;
  20074. }
  20075. #elif (defined(__GNUC__) && defined(__ppc__))
  20076. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20077. unsigned long long retval;
  20078. unsigned long junk;
  20079. __asm__ __volatile__ ("\n\
  20080. 1: mftbu %1\n\
  20081. mftb %L0\n\
  20082. mftbu %0\n\
  20083. cmpw %0,%1\n\
  20084. bne 1b"
  20085. : "=r" (retval), "=r" (junk));
  20086. return retval;
  20087. }
  20088. #else
  20089. #error Need implementation of sqlite3Hwtime() for your platform.
  20090. /*
  20091. ** To compile without implementing sqlite3Hwtime() for your platform,
  20092. ** you can remove the above #error and use the following
  20093. ** stub function. You will lose timing support for many
  20094. ** of the debugging and testing utilities, but it should at
  20095. ** least compile and run.
  20096. */
  20097. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  20098. #endif
  20099. #endif /* !defined(_HWTIME_H_) */
  20100. /************** End of hwtime.h **********************************************/
  20101. /************** Continuing where we left off in os_common.h ******************/
  20102. static sqlite_uint64 g_start;
  20103. static sqlite_uint64 g_elapsed;
  20104. #define TIMER_START g_start=sqlite3Hwtime()
  20105. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  20106. #define TIMER_ELAPSED g_elapsed
  20107. #else
  20108. #define TIMER_START
  20109. #define TIMER_END
  20110. #define TIMER_ELAPSED ((sqlite_uint64)0)
  20111. #endif
  20112. /*
  20113. ** If we compile with the SQLITE_TEST macro set, then the following block
  20114. ** of code will give us the ability to simulate a disk I/O error. This
  20115. ** is used for testing the I/O recovery logic.
  20116. */
  20117. #ifdef SQLITE_TEST
  20118. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  20119. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  20120. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  20121. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  20122. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  20123. SQLITE_API int sqlite3_diskfull_pending = 0;
  20124. SQLITE_API int sqlite3_diskfull = 0;
  20125. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  20126. #define SimulateIOError(CODE) \
  20127. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  20128. || sqlite3_io_error_pending-- == 1 ) \
  20129. { local_ioerr(); CODE; }
  20130. static void local_ioerr(){
  20131. IOTRACE(("IOERR\n"));
  20132. sqlite3_io_error_hit++;
  20133. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  20134. }
  20135. #define SimulateDiskfullError(CODE) \
  20136. if( sqlite3_diskfull_pending ){ \
  20137. if( sqlite3_diskfull_pending == 1 ){ \
  20138. local_ioerr(); \
  20139. sqlite3_diskfull = 1; \
  20140. sqlite3_io_error_hit = 1; \
  20141. CODE; \
  20142. }else{ \
  20143. sqlite3_diskfull_pending--; \
  20144. } \
  20145. }
  20146. #else
  20147. #define SimulateIOErrorBenign(X)
  20148. #define SimulateIOError(A)
  20149. #define SimulateDiskfullError(A)
  20150. #endif
  20151. /*
  20152. ** When testing, keep a count of the number of open files.
  20153. */
  20154. #ifdef SQLITE_TEST
  20155. SQLITE_API int sqlite3_open_file_count = 0;
  20156. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  20157. #else
  20158. #define OpenCounter(X)
  20159. #endif
  20160. #endif /* !defined(_OS_COMMON_H_) */
  20161. /************** End of os_common.h *******************************************/
  20162. /************** Continuing where we left off in mutex_w32.c ******************/
  20163. /*
  20164. ** Include the header file for the Windows VFS.
  20165. */
  20166. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  20167. /************** Begin file os_win.h ******************************************/
  20168. /*
  20169. ** 2013 November 25
  20170. **
  20171. ** The author disclaims copyright to this source code. In place of
  20172. ** a legal notice, here is a blessing:
  20173. **
  20174. ** May you do good and not evil.
  20175. ** May you find forgiveness for yourself and forgive others.
  20176. ** May you share freely, never taking more than you give.
  20177. **
  20178. ******************************************************************************
  20179. **
  20180. ** This file contains code that is specific to Windows.
  20181. */
  20182. #ifndef _OS_WIN_H_
  20183. #define _OS_WIN_H_
  20184. /*
  20185. ** Include the primary Windows SDK header file.
  20186. */
  20187. #include "windows.h"
  20188. #ifdef __CYGWIN__
  20189. # include <sys/cygwin.h>
  20190. # include <errno.h> /* amalgamator: dontcache */
  20191. #endif
  20192. /*
  20193. ** Determine if we are dealing with Windows NT.
  20194. **
  20195. ** We ought to be able to determine if we are compiling for Windows 9x or
  20196. ** Windows NT using the _WIN32_WINNT macro as follows:
  20197. **
  20198. ** #if defined(_WIN32_WINNT)
  20199. ** # define SQLITE_OS_WINNT 1
  20200. ** #else
  20201. ** # define SQLITE_OS_WINNT 0
  20202. ** #endif
  20203. **
  20204. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  20205. ** it ought to, so the above test does not work. We'll just assume that
  20206. ** everything is Windows NT unless the programmer explicitly says otherwise
  20207. ** by setting SQLITE_OS_WINNT to 0.
  20208. */
  20209. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  20210. # define SQLITE_OS_WINNT 1
  20211. #endif
  20212. /*
  20213. ** Determine if we are dealing with Windows CE - which has a much reduced
  20214. ** API.
  20215. */
  20216. #if defined(_WIN32_WCE)
  20217. # define SQLITE_OS_WINCE 1
  20218. #else
  20219. # define SQLITE_OS_WINCE 0
  20220. #endif
  20221. /*
  20222. ** Determine if we are dealing with WinRT, which provides only a subset of
  20223. ** the full Win32 API.
  20224. */
  20225. #if !defined(SQLITE_OS_WINRT)
  20226. # define SQLITE_OS_WINRT 0
  20227. #endif
  20228. /*
  20229. ** For WinCE, some API function parameters do not appear to be declared as
  20230. ** volatile.
  20231. */
  20232. #if SQLITE_OS_WINCE
  20233. # define SQLITE_WIN32_VOLATILE
  20234. #else
  20235. # define SQLITE_WIN32_VOLATILE volatile
  20236. #endif
  20237. /*
  20238. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  20239. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  20240. */
  20241. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  20242. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  20243. # define SQLITE_OS_WIN_THREADS 1
  20244. #else
  20245. # define SQLITE_OS_WIN_THREADS 0
  20246. #endif
  20247. #endif /* _OS_WIN_H_ */
  20248. /************** End of os_win.h **********************************************/
  20249. /************** Continuing where we left off in mutex_w32.c ******************/
  20250. #endif
  20251. /*
  20252. ** The code in this file is only used if we are compiling multithreaded
  20253. ** on a Win32 system.
  20254. */
  20255. #ifdef SQLITE_MUTEX_W32
  20256. /*
  20257. ** Each recursive mutex is an instance of the following structure.
  20258. */
  20259. struct sqlite3_mutex {
  20260. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  20261. int id; /* Mutex type */
  20262. #ifdef SQLITE_DEBUG
  20263. volatile int nRef; /* Number of enterances */
  20264. volatile DWORD owner; /* Thread holding this mutex */
  20265. volatile int trace; /* True to trace changes */
  20266. #endif
  20267. };
  20268. /*
  20269. ** These are the initializer values used when declaring a "static" mutex
  20270. ** on Win32. It should be noted that all mutexes require initialization
  20271. ** on the Win32 platform.
  20272. */
  20273. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  20274. #ifdef SQLITE_DEBUG
  20275. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  20276. 0L, (DWORD)0, 0 }
  20277. #else
  20278. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  20279. #endif
  20280. #ifdef SQLITE_DEBUG
  20281. /*
  20282. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  20283. ** intended for use only inside assert() statements.
  20284. */
  20285. static int winMutexHeld(sqlite3_mutex *p){
  20286. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  20287. }
  20288. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  20289. return p->nRef==0 || p->owner!=tid;
  20290. }
  20291. static int winMutexNotheld(sqlite3_mutex *p){
  20292. DWORD tid = GetCurrentThreadId();
  20293. return winMutexNotheld2(p, tid);
  20294. }
  20295. #endif
  20296. /*
  20297. ** Try to provide a memory barrier operation, needed for initialization
  20298. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  20299. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  20300. */
  20301. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  20302. #if defined(SQLITE_MEMORY_BARRIER)
  20303. SQLITE_MEMORY_BARRIER;
  20304. #elif defined(__GNUC__)
  20305. __sync_synchronize();
  20306. #elif !defined(SQLITE_DISABLE_INTRINSIC) && \
  20307. defined(_MSC_VER) && _MSC_VER>=1300
  20308. _ReadWriteBarrier();
  20309. #elif defined(MemoryBarrier)
  20310. MemoryBarrier();
  20311. #endif
  20312. }
  20313. /*
  20314. ** Initialize and deinitialize the mutex subsystem.
  20315. */
  20316. static sqlite3_mutex winMutex_staticMutexes[] = {
  20317. SQLITE3_MUTEX_INITIALIZER,
  20318. SQLITE3_MUTEX_INITIALIZER,
  20319. SQLITE3_MUTEX_INITIALIZER,
  20320. SQLITE3_MUTEX_INITIALIZER,
  20321. SQLITE3_MUTEX_INITIALIZER,
  20322. SQLITE3_MUTEX_INITIALIZER,
  20323. SQLITE3_MUTEX_INITIALIZER,
  20324. SQLITE3_MUTEX_INITIALIZER,
  20325. SQLITE3_MUTEX_INITIALIZER,
  20326. SQLITE3_MUTEX_INITIALIZER,
  20327. SQLITE3_MUTEX_INITIALIZER,
  20328. SQLITE3_MUTEX_INITIALIZER
  20329. };
  20330. static int winMutex_isInit = 0;
  20331. static int winMutex_isNt = -1; /* <0 means "need to query" */
  20332. /* As the winMutexInit() and winMutexEnd() functions are called as part
  20333. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  20334. ** "interlocked" magic used here is probably not strictly necessary.
  20335. */
  20336. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  20337. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
  20338. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  20339. static int winMutexInit(void){
  20340. /* The first to increment to 1 does actual initialization */
  20341. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  20342. int i;
  20343. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  20344. #if SQLITE_OS_WINRT
  20345. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  20346. #else
  20347. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  20348. #endif
  20349. }
  20350. winMutex_isInit = 1;
  20351. }else{
  20352. /* Another thread is (in the process of) initializing the static
  20353. ** mutexes */
  20354. while( !winMutex_isInit ){
  20355. sqlite3_win32_sleep(1);
  20356. }
  20357. }
  20358. return SQLITE_OK;
  20359. }
  20360. static int winMutexEnd(void){
  20361. /* The first to decrement to 0 does actual shutdown
  20362. ** (which should be the last to shutdown.) */
  20363. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  20364. if( winMutex_isInit==1 ){
  20365. int i;
  20366. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  20367. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  20368. }
  20369. winMutex_isInit = 0;
  20370. }
  20371. }
  20372. return SQLITE_OK;
  20373. }
  20374. /*
  20375. ** The sqlite3_mutex_alloc() routine allocates a new
  20376. ** mutex and returns a pointer to it. If it returns NULL
  20377. ** that means that a mutex could not be allocated. SQLite
  20378. ** will unwind its stack and return an error. The argument
  20379. ** to sqlite3_mutex_alloc() is one of these integer constants:
  20380. **
  20381. ** <ul>
  20382. ** <li> SQLITE_MUTEX_FAST
  20383. ** <li> SQLITE_MUTEX_RECURSIVE
  20384. ** <li> SQLITE_MUTEX_STATIC_MASTER
  20385. ** <li> SQLITE_MUTEX_STATIC_MEM
  20386. ** <li> SQLITE_MUTEX_STATIC_OPEN
  20387. ** <li> SQLITE_MUTEX_STATIC_PRNG
  20388. ** <li> SQLITE_MUTEX_STATIC_LRU
  20389. ** <li> SQLITE_MUTEX_STATIC_PMEM
  20390. ** <li> SQLITE_MUTEX_STATIC_APP1
  20391. ** <li> SQLITE_MUTEX_STATIC_APP2
  20392. ** <li> SQLITE_MUTEX_STATIC_APP3
  20393. ** <li> SQLITE_MUTEX_STATIC_VFS1
  20394. ** <li> SQLITE_MUTEX_STATIC_VFS2
  20395. ** <li> SQLITE_MUTEX_STATIC_VFS3
  20396. ** </ul>
  20397. **
  20398. ** The first two constants cause sqlite3_mutex_alloc() to create
  20399. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  20400. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  20401. ** The mutex implementation does not need to make a distinction
  20402. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  20403. ** not want to. But SQLite will only request a recursive mutex in
  20404. ** cases where it really needs one. If a faster non-recursive mutex
  20405. ** implementation is available on the host platform, the mutex subsystem
  20406. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  20407. **
  20408. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  20409. ** a pointer to a static preexisting mutex. Six static mutexes are
  20410. ** used by the current version of SQLite. Future versions of SQLite
  20411. ** may add additional static mutexes. Static mutexes are for internal
  20412. ** use by SQLite only. Applications that use SQLite mutexes should
  20413. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  20414. ** SQLITE_MUTEX_RECURSIVE.
  20415. **
  20416. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  20417. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  20418. ** returns a different mutex on every call. But for the static
  20419. ** mutex types, the same mutex is returned on every call that has
  20420. ** the same type number.
  20421. */
  20422. static sqlite3_mutex *winMutexAlloc(int iType){
  20423. sqlite3_mutex *p;
  20424. switch( iType ){
  20425. case SQLITE_MUTEX_FAST:
  20426. case SQLITE_MUTEX_RECURSIVE: {
  20427. p = sqlite3MallocZero( sizeof(*p) );
  20428. if( p ){
  20429. p->id = iType;
  20430. #ifdef SQLITE_DEBUG
  20431. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  20432. p->trace = 1;
  20433. #endif
  20434. #endif
  20435. #if SQLITE_OS_WINRT
  20436. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  20437. #else
  20438. InitializeCriticalSection(&p->mutex);
  20439. #endif
  20440. }
  20441. break;
  20442. }
  20443. default: {
  20444. #ifdef SQLITE_ENABLE_API_ARMOR
  20445. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  20446. (void)SQLITE_MISUSE_BKPT;
  20447. return 0;
  20448. }
  20449. #endif
  20450. p = &winMutex_staticMutexes[iType-2];
  20451. p->id = iType;
  20452. #ifdef SQLITE_DEBUG
  20453. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  20454. p->trace = 1;
  20455. #endif
  20456. #endif
  20457. break;
  20458. }
  20459. }
  20460. return p;
  20461. }
  20462. /*
  20463. ** This routine deallocates a previously
  20464. ** allocated mutex. SQLite is careful to deallocate every
  20465. ** mutex that it allocates.
  20466. */
  20467. static void winMutexFree(sqlite3_mutex *p){
  20468. assert( p );
  20469. assert( p->nRef==0 && p->owner==0 );
  20470. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  20471. DeleteCriticalSection(&p->mutex);
  20472. sqlite3_free(p);
  20473. }else{
  20474. #ifdef SQLITE_ENABLE_API_ARMOR
  20475. (void)SQLITE_MISUSE_BKPT;
  20476. #endif
  20477. }
  20478. }
  20479. /*
  20480. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  20481. ** to enter a mutex. If another thread is already within the mutex,
  20482. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  20483. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  20484. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  20485. ** be entered multiple times by the same thread. In such cases the,
  20486. ** mutex must be exited an equal number of times before another thread
  20487. ** can enter. If the same thread tries to enter any other kind of mutex
  20488. ** more than once, the behavior is undefined.
  20489. */
  20490. static void winMutexEnter(sqlite3_mutex *p){
  20491. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20492. DWORD tid = GetCurrentThreadId();
  20493. #endif
  20494. #ifdef SQLITE_DEBUG
  20495. assert( p );
  20496. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  20497. #else
  20498. assert( p );
  20499. #endif
  20500. assert( winMutex_isInit==1 );
  20501. EnterCriticalSection(&p->mutex);
  20502. #ifdef SQLITE_DEBUG
  20503. assert( p->nRef>0 || p->owner==0 );
  20504. p->owner = tid;
  20505. p->nRef++;
  20506. if( p->trace ){
  20507. OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  20508. tid, p, p->trace, p->nRef));
  20509. }
  20510. #endif
  20511. }
  20512. static int winMutexTry(sqlite3_mutex *p){
  20513. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20514. DWORD tid = GetCurrentThreadId();
  20515. #endif
  20516. int rc = SQLITE_BUSY;
  20517. assert( p );
  20518. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  20519. /*
  20520. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  20521. ** is used it is merely an optimization. So it is OK for it to always
  20522. ** fail.
  20523. **
  20524. ** The TryEnterCriticalSection() interface is only available on WinNT.
  20525. ** And some windows compilers complain if you try to use it without
  20526. ** first doing some #defines that prevent SQLite from building on Win98.
  20527. ** For that reason, we will omit this optimization for now. See
  20528. ** ticket #2685.
  20529. */
  20530. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  20531. assert( winMutex_isInit==1 );
  20532. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  20533. if( winMutex_isNt<0 ){
  20534. winMutex_isNt = sqlite3_win32_is_nt();
  20535. }
  20536. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  20537. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  20538. #ifdef SQLITE_DEBUG
  20539. p->owner = tid;
  20540. p->nRef++;
  20541. #endif
  20542. rc = SQLITE_OK;
  20543. }
  20544. #else
  20545. UNUSED_PARAMETER(p);
  20546. #endif
  20547. #ifdef SQLITE_DEBUG
  20548. if( p->trace ){
  20549. OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  20550. tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  20551. }
  20552. #endif
  20553. return rc;
  20554. }
  20555. /*
  20556. ** The sqlite3_mutex_leave() routine exits a mutex that was
  20557. ** previously entered by the same thread. The behavior
  20558. ** is undefined if the mutex is not currently entered or
  20559. ** is not currently allocated. SQLite will never do either.
  20560. */
  20561. static void winMutexLeave(sqlite3_mutex *p){
  20562. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  20563. DWORD tid = GetCurrentThreadId();
  20564. #endif
  20565. assert( p );
  20566. #ifdef SQLITE_DEBUG
  20567. assert( p->nRef>0 );
  20568. assert( p->owner==tid );
  20569. p->nRef--;
  20570. if( p->nRef==0 ) p->owner = 0;
  20571. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  20572. #endif
  20573. assert( winMutex_isInit==1 );
  20574. LeaveCriticalSection(&p->mutex);
  20575. #ifdef SQLITE_DEBUG
  20576. if( p->trace ){
  20577. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  20578. tid, p, p->trace, p->nRef));
  20579. }
  20580. #endif
  20581. }
  20582. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  20583. static const sqlite3_mutex_methods sMutex = {
  20584. winMutexInit,
  20585. winMutexEnd,
  20586. winMutexAlloc,
  20587. winMutexFree,
  20588. winMutexEnter,
  20589. winMutexTry,
  20590. winMutexLeave,
  20591. #ifdef SQLITE_DEBUG
  20592. winMutexHeld,
  20593. winMutexNotheld
  20594. #else
  20595. 0,
  20596. 0
  20597. #endif
  20598. };
  20599. return &sMutex;
  20600. }
  20601. #endif /* SQLITE_MUTEX_W32 */
  20602. /************** End of mutex_w32.c *******************************************/
  20603. /************** Begin file malloc.c ******************************************/
  20604. /*
  20605. ** 2001 September 15
  20606. **
  20607. ** The author disclaims copyright to this source code. In place of
  20608. ** a legal notice, here is a blessing:
  20609. **
  20610. ** May you do good and not evil.
  20611. ** May you find forgiveness for yourself and forgive others.
  20612. ** May you share freely, never taking more than you give.
  20613. **
  20614. *************************************************************************
  20615. **
  20616. ** Memory allocation functions used throughout sqlite.
  20617. */
  20618. /* #include "sqliteInt.h" */
  20619. /* #include <stdarg.h> */
  20620. /*
  20621. ** Attempt to release up to n bytes of non-essential memory currently
  20622. ** held by SQLite. An example of non-essential memory is memory used to
  20623. ** cache database pages that are not currently in use.
  20624. */
  20625. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
  20626. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  20627. return sqlite3PcacheReleaseMemory(n);
  20628. #else
  20629. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  20630. ** is a no-op returning zero if SQLite is not compiled with
  20631. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  20632. UNUSED_PARAMETER(n);
  20633. return 0;
  20634. #endif
  20635. }
  20636. /*
  20637. ** An instance of the following object records the location of
  20638. ** each unused scratch buffer.
  20639. */
  20640. typedef struct ScratchFreeslot {
  20641. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  20642. } ScratchFreeslot;
  20643. /*
  20644. ** State information local to the memory allocation subsystem.
  20645. */
  20646. static SQLITE_WSD struct Mem0Global {
  20647. sqlite3_mutex *mutex; /* Mutex to serialize access */
  20648. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  20649. /*
  20650. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  20651. ** (so that a range test can be used to determine if an allocation
  20652. ** being freed came from pScratch) and a pointer to the list of
  20653. ** unused scratch allocations.
  20654. */
  20655. void *pScratchEnd;
  20656. ScratchFreeslot *pScratchFree;
  20657. u32 nScratchFree;
  20658. /*
  20659. ** True if heap is nearly "full" where "full" is defined by the
  20660. ** sqlite3_soft_heap_limit() setting.
  20661. */
  20662. int nearlyFull;
  20663. } mem0 = { 0, 0, 0, 0, 0, 0 };
  20664. #define mem0 GLOBAL(struct Mem0Global, mem0)
  20665. /*
  20666. ** Return the memory allocator mutex. sqlite3_status() needs it.
  20667. */
  20668. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  20669. return mem0.mutex;
  20670. }
  20671. #ifndef SQLITE_OMIT_DEPRECATED
  20672. /*
  20673. ** Deprecated external interface. It used to set an alarm callback
  20674. ** that was invoked when memory usage grew too large. Now it is a
  20675. ** no-op.
  20676. */
  20677. SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
  20678. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  20679. void *pArg,
  20680. sqlite3_int64 iThreshold
  20681. ){
  20682. (void)xCallback;
  20683. (void)pArg;
  20684. (void)iThreshold;
  20685. return SQLITE_OK;
  20686. }
  20687. #endif
  20688. /*
  20689. ** Set the soft heap-size limit for the library. Passing a zero or
  20690. ** negative value indicates no limit.
  20691. */
  20692. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
  20693. sqlite3_int64 priorLimit;
  20694. sqlite3_int64 excess;
  20695. sqlite3_int64 nUsed;
  20696. #ifndef SQLITE_OMIT_AUTOINIT
  20697. int rc = sqlite3_initialize();
  20698. if( rc ) return -1;
  20699. #endif
  20700. sqlite3_mutex_enter(mem0.mutex);
  20701. priorLimit = mem0.alarmThreshold;
  20702. if( n<0 ){
  20703. sqlite3_mutex_leave(mem0.mutex);
  20704. return priorLimit;
  20705. }
  20706. mem0.alarmThreshold = n;
  20707. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  20708. mem0.nearlyFull = (n>0 && n<=nUsed);
  20709. sqlite3_mutex_leave(mem0.mutex);
  20710. excess = sqlite3_memory_used() - n;
  20711. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  20712. return priorLimit;
  20713. }
  20714. SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
  20715. if( n<0 ) n = 0;
  20716. sqlite3_soft_heap_limit64(n);
  20717. }
  20718. /*
  20719. ** Initialize the memory allocation subsystem.
  20720. */
  20721. SQLITE_PRIVATE int sqlite3MallocInit(void){
  20722. int rc;
  20723. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  20724. sqlite3MemSetDefault();
  20725. }
  20726. memset(&mem0, 0, sizeof(mem0));
  20727. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  20728. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  20729. && sqlite3GlobalConfig.nScratch>0 ){
  20730. int i, n, sz;
  20731. ScratchFreeslot *pSlot;
  20732. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  20733. sqlite3GlobalConfig.szScratch = sz;
  20734. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  20735. n = sqlite3GlobalConfig.nScratch;
  20736. mem0.pScratchFree = pSlot;
  20737. mem0.nScratchFree = n;
  20738. for(i=0; i<n-1; i++){
  20739. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  20740. pSlot = pSlot->pNext;
  20741. }
  20742. pSlot->pNext = 0;
  20743. mem0.pScratchEnd = (void*)&pSlot[1];
  20744. }else{
  20745. mem0.pScratchEnd = 0;
  20746. sqlite3GlobalConfig.pScratch = 0;
  20747. sqlite3GlobalConfig.szScratch = 0;
  20748. sqlite3GlobalConfig.nScratch = 0;
  20749. }
  20750. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  20751. || sqlite3GlobalConfig.nPage<=0 ){
  20752. sqlite3GlobalConfig.pPage = 0;
  20753. sqlite3GlobalConfig.szPage = 0;
  20754. }
  20755. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  20756. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  20757. return rc;
  20758. }
  20759. /*
  20760. ** Return true if the heap is currently under memory pressure - in other
  20761. ** words if the amount of heap used is close to the limit set by
  20762. ** sqlite3_soft_heap_limit().
  20763. */
  20764. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  20765. return mem0.nearlyFull;
  20766. }
  20767. /*
  20768. ** Deinitialize the memory allocation subsystem.
  20769. */
  20770. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  20771. if( sqlite3GlobalConfig.m.xShutdown ){
  20772. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  20773. }
  20774. memset(&mem0, 0, sizeof(mem0));
  20775. }
  20776. /*
  20777. ** Return the amount of memory currently checked out.
  20778. */
  20779. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
  20780. sqlite3_int64 res, mx;
  20781. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  20782. return res;
  20783. }
  20784. /*
  20785. ** Return the maximum amount of memory that has ever been
  20786. ** checked out since either the beginning of this process
  20787. ** or since the most recent reset.
  20788. */
  20789. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
  20790. sqlite3_int64 res, mx;
  20791. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  20792. return mx;
  20793. }
  20794. /*
  20795. ** Trigger the alarm
  20796. */
  20797. static void sqlite3MallocAlarm(int nByte){
  20798. if( mem0.alarmThreshold<=0 ) return;
  20799. sqlite3_mutex_leave(mem0.mutex);
  20800. sqlite3_release_memory(nByte);
  20801. sqlite3_mutex_enter(mem0.mutex);
  20802. }
  20803. /*
  20804. ** Do a memory allocation with statistics and alarms. Assume the
  20805. ** lock is already held.
  20806. */
  20807. static int mallocWithAlarm(int n, void **pp){
  20808. int nFull;
  20809. void *p;
  20810. assert( sqlite3_mutex_held(mem0.mutex) );
  20811. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  20812. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  20813. if( mem0.alarmThreshold>0 ){
  20814. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  20815. if( nUsed >= mem0.alarmThreshold - nFull ){
  20816. mem0.nearlyFull = 1;
  20817. sqlite3MallocAlarm(nFull);
  20818. }else{
  20819. mem0.nearlyFull = 0;
  20820. }
  20821. }
  20822. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  20823. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  20824. if( p==0 && mem0.alarmThreshold>0 ){
  20825. sqlite3MallocAlarm(nFull);
  20826. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  20827. }
  20828. #endif
  20829. if( p ){
  20830. nFull = sqlite3MallocSize(p);
  20831. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  20832. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  20833. }
  20834. *pp = p;
  20835. return nFull;
  20836. }
  20837. /*
  20838. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  20839. ** assumes the memory subsystem has already been initialized.
  20840. */
  20841. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  20842. void *p;
  20843. if( n==0 || n>=0x7fffff00 ){
  20844. /* A memory allocation of a number of bytes which is near the maximum
  20845. ** signed integer value might cause an integer overflow inside of the
  20846. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  20847. ** 255 bytes of overhead. SQLite itself will never use anything near
  20848. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  20849. p = 0;
  20850. }else if( sqlite3GlobalConfig.bMemstat ){
  20851. sqlite3_mutex_enter(mem0.mutex);
  20852. mallocWithAlarm((int)n, &p);
  20853. sqlite3_mutex_leave(mem0.mutex);
  20854. }else{
  20855. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  20856. }
  20857. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  20858. return p;
  20859. }
  20860. /*
  20861. ** This version of the memory allocation is for use by the application.
  20862. ** First make sure the memory subsystem is initialized, then do the
  20863. ** allocation.
  20864. */
  20865. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
  20866. #ifndef SQLITE_OMIT_AUTOINIT
  20867. if( sqlite3_initialize() ) return 0;
  20868. #endif
  20869. return n<=0 ? 0 : sqlite3Malloc(n);
  20870. }
  20871. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
  20872. #ifndef SQLITE_OMIT_AUTOINIT
  20873. if( sqlite3_initialize() ) return 0;
  20874. #endif
  20875. return sqlite3Malloc(n);
  20876. }
  20877. /*
  20878. ** Each thread may only have a single outstanding allocation from
  20879. ** xScratchMalloc(). We verify this constraint in the single-threaded
  20880. ** case by setting scratchAllocOut to 1 when an allocation
  20881. ** is outstanding clearing it when the allocation is freed.
  20882. */
  20883. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  20884. static int scratchAllocOut = 0;
  20885. #endif
  20886. /*
  20887. ** Allocate memory that is to be used and released right away.
  20888. ** This routine is similar to alloca() in that it is not intended
  20889. ** for situations where the memory might be held long-term. This
  20890. ** routine is intended to get memory to old large transient data
  20891. ** structures that would not normally fit on the stack of an
  20892. ** embedded processor.
  20893. */
  20894. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  20895. void *p;
  20896. assert( n>0 );
  20897. sqlite3_mutex_enter(mem0.mutex);
  20898. sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
  20899. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  20900. p = mem0.pScratchFree;
  20901. mem0.pScratchFree = mem0.pScratchFree->pNext;
  20902. mem0.nScratchFree--;
  20903. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
  20904. sqlite3_mutex_leave(mem0.mutex);
  20905. }else{
  20906. sqlite3_mutex_leave(mem0.mutex);
  20907. p = sqlite3Malloc(n);
  20908. if( sqlite3GlobalConfig.bMemstat && p ){
  20909. sqlite3_mutex_enter(mem0.mutex);
  20910. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  20911. sqlite3_mutex_leave(mem0.mutex);
  20912. }
  20913. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  20914. }
  20915. assert( sqlite3_mutex_notheld(mem0.mutex) );
  20916. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  20917. /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
  20918. ** buffers per thread.
  20919. **
  20920. ** This can only be checked in single-threaded mode.
  20921. */
  20922. assert( scratchAllocOut==0 );
  20923. if( p ) scratchAllocOut++;
  20924. #endif
  20925. return p;
  20926. }
  20927. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  20928. if( p ){
  20929. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  20930. /* Verify that no more than two scratch allocation per thread
  20931. ** is outstanding at one time. (This is only checked in the
  20932. ** single-threaded case since checking in the multi-threaded case
  20933. ** would be much more complicated.) */
  20934. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  20935. scratchAllocOut--;
  20936. #endif
  20937. if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
  20938. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  20939. ScratchFreeslot *pSlot;
  20940. pSlot = (ScratchFreeslot*)p;
  20941. sqlite3_mutex_enter(mem0.mutex);
  20942. pSlot->pNext = mem0.pScratchFree;
  20943. mem0.pScratchFree = pSlot;
  20944. mem0.nScratchFree++;
  20945. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  20946. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
  20947. sqlite3_mutex_leave(mem0.mutex);
  20948. }else{
  20949. /* Release memory back to the heap */
  20950. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  20951. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
  20952. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  20953. if( sqlite3GlobalConfig.bMemstat ){
  20954. int iSize = sqlite3MallocSize(p);
  20955. sqlite3_mutex_enter(mem0.mutex);
  20956. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
  20957. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
  20958. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  20959. sqlite3GlobalConfig.m.xFree(p);
  20960. sqlite3_mutex_leave(mem0.mutex);
  20961. }else{
  20962. sqlite3GlobalConfig.m.xFree(p);
  20963. }
  20964. }
  20965. }
  20966. }
  20967. /*
  20968. ** TRUE if p is a lookaside memory allocation from db
  20969. */
  20970. #ifndef SQLITE_OMIT_LOOKASIDE
  20971. static int isLookaside(sqlite3 *db, void *p){
  20972. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  20973. }
  20974. #else
  20975. #define isLookaside(A,B) 0
  20976. #endif
  20977. /*
  20978. ** Return the size of a memory allocation previously obtained from
  20979. ** sqlite3Malloc() or sqlite3_malloc().
  20980. */
  20981. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  20982. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20983. return sqlite3GlobalConfig.m.xSize(p);
  20984. }
  20985. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  20986. assert( p!=0 );
  20987. if( db==0 || !isLookaside(db,p) ){
  20988. #if SQLITE_DEBUG
  20989. if( db==0 ){
  20990. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  20991. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20992. }else{
  20993. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20994. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20995. }
  20996. #endif
  20997. return sqlite3GlobalConfig.m.xSize(p);
  20998. }else{
  20999. assert( sqlite3_mutex_held(db->mutex) );
  21000. return db->lookaside.sz;
  21001. }
  21002. }
  21003. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
  21004. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  21005. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  21006. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  21007. }
  21008. /*
  21009. ** Free memory previously obtained from sqlite3Malloc().
  21010. */
  21011. SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
  21012. if( p==0 ) return; /* IMP: R-49053-54554 */
  21013. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  21014. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  21015. if( sqlite3GlobalConfig.bMemstat ){
  21016. sqlite3_mutex_enter(mem0.mutex);
  21017. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  21018. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  21019. sqlite3GlobalConfig.m.xFree(p);
  21020. sqlite3_mutex_leave(mem0.mutex);
  21021. }else{
  21022. sqlite3GlobalConfig.m.xFree(p);
  21023. }
  21024. }
  21025. /*
  21026. ** Add the size of memory allocation "p" to the count in
  21027. ** *db->pnBytesFreed.
  21028. */
  21029. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  21030. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  21031. }
  21032. /*
  21033. ** Free memory that might be associated with a particular database
  21034. ** connection.
  21035. */
  21036. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  21037. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  21038. if( p==0 ) return;
  21039. if( db ){
  21040. if( db->pnBytesFreed ){
  21041. measureAllocationSize(db, p);
  21042. return;
  21043. }
  21044. if( isLookaside(db, p) ){
  21045. LookasideSlot *pBuf = (LookasideSlot*)p;
  21046. #if SQLITE_DEBUG
  21047. /* Trash all content in the buffer being freed */
  21048. memset(p, 0xaa, db->lookaside.sz);
  21049. #endif
  21050. pBuf->pNext = db->lookaside.pFree;
  21051. db->lookaside.pFree = pBuf;
  21052. db->lookaside.nOut--;
  21053. return;
  21054. }
  21055. }
  21056. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21057. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21058. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  21059. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  21060. sqlite3_free(p);
  21061. }
  21062. /*
  21063. ** Change the size of an existing memory allocation
  21064. */
  21065. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  21066. int nOld, nNew, nDiff;
  21067. void *pNew;
  21068. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  21069. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  21070. if( pOld==0 ){
  21071. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  21072. }
  21073. if( nBytes==0 ){
  21074. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  21075. return 0;
  21076. }
  21077. if( nBytes>=0x7fffff00 ){
  21078. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  21079. return 0;
  21080. }
  21081. nOld = sqlite3MallocSize(pOld);
  21082. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  21083. ** argument to xRealloc is always a value returned by a prior call to
  21084. ** xRoundup. */
  21085. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  21086. if( nOld==nNew ){
  21087. pNew = pOld;
  21088. }else if( sqlite3GlobalConfig.bMemstat ){
  21089. sqlite3_mutex_enter(mem0.mutex);
  21090. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  21091. nDiff = nNew - nOld;
  21092. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  21093. mem0.alarmThreshold-nDiff ){
  21094. sqlite3MallocAlarm(nDiff);
  21095. }
  21096. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  21097. if( pNew==0 && mem0.alarmThreshold>0 ){
  21098. sqlite3MallocAlarm((int)nBytes);
  21099. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  21100. }
  21101. if( pNew ){
  21102. nNew = sqlite3MallocSize(pNew);
  21103. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  21104. }
  21105. sqlite3_mutex_leave(mem0.mutex);
  21106. }else{
  21107. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  21108. }
  21109. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  21110. return pNew;
  21111. }
  21112. /*
  21113. ** The public interface to sqlite3Realloc. Make sure that the memory
  21114. ** subsystem is initialized prior to invoking sqliteRealloc.
  21115. */
  21116. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
  21117. #ifndef SQLITE_OMIT_AUTOINIT
  21118. if( sqlite3_initialize() ) return 0;
  21119. #endif
  21120. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  21121. return sqlite3Realloc(pOld, n);
  21122. }
  21123. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  21124. #ifndef SQLITE_OMIT_AUTOINIT
  21125. if( sqlite3_initialize() ) return 0;
  21126. #endif
  21127. return sqlite3Realloc(pOld, n);
  21128. }
  21129. /*
  21130. ** Allocate and zero memory.
  21131. */
  21132. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  21133. void *p = sqlite3Malloc(n);
  21134. if( p ){
  21135. memset(p, 0, (size_t)n);
  21136. }
  21137. return p;
  21138. }
  21139. /*
  21140. ** Allocate and zero memory. If the allocation fails, make
  21141. ** the mallocFailed flag in the connection pointer.
  21142. */
  21143. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  21144. void *p = sqlite3DbMallocRaw(db, n);
  21145. if( p ){
  21146. memset(p, 0, (size_t)n);
  21147. }
  21148. return p;
  21149. }
  21150. /*
  21151. ** Allocate and zero memory. If the allocation fails, make
  21152. ** the mallocFailed flag in the connection pointer.
  21153. **
  21154. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  21155. ** failure on the same database connection) then always return 0.
  21156. ** Hence for a particular database connection, once malloc starts
  21157. ** failing, it fails consistently until mallocFailed is reset.
  21158. ** This is an important assumption. There are many places in the
  21159. ** code that do things like this:
  21160. **
  21161. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  21162. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  21163. ** if( b ) a[10] = 9;
  21164. **
  21165. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  21166. ** that all prior mallocs (ex: "a") worked too.
  21167. */
  21168. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  21169. void *p;
  21170. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  21171. assert( db==0 || db->pnBytesFreed==0 );
  21172. #ifndef SQLITE_OMIT_LOOKASIDE
  21173. if( db ){
  21174. LookasideSlot *pBuf;
  21175. if( db->mallocFailed ){
  21176. return 0;
  21177. }
  21178. if( db->lookaside.bEnabled ){
  21179. if( n>db->lookaside.sz ){
  21180. db->lookaside.anStat[1]++;
  21181. }else if( (pBuf = db->lookaside.pFree)==0 ){
  21182. db->lookaside.anStat[2]++;
  21183. }else{
  21184. db->lookaside.pFree = pBuf->pNext;
  21185. db->lookaside.nOut++;
  21186. db->lookaside.anStat[0]++;
  21187. if( db->lookaside.nOut>db->lookaside.mxOut ){
  21188. db->lookaside.mxOut = db->lookaside.nOut;
  21189. }
  21190. return (void*)pBuf;
  21191. }
  21192. }
  21193. }
  21194. #else
  21195. if( db && db->mallocFailed ){
  21196. return 0;
  21197. }
  21198. #endif
  21199. p = sqlite3Malloc(n);
  21200. if( !p && db ){
  21201. db->mallocFailed = 1;
  21202. }
  21203. sqlite3MemdebugSetType(p,
  21204. (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  21205. return p;
  21206. }
  21207. /*
  21208. ** Resize the block of memory pointed to by p to n bytes. If the
  21209. ** resize fails, set the mallocFailed flag in the connection object.
  21210. */
  21211. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  21212. void *pNew = 0;
  21213. assert( db!=0 );
  21214. assert( sqlite3_mutex_held(db->mutex) );
  21215. if( db->mallocFailed==0 ){
  21216. if( p==0 ){
  21217. return sqlite3DbMallocRaw(db, n);
  21218. }
  21219. if( isLookaside(db, p) ){
  21220. if( n<=db->lookaside.sz ){
  21221. return p;
  21222. }
  21223. pNew = sqlite3DbMallocRaw(db, n);
  21224. if( pNew ){
  21225. memcpy(pNew, p, db->lookaside.sz);
  21226. sqlite3DbFree(db, p);
  21227. }
  21228. }else{
  21229. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21230. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  21231. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  21232. pNew = sqlite3_realloc64(p, n);
  21233. if( !pNew ){
  21234. db->mallocFailed = 1;
  21235. }
  21236. sqlite3MemdebugSetType(pNew,
  21237. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  21238. }
  21239. }
  21240. return pNew;
  21241. }
  21242. /*
  21243. ** Attempt to reallocate p. If the reallocation fails, then free p
  21244. ** and set the mallocFailed flag in the database connection.
  21245. */
  21246. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  21247. void *pNew;
  21248. pNew = sqlite3DbRealloc(db, p, n);
  21249. if( !pNew ){
  21250. sqlite3DbFree(db, p);
  21251. }
  21252. return pNew;
  21253. }
  21254. /*
  21255. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  21256. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  21257. ** is because when memory debugging is turned on, these two functions are
  21258. ** called via macros that record the current file and line number in the
  21259. ** ThreadData structure.
  21260. */
  21261. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  21262. char *zNew;
  21263. size_t n;
  21264. if( z==0 ){
  21265. return 0;
  21266. }
  21267. n = sqlite3Strlen30(z) + 1;
  21268. assert( (n&0x7fffffff)==n );
  21269. zNew = sqlite3DbMallocRaw(db, (int)n);
  21270. if( zNew ){
  21271. memcpy(zNew, z, n);
  21272. }
  21273. return zNew;
  21274. }
  21275. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  21276. char *zNew;
  21277. if( z==0 ){
  21278. return 0;
  21279. }
  21280. assert( (n&0x7fffffff)==n );
  21281. zNew = sqlite3DbMallocRaw(db, n+1);
  21282. if( zNew ){
  21283. memcpy(zNew, z, (size_t)n);
  21284. zNew[n] = 0;
  21285. }
  21286. return zNew;
  21287. }
  21288. /*
  21289. ** Free any prior content in *pz and replace it with a copy of zNew.
  21290. */
  21291. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  21292. sqlite3DbFree(db, *pz);
  21293. *pz = sqlite3DbStrDup(db, zNew);
  21294. }
  21295. /*
  21296. ** Take actions at the end of an API call to indicate an OOM error
  21297. */
  21298. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  21299. db->mallocFailed = 0;
  21300. sqlite3Error(db, SQLITE_NOMEM);
  21301. return SQLITE_NOMEM;
  21302. }
  21303. /*
  21304. ** This function must be called before exiting any API function (i.e.
  21305. ** returning control to the user) that has called sqlite3_malloc or
  21306. ** sqlite3_realloc.
  21307. **
  21308. ** The returned value is normally a copy of the second argument to this
  21309. ** function. However, if a malloc() failure has occurred since the previous
  21310. ** invocation SQLITE_NOMEM is returned instead.
  21311. **
  21312. ** If an OOM as occurred, then the connection error-code (the value
  21313. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  21314. */
  21315. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  21316. /* If the db handle must hold the connection handle mutex here.
  21317. ** Otherwise the read (and possible write) of db->mallocFailed
  21318. ** is unsafe, as is the call to sqlite3Error().
  21319. */
  21320. assert( db!=0 );
  21321. assert( sqlite3_mutex_held(db->mutex) );
  21322. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  21323. return apiOomError(db);
  21324. }
  21325. return rc & db->errMask;
  21326. }
  21327. /************** End of malloc.c **********************************************/
  21328. /************** Begin file printf.c ******************************************/
  21329. /*
  21330. ** The "printf" code that follows dates from the 1980's. It is in
  21331. ** the public domain.
  21332. **
  21333. **************************************************************************
  21334. **
  21335. ** This file contains code for a set of "printf"-like routines. These
  21336. ** routines format strings much like the printf() from the standard C
  21337. ** library, though the implementation here has enhancements to support
  21338. ** SQLite.
  21339. */
  21340. /* #include "sqliteInt.h" */
  21341. /*
  21342. ** Conversion types fall into various categories as defined by the
  21343. ** following enumeration.
  21344. */
  21345. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  21346. #define etFLOAT 2 /* Floating point. %f */
  21347. #define etEXP 3 /* Exponentional notation. %e and %E */
  21348. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  21349. #define etSIZE 5 /* Return number of characters processed so far. %n */
  21350. #define etSTRING 6 /* Strings. %s */
  21351. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  21352. #define etPERCENT 8 /* Percent symbol. %% */
  21353. #define etCHARX 9 /* Characters. %c */
  21354. /* The rest are extensions, not normally found in printf() */
  21355. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  21356. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  21357. NULL pointers replaced by SQL NULL. %Q */
  21358. #define etTOKEN 12 /* a pointer to a Token structure */
  21359. #define etSRCLIST 13 /* a pointer to a SrcList */
  21360. #define etPOINTER 14 /* The %p conversion */
  21361. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  21362. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  21363. #define etINVALID 0 /* Any unrecognized conversion type */
  21364. /*
  21365. ** An "etByte" is an 8-bit unsigned value.
  21366. */
  21367. typedef unsigned char etByte;
  21368. /*
  21369. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  21370. ** by an instance of the following structure
  21371. */
  21372. typedef struct et_info { /* Information about each format field */
  21373. char fmttype; /* The format field code letter */
  21374. etByte base; /* The base for radix conversion */
  21375. etByte flags; /* One or more of FLAG_ constants below */
  21376. etByte type; /* Conversion paradigm */
  21377. etByte charset; /* Offset into aDigits[] of the digits string */
  21378. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  21379. } et_info;
  21380. /*
  21381. ** Allowed values for et_info.flags
  21382. */
  21383. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  21384. #define FLAG_INTERN 2 /* True if for internal use only */
  21385. #define FLAG_STRING 4 /* Allow infinity precision */
  21386. /*
  21387. ** The following table is searched linearly, so it is good to put the
  21388. ** most frequently used conversion types first.
  21389. */
  21390. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  21391. static const char aPrefix[] = "-x0\000X0";
  21392. static const et_info fmtinfo[] = {
  21393. { 'd', 10, 1, etRADIX, 0, 0 },
  21394. { 's', 0, 4, etSTRING, 0, 0 },
  21395. { 'g', 0, 1, etGENERIC, 30, 0 },
  21396. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  21397. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  21398. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  21399. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  21400. { 'c', 0, 0, etCHARX, 0, 0 },
  21401. { 'o', 8, 0, etRADIX, 0, 2 },
  21402. { 'u', 10, 0, etRADIX, 0, 0 },
  21403. { 'x', 16, 0, etRADIX, 16, 1 },
  21404. { 'X', 16, 0, etRADIX, 0, 4 },
  21405. #ifndef SQLITE_OMIT_FLOATING_POINT
  21406. { 'f', 0, 1, etFLOAT, 0, 0 },
  21407. { 'e', 0, 1, etEXP, 30, 0 },
  21408. { 'E', 0, 1, etEXP, 14, 0 },
  21409. { 'G', 0, 1, etGENERIC, 14, 0 },
  21410. #endif
  21411. { 'i', 10, 1, etRADIX, 0, 0 },
  21412. { 'n', 0, 0, etSIZE, 0, 0 },
  21413. { '%', 0, 0, etPERCENT, 0, 0 },
  21414. { 'p', 16, 0, etPOINTER, 0, 1 },
  21415. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  21416. ** use only */
  21417. { 'T', 0, 2, etTOKEN, 0, 0 },
  21418. { 'S', 0, 2, etSRCLIST, 0, 0 },
  21419. { 'r', 10, 3, etORDINAL, 0, 0 },
  21420. };
  21421. /*
  21422. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  21423. ** conversions will work.
  21424. */
  21425. #ifndef SQLITE_OMIT_FLOATING_POINT
  21426. /*
  21427. ** "*val" is a double such that 0.1 <= *val < 10.0
  21428. ** Return the ascii code for the leading digit of *val, then
  21429. ** multiply "*val" by 10.0 to renormalize.
  21430. **
  21431. ** Example:
  21432. ** input: *val = 3.14159
  21433. ** output: *val = 1.4159 function return = '3'
  21434. **
  21435. ** The counter *cnt is incremented each time. After counter exceeds
  21436. ** 16 (the number of significant digits in a 64-bit float) '0' is
  21437. ** always returned.
  21438. */
  21439. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  21440. int digit;
  21441. LONGDOUBLE_TYPE d;
  21442. if( (*cnt)<=0 ) return '0';
  21443. (*cnt)--;
  21444. digit = (int)*val;
  21445. d = digit;
  21446. digit += '0';
  21447. *val = (*val - d)*10.0;
  21448. return (char)digit;
  21449. }
  21450. #endif /* SQLITE_OMIT_FLOATING_POINT */
  21451. /*
  21452. ** Set the StrAccum object to an error mode.
  21453. */
  21454. static void setStrAccumError(StrAccum *p, u8 eError){
  21455. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  21456. p->accError = eError;
  21457. p->nAlloc = 0;
  21458. }
  21459. /*
  21460. ** Extra argument values from a PrintfArguments object
  21461. */
  21462. static sqlite3_int64 getIntArg(PrintfArguments *p){
  21463. if( p->nArg<=p->nUsed ) return 0;
  21464. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  21465. }
  21466. static double getDoubleArg(PrintfArguments *p){
  21467. if( p->nArg<=p->nUsed ) return 0.0;
  21468. return sqlite3_value_double(p->apArg[p->nUsed++]);
  21469. }
  21470. static char *getTextArg(PrintfArguments *p){
  21471. if( p->nArg<=p->nUsed ) return 0;
  21472. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  21473. }
  21474. /*
  21475. ** On machines with a small stack size, you can redefine the
  21476. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  21477. */
  21478. #ifndef SQLITE_PRINT_BUF_SIZE
  21479. # define SQLITE_PRINT_BUF_SIZE 70
  21480. #endif
  21481. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  21482. /*
  21483. ** Render a string given by "fmt" into the StrAccum object.
  21484. */
  21485. SQLITE_PRIVATE void sqlite3VXPrintf(
  21486. StrAccum *pAccum, /* Accumulate results here */
  21487. u32 bFlags, /* SQLITE_PRINTF_* flags */
  21488. const char *fmt, /* Format string */
  21489. va_list ap /* arguments */
  21490. ){
  21491. int c; /* Next character in the format string */
  21492. char *bufpt; /* Pointer to the conversion buffer */
  21493. int precision; /* Precision of the current field */
  21494. int length; /* Length of the field */
  21495. int idx; /* A general purpose loop counter */
  21496. int width; /* Width of the current field */
  21497. etByte flag_leftjustify; /* True if "-" flag is present */
  21498. etByte flag_plussign; /* True if "+" flag is present */
  21499. etByte flag_blanksign; /* True if " " flag is present */
  21500. etByte flag_alternateform; /* True if "#" flag is present */
  21501. etByte flag_altform2; /* True if "!" flag is present */
  21502. etByte flag_zeropad; /* True if field width constant starts with zero */
  21503. etByte flag_long; /* True if "l" flag is present */
  21504. etByte flag_longlong; /* True if the "ll" flag is present */
  21505. etByte done; /* Loop termination flag */
  21506. etByte xtype = 0; /* Conversion paradigm */
  21507. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  21508. u8 useIntern; /* Ok to use internal conversions (ex: %T) */
  21509. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  21510. sqlite_uint64 longvalue; /* Value for integer types */
  21511. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  21512. const et_info *infop; /* Pointer to the appropriate info structure */
  21513. char *zOut; /* Rendering buffer */
  21514. int nOut; /* Size of the rendering buffer */
  21515. char *zExtra = 0; /* Malloced memory used by some conversion */
  21516. #ifndef SQLITE_OMIT_FLOATING_POINT
  21517. int exp, e2; /* exponent of real numbers */
  21518. int nsd; /* Number of significant digits returned */
  21519. double rounder; /* Used for rounding floating point values */
  21520. etByte flag_dp; /* True if decimal point should be shown */
  21521. etByte flag_rtz; /* True if trailing zeros should be removed */
  21522. #endif
  21523. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  21524. char buf[etBUFSIZE]; /* Conversion buffer */
  21525. bufpt = 0;
  21526. if( bFlags ){
  21527. if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
  21528. pArgList = va_arg(ap, PrintfArguments*);
  21529. }
  21530. useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
  21531. }else{
  21532. bArgList = useIntern = 0;
  21533. }
  21534. for(; (c=(*fmt))!=0; ++fmt){
  21535. if( c!='%' ){
  21536. bufpt = (char *)fmt;
  21537. #if HAVE_STRCHRNUL
  21538. fmt = strchrnul(fmt, '%');
  21539. #else
  21540. do{ fmt++; }while( *fmt && *fmt != '%' );
  21541. #endif
  21542. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  21543. if( *fmt==0 ) break;
  21544. }
  21545. if( (c=(*++fmt))==0 ){
  21546. sqlite3StrAccumAppend(pAccum, "%", 1);
  21547. break;
  21548. }
  21549. /* Find out what flags are present */
  21550. flag_leftjustify = flag_plussign = flag_blanksign =
  21551. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  21552. done = 0;
  21553. do{
  21554. switch( c ){
  21555. case '-': flag_leftjustify = 1; break;
  21556. case '+': flag_plussign = 1; break;
  21557. case ' ': flag_blanksign = 1; break;
  21558. case '#': flag_alternateform = 1; break;
  21559. case '!': flag_altform2 = 1; break;
  21560. case '0': flag_zeropad = 1; break;
  21561. default: done = 1; break;
  21562. }
  21563. }while( !done && (c=(*++fmt))!=0 );
  21564. /* Get the field width */
  21565. if( c=='*' ){
  21566. if( bArgList ){
  21567. width = (int)getIntArg(pArgList);
  21568. }else{
  21569. width = va_arg(ap,int);
  21570. }
  21571. if( width<0 ){
  21572. flag_leftjustify = 1;
  21573. width = width >= -2147483647 ? -width : 0;
  21574. }
  21575. c = *++fmt;
  21576. }else{
  21577. unsigned wx = 0;
  21578. while( c>='0' && c<='9' ){
  21579. wx = wx*10 + c - '0';
  21580. c = *++fmt;
  21581. }
  21582. testcase( wx>0x7fffffff );
  21583. width = wx & 0x7fffffff;
  21584. }
  21585. assert( width>=0 );
  21586. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  21587. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  21588. width = SQLITE_PRINTF_PRECISION_LIMIT;
  21589. }
  21590. #endif
  21591. /* Get the precision */
  21592. if( c=='.' ){
  21593. c = *++fmt;
  21594. if( c=='*' ){
  21595. if( bArgList ){
  21596. precision = (int)getIntArg(pArgList);
  21597. }else{
  21598. precision = va_arg(ap,int);
  21599. }
  21600. c = *++fmt;
  21601. if( precision<0 ){
  21602. precision = precision >= -2147483647 ? -precision : -1;
  21603. }
  21604. }else{
  21605. unsigned px = 0;
  21606. while( c>='0' && c<='9' ){
  21607. px = px*10 + c - '0';
  21608. c = *++fmt;
  21609. }
  21610. testcase( px>0x7fffffff );
  21611. precision = px & 0x7fffffff;
  21612. }
  21613. }else{
  21614. precision = -1;
  21615. }
  21616. assert( precision>=(-1) );
  21617. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  21618. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  21619. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  21620. }
  21621. #endif
  21622. /* Get the conversion type modifier */
  21623. if( c=='l' ){
  21624. flag_long = 1;
  21625. c = *++fmt;
  21626. if( c=='l' ){
  21627. flag_longlong = 1;
  21628. c = *++fmt;
  21629. }else{
  21630. flag_longlong = 0;
  21631. }
  21632. }else{
  21633. flag_long = flag_longlong = 0;
  21634. }
  21635. /* Fetch the info entry for the field */
  21636. infop = &fmtinfo[0];
  21637. xtype = etINVALID;
  21638. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  21639. if( c==fmtinfo[idx].fmttype ){
  21640. infop = &fmtinfo[idx];
  21641. if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
  21642. xtype = infop->type;
  21643. }else{
  21644. return;
  21645. }
  21646. break;
  21647. }
  21648. }
  21649. /*
  21650. ** At this point, variables are initialized as follows:
  21651. **
  21652. ** flag_alternateform TRUE if a '#' is present.
  21653. ** flag_altform2 TRUE if a '!' is present.
  21654. ** flag_plussign TRUE if a '+' is present.
  21655. ** flag_leftjustify TRUE if a '-' is present or if the
  21656. ** field width was negative.
  21657. ** flag_zeropad TRUE if the width began with 0.
  21658. ** flag_long TRUE if the letter 'l' (ell) prefixed
  21659. ** the conversion character.
  21660. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  21661. ** the conversion character.
  21662. ** flag_blanksign TRUE if a ' ' is present.
  21663. ** width The specified field width. This is
  21664. ** always non-negative. Zero is the default.
  21665. ** precision The specified precision. The default
  21666. ** is -1.
  21667. ** xtype The class of the conversion.
  21668. ** infop Pointer to the appropriate info struct.
  21669. */
  21670. switch( xtype ){
  21671. case etPOINTER:
  21672. flag_longlong = sizeof(char*)==sizeof(i64);
  21673. flag_long = sizeof(char*)==sizeof(long int);
  21674. /* Fall through into the next case */
  21675. case etORDINAL:
  21676. case etRADIX:
  21677. if( infop->flags & FLAG_SIGNED ){
  21678. i64 v;
  21679. if( bArgList ){
  21680. v = getIntArg(pArgList);
  21681. }else if( flag_longlong ){
  21682. v = va_arg(ap,i64);
  21683. }else if( flag_long ){
  21684. v = va_arg(ap,long int);
  21685. }else{
  21686. v = va_arg(ap,int);
  21687. }
  21688. if( v<0 ){
  21689. if( v==SMALLEST_INT64 ){
  21690. longvalue = ((u64)1)<<63;
  21691. }else{
  21692. longvalue = -v;
  21693. }
  21694. prefix = '-';
  21695. }else{
  21696. longvalue = v;
  21697. if( flag_plussign ) prefix = '+';
  21698. else if( flag_blanksign ) prefix = ' ';
  21699. else prefix = 0;
  21700. }
  21701. }else{
  21702. if( bArgList ){
  21703. longvalue = (u64)getIntArg(pArgList);
  21704. }else if( flag_longlong ){
  21705. longvalue = va_arg(ap,u64);
  21706. }else if( flag_long ){
  21707. longvalue = va_arg(ap,unsigned long int);
  21708. }else{
  21709. longvalue = va_arg(ap,unsigned int);
  21710. }
  21711. prefix = 0;
  21712. }
  21713. if( longvalue==0 ) flag_alternateform = 0;
  21714. if( flag_zeropad && precision<width-(prefix!=0) ){
  21715. precision = width-(prefix!=0);
  21716. }
  21717. if( precision<etBUFSIZE-10 ){
  21718. nOut = etBUFSIZE;
  21719. zOut = buf;
  21720. }else{
  21721. nOut = precision + 10;
  21722. zOut = zExtra = sqlite3Malloc( nOut );
  21723. if( zOut==0 ){
  21724. setStrAccumError(pAccum, STRACCUM_NOMEM);
  21725. return;
  21726. }
  21727. }
  21728. bufpt = &zOut[nOut-1];
  21729. if( xtype==etORDINAL ){
  21730. static const char zOrd[] = "thstndrd";
  21731. int x = (int)(longvalue % 10);
  21732. if( x>=4 || (longvalue/10)%10==1 ){
  21733. x = 0;
  21734. }
  21735. *(--bufpt) = zOrd[x*2+1];
  21736. *(--bufpt) = zOrd[x*2];
  21737. }
  21738. {
  21739. const char *cset = &aDigits[infop->charset];
  21740. u8 base = infop->base;
  21741. do{ /* Convert to ascii */
  21742. *(--bufpt) = cset[longvalue%base];
  21743. longvalue = longvalue/base;
  21744. }while( longvalue>0 );
  21745. }
  21746. length = (int)(&zOut[nOut-1]-bufpt);
  21747. for(idx=precision-length; idx>0; idx--){
  21748. *(--bufpt) = '0'; /* Zero pad */
  21749. }
  21750. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  21751. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  21752. const char *pre;
  21753. char x;
  21754. pre = &aPrefix[infop->prefix];
  21755. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  21756. }
  21757. length = (int)(&zOut[nOut-1]-bufpt);
  21758. break;
  21759. case etFLOAT:
  21760. case etEXP:
  21761. case etGENERIC:
  21762. if( bArgList ){
  21763. realvalue = getDoubleArg(pArgList);
  21764. }else{
  21765. realvalue = va_arg(ap,double);
  21766. }
  21767. #ifdef SQLITE_OMIT_FLOATING_POINT
  21768. length = 0;
  21769. #else
  21770. if( precision<0 ) precision = 6; /* Set default precision */
  21771. if( realvalue<0.0 ){
  21772. realvalue = -realvalue;
  21773. prefix = '-';
  21774. }else{
  21775. if( flag_plussign ) prefix = '+';
  21776. else if( flag_blanksign ) prefix = ' ';
  21777. else prefix = 0;
  21778. }
  21779. if( xtype==etGENERIC && precision>0 ) precision--;
  21780. testcase( precision>0xfff );
  21781. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  21782. if( xtype==etFLOAT ) realvalue += rounder;
  21783. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  21784. exp = 0;
  21785. if( sqlite3IsNaN((double)realvalue) ){
  21786. bufpt = "NaN";
  21787. length = 3;
  21788. break;
  21789. }
  21790. if( realvalue>0.0 ){
  21791. LONGDOUBLE_TYPE scale = 1.0;
  21792. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  21793. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  21794. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  21795. realvalue /= scale;
  21796. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  21797. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  21798. if( exp>350 ){
  21799. bufpt = buf;
  21800. buf[0] = prefix;
  21801. memcpy(buf+(prefix!=0),"Inf",4);
  21802. length = 3+(prefix!=0);
  21803. break;
  21804. }
  21805. }
  21806. bufpt = buf;
  21807. /*
  21808. ** If the field type is etGENERIC, then convert to either etEXP
  21809. ** or etFLOAT, as appropriate.
  21810. */
  21811. if( xtype!=etFLOAT ){
  21812. realvalue += rounder;
  21813. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  21814. }
  21815. if( xtype==etGENERIC ){
  21816. flag_rtz = !flag_alternateform;
  21817. if( exp<-4 || exp>precision ){
  21818. xtype = etEXP;
  21819. }else{
  21820. precision = precision - exp;
  21821. xtype = etFLOAT;
  21822. }
  21823. }else{
  21824. flag_rtz = flag_altform2;
  21825. }
  21826. if( xtype==etEXP ){
  21827. e2 = 0;
  21828. }else{
  21829. e2 = exp;
  21830. }
  21831. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  21832. bufpt = zExtra
  21833. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  21834. if( bufpt==0 ){
  21835. setStrAccumError(pAccum, STRACCUM_NOMEM);
  21836. return;
  21837. }
  21838. }
  21839. zOut = bufpt;
  21840. nsd = 16 + flag_altform2*10;
  21841. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  21842. /* The sign in front of the number */
  21843. if( prefix ){
  21844. *(bufpt++) = prefix;
  21845. }
  21846. /* Digits prior to the decimal point */
  21847. if( e2<0 ){
  21848. *(bufpt++) = '0';
  21849. }else{
  21850. for(; e2>=0; e2--){
  21851. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  21852. }
  21853. }
  21854. /* The decimal point */
  21855. if( flag_dp ){
  21856. *(bufpt++) = '.';
  21857. }
  21858. /* "0" digits after the decimal point but before the first
  21859. ** significant digit of the number */
  21860. for(e2++; e2<0; precision--, e2++){
  21861. assert( precision>0 );
  21862. *(bufpt++) = '0';
  21863. }
  21864. /* Significant digits after the decimal point */
  21865. while( (precision--)>0 ){
  21866. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  21867. }
  21868. /* Remove trailing zeros and the "." if no digits follow the "." */
  21869. if( flag_rtz && flag_dp ){
  21870. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  21871. assert( bufpt>zOut );
  21872. if( bufpt[-1]=='.' ){
  21873. if( flag_altform2 ){
  21874. *(bufpt++) = '0';
  21875. }else{
  21876. *(--bufpt) = 0;
  21877. }
  21878. }
  21879. }
  21880. /* Add the "eNNN" suffix */
  21881. if( xtype==etEXP ){
  21882. *(bufpt++) = aDigits[infop->charset];
  21883. if( exp<0 ){
  21884. *(bufpt++) = '-'; exp = -exp;
  21885. }else{
  21886. *(bufpt++) = '+';
  21887. }
  21888. if( exp>=100 ){
  21889. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  21890. exp %= 100;
  21891. }
  21892. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  21893. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  21894. }
  21895. *bufpt = 0;
  21896. /* The converted number is in buf[] and zero terminated. Output it.
  21897. ** Note that the number is in the usual order, not reversed as with
  21898. ** integer conversions. */
  21899. length = (int)(bufpt-zOut);
  21900. bufpt = zOut;
  21901. /* Special case: Add leading zeros if the flag_zeropad flag is
  21902. ** set and we are not left justified */
  21903. if( flag_zeropad && !flag_leftjustify && length < width){
  21904. int i;
  21905. int nPad = width - length;
  21906. for(i=width; i>=nPad; i--){
  21907. bufpt[i] = bufpt[i-nPad];
  21908. }
  21909. i = prefix!=0;
  21910. while( nPad-- ) bufpt[i++] = '0';
  21911. length = width;
  21912. }
  21913. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  21914. break;
  21915. case etSIZE:
  21916. if( !bArgList ){
  21917. *(va_arg(ap,int*)) = pAccum->nChar;
  21918. }
  21919. length = width = 0;
  21920. break;
  21921. case etPERCENT:
  21922. buf[0] = '%';
  21923. bufpt = buf;
  21924. length = 1;
  21925. break;
  21926. case etCHARX:
  21927. if( bArgList ){
  21928. bufpt = getTextArg(pArgList);
  21929. c = bufpt ? bufpt[0] : 0;
  21930. }else{
  21931. c = va_arg(ap,int);
  21932. }
  21933. if( precision>1 ){
  21934. width -= precision-1;
  21935. if( width>1 && !flag_leftjustify ){
  21936. sqlite3AppendChar(pAccum, width-1, ' ');
  21937. width = 0;
  21938. }
  21939. sqlite3AppendChar(pAccum, precision-1, c);
  21940. }
  21941. length = 1;
  21942. buf[0] = c;
  21943. bufpt = buf;
  21944. break;
  21945. case etSTRING:
  21946. case etDYNSTRING:
  21947. if( bArgList ){
  21948. bufpt = getTextArg(pArgList);
  21949. xtype = etSTRING;
  21950. }else{
  21951. bufpt = va_arg(ap,char*);
  21952. }
  21953. if( bufpt==0 ){
  21954. bufpt = "";
  21955. }else if( xtype==etDYNSTRING ){
  21956. zExtra = bufpt;
  21957. }
  21958. if( precision>=0 ){
  21959. for(length=0; length<precision && bufpt[length]; length++){}
  21960. }else{
  21961. length = sqlite3Strlen30(bufpt);
  21962. }
  21963. break;
  21964. case etSQLESCAPE: /* Escape ' characters */
  21965. case etSQLESCAPE2: /* Escape ' and enclose in '...' */
  21966. case etSQLESCAPE3: { /* Escape " characters */
  21967. int i, j, k, n, isnull;
  21968. int needQuote;
  21969. char ch;
  21970. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  21971. char *escarg;
  21972. if( bArgList ){
  21973. escarg = getTextArg(pArgList);
  21974. }else{
  21975. escarg = va_arg(ap,char*);
  21976. }
  21977. isnull = escarg==0;
  21978. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  21979. k = precision;
  21980. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  21981. if( ch==q ) n++;
  21982. }
  21983. needQuote = !isnull && xtype==etSQLESCAPE2;
  21984. n += i + 3;
  21985. if( n>etBUFSIZE ){
  21986. bufpt = zExtra = sqlite3Malloc( n );
  21987. if( bufpt==0 ){
  21988. setStrAccumError(pAccum, STRACCUM_NOMEM);
  21989. return;
  21990. }
  21991. }else{
  21992. bufpt = buf;
  21993. }
  21994. j = 0;
  21995. if( needQuote ) bufpt[j++] = q;
  21996. k = i;
  21997. for(i=0; i<k; i++){
  21998. bufpt[j++] = ch = escarg[i];
  21999. if( ch==q ) bufpt[j++] = ch;
  22000. }
  22001. if( needQuote ) bufpt[j++] = q;
  22002. bufpt[j] = 0;
  22003. length = j;
  22004. /* The precision in %q and %Q means how many input characters to
  22005. ** consume, not the length of the output...
  22006. ** if( precision>=0 && precision<length ) length = precision; */
  22007. break;
  22008. }
  22009. case etTOKEN: {
  22010. Token *pToken = va_arg(ap, Token*);
  22011. assert( bArgList==0 );
  22012. if( pToken && pToken->n ){
  22013. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  22014. }
  22015. length = width = 0;
  22016. break;
  22017. }
  22018. case etSRCLIST: {
  22019. SrcList *pSrc = va_arg(ap, SrcList*);
  22020. int k = va_arg(ap, int);
  22021. struct SrcList_item *pItem = &pSrc->a[k];
  22022. assert( bArgList==0 );
  22023. assert( k>=0 && k<pSrc->nSrc );
  22024. if( pItem->zDatabase ){
  22025. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  22026. sqlite3StrAccumAppend(pAccum, ".", 1);
  22027. }
  22028. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  22029. length = width = 0;
  22030. break;
  22031. }
  22032. default: {
  22033. assert( xtype==etINVALID );
  22034. return;
  22035. }
  22036. }/* End switch over the format type */
  22037. /*
  22038. ** The text of the conversion is pointed to by "bufpt" and is
  22039. ** "length" characters long. The field width is "width". Do
  22040. ** the output.
  22041. */
  22042. width -= length;
  22043. if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  22044. sqlite3StrAccumAppend(pAccum, bufpt, length);
  22045. if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  22046. if( zExtra ){
  22047. sqlite3DbFree(pAccum->db, zExtra);
  22048. zExtra = 0;
  22049. }
  22050. }/* End for loop over the format string */
  22051. } /* End of function */
  22052. /*
  22053. ** Enlarge the memory allocation on a StrAccum object so that it is
  22054. ** able to accept at least N more bytes of text.
  22055. **
  22056. ** Return the number of bytes of text that StrAccum is able to accept
  22057. ** after the attempted enlargement. The value returned might be zero.
  22058. */
  22059. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  22060. char *zNew;
  22061. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  22062. if( p->accError ){
  22063. testcase(p->accError==STRACCUM_TOOBIG);
  22064. testcase(p->accError==STRACCUM_NOMEM);
  22065. return 0;
  22066. }
  22067. if( p->mxAlloc==0 ){
  22068. N = p->nAlloc - p->nChar - 1;
  22069. setStrAccumError(p, STRACCUM_TOOBIG);
  22070. return N;
  22071. }else{
  22072. char *zOld = p->bMalloced ? p->zText : 0;
  22073. i64 szNew = p->nChar;
  22074. assert( (p->zText==0 || p->zText==p->zBase)==(p->bMalloced==0) );
  22075. szNew += N + 1;
  22076. if( szNew+p->nChar<=p->mxAlloc ){
  22077. /* Force exponential buffer size growth as long as it does not overflow,
  22078. ** to avoid having to call this routine too often */
  22079. szNew += p->nChar;
  22080. }
  22081. if( szNew > p->mxAlloc ){
  22082. sqlite3StrAccumReset(p);
  22083. setStrAccumError(p, STRACCUM_TOOBIG);
  22084. return 0;
  22085. }else{
  22086. p->nAlloc = (int)szNew;
  22087. }
  22088. if( p->db ){
  22089. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  22090. }else{
  22091. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  22092. }
  22093. if( zNew ){
  22094. assert( p->zText!=0 || p->nChar==0 );
  22095. if( !p->bMalloced && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  22096. p->zText = zNew;
  22097. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  22098. p->bMalloced = 1;
  22099. }else{
  22100. sqlite3StrAccumReset(p);
  22101. setStrAccumError(p, STRACCUM_NOMEM);
  22102. return 0;
  22103. }
  22104. }
  22105. return N;
  22106. }
  22107. /*
  22108. ** Append N copies of character c to the given string buffer.
  22109. */
  22110. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  22111. testcase( p->nChar + (i64)N > 0x7fffffff );
  22112. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  22113. return;
  22114. }
  22115. assert( (p->zText==p->zBase)==(p->bMalloced==0) );
  22116. while( (N--)>0 ) p->zText[p->nChar++] = c;
  22117. }
  22118. /*
  22119. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  22120. ** So enlarge if first, then do the append.
  22121. **
  22122. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  22123. ** work (enlarging the buffer) using tail recursion, so that the
  22124. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  22125. */
  22126. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  22127. N = sqlite3StrAccumEnlarge(p, N);
  22128. if( N>0 ){
  22129. memcpy(&p->zText[p->nChar], z, N);
  22130. p->nChar += N;
  22131. }
  22132. assert( (p->zText==0 || p->zText==p->zBase)==(p->bMalloced==0) );
  22133. }
  22134. /*
  22135. ** Append N bytes of text from z to the StrAccum object. Increase the
  22136. ** size of the memory allocation for StrAccum if necessary.
  22137. */
  22138. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  22139. assert( z!=0 || N==0 );
  22140. assert( p->zText!=0 || p->nChar==0 || p->accError );
  22141. assert( N>=0 );
  22142. assert( p->accError==0 || p->nAlloc==0 );
  22143. if( p->nChar+N >= p->nAlloc ){
  22144. enlargeAndAppend(p,z,N);
  22145. }else{
  22146. assert( p->zText );
  22147. p->nChar += N;
  22148. memcpy(&p->zText[p->nChar-N], z, N);
  22149. }
  22150. }
  22151. /*
  22152. ** Append the complete text of zero-terminated string z[] to the p string.
  22153. */
  22154. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  22155. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  22156. }
  22157. /*
  22158. ** Finish off a string by making sure it is zero-terminated.
  22159. ** Return a pointer to the resulting string. Return a NULL
  22160. ** pointer if any kind of error was encountered.
  22161. */
  22162. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  22163. if( p->zText ){
  22164. assert( (p->zText==p->zBase)==(p->bMalloced==0) );
  22165. p->zText[p->nChar] = 0;
  22166. if( p->mxAlloc>0 && p->bMalloced==0 ){
  22167. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  22168. if( p->zText ){
  22169. memcpy(p->zText, p->zBase, p->nChar+1);
  22170. p->bMalloced = 1;
  22171. }else{
  22172. setStrAccumError(p, STRACCUM_NOMEM);
  22173. }
  22174. }
  22175. }
  22176. return p->zText;
  22177. }
  22178. /*
  22179. ** Reset an StrAccum string. Reclaim all malloced memory.
  22180. */
  22181. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  22182. assert( (p->zText==0 || p->zText==p->zBase)==(p->bMalloced==0) );
  22183. if( p->bMalloced ){
  22184. sqlite3DbFree(p->db, p->zText);
  22185. p->bMalloced = 0;
  22186. }
  22187. p->zText = 0;
  22188. }
  22189. /*
  22190. ** Initialize a string accumulator.
  22191. **
  22192. ** p: The accumulator to be initialized.
  22193. ** db: Pointer to a database connection. May be NULL. Lookaside
  22194. ** memory is used if not NULL. db->mallocFailed is set appropriately
  22195. ** when not NULL.
  22196. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  22197. ** is malloced.
  22198. ** n: Size of zBase in bytes. If total space requirements never exceed
  22199. ** n then no memory allocations ever occur.
  22200. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  22201. ** allocations will ever occur.
  22202. */
  22203. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  22204. p->zText = p->zBase = zBase;
  22205. p->db = db;
  22206. p->nChar = 0;
  22207. p->nAlloc = n;
  22208. p->mxAlloc = mx;
  22209. p->accError = 0;
  22210. p->bMalloced = 0;
  22211. }
  22212. /*
  22213. ** Print into memory obtained from sqliteMalloc(). Use the internal
  22214. ** %-conversion extensions.
  22215. */
  22216. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  22217. char *z;
  22218. char zBase[SQLITE_PRINT_BUF_SIZE];
  22219. StrAccum acc;
  22220. assert( db!=0 );
  22221. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  22222. db->aLimit[SQLITE_LIMIT_LENGTH]);
  22223. sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
  22224. z = sqlite3StrAccumFinish(&acc);
  22225. if( acc.accError==STRACCUM_NOMEM ){
  22226. db->mallocFailed = 1;
  22227. }
  22228. return z;
  22229. }
  22230. /*
  22231. ** Print into memory obtained from sqliteMalloc(). Use the internal
  22232. ** %-conversion extensions.
  22233. */
  22234. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  22235. va_list ap;
  22236. char *z;
  22237. va_start(ap, zFormat);
  22238. z = sqlite3VMPrintf(db, zFormat, ap);
  22239. va_end(ap);
  22240. return z;
  22241. }
  22242. /*
  22243. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  22244. ** %-conversion extensions.
  22245. */
  22246. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
  22247. char *z;
  22248. char zBase[SQLITE_PRINT_BUF_SIZE];
  22249. StrAccum acc;
  22250. #ifdef SQLITE_ENABLE_API_ARMOR
  22251. if( zFormat==0 ){
  22252. (void)SQLITE_MISUSE_BKPT;
  22253. return 0;
  22254. }
  22255. #endif
  22256. #ifndef SQLITE_OMIT_AUTOINIT
  22257. if( sqlite3_initialize() ) return 0;
  22258. #endif
  22259. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  22260. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  22261. z = sqlite3StrAccumFinish(&acc);
  22262. return z;
  22263. }
  22264. /*
  22265. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  22266. ** %-conversion extensions.
  22267. */
  22268. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
  22269. va_list ap;
  22270. char *z;
  22271. #ifndef SQLITE_OMIT_AUTOINIT
  22272. if( sqlite3_initialize() ) return 0;
  22273. #endif
  22274. va_start(ap, zFormat);
  22275. z = sqlite3_vmprintf(zFormat, ap);
  22276. va_end(ap);
  22277. return z;
  22278. }
  22279. /*
  22280. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  22281. ** current locale settings. This is important for SQLite because we
  22282. ** are not able to use a "," as the decimal point in place of "." as
  22283. ** specified by some locales.
  22284. **
  22285. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  22286. ** from the snprintf() standard. Unfortunately, it is too late to change
  22287. ** this without breaking compatibility, so we just have to live with the
  22288. ** mistake.
  22289. **
  22290. ** sqlite3_vsnprintf() is the varargs version.
  22291. */
  22292. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  22293. StrAccum acc;
  22294. if( n<=0 ) return zBuf;
  22295. #ifdef SQLITE_ENABLE_API_ARMOR
  22296. if( zBuf==0 || zFormat==0 ) {
  22297. (void)SQLITE_MISUSE_BKPT;
  22298. if( zBuf ) zBuf[0] = 0;
  22299. return zBuf;
  22300. }
  22301. #endif
  22302. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  22303. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  22304. return sqlite3StrAccumFinish(&acc);
  22305. }
  22306. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  22307. char *z;
  22308. va_list ap;
  22309. va_start(ap,zFormat);
  22310. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  22311. va_end(ap);
  22312. return z;
  22313. }
  22314. /*
  22315. ** This is the routine that actually formats the sqlite3_log() message.
  22316. ** We house it in a separate routine from sqlite3_log() to avoid using
  22317. ** stack space on small-stack systems when logging is disabled.
  22318. **
  22319. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  22320. ** allocate memory because it might be called while the memory allocator
  22321. ** mutex is held.
  22322. **
  22323. ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
  22324. ** certain format characters (%q) or for very large precisions or widths.
  22325. ** Care must be taken that any sqlite3_log() calls that occur while the
  22326. ** memory mutex is held do not use these mechanisms.
  22327. */
  22328. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  22329. StrAccum acc; /* String accumulator */
  22330. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  22331. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  22332. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  22333. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  22334. sqlite3StrAccumFinish(&acc));
  22335. }
  22336. /*
  22337. ** Format and write a message to the log if logging is enabled.
  22338. */
  22339. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
  22340. va_list ap; /* Vararg list */
  22341. if( sqlite3GlobalConfig.xLog ){
  22342. va_start(ap, zFormat);
  22343. renderLogMsg(iErrCode, zFormat, ap);
  22344. va_end(ap);
  22345. }
  22346. }
  22347. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  22348. /*
  22349. ** A version of printf() that understands %lld. Used for debugging.
  22350. ** The printf() built into some versions of windows does not understand %lld
  22351. ** and segfaults if you give it a long long int.
  22352. */
  22353. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  22354. va_list ap;
  22355. StrAccum acc;
  22356. char zBuf[500];
  22357. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  22358. va_start(ap,zFormat);
  22359. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  22360. va_end(ap);
  22361. sqlite3StrAccumFinish(&acc);
  22362. fprintf(stdout,"%s", zBuf);
  22363. fflush(stdout);
  22364. }
  22365. #endif
  22366. /*
  22367. ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
  22368. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  22369. */
  22370. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
  22371. va_list ap;
  22372. va_start(ap,zFormat);
  22373. sqlite3VXPrintf(p, bFlags, zFormat, ap);
  22374. va_end(ap);
  22375. }
  22376. /************** End of printf.c **********************************************/
  22377. /************** Begin file treeview.c ****************************************/
  22378. /*
  22379. ** 2015-06-08
  22380. **
  22381. ** The author disclaims copyright to this source code. In place of
  22382. ** a legal notice, here is a blessing:
  22383. **
  22384. ** May you do good and not evil.
  22385. ** May you find forgiveness for yourself and forgive others.
  22386. ** May you share freely, never taking more than you give.
  22387. **
  22388. *************************************************************************
  22389. **
  22390. ** This file contains C code to implement the TreeView debugging routines.
  22391. ** These routines print a parse tree to standard output for debugging and
  22392. ** analysis.
  22393. **
  22394. ** The interfaces in this file is only available when compiling
  22395. ** with SQLITE_DEBUG.
  22396. */
  22397. /* #include "sqliteInt.h" */
  22398. #ifdef SQLITE_DEBUG
  22399. /*
  22400. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  22401. ** is not the last item in the tree.
  22402. */
  22403. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  22404. if( p==0 ){
  22405. p = sqlite3_malloc64( sizeof(*p) );
  22406. if( p==0 ) return 0;
  22407. memset(p, 0, sizeof(*p));
  22408. }else{
  22409. p->iLevel++;
  22410. }
  22411. assert( moreToFollow==0 || moreToFollow==1 );
  22412. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  22413. return p;
  22414. }
  22415. /*
  22416. ** Finished with one layer of the tree
  22417. */
  22418. static void sqlite3TreeViewPop(TreeView *p){
  22419. if( p==0 ) return;
  22420. p->iLevel--;
  22421. if( p->iLevel<0 ) sqlite3_free(p);
  22422. }
  22423. /*
  22424. ** Generate a single line of output for the tree, with a prefix that contains
  22425. ** all the appropriate tree lines
  22426. */
  22427. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  22428. va_list ap;
  22429. int i;
  22430. StrAccum acc;
  22431. char zBuf[500];
  22432. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  22433. if( p ){
  22434. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  22435. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  22436. }
  22437. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  22438. }
  22439. va_start(ap, zFormat);
  22440. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  22441. va_end(ap);
  22442. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  22443. sqlite3StrAccumFinish(&acc);
  22444. fprintf(stdout,"%s", zBuf);
  22445. fflush(stdout);
  22446. }
  22447. /*
  22448. ** Shorthand for starting a new tree item that consists of a single label
  22449. */
  22450. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  22451. p = sqlite3TreeViewPush(p, moreFollows);
  22452. sqlite3TreeViewLine(p, "%s", zLabel);
  22453. }
  22454. /*
  22455. ** Generate a human-readable description of a WITH clause.
  22456. */
  22457. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  22458. int i;
  22459. if( pWith==0 ) return;
  22460. if( pWith->nCte==0 ) return;
  22461. if( pWith->pOuter ){
  22462. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  22463. }else{
  22464. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  22465. }
  22466. if( pWith->nCte>0 ){
  22467. pView = sqlite3TreeViewPush(pView, 1);
  22468. for(i=0; i<pWith->nCte; i++){
  22469. StrAccum x;
  22470. char zLine[1000];
  22471. const struct Cte *pCte = &pWith->a[i];
  22472. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  22473. sqlite3XPrintf(&x, 0, "%s", pCte->zName);
  22474. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  22475. char cSep = '(';
  22476. int j;
  22477. for(j=0; j<pCte->pCols->nExpr; j++){
  22478. sqlite3XPrintf(&x, 0, "%c%s", cSep, pCte->pCols->a[j].zName);
  22479. cSep = ',';
  22480. }
  22481. sqlite3XPrintf(&x, 0, ")");
  22482. }
  22483. sqlite3XPrintf(&x, 0, " AS");
  22484. sqlite3StrAccumFinish(&x);
  22485. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  22486. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  22487. sqlite3TreeViewPop(pView);
  22488. }
  22489. sqlite3TreeViewPop(pView);
  22490. }
  22491. }
  22492. /*
  22493. ** Generate a human-readable description of a the Select object.
  22494. */
  22495. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  22496. int n = 0;
  22497. int cnt = 0;
  22498. pView = sqlite3TreeViewPush(pView, moreToFollow);
  22499. if( p->pWith ){
  22500. sqlite3TreeViewWith(pView, p->pWith, 1);
  22501. cnt = 1;
  22502. sqlite3TreeViewPush(pView, 1);
  22503. }
  22504. do{
  22505. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x",
  22506. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  22507. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags
  22508. );
  22509. if( cnt++ ) sqlite3TreeViewPop(pView);
  22510. if( p->pPrior ){
  22511. n = 1000;
  22512. }else{
  22513. n = 0;
  22514. if( p->pSrc && p->pSrc->nSrc ) n++;
  22515. if( p->pWhere ) n++;
  22516. if( p->pGroupBy ) n++;
  22517. if( p->pHaving ) n++;
  22518. if( p->pOrderBy ) n++;
  22519. if( p->pLimit ) n++;
  22520. if( p->pOffset ) n++;
  22521. }
  22522. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  22523. if( p->pSrc && p->pSrc->nSrc ){
  22524. int i;
  22525. pView = sqlite3TreeViewPush(pView, (n--)>0);
  22526. sqlite3TreeViewLine(pView, "FROM");
  22527. for(i=0; i<p->pSrc->nSrc; i++){
  22528. struct SrcList_item *pItem = &p->pSrc->a[i];
  22529. StrAccum x;
  22530. char zLine[100];
  22531. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  22532. sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
  22533. if( pItem->zDatabase ){
  22534. sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
  22535. }else if( pItem->zName ){
  22536. sqlite3XPrintf(&x, 0, " %s", pItem->zName);
  22537. }
  22538. if( pItem->pTab ){
  22539. sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
  22540. }
  22541. if( pItem->zAlias ){
  22542. sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
  22543. }
  22544. if( pItem->fg.jointype & JT_LEFT ){
  22545. sqlite3XPrintf(&x, 0, " LEFT-JOIN");
  22546. }
  22547. sqlite3StrAccumFinish(&x);
  22548. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  22549. if( pItem->pSelect ){
  22550. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  22551. }
  22552. if( pItem->fg.isTabFunc ){
  22553. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  22554. }
  22555. sqlite3TreeViewPop(pView);
  22556. }
  22557. sqlite3TreeViewPop(pView);
  22558. }
  22559. if( p->pWhere ){
  22560. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  22561. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  22562. sqlite3TreeViewPop(pView);
  22563. }
  22564. if( p->pGroupBy ){
  22565. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  22566. }
  22567. if( p->pHaving ){
  22568. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  22569. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  22570. sqlite3TreeViewPop(pView);
  22571. }
  22572. if( p->pOrderBy ){
  22573. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  22574. }
  22575. if( p->pLimit ){
  22576. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  22577. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  22578. sqlite3TreeViewPop(pView);
  22579. }
  22580. if( p->pOffset ){
  22581. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  22582. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  22583. sqlite3TreeViewPop(pView);
  22584. }
  22585. if( p->pPrior ){
  22586. const char *zOp = "UNION";
  22587. switch( p->op ){
  22588. case TK_ALL: zOp = "UNION ALL"; break;
  22589. case TK_INTERSECT: zOp = "INTERSECT"; break;
  22590. case TK_EXCEPT: zOp = "EXCEPT"; break;
  22591. }
  22592. sqlite3TreeViewItem(pView, zOp, 1);
  22593. }
  22594. p = p->pPrior;
  22595. }while( p!=0 );
  22596. sqlite3TreeViewPop(pView);
  22597. }
  22598. /*
  22599. ** Generate a human-readable explanation of an expression tree.
  22600. */
  22601. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  22602. const char *zBinOp = 0; /* Binary operator */
  22603. const char *zUniOp = 0; /* Unary operator */
  22604. char zFlgs[30];
  22605. pView = sqlite3TreeViewPush(pView, moreToFollow);
  22606. if( pExpr==0 ){
  22607. sqlite3TreeViewLine(pView, "nil");
  22608. sqlite3TreeViewPop(pView);
  22609. return;
  22610. }
  22611. if( pExpr->flags ){
  22612. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  22613. }else{
  22614. zFlgs[0] = 0;
  22615. }
  22616. switch( pExpr->op ){
  22617. case TK_AGG_COLUMN: {
  22618. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  22619. pExpr->iTable, pExpr->iColumn, zFlgs);
  22620. break;
  22621. }
  22622. case TK_COLUMN: {
  22623. if( pExpr->iTable<0 ){
  22624. /* This only happens when coding check constraints */
  22625. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  22626. }else{
  22627. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  22628. pExpr->iTable, pExpr->iColumn, zFlgs);
  22629. }
  22630. break;
  22631. }
  22632. case TK_INTEGER: {
  22633. if( pExpr->flags & EP_IntValue ){
  22634. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  22635. }else{
  22636. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  22637. }
  22638. break;
  22639. }
  22640. #ifndef SQLITE_OMIT_FLOATING_POINT
  22641. case TK_FLOAT: {
  22642. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  22643. break;
  22644. }
  22645. #endif
  22646. case TK_STRING: {
  22647. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  22648. break;
  22649. }
  22650. case TK_NULL: {
  22651. sqlite3TreeViewLine(pView,"NULL");
  22652. break;
  22653. }
  22654. #ifndef SQLITE_OMIT_BLOB_LITERAL
  22655. case TK_BLOB: {
  22656. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  22657. break;
  22658. }
  22659. #endif
  22660. case TK_VARIABLE: {
  22661. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  22662. pExpr->u.zToken, pExpr->iColumn);
  22663. break;
  22664. }
  22665. case TK_REGISTER: {
  22666. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  22667. break;
  22668. }
  22669. case TK_ID: {
  22670. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  22671. break;
  22672. }
  22673. #ifndef SQLITE_OMIT_CAST
  22674. case TK_CAST: {
  22675. /* Expressions of the form: CAST(pLeft AS token) */
  22676. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  22677. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  22678. break;
  22679. }
  22680. #endif /* SQLITE_OMIT_CAST */
  22681. case TK_LT: zBinOp = "LT"; break;
  22682. case TK_LE: zBinOp = "LE"; break;
  22683. case TK_GT: zBinOp = "GT"; break;
  22684. case TK_GE: zBinOp = "GE"; break;
  22685. case TK_NE: zBinOp = "NE"; break;
  22686. case TK_EQ: zBinOp = "EQ"; break;
  22687. case TK_IS: zBinOp = "IS"; break;
  22688. case TK_ISNOT: zBinOp = "ISNOT"; break;
  22689. case TK_AND: zBinOp = "AND"; break;
  22690. case TK_OR: zBinOp = "OR"; break;
  22691. case TK_PLUS: zBinOp = "ADD"; break;
  22692. case TK_STAR: zBinOp = "MUL"; break;
  22693. case TK_MINUS: zBinOp = "SUB"; break;
  22694. case TK_REM: zBinOp = "REM"; break;
  22695. case TK_BITAND: zBinOp = "BITAND"; break;
  22696. case TK_BITOR: zBinOp = "BITOR"; break;
  22697. case TK_SLASH: zBinOp = "DIV"; break;
  22698. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  22699. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  22700. case TK_CONCAT: zBinOp = "CONCAT"; break;
  22701. case TK_DOT: zBinOp = "DOT"; break;
  22702. case TK_UMINUS: zUniOp = "UMINUS"; break;
  22703. case TK_UPLUS: zUniOp = "UPLUS"; break;
  22704. case TK_BITNOT: zUniOp = "BITNOT"; break;
  22705. case TK_NOT: zUniOp = "NOT"; break;
  22706. case TK_ISNULL: zUniOp = "ISNULL"; break;
  22707. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  22708. case TK_COLLATE: {
  22709. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  22710. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  22711. break;
  22712. }
  22713. case TK_AGG_FUNCTION:
  22714. case TK_FUNCTION: {
  22715. ExprList *pFarg; /* List of function arguments */
  22716. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  22717. pFarg = 0;
  22718. }else{
  22719. pFarg = pExpr->x.pList;
  22720. }
  22721. if( pExpr->op==TK_AGG_FUNCTION ){
  22722. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  22723. pExpr->op2, pExpr->u.zToken);
  22724. }else{
  22725. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  22726. }
  22727. if( pFarg ){
  22728. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  22729. }
  22730. break;
  22731. }
  22732. #ifndef SQLITE_OMIT_SUBQUERY
  22733. case TK_EXISTS: {
  22734. sqlite3TreeViewLine(pView, "EXISTS-expr");
  22735. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  22736. break;
  22737. }
  22738. case TK_SELECT: {
  22739. sqlite3TreeViewLine(pView, "SELECT-expr");
  22740. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  22741. break;
  22742. }
  22743. case TK_IN: {
  22744. sqlite3TreeViewLine(pView, "IN");
  22745. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  22746. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  22747. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  22748. }else{
  22749. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  22750. }
  22751. break;
  22752. }
  22753. #endif /* SQLITE_OMIT_SUBQUERY */
  22754. /*
  22755. ** x BETWEEN y AND z
  22756. **
  22757. ** This is equivalent to
  22758. **
  22759. ** x>=y AND x<=z
  22760. **
  22761. ** X is stored in pExpr->pLeft.
  22762. ** Y is stored in pExpr->pList->a[0].pExpr.
  22763. ** Z is stored in pExpr->pList->a[1].pExpr.
  22764. */
  22765. case TK_BETWEEN: {
  22766. Expr *pX = pExpr->pLeft;
  22767. Expr *pY = pExpr->x.pList->a[0].pExpr;
  22768. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  22769. sqlite3TreeViewLine(pView, "BETWEEN");
  22770. sqlite3TreeViewExpr(pView, pX, 1);
  22771. sqlite3TreeViewExpr(pView, pY, 1);
  22772. sqlite3TreeViewExpr(pView, pZ, 0);
  22773. break;
  22774. }
  22775. case TK_TRIGGER: {
  22776. /* If the opcode is TK_TRIGGER, then the expression is a reference
  22777. ** to a column in the new.* or old.* pseudo-tables available to
  22778. ** trigger programs. In this case Expr.iTable is set to 1 for the
  22779. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  22780. ** is set to the column of the pseudo-table to read, or to -1 to
  22781. ** read the rowid field.
  22782. */
  22783. sqlite3TreeViewLine(pView, "%s(%d)",
  22784. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  22785. break;
  22786. }
  22787. case TK_CASE: {
  22788. sqlite3TreeViewLine(pView, "CASE");
  22789. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  22790. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  22791. break;
  22792. }
  22793. #ifndef SQLITE_OMIT_TRIGGER
  22794. case TK_RAISE: {
  22795. const char *zType = "unk";
  22796. switch( pExpr->affinity ){
  22797. case OE_Rollback: zType = "rollback"; break;
  22798. case OE_Abort: zType = "abort"; break;
  22799. case OE_Fail: zType = "fail"; break;
  22800. case OE_Ignore: zType = "ignore"; break;
  22801. }
  22802. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  22803. break;
  22804. }
  22805. #endif
  22806. default: {
  22807. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  22808. break;
  22809. }
  22810. }
  22811. if( zBinOp ){
  22812. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  22813. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  22814. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  22815. }else if( zUniOp ){
  22816. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  22817. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  22818. }
  22819. sqlite3TreeViewPop(pView);
  22820. }
  22821. /*
  22822. ** Generate a human-readable explanation of an expression list.
  22823. */
  22824. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  22825. TreeView *pView,
  22826. const ExprList *pList,
  22827. u8 moreToFollow,
  22828. const char *zLabel
  22829. ){
  22830. int i;
  22831. pView = sqlite3TreeViewPush(pView, moreToFollow);
  22832. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  22833. if( pList==0 ){
  22834. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  22835. }else{
  22836. sqlite3TreeViewLine(pView, "%s", zLabel);
  22837. for(i=0; i<pList->nExpr; i++){
  22838. int j = pList->a[i].u.x.iOrderByCol;
  22839. if( j ){
  22840. sqlite3TreeViewPush(pView, 0);
  22841. sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
  22842. }
  22843. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  22844. if( j ) sqlite3TreeViewPop(pView);
  22845. }
  22846. }
  22847. sqlite3TreeViewPop(pView);
  22848. }
  22849. #endif /* SQLITE_DEBUG */
  22850. /************** End of treeview.c ********************************************/
  22851. /************** Begin file random.c ******************************************/
  22852. /*
  22853. ** 2001 September 15
  22854. **
  22855. ** The author disclaims copyright to this source code. In place of
  22856. ** a legal notice, here is a blessing:
  22857. **
  22858. ** May you do good and not evil.
  22859. ** May you find forgiveness for yourself and forgive others.
  22860. ** May you share freely, never taking more than you give.
  22861. **
  22862. *************************************************************************
  22863. ** This file contains code to implement a pseudo-random number
  22864. ** generator (PRNG) for SQLite.
  22865. **
  22866. ** Random numbers are used by some of the database backends in order
  22867. ** to generate random integer keys for tables or random filenames.
  22868. */
  22869. /* #include "sqliteInt.h" */
  22870. /* All threads share a single random number generator.
  22871. ** This structure is the current state of the generator.
  22872. */
  22873. static SQLITE_WSD struct sqlite3PrngType {
  22874. unsigned char isInit; /* True if initialized */
  22875. unsigned char i, j; /* State variables */
  22876. unsigned char s[256]; /* State variables */
  22877. } sqlite3Prng;
  22878. /*
  22879. ** Return N random bytes.
  22880. */
  22881. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
  22882. unsigned char t;
  22883. unsigned char *zBuf = pBuf;
  22884. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  22885. ** state vector. If writable static data is unsupported on the target,
  22886. ** we have to locate the state vector at run-time. In the more common
  22887. ** case where writable static data is supported, wsdPrng can refer directly
  22888. ** to the "sqlite3Prng" state vector declared above.
  22889. */
  22890. #ifdef SQLITE_OMIT_WSD
  22891. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  22892. # define wsdPrng p[0]
  22893. #else
  22894. # define wsdPrng sqlite3Prng
  22895. #endif
  22896. #if SQLITE_THREADSAFE
  22897. sqlite3_mutex *mutex;
  22898. #endif
  22899. #ifndef SQLITE_OMIT_AUTOINIT
  22900. if( sqlite3_initialize() ) return;
  22901. #endif
  22902. #if SQLITE_THREADSAFE
  22903. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  22904. #endif
  22905. sqlite3_mutex_enter(mutex);
  22906. if( N<=0 || pBuf==0 ){
  22907. wsdPrng.isInit = 0;
  22908. sqlite3_mutex_leave(mutex);
  22909. return;
  22910. }
  22911. /* Initialize the state of the random number generator once,
  22912. ** the first time this routine is called. The seed value does
  22913. ** not need to contain a lot of randomness since we are not
  22914. ** trying to do secure encryption or anything like that...
  22915. **
  22916. ** Nothing in this file or anywhere else in SQLite does any kind of
  22917. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  22918. ** number generator) not as an encryption device.
  22919. */
  22920. if( !wsdPrng.isInit ){
  22921. int i;
  22922. char k[256];
  22923. wsdPrng.j = 0;
  22924. wsdPrng.i = 0;
  22925. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  22926. for(i=0; i<256; i++){
  22927. wsdPrng.s[i] = (u8)i;
  22928. }
  22929. for(i=0; i<256; i++){
  22930. wsdPrng.j += wsdPrng.s[i] + k[i];
  22931. t = wsdPrng.s[wsdPrng.j];
  22932. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  22933. wsdPrng.s[i] = t;
  22934. }
  22935. wsdPrng.isInit = 1;
  22936. }
  22937. assert( N>0 );
  22938. do{
  22939. wsdPrng.i++;
  22940. t = wsdPrng.s[wsdPrng.i];
  22941. wsdPrng.j += t;
  22942. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  22943. wsdPrng.s[wsdPrng.j] = t;
  22944. t += wsdPrng.s[wsdPrng.i];
  22945. *(zBuf++) = wsdPrng.s[t];
  22946. }while( --N );
  22947. sqlite3_mutex_leave(mutex);
  22948. }
  22949. #ifndef SQLITE_OMIT_BUILTIN_TEST
  22950. /*
  22951. ** For testing purposes, we sometimes want to preserve the state of
  22952. ** PRNG and restore the PRNG to its saved state at a later time, or
  22953. ** to reset the PRNG to its initial state. These routines accomplish
  22954. ** those tasks.
  22955. **
  22956. ** The sqlite3_test_control() interface calls these routines to
  22957. ** control the PRNG.
  22958. */
  22959. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  22960. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  22961. memcpy(
  22962. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  22963. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  22964. sizeof(sqlite3Prng)
  22965. );
  22966. }
  22967. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  22968. memcpy(
  22969. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  22970. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  22971. sizeof(sqlite3Prng)
  22972. );
  22973. }
  22974. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  22975. /************** End of random.c **********************************************/
  22976. /************** Begin file threads.c *****************************************/
  22977. /*
  22978. ** 2012 July 21
  22979. **
  22980. ** The author disclaims copyright to this source code. In place of
  22981. ** a legal notice, here is a blessing:
  22982. **
  22983. ** May you do good and not evil.
  22984. ** May you find forgiveness for yourself and forgive others.
  22985. ** May you share freely, never taking more than you give.
  22986. **
  22987. ******************************************************************************
  22988. **
  22989. ** This file presents a simple cross-platform threading interface for
  22990. ** use internally by SQLite.
  22991. **
  22992. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  22993. ** runs independently of its creator until it is joined using
  22994. ** sqlite3ThreadJoin(), at which point it terminates.
  22995. **
  22996. ** Threads do not have to be real. It could be that the work of the
  22997. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  22998. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  22999. ** single threaded systems. Nothing in SQLite requires multiple threads.
  23000. ** This interface exists so that applications that want to take advantage
  23001. ** of multiple cores can do so, while also allowing applications to stay
  23002. ** single-threaded if desired.
  23003. */
  23004. /* #include "sqliteInt.h" */
  23005. #if SQLITE_OS_WIN
  23006. /* # include "os_win.h" */
  23007. #endif
  23008. #if SQLITE_MAX_WORKER_THREADS>0
  23009. /********************************* Unix Pthreads ****************************/
  23010. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  23011. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  23012. /* #include <pthread.h> */
  23013. /* A running thread */
  23014. struct SQLiteThread {
  23015. pthread_t tid; /* Thread ID */
  23016. int done; /* Set to true when thread finishes */
  23017. void *pOut; /* Result returned by the thread */
  23018. void *(*xTask)(void*); /* The thread routine */
  23019. void *pIn; /* Argument to the thread */
  23020. };
  23021. /* Create a new thread */
  23022. SQLITE_PRIVATE int sqlite3ThreadCreate(
  23023. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  23024. void *(*xTask)(void*), /* Routine to run in a separate thread */
  23025. void *pIn /* Argument passed into xTask() */
  23026. ){
  23027. SQLiteThread *p;
  23028. int rc;
  23029. assert( ppThread!=0 );
  23030. assert( xTask!=0 );
  23031. /* This routine is never used in single-threaded mode */
  23032. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  23033. *ppThread = 0;
  23034. p = sqlite3Malloc(sizeof(*p));
  23035. if( p==0 ) return SQLITE_NOMEM;
  23036. memset(p, 0, sizeof(*p));
  23037. p->xTask = xTask;
  23038. p->pIn = pIn;
  23039. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  23040. ** function that returns SQLITE_ERROR when passed the argument 200, that
  23041. ** forces worker threads to run sequentially and deterministically
  23042. ** for testing purposes. */
  23043. if( sqlite3FaultSim(200) ){
  23044. rc = 1;
  23045. }else{
  23046. rc = pthread_create(&p->tid, 0, xTask, pIn);
  23047. }
  23048. if( rc ){
  23049. p->done = 1;
  23050. p->pOut = xTask(pIn);
  23051. }
  23052. *ppThread = p;
  23053. return SQLITE_OK;
  23054. }
  23055. /* Get the results of the thread */
  23056. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  23057. int rc;
  23058. assert( ppOut!=0 );
  23059. if( NEVER(p==0) ) return SQLITE_NOMEM;
  23060. if( p->done ){
  23061. *ppOut = p->pOut;
  23062. rc = SQLITE_OK;
  23063. }else{
  23064. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  23065. }
  23066. sqlite3_free(p);
  23067. return rc;
  23068. }
  23069. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  23070. /******************************** End Unix Pthreads *************************/
  23071. /********************************* Win32 Threads ****************************/
  23072. #if SQLITE_OS_WIN_THREADS
  23073. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  23074. #include <process.h>
  23075. /* A running thread */
  23076. struct SQLiteThread {
  23077. void *tid; /* The thread handle */
  23078. unsigned id; /* The thread identifier */
  23079. void *(*xTask)(void*); /* The routine to run as a thread */
  23080. void *pIn; /* Argument to xTask */
  23081. void *pResult; /* Result of xTask */
  23082. };
  23083. /* Thread procedure Win32 compatibility shim */
  23084. static unsigned __stdcall sqlite3ThreadProc(
  23085. void *pArg /* IN: Pointer to the SQLiteThread structure */
  23086. ){
  23087. SQLiteThread *p = (SQLiteThread *)pArg;
  23088. assert( p!=0 );
  23089. #if 0
  23090. /*
  23091. ** This assert appears to trigger spuriously on certain
  23092. ** versions of Windows, possibly due to _beginthreadex()
  23093. ** and/or CreateThread() not fully setting their thread
  23094. ** ID parameter before starting the thread.
  23095. */
  23096. assert( p->id==GetCurrentThreadId() );
  23097. #endif
  23098. assert( p->xTask!=0 );
  23099. p->pResult = p->xTask(p->pIn);
  23100. _endthreadex(0);
  23101. return 0; /* NOT REACHED */
  23102. }
  23103. /* Create a new thread */
  23104. SQLITE_PRIVATE int sqlite3ThreadCreate(
  23105. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  23106. void *(*xTask)(void*), /* Routine to run in a separate thread */
  23107. void *pIn /* Argument passed into xTask() */
  23108. ){
  23109. SQLiteThread *p;
  23110. assert( ppThread!=0 );
  23111. assert( xTask!=0 );
  23112. *ppThread = 0;
  23113. p = sqlite3Malloc(sizeof(*p));
  23114. if( p==0 ) return SQLITE_NOMEM;
  23115. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  23116. ** function that returns SQLITE_ERROR when passed the argument 200, that
  23117. ** forces worker threads to run sequentially and deterministically
  23118. ** (via the sqlite3FaultSim() term of the conditional) for testing
  23119. ** purposes. */
  23120. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  23121. memset(p, 0, sizeof(*p));
  23122. }else{
  23123. p->xTask = xTask;
  23124. p->pIn = pIn;
  23125. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  23126. if( p->tid==0 ){
  23127. memset(p, 0, sizeof(*p));
  23128. }
  23129. }
  23130. if( p->xTask==0 ){
  23131. p->id = GetCurrentThreadId();
  23132. p->pResult = xTask(pIn);
  23133. }
  23134. *ppThread = p;
  23135. return SQLITE_OK;
  23136. }
  23137. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  23138. /* Get the results of the thread */
  23139. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  23140. DWORD rc;
  23141. BOOL bRc;
  23142. assert( ppOut!=0 );
  23143. if( NEVER(p==0) ) return SQLITE_NOMEM;
  23144. if( p->xTask==0 ){
  23145. /* assert( p->id==GetCurrentThreadId() ); */
  23146. rc = WAIT_OBJECT_0;
  23147. assert( p->tid==0 );
  23148. }else{
  23149. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  23150. rc = sqlite3Win32Wait((HANDLE)p->tid);
  23151. assert( rc!=WAIT_IO_COMPLETION );
  23152. bRc = CloseHandle((HANDLE)p->tid);
  23153. assert( bRc );
  23154. }
  23155. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  23156. sqlite3_free(p);
  23157. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  23158. }
  23159. #endif /* SQLITE_OS_WIN_THREADS */
  23160. /******************************** End Win32 Threads *************************/
  23161. /********************************* Single-Threaded **************************/
  23162. #ifndef SQLITE_THREADS_IMPLEMENTED
  23163. /*
  23164. ** This implementation does not actually create a new thread. It does the
  23165. ** work of the thread in the main thread, when either the thread is created
  23166. ** or when it is joined
  23167. */
  23168. /* A running thread */
  23169. struct SQLiteThread {
  23170. void *(*xTask)(void*); /* The routine to run as a thread */
  23171. void *pIn; /* Argument to xTask */
  23172. void *pResult; /* Result of xTask */
  23173. };
  23174. /* Create a new thread */
  23175. SQLITE_PRIVATE int sqlite3ThreadCreate(
  23176. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  23177. void *(*xTask)(void*), /* Routine to run in a separate thread */
  23178. void *pIn /* Argument passed into xTask() */
  23179. ){
  23180. SQLiteThread *p;
  23181. assert( ppThread!=0 );
  23182. assert( xTask!=0 );
  23183. *ppThread = 0;
  23184. p = sqlite3Malloc(sizeof(*p));
  23185. if( p==0 ) return SQLITE_NOMEM;
  23186. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  23187. p->xTask = xTask;
  23188. p->pIn = pIn;
  23189. }else{
  23190. p->xTask = 0;
  23191. p->pResult = xTask(pIn);
  23192. }
  23193. *ppThread = p;
  23194. return SQLITE_OK;
  23195. }
  23196. /* Get the results of the thread */
  23197. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  23198. assert( ppOut!=0 );
  23199. if( NEVER(p==0) ) return SQLITE_NOMEM;
  23200. if( p->xTask ){
  23201. *ppOut = p->xTask(p->pIn);
  23202. }else{
  23203. *ppOut = p->pResult;
  23204. }
  23205. sqlite3_free(p);
  23206. #if defined(SQLITE_TEST)
  23207. {
  23208. void *pTstAlloc = sqlite3Malloc(10);
  23209. if (!pTstAlloc) return SQLITE_NOMEM;
  23210. sqlite3_free(pTstAlloc);
  23211. }
  23212. #endif
  23213. return SQLITE_OK;
  23214. }
  23215. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  23216. /****************************** End Single-Threaded *************************/
  23217. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  23218. /************** End of threads.c *********************************************/
  23219. /************** Begin file utf.c *********************************************/
  23220. /*
  23221. ** 2004 April 13
  23222. **
  23223. ** The author disclaims copyright to this source code. In place of
  23224. ** a legal notice, here is a blessing:
  23225. **
  23226. ** May you do good and not evil.
  23227. ** May you find forgiveness for yourself and forgive others.
  23228. ** May you share freely, never taking more than you give.
  23229. **
  23230. *************************************************************************
  23231. ** This file contains routines used to translate between UTF-8,
  23232. ** UTF-16, UTF-16BE, and UTF-16LE.
  23233. **
  23234. ** Notes on UTF-8:
  23235. **
  23236. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  23237. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  23238. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  23239. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  23240. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  23241. **
  23242. **
  23243. ** Notes on UTF-16: (with wwww+1==uuuuu)
  23244. **
  23245. ** Word-0 Word-1 Value
  23246. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  23247. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  23248. **
  23249. **
  23250. ** BOM or Byte Order Mark:
  23251. ** 0xff 0xfe little-endian utf-16 follows
  23252. ** 0xfe 0xff big-endian utf-16 follows
  23253. **
  23254. */
  23255. /* #include "sqliteInt.h" */
  23256. /* #include <assert.h> */
  23257. /* #include "vdbeInt.h" */
  23258. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  23259. /*
  23260. ** The following constant value is used by the SQLITE_BIGENDIAN and
  23261. ** SQLITE_LITTLEENDIAN macros.
  23262. */
  23263. SQLITE_PRIVATE const int sqlite3one = 1;
  23264. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  23265. /*
  23266. ** This lookup table is used to help decode the first byte of
  23267. ** a multi-byte UTF8 character.
  23268. */
  23269. static const unsigned char sqlite3Utf8Trans1[] = {
  23270. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  23271. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  23272. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  23273. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  23274. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  23275. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  23276. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  23277. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  23278. };
  23279. #define WRITE_UTF8(zOut, c) { \
  23280. if( c<0x00080 ){ \
  23281. *zOut++ = (u8)(c&0xFF); \
  23282. } \
  23283. else if( c<0x00800 ){ \
  23284. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  23285. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  23286. } \
  23287. else if( c<0x10000 ){ \
  23288. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  23289. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  23290. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  23291. }else{ \
  23292. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  23293. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  23294. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  23295. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  23296. } \
  23297. }
  23298. #define WRITE_UTF16LE(zOut, c) { \
  23299. if( c<=0xFFFF ){ \
  23300. *zOut++ = (u8)(c&0x00FF); \
  23301. *zOut++ = (u8)((c>>8)&0x00FF); \
  23302. }else{ \
  23303. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  23304. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  23305. *zOut++ = (u8)(c&0x00FF); \
  23306. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  23307. } \
  23308. }
  23309. #define WRITE_UTF16BE(zOut, c) { \
  23310. if( c<=0xFFFF ){ \
  23311. *zOut++ = (u8)((c>>8)&0x00FF); \
  23312. *zOut++ = (u8)(c&0x00FF); \
  23313. }else{ \
  23314. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  23315. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  23316. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  23317. *zOut++ = (u8)(c&0x00FF); \
  23318. } \
  23319. }
  23320. #define READ_UTF16LE(zIn, TERM, c){ \
  23321. c = (*zIn++); \
  23322. c += ((*zIn++)<<8); \
  23323. if( c>=0xD800 && c<0xE000 && TERM ){ \
  23324. int c2 = (*zIn++); \
  23325. c2 += ((*zIn++)<<8); \
  23326. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  23327. } \
  23328. }
  23329. #define READ_UTF16BE(zIn, TERM, c){ \
  23330. c = ((*zIn++)<<8); \
  23331. c += (*zIn++); \
  23332. if( c>=0xD800 && c<0xE000 && TERM ){ \
  23333. int c2 = ((*zIn++)<<8); \
  23334. c2 += (*zIn++); \
  23335. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  23336. } \
  23337. }
  23338. /*
  23339. ** Translate a single UTF-8 character. Return the unicode value.
  23340. **
  23341. ** During translation, assume that the byte that zTerm points
  23342. ** is a 0x00.
  23343. **
  23344. ** Write a pointer to the next unread byte back into *pzNext.
  23345. **
  23346. ** Notes On Invalid UTF-8:
  23347. **
  23348. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  23349. ** be encoded as a multi-byte character. Any multi-byte character that
  23350. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  23351. **
  23352. ** * This routine never allows a UTF16 surrogate value to be encoded.
  23353. ** If a multi-byte character attempts to encode a value between
  23354. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  23355. **
  23356. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  23357. ** byte of a character are interpreted as single-byte characters
  23358. ** and rendered as themselves even though they are technically
  23359. ** invalid characters.
  23360. **
  23361. ** * This routine accepts over-length UTF8 encodings
  23362. ** for unicode values 0x80 and greater. It does not change over-length
  23363. ** encodings to 0xfffd as some systems recommend.
  23364. */
  23365. #define READ_UTF8(zIn, zTerm, c) \
  23366. c = *(zIn++); \
  23367. if( c>=0xc0 ){ \
  23368. c = sqlite3Utf8Trans1[c-0xc0]; \
  23369. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  23370. c = (c<<6) + (0x3f & *(zIn++)); \
  23371. } \
  23372. if( c<0x80 \
  23373. || (c&0xFFFFF800)==0xD800 \
  23374. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  23375. }
  23376. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  23377. const unsigned char **pz /* Pointer to string from which to read char */
  23378. ){
  23379. unsigned int c;
  23380. /* Same as READ_UTF8() above but without the zTerm parameter.
  23381. ** For this routine, we assume the UTF8 string is always zero-terminated.
  23382. */
  23383. c = *((*pz)++);
  23384. if( c>=0xc0 ){
  23385. c = sqlite3Utf8Trans1[c-0xc0];
  23386. while( (*(*pz) & 0xc0)==0x80 ){
  23387. c = (c<<6) + (0x3f & *((*pz)++));
  23388. }
  23389. if( c<0x80
  23390. || (c&0xFFFFF800)==0xD800
  23391. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  23392. }
  23393. return c;
  23394. }
  23395. /*
  23396. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  23397. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  23398. */
  23399. /* #define TRANSLATE_TRACE 1 */
  23400. #ifndef SQLITE_OMIT_UTF16
  23401. /*
  23402. ** This routine transforms the internal text encoding used by pMem to
  23403. ** desiredEnc. It is an error if the string is already of the desired
  23404. ** encoding, or if *pMem does not contain a string value.
  23405. */
  23406. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  23407. int len; /* Maximum length of output string in bytes */
  23408. unsigned char *zOut; /* Output buffer */
  23409. unsigned char *zIn; /* Input iterator */
  23410. unsigned char *zTerm; /* End of input */
  23411. unsigned char *z; /* Output iterator */
  23412. unsigned int c;
  23413. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  23414. assert( pMem->flags&MEM_Str );
  23415. assert( pMem->enc!=desiredEnc );
  23416. assert( pMem->enc!=0 );
  23417. assert( pMem->n>=0 );
  23418. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  23419. {
  23420. char zBuf[100];
  23421. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  23422. fprintf(stderr, "INPUT: %s\n", zBuf);
  23423. }
  23424. #endif
  23425. /* If the translation is between UTF-16 little and big endian, then
  23426. ** all that is required is to swap the byte order. This case is handled
  23427. ** differently from the others.
  23428. */
  23429. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  23430. u8 temp;
  23431. int rc;
  23432. rc = sqlite3VdbeMemMakeWriteable(pMem);
  23433. if( rc!=SQLITE_OK ){
  23434. assert( rc==SQLITE_NOMEM );
  23435. return SQLITE_NOMEM;
  23436. }
  23437. zIn = (u8*)pMem->z;
  23438. zTerm = &zIn[pMem->n&~1];
  23439. while( zIn<zTerm ){
  23440. temp = *zIn;
  23441. *zIn = *(zIn+1);
  23442. zIn++;
  23443. *zIn++ = temp;
  23444. }
  23445. pMem->enc = desiredEnc;
  23446. goto translate_out;
  23447. }
  23448. /* Set len to the maximum number of bytes required in the output buffer. */
  23449. if( desiredEnc==SQLITE_UTF8 ){
  23450. /* When converting from UTF-16, the maximum growth results from
  23451. ** translating a 2-byte character to a 4-byte UTF-8 character.
  23452. ** A single byte is required for the output string
  23453. ** nul-terminator.
  23454. */
  23455. pMem->n &= ~1;
  23456. len = pMem->n * 2 + 1;
  23457. }else{
  23458. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  23459. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  23460. ** character. Two bytes are required in the output buffer for the
  23461. ** nul-terminator.
  23462. */
  23463. len = pMem->n * 2 + 2;
  23464. }
  23465. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  23466. ** byte past the end.
  23467. **
  23468. ** Variable zOut is set to point at the output buffer, space obtained
  23469. ** from sqlite3_malloc().
  23470. */
  23471. zIn = (u8*)pMem->z;
  23472. zTerm = &zIn[pMem->n];
  23473. zOut = sqlite3DbMallocRaw(pMem->db, len);
  23474. if( !zOut ){
  23475. return SQLITE_NOMEM;
  23476. }
  23477. z = zOut;
  23478. if( pMem->enc==SQLITE_UTF8 ){
  23479. if( desiredEnc==SQLITE_UTF16LE ){
  23480. /* UTF-8 -> UTF-16 Little-endian */
  23481. while( zIn<zTerm ){
  23482. READ_UTF8(zIn, zTerm, c);
  23483. WRITE_UTF16LE(z, c);
  23484. }
  23485. }else{
  23486. assert( desiredEnc==SQLITE_UTF16BE );
  23487. /* UTF-8 -> UTF-16 Big-endian */
  23488. while( zIn<zTerm ){
  23489. READ_UTF8(zIn, zTerm, c);
  23490. WRITE_UTF16BE(z, c);
  23491. }
  23492. }
  23493. pMem->n = (int)(z - zOut);
  23494. *z++ = 0;
  23495. }else{
  23496. assert( desiredEnc==SQLITE_UTF8 );
  23497. if( pMem->enc==SQLITE_UTF16LE ){
  23498. /* UTF-16 Little-endian -> UTF-8 */
  23499. while( zIn<zTerm ){
  23500. READ_UTF16LE(zIn, zIn<zTerm, c);
  23501. WRITE_UTF8(z, c);
  23502. }
  23503. }else{
  23504. /* UTF-16 Big-endian -> UTF-8 */
  23505. while( zIn<zTerm ){
  23506. READ_UTF16BE(zIn, zIn<zTerm, c);
  23507. WRITE_UTF8(z, c);
  23508. }
  23509. }
  23510. pMem->n = (int)(z - zOut);
  23511. }
  23512. *z = 0;
  23513. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  23514. c = pMem->flags;
  23515. sqlite3VdbeMemRelease(pMem);
  23516. pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
  23517. pMem->enc = desiredEnc;
  23518. pMem->z = (char*)zOut;
  23519. pMem->zMalloc = pMem->z;
  23520. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  23521. translate_out:
  23522. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  23523. {
  23524. char zBuf[100];
  23525. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  23526. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  23527. }
  23528. #endif
  23529. return SQLITE_OK;
  23530. }
  23531. /*
  23532. ** This routine checks for a byte-order mark at the beginning of the
  23533. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  23534. ** the encoding of the Mem adjusted. This routine does not do any
  23535. ** byte-swapping, it just sets Mem.enc appropriately.
  23536. **
  23537. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  23538. ** changed by this function.
  23539. */
  23540. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  23541. int rc = SQLITE_OK;
  23542. u8 bom = 0;
  23543. assert( pMem->n>=0 );
  23544. if( pMem->n>1 ){
  23545. u8 b1 = *(u8 *)pMem->z;
  23546. u8 b2 = *(((u8 *)pMem->z) + 1);
  23547. if( b1==0xFE && b2==0xFF ){
  23548. bom = SQLITE_UTF16BE;
  23549. }
  23550. if( b1==0xFF && b2==0xFE ){
  23551. bom = SQLITE_UTF16LE;
  23552. }
  23553. }
  23554. if( bom ){
  23555. rc = sqlite3VdbeMemMakeWriteable(pMem);
  23556. if( rc==SQLITE_OK ){
  23557. pMem->n -= 2;
  23558. memmove(pMem->z, &pMem->z[2], pMem->n);
  23559. pMem->z[pMem->n] = '\0';
  23560. pMem->z[pMem->n+1] = '\0';
  23561. pMem->flags |= MEM_Term;
  23562. pMem->enc = bom;
  23563. }
  23564. }
  23565. return rc;
  23566. }
  23567. #endif /* SQLITE_OMIT_UTF16 */
  23568. /*
  23569. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  23570. ** return the number of unicode characters in pZ up to (but not including)
  23571. ** the first 0x00 byte. If nByte is not less than zero, return the
  23572. ** number of unicode characters in the first nByte of pZ (or up to
  23573. ** the first 0x00, whichever comes first).
  23574. */
  23575. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  23576. int r = 0;
  23577. const u8 *z = (const u8*)zIn;
  23578. const u8 *zTerm;
  23579. if( nByte>=0 ){
  23580. zTerm = &z[nByte];
  23581. }else{
  23582. zTerm = (const u8*)(-1);
  23583. }
  23584. assert( z<=zTerm );
  23585. while( *z!=0 && z<zTerm ){
  23586. SQLITE_SKIP_UTF8(z);
  23587. r++;
  23588. }
  23589. return r;
  23590. }
  23591. /* This test function is not currently used by the automated test-suite.
  23592. ** Hence it is only available in debug builds.
  23593. */
  23594. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  23595. /*
  23596. ** Translate UTF-8 to UTF-8.
  23597. **
  23598. ** This has the effect of making sure that the string is well-formed
  23599. ** UTF-8. Miscoded characters are removed.
  23600. **
  23601. ** The translation is done in-place and aborted if the output
  23602. ** overruns the input.
  23603. */
  23604. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  23605. unsigned char *zOut = zIn;
  23606. unsigned char *zStart = zIn;
  23607. u32 c;
  23608. while( zIn[0] && zOut<=zIn ){
  23609. c = sqlite3Utf8Read((const u8**)&zIn);
  23610. if( c!=0xfffd ){
  23611. WRITE_UTF8(zOut, c);
  23612. }
  23613. }
  23614. *zOut = 0;
  23615. return (int)(zOut - zStart);
  23616. }
  23617. #endif
  23618. #ifndef SQLITE_OMIT_UTF16
  23619. /*
  23620. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  23621. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  23622. ** be freed by the calling function.
  23623. **
  23624. ** NULL is returned if there is an allocation error.
  23625. */
  23626. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  23627. Mem m;
  23628. memset(&m, 0, sizeof(m));
  23629. m.db = db;
  23630. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  23631. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  23632. if( db->mallocFailed ){
  23633. sqlite3VdbeMemRelease(&m);
  23634. m.z = 0;
  23635. }
  23636. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  23637. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  23638. assert( m.z || db->mallocFailed );
  23639. return m.z;
  23640. }
  23641. /*
  23642. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  23643. ** Return the number of bytes in the first nChar unicode characters
  23644. ** in pZ. nChar must be non-negative.
  23645. */
  23646. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  23647. int c;
  23648. unsigned char const *z = zIn;
  23649. int n = 0;
  23650. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  23651. while( n<nChar ){
  23652. READ_UTF16BE(z, 1, c);
  23653. n++;
  23654. }
  23655. }else{
  23656. while( n<nChar ){
  23657. READ_UTF16LE(z, 1, c);
  23658. n++;
  23659. }
  23660. }
  23661. return (int)(z-(unsigned char const *)zIn);
  23662. }
  23663. #if defined(SQLITE_TEST)
  23664. /*
  23665. ** This routine is called from the TCL test function "translate_selftest".
  23666. ** It checks that the primitives for serializing and deserializing
  23667. ** characters in each encoding are inverses of each other.
  23668. */
  23669. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  23670. unsigned int i, t;
  23671. unsigned char zBuf[20];
  23672. unsigned char *z;
  23673. int n;
  23674. unsigned int c;
  23675. for(i=0; i<0x00110000; i++){
  23676. z = zBuf;
  23677. WRITE_UTF8(z, i);
  23678. n = (int)(z-zBuf);
  23679. assert( n>0 && n<=4 );
  23680. z[0] = 0;
  23681. z = zBuf;
  23682. c = sqlite3Utf8Read((const u8**)&z);
  23683. t = i;
  23684. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  23685. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  23686. assert( c==t );
  23687. assert( (z-zBuf)==n );
  23688. }
  23689. for(i=0; i<0x00110000; i++){
  23690. if( i>=0xD800 && i<0xE000 ) continue;
  23691. z = zBuf;
  23692. WRITE_UTF16LE(z, i);
  23693. n = (int)(z-zBuf);
  23694. assert( n>0 && n<=4 );
  23695. z[0] = 0;
  23696. z = zBuf;
  23697. READ_UTF16LE(z, 1, c);
  23698. assert( c==i );
  23699. assert( (z-zBuf)==n );
  23700. }
  23701. for(i=0; i<0x00110000; i++){
  23702. if( i>=0xD800 && i<0xE000 ) continue;
  23703. z = zBuf;
  23704. WRITE_UTF16BE(z, i);
  23705. n = (int)(z-zBuf);
  23706. assert( n>0 && n<=4 );
  23707. z[0] = 0;
  23708. z = zBuf;
  23709. READ_UTF16BE(z, 1, c);
  23710. assert( c==i );
  23711. assert( (z-zBuf)==n );
  23712. }
  23713. }
  23714. #endif /* SQLITE_TEST */
  23715. #endif /* SQLITE_OMIT_UTF16 */
  23716. /************** End of utf.c *************************************************/
  23717. /************** Begin file util.c ********************************************/
  23718. /*
  23719. ** 2001 September 15
  23720. **
  23721. ** The author disclaims copyright to this source code. In place of
  23722. ** a legal notice, here is a blessing:
  23723. **
  23724. ** May you do good and not evil.
  23725. ** May you find forgiveness for yourself and forgive others.
  23726. ** May you share freely, never taking more than you give.
  23727. **
  23728. *************************************************************************
  23729. ** Utility functions used throughout sqlite.
  23730. **
  23731. ** This file contains functions for allocating memory, comparing
  23732. ** strings, and stuff like that.
  23733. **
  23734. */
  23735. /* #include "sqliteInt.h" */
  23736. /* #include <stdarg.h> */
  23737. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  23738. # include <math.h>
  23739. #endif
  23740. /*
  23741. ** Routine needed to support the testcase() macro.
  23742. */
  23743. #ifdef SQLITE_COVERAGE_TEST
  23744. SQLITE_PRIVATE void sqlite3Coverage(int x){
  23745. static unsigned dummy = 0;
  23746. dummy += (unsigned)x;
  23747. }
  23748. #endif
  23749. /*
  23750. ** Give a callback to the test harness that can be used to simulate faults
  23751. ** in places where it is difficult or expensive to do so purely by means
  23752. ** of inputs.
  23753. **
  23754. ** The intent of the integer argument is to let the fault simulator know
  23755. ** which of multiple sqlite3FaultSim() calls has been hit.
  23756. **
  23757. ** Return whatever integer value the test callback returns, or return
  23758. ** SQLITE_OK if no test callback is installed.
  23759. */
  23760. #ifndef SQLITE_OMIT_BUILTIN_TEST
  23761. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  23762. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  23763. return xCallback ? xCallback(iTest) : SQLITE_OK;
  23764. }
  23765. #endif
  23766. #ifndef SQLITE_OMIT_FLOATING_POINT
  23767. /*
  23768. ** Return true if the floating point value is Not a Number (NaN).
  23769. **
  23770. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  23771. ** Otherwise, we have our own implementation that works on most systems.
  23772. */
  23773. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  23774. int rc; /* The value return */
  23775. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  23776. /*
  23777. ** Systems that support the isnan() library function should probably
  23778. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  23779. ** found that many systems do not have a working isnan() function so
  23780. ** this implementation is provided as an alternative.
  23781. **
  23782. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  23783. ** On the other hand, the use of -ffast-math comes with the following
  23784. ** warning:
  23785. **
  23786. ** This option [-ffast-math] should never be turned on by any
  23787. ** -O option since it can result in incorrect output for programs
  23788. ** which depend on an exact implementation of IEEE or ISO
  23789. ** rules/specifications for math functions.
  23790. **
  23791. ** Under MSVC, this NaN test may fail if compiled with a floating-
  23792. ** point precision mode other than /fp:precise. From the MSDN
  23793. ** documentation:
  23794. **
  23795. ** The compiler [with /fp:precise] will properly handle comparisons
  23796. ** involving NaN. For example, x != x evaluates to true if x is NaN
  23797. ** ...
  23798. */
  23799. #ifdef __FAST_MATH__
  23800. # error SQLite will not work correctly with the -ffast-math option of GCC.
  23801. #endif
  23802. volatile double y = x;
  23803. volatile double z = y;
  23804. rc = (y!=z);
  23805. #else /* if HAVE_ISNAN */
  23806. rc = isnan(x);
  23807. #endif /* HAVE_ISNAN */
  23808. testcase( rc );
  23809. return rc;
  23810. }
  23811. #endif /* SQLITE_OMIT_FLOATING_POINT */
  23812. /*
  23813. ** Compute a string length that is limited to what can be stored in
  23814. ** lower 30 bits of a 32-bit signed integer.
  23815. **
  23816. ** The value returned will never be negative. Nor will it ever be greater
  23817. ** than the actual length of the string. For very long strings (greater
  23818. ** than 1GiB) the value returned might be less than the true string length.
  23819. */
  23820. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  23821. if( z==0 ) return 0;
  23822. return 0x3fffffff & (int)strlen(z);
  23823. }
  23824. /*
  23825. ** Set the current error code to err_code and clear any prior error message.
  23826. */
  23827. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  23828. assert( db!=0 );
  23829. db->errCode = err_code;
  23830. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  23831. }
  23832. /*
  23833. ** Set the most recent error code and error string for the sqlite
  23834. ** handle "db". The error code is set to "err_code".
  23835. **
  23836. ** If it is not NULL, string zFormat specifies the format of the
  23837. ** error string in the style of the printf functions: The following
  23838. ** format characters are allowed:
  23839. **
  23840. ** %s Insert a string
  23841. ** %z A string that should be freed after use
  23842. ** %d Insert an integer
  23843. ** %T Insert a token
  23844. ** %S Insert the first element of a SrcList
  23845. **
  23846. ** zFormat and any string tokens that follow it are assumed to be
  23847. ** encoded in UTF-8.
  23848. **
  23849. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  23850. ** should be called with err_code set to SQLITE_OK and zFormat set
  23851. ** to NULL.
  23852. */
  23853. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  23854. assert( db!=0 );
  23855. db->errCode = err_code;
  23856. if( zFormat==0 ){
  23857. sqlite3Error(db, err_code);
  23858. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  23859. char *z;
  23860. va_list ap;
  23861. va_start(ap, zFormat);
  23862. z = sqlite3VMPrintf(db, zFormat, ap);
  23863. va_end(ap);
  23864. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  23865. }
  23866. }
  23867. /*
  23868. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  23869. ** The following formatting characters are allowed:
  23870. **
  23871. ** %s Insert a string
  23872. ** %z A string that should be freed after use
  23873. ** %d Insert an integer
  23874. ** %T Insert a token
  23875. ** %S Insert the first element of a SrcList
  23876. **
  23877. ** This function should be used to report any error that occurs while
  23878. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  23879. ** last thing the sqlite3_prepare() function does is copy the error
  23880. ** stored by this function into the database handle using sqlite3Error().
  23881. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  23882. ** during statement execution (sqlite3_step() etc.).
  23883. */
  23884. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  23885. char *zMsg;
  23886. va_list ap;
  23887. sqlite3 *db = pParse->db;
  23888. va_start(ap, zFormat);
  23889. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  23890. va_end(ap);
  23891. if( db->suppressErr ){
  23892. sqlite3DbFree(db, zMsg);
  23893. }else{
  23894. pParse->nErr++;
  23895. sqlite3DbFree(db, pParse->zErrMsg);
  23896. pParse->zErrMsg = zMsg;
  23897. pParse->rc = SQLITE_ERROR;
  23898. }
  23899. }
  23900. /*
  23901. ** Convert an SQL-style quoted string into a normal string by removing
  23902. ** the quote characters. The conversion is done in-place. If the
  23903. ** input does not begin with a quote character, then this routine
  23904. ** is a no-op.
  23905. **
  23906. ** The input string must be zero-terminated. A new zero-terminator
  23907. ** is added to the dequoted string.
  23908. **
  23909. ** The return value is -1 if no dequoting occurs or the length of the
  23910. ** dequoted string, exclusive of the zero terminator, if dequoting does
  23911. ** occur.
  23912. **
  23913. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  23914. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  23915. ** "a-b-c".
  23916. */
  23917. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  23918. char quote;
  23919. int i, j;
  23920. if( z==0 ) return -1;
  23921. quote = z[0];
  23922. switch( quote ){
  23923. case '\'': break;
  23924. case '"': break;
  23925. case '`': break; /* For MySQL compatibility */
  23926. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  23927. default: return -1;
  23928. }
  23929. for(i=1, j=0;; i++){
  23930. assert( z[i] );
  23931. if( z[i]==quote ){
  23932. if( z[i+1]==quote ){
  23933. z[j++] = quote;
  23934. i++;
  23935. }else{
  23936. break;
  23937. }
  23938. }else{
  23939. z[j++] = z[i];
  23940. }
  23941. }
  23942. z[j] = 0;
  23943. return j;
  23944. }
  23945. /* Convenient short-hand */
  23946. #define UpperToLower sqlite3UpperToLower
  23947. /*
  23948. ** Some systems have stricmp(). Others have strcasecmp(). Because
  23949. ** there is no consistency, we will define our own.
  23950. **
  23951. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  23952. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  23953. ** the contents of two buffers containing UTF-8 strings in a
  23954. ** case-independent fashion, using the same definition of "case
  23955. ** independence" that SQLite uses internally when comparing identifiers.
  23956. */
  23957. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
  23958. register unsigned char *a, *b;
  23959. if( zLeft==0 ){
  23960. return zRight ? -1 : 0;
  23961. }else if( zRight==0 ){
  23962. return 1;
  23963. }
  23964. a = (unsigned char *)zLeft;
  23965. b = (unsigned char *)zRight;
  23966. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  23967. return UpperToLower[*a] - UpperToLower[*b];
  23968. }
  23969. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  23970. register unsigned char *a, *b;
  23971. if( zLeft==0 ){
  23972. return zRight ? -1 : 0;
  23973. }else if( zRight==0 ){
  23974. return 1;
  23975. }
  23976. a = (unsigned char *)zLeft;
  23977. b = (unsigned char *)zRight;
  23978. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  23979. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  23980. }
  23981. /*
  23982. ** The string z[] is an text representation of a real number.
  23983. ** Convert this string to a double and write it into *pResult.
  23984. **
  23985. ** The string z[] is length bytes in length (bytes, not characters) and
  23986. ** uses the encoding enc. The string is not necessarily zero-terminated.
  23987. **
  23988. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  23989. ** if the string is empty or contains extraneous text. Valid numbers
  23990. ** are in one of these formats:
  23991. **
  23992. ** [+-]digits[E[+-]digits]
  23993. ** [+-]digits.[digits][E[+-]digits]
  23994. ** [+-].digits[E[+-]digits]
  23995. **
  23996. ** Leading and trailing whitespace is ignored for the purpose of determining
  23997. ** validity.
  23998. **
  23999. ** If some prefix of the input string is a valid number, this routine
  24000. ** returns FALSE but it still converts the prefix and writes the result
  24001. ** into *pResult.
  24002. */
  24003. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  24004. #ifndef SQLITE_OMIT_FLOATING_POINT
  24005. int incr;
  24006. const char *zEnd = z + length;
  24007. /* sign * significand * (10 ^ (esign * exponent)) */
  24008. int sign = 1; /* sign of significand */
  24009. i64 s = 0; /* significand */
  24010. int d = 0; /* adjust exponent for shifting decimal point */
  24011. int esign = 1; /* sign of exponent */
  24012. int e = 0; /* exponent */
  24013. int eValid = 1; /* True exponent is either not used or is well-formed */
  24014. double result;
  24015. int nDigits = 0;
  24016. int nonNum = 0;
  24017. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  24018. *pResult = 0.0; /* Default return value, in case of an error */
  24019. if( enc==SQLITE_UTF8 ){
  24020. incr = 1;
  24021. }else{
  24022. int i;
  24023. incr = 2;
  24024. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  24025. for(i=3-enc; i<length && z[i]==0; i+=2){}
  24026. nonNum = i<length;
  24027. zEnd = z+i+enc-3;
  24028. z += (enc&1);
  24029. }
  24030. /* skip leading spaces */
  24031. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  24032. if( z>=zEnd ) return 0;
  24033. /* get sign of significand */
  24034. if( *z=='-' ){
  24035. sign = -1;
  24036. z+=incr;
  24037. }else if( *z=='+' ){
  24038. z+=incr;
  24039. }
  24040. /* skip leading zeroes */
  24041. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  24042. /* copy max significant digits to significand */
  24043. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  24044. s = s*10 + (*z - '0');
  24045. z+=incr, nDigits++;
  24046. }
  24047. /* skip non-significant significand digits
  24048. ** (increase exponent by d to shift decimal left) */
  24049. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  24050. if( z>=zEnd ) goto do_atof_calc;
  24051. /* if decimal point is present */
  24052. if( *z=='.' ){
  24053. z+=incr;
  24054. /* copy digits from after decimal to significand
  24055. ** (decrease exponent by d to shift decimal right) */
  24056. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  24057. s = s*10 + (*z - '0');
  24058. z+=incr, nDigits++, d--;
  24059. }
  24060. /* skip non-significant digits */
  24061. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  24062. }
  24063. if( z>=zEnd ) goto do_atof_calc;
  24064. /* if exponent is present */
  24065. if( *z=='e' || *z=='E' ){
  24066. z+=incr;
  24067. eValid = 0;
  24068. if( z>=zEnd ) goto do_atof_calc;
  24069. /* get sign of exponent */
  24070. if( *z=='-' ){
  24071. esign = -1;
  24072. z+=incr;
  24073. }else if( *z=='+' ){
  24074. z+=incr;
  24075. }
  24076. /* copy digits to exponent */
  24077. while( z<zEnd && sqlite3Isdigit(*z) ){
  24078. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  24079. z+=incr;
  24080. eValid = 1;
  24081. }
  24082. }
  24083. /* skip trailing spaces */
  24084. if( nDigits && eValid ){
  24085. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  24086. }
  24087. do_atof_calc:
  24088. /* adjust exponent by d, and update sign */
  24089. e = (e*esign) + d;
  24090. if( e<0 ) {
  24091. esign = -1;
  24092. e *= -1;
  24093. } else {
  24094. esign = 1;
  24095. }
  24096. /* if 0 significand */
  24097. if( !s ) {
  24098. /* In the IEEE 754 standard, zero is signed.
  24099. ** Add the sign if we've seen at least one digit */
  24100. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  24101. } else {
  24102. /* attempt to reduce exponent */
  24103. if( esign>0 ){
  24104. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  24105. }else{
  24106. while( !(s%10) && e>0 ) e--,s/=10;
  24107. }
  24108. /* adjust the sign of significand */
  24109. s = sign<0 ? -s : s;
  24110. /* if exponent, scale significand as appropriate
  24111. ** and store in result. */
  24112. if( e ){
  24113. LONGDOUBLE_TYPE scale = 1.0;
  24114. /* attempt to handle extremely small/large numbers better */
  24115. if( e>307 && e<342 ){
  24116. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  24117. if( esign<0 ){
  24118. result = s / scale;
  24119. result /= 1.0e+308;
  24120. }else{
  24121. result = s * scale;
  24122. result *= 1.0e+308;
  24123. }
  24124. }else if( e>=342 ){
  24125. if( esign<0 ){
  24126. result = 0.0*s;
  24127. }else{
  24128. result = 1e308*1e308*s; /* Infinity */
  24129. }
  24130. }else{
  24131. /* 1.0e+22 is the largest power of 10 than can be
  24132. ** represented exactly. */
  24133. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  24134. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  24135. if( esign<0 ){
  24136. result = s / scale;
  24137. }else{
  24138. result = s * scale;
  24139. }
  24140. }
  24141. } else {
  24142. result = (double)s;
  24143. }
  24144. }
  24145. /* store the result */
  24146. *pResult = result;
  24147. /* return true if number and no extra non-whitespace chracters after */
  24148. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  24149. #else
  24150. return !sqlite3Atoi64(z, pResult, length, enc);
  24151. #endif /* SQLITE_OMIT_FLOATING_POINT */
  24152. }
  24153. /*
  24154. ** Compare the 19-character string zNum against the text representation
  24155. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  24156. ** if zNum is less than, equal to, or greater than the string.
  24157. ** Note that zNum must contain exactly 19 characters.
  24158. **
  24159. ** Unlike memcmp() this routine is guaranteed to return the difference
  24160. ** in the values of the last digit if the only difference is in the
  24161. ** last digit. So, for example,
  24162. **
  24163. ** compare2pow63("9223372036854775800", 1)
  24164. **
  24165. ** will return -8.
  24166. */
  24167. static int compare2pow63(const char *zNum, int incr){
  24168. int c = 0;
  24169. int i;
  24170. /* 012345678901234567 */
  24171. const char *pow63 = "922337203685477580";
  24172. for(i=0; c==0 && i<18; i++){
  24173. c = (zNum[i*incr]-pow63[i])*10;
  24174. }
  24175. if( c==0 ){
  24176. c = zNum[18*incr] - '8';
  24177. testcase( c==(-1) );
  24178. testcase( c==0 );
  24179. testcase( c==(+1) );
  24180. }
  24181. return c;
  24182. }
  24183. /*
  24184. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  24185. ** routine does *not* accept hexadecimal notation.
  24186. **
  24187. ** If the zNum value is representable as a 64-bit twos-complement
  24188. ** integer, then write that value into *pNum and return 0.
  24189. **
  24190. ** If zNum is exactly 9223372036854775808, return 2. This special
  24191. ** case is broken out because while 9223372036854775808 cannot be a
  24192. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  24193. **
  24194. ** If zNum is too big for a 64-bit integer and is not
  24195. ** 9223372036854775808 or if zNum contains any non-numeric text,
  24196. ** then return 1.
  24197. **
  24198. ** length is the number of bytes in the string (bytes, not characters).
  24199. ** The string is not necessarily zero-terminated. The encoding is
  24200. ** given by enc.
  24201. */
  24202. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  24203. int incr;
  24204. u64 u = 0;
  24205. int neg = 0; /* assume positive */
  24206. int i;
  24207. int c = 0;
  24208. int nonNum = 0;
  24209. const char *zStart;
  24210. const char *zEnd = zNum + length;
  24211. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  24212. if( enc==SQLITE_UTF8 ){
  24213. incr = 1;
  24214. }else{
  24215. incr = 2;
  24216. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  24217. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  24218. nonNum = i<length;
  24219. zEnd = zNum+i+enc-3;
  24220. zNum += (enc&1);
  24221. }
  24222. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  24223. if( zNum<zEnd ){
  24224. if( *zNum=='-' ){
  24225. neg = 1;
  24226. zNum+=incr;
  24227. }else if( *zNum=='+' ){
  24228. zNum+=incr;
  24229. }
  24230. }
  24231. zStart = zNum;
  24232. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  24233. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  24234. u = u*10 + c - '0';
  24235. }
  24236. if( u>LARGEST_INT64 ){
  24237. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  24238. }else if( neg ){
  24239. *pNum = -(i64)u;
  24240. }else{
  24241. *pNum = (i64)u;
  24242. }
  24243. testcase( i==18 );
  24244. testcase( i==19 );
  24245. testcase( i==20 );
  24246. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum)
  24247. || i>19*incr || nonNum ){
  24248. /* zNum is empty or contains non-numeric text or is longer
  24249. ** than 19 digits (thus guaranteeing that it is too large) */
  24250. return 1;
  24251. }else if( i<19*incr ){
  24252. /* Less than 19 digits, so we know that it fits in 64 bits */
  24253. assert( u<=LARGEST_INT64 );
  24254. return 0;
  24255. }else{
  24256. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  24257. c = compare2pow63(zNum, incr);
  24258. if( c<0 ){
  24259. /* zNum is less than 9223372036854775808 so it fits */
  24260. assert( u<=LARGEST_INT64 );
  24261. return 0;
  24262. }else if( c>0 ){
  24263. /* zNum is greater than 9223372036854775808 so it overflows */
  24264. return 1;
  24265. }else{
  24266. /* zNum is exactly 9223372036854775808. Fits if negative. The
  24267. ** special case 2 overflow if positive */
  24268. assert( u-1==LARGEST_INT64 );
  24269. return neg ? 0 : 2;
  24270. }
  24271. }
  24272. }
  24273. /*
  24274. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  24275. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  24276. ** whereas sqlite3Atoi64() does not.
  24277. **
  24278. ** Returns:
  24279. **
  24280. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  24281. ** 1 Integer too large for a 64-bit signed integer or is malformed
  24282. ** 2 Special case of 9223372036854775808
  24283. */
  24284. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  24285. #ifndef SQLITE_OMIT_HEX_INTEGER
  24286. if( z[0]=='0'
  24287. && (z[1]=='x' || z[1]=='X')
  24288. && sqlite3Isxdigit(z[2])
  24289. ){
  24290. u64 u = 0;
  24291. int i, k;
  24292. for(i=2; z[i]=='0'; i++){}
  24293. for(k=i; sqlite3Isxdigit(z[k]); k++){
  24294. u = u*16 + sqlite3HexToInt(z[k]);
  24295. }
  24296. memcpy(pOut, &u, 8);
  24297. return (z[k]==0 && k-i<=16) ? 0 : 1;
  24298. }else
  24299. #endif /* SQLITE_OMIT_HEX_INTEGER */
  24300. {
  24301. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  24302. }
  24303. }
  24304. /*
  24305. ** If zNum represents an integer that will fit in 32-bits, then set
  24306. ** *pValue to that integer and return true. Otherwise return false.
  24307. **
  24308. ** This routine accepts both decimal and hexadecimal notation for integers.
  24309. **
  24310. ** Any non-numeric characters that following zNum are ignored.
  24311. ** This is different from sqlite3Atoi64() which requires the
  24312. ** input number to be zero-terminated.
  24313. */
  24314. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  24315. sqlite_int64 v = 0;
  24316. int i, c;
  24317. int neg = 0;
  24318. if( zNum[0]=='-' ){
  24319. neg = 1;
  24320. zNum++;
  24321. }else if( zNum[0]=='+' ){
  24322. zNum++;
  24323. }
  24324. #ifndef SQLITE_OMIT_HEX_INTEGER
  24325. else if( zNum[0]=='0'
  24326. && (zNum[1]=='x' || zNum[1]=='X')
  24327. && sqlite3Isxdigit(zNum[2])
  24328. ){
  24329. u32 u = 0;
  24330. zNum += 2;
  24331. while( zNum[0]=='0' ) zNum++;
  24332. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  24333. u = u*16 + sqlite3HexToInt(zNum[i]);
  24334. }
  24335. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  24336. memcpy(pValue, &u, 4);
  24337. return 1;
  24338. }else{
  24339. return 0;
  24340. }
  24341. }
  24342. #endif
  24343. while( zNum[0]=='0' ) zNum++;
  24344. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  24345. v = v*10 + c;
  24346. }
  24347. /* The longest decimal representation of a 32 bit integer is 10 digits:
  24348. **
  24349. ** 1234567890
  24350. ** 2^31 -> 2147483648
  24351. */
  24352. testcase( i==10 );
  24353. if( i>10 ){
  24354. return 0;
  24355. }
  24356. testcase( v-neg==2147483647 );
  24357. if( v-neg>2147483647 ){
  24358. return 0;
  24359. }
  24360. if( neg ){
  24361. v = -v;
  24362. }
  24363. *pValue = (int)v;
  24364. return 1;
  24365. }
  24366. /*
  24367. ** Return a 32-bit integer value extracted from a string. If the
  24368. ** string is not an integer, just return 0.
  24369. */
  24370. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  24371. int x = 0;
  24372. if( z ) sqlite3GetInt32(z, &x);
  24373. return x;
  24374. }
  24375. /*
  24376. ** The variable-length integer encoding is as follows:
  24377. **
  24378. ** KEY:
  24379. ** A = 0xxxxxxx 7 bits of data and one flag bit
  24380. ** B = 1xxxxxxx 7 bits of data and one flag bit
  24381. ** C = xxxxxxxx 8 bits of data
  24382. **
  24383. ** 7 bits - A
  24384. ** 14 bits - BA
  24385. ** 21 bits - BBA
  24386. ** 28 bits - BBBA
  24387. ** 35 bits - BBBBA
  24388. ** 42 bits - BBBBBA
  24389. ** 49 bits - BBBBBBA
  24390. ** 56 bits - BBBBBBBA
  24391. ** 64 bits - BBBBBBBBC
  24392. */
  24393. /*
  24394. ** Write a 64-bit variable-length integer to memory starting at p[0].
  24395. ** The length of data write will be between 1 and 9 bytes. The number
  24396. ** of bytes written is returned.
  24397. **
  24398. ** A variable-length integer consists of the lower 7 bits of each byte
  24399. ** for all bytes that have the 8th bit set and one byte with the 8th
  24400. ** bit clear. Except, if we get to the 9th byte, it stores the full
  24401. ** 8 bits and is the last byte.
  24402. */
  24403. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  24404. int i, j, n;
  24405. u8 buf[10];
  24406. if( v & (((u64)0xff000000)<<32) ){
  24407. p[8] = (u8)v;
  24408. v >>= 8;
  24409. for(i=7; i>=0; i--){
  24410. p[i] = (u8)((v & 0x7f) | 0x80);
  24411. v >>= 7;
  24412. }
  24413. return 9;
  24414. }
  24415. n = 0;
  24416. do{
  24417. buf[n++] = (u8)((v & 0x7f) | 0x80);
  24418. v >>= 7;
  24419. }while( v!=0 );
  24420. buf[0] &= 0x7f;
  24421. assert( n<=9 );
  24422. for(i=0, j=n-1; j>=0; j--, i++){
  24423. p[i] = buf[j];
  24424. }
  24425. return n;
  24426. }
  24427. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  24428. if( v<=0x7f ){
  24429. p[0] = v&0x7f;
  24430. return 1;
  24431. }
  24432. if( v<=0x3fff ){
  24433. p[0] = ((v>>7)&0x7f)|0x80;
  24434. p[1] = v&0x7f;
  24435. return 2;
  24436. }
  24437. return putVarint64(p,v);
  24438. }
  24439. /*
  24440. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  24441. ** are defined here rather than simply putting the constant expressions
  24442. ** inline in order to work around bugs in the RVT compiler.
  24443. **
  24444. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  24445. **
  24446. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  24447. */
  24448. #define SLOT_2_0 0x001fc07f
  24449. #define SLOT_4_2_0 0xf01fc07f
  24450. /*
  24451. ** Read a 64-bit variable-length integer from memory starting at p[0].
  24452. ** Return the number of bytes read. The value is stored in *v.
  24453. */
  24454. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  24455. u32 a,b,s;
  24456. a = *p;
  24457. /* a: p0 (unmasked) */
  24458. if (!(a&0x80))
  24459. {
  24460. *v = a;
  24461. return 1;
  24462. }
  24463. p++;
  24464. b = *p;
  24465. /* b: p1 (unmasked) */
  24466. if (!(b&0x80))
  24467. {
  24468. a &= 0x7f;
  24469. a = a<<7;
  24470. a |= b;
  24471. *v = a;
  24472. return 2;
  24473. }
  24474. /* Verify that constants are precomputed correctly */
  24475. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  24476. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  24477. p++;
  24478. a = a<<14;
  24479. a |= *p;
  24480. /* a: p0<<14 | p2 (unmasked) */
  24481. if (!(a&0x80))
  24482. {
  24483. a &= SLOT_2_0;
  24484. b &= 0x7f;
  24485. b = b<<7;
  24486. a |= b;
  24487. *v = a;
  24488. return 3;
  24489. }
  24490. /* CSE1 from below */
  24491. a &= SLOT_2_0;
  24492. p++;
  24493. b = b<<14;
  24494. b |= *p;
  24495. /* b: p1<<14 | p3 (unmasked) */
  24496. if (!(b&0x80))
  24497. {
  24498. b &= SLOT_2_0;
  24499. /* moved CSE1 up */
  24500. /* a &= (0x7f<<14)|(0x7f); */
  24501. a = a<<7;
  24502. a |= b;
  24503. *v = a;
  24504. return 4;
  24505. }
  24506. /* a: p0<<14 | p2 (masked) */
  24507. /* b: p1<<14 | p3 (unmasked) */
  24508. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24509. /* moved CSE1 up */
  24510. /* a &= (0x7f<<14)|(0x7f); */
  24511. b &= SLOT_2_0;
  24512. s = a;
  24513. /* s: p0<<14 | p2 (masked) */
  24514. p++;
  24515. a = a<<14;
  24516. a |= *p;
  24517. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  24518. if (!(a&0x80))
  24519. {
  24520. /* we can skip these cause they were (effectively) done above
  24521. ** while calculating s */
  24522. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  24523. /* b &= (0x7f<<14)|(0x7f); */
  24524. b = b<<7;
  24525. a |= b;
  24526. s = s>>18;
  24527. *v = ((u64)s)<<32 | a;
  24528. return 5;
  24529. }
  24530. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24531. s = s<<7;
  24532. s |= b;
  24533. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  24534. p++;
  24535. b = b<<14;
  24536. b |= *p;
  24537. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  24538. if (!(b&0x80))
  24539. {
  24540. /* we can skip this cause it was (effectively) done above in calc'ing s */
  24541. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  24542. a &= SLOT_2_0;
  24543. a = a<<7;
  24544. a |= b;
  24545. s = s>>18;
  24546. *v = ((u64)s)<<32 | a;
  24547. return 6;
  24548. }
  24549. p++;
  24550. a = a<<14;
  24551. a |= *p;
  24552. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  24553. if (!(a&0x80))
  24554. {
  24555. a &= SLOT_4_2_0;
  24556. b &= SLOT_2_0;
  24557. b = b<<7;
  24558. a |= b;
  24559. s = s>>11;
  24560. *v = ((u64)s)<<32 | a;
  24561. return 7;
  24562. }
  24563. /* CSE2 from below */
  24564. a &= SLOT_2_0;
  24565. p++;
  24566. b = b<<14;
  24567. b |= *p;
  24568. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  24569. if (!(b&0x80))
  24570. {
  24571. b &= SLOT_4_2_0;
  24572. /* moved CSE2 up */
  24573. /* a &= (0x7f<<14)|(0x7f); */
  24574. a = a<<7;
  24575. a |= b;
  24576. s = s>>4;
  24577. *v = ((u64)s)<<32 | a;
  24578. return 8;
  24579. }
  24580. p++;
  24581. a = a<<15;
  24582. a |= *p;
  24583. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  24584. /* moved CSE2 up */
  24585. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  24586. b &= SLOT_2_0;
  24587. b = b<<8;
  24588. a |= b;
  24589. s = s<<4;
  24590. b = p[-4];
  24591. b &= 0x7f;
  24592. b = b>>3;
  24593. s |= b;
  24594. *v = ((u64)s)<<32 | a;
  24595. return 9;
  24596. }
  24597. /*
  24598. ** Read a 32-bit variable-length integer from memory starting at p[0].
  24599. ** Return the number of bytes read. The value is stored in *v.
  24600. **
  24601. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  24602. ** integer, then set *v to 0xffffffff.
  24603. **
  24604. ** A MACRO version, getVarint32, is provided which inlines the
  24605. ** single-byte case. All code should use the MACRO version as
  24606. ** this function assumes the single-byte case has already been handled.
  24607. */
  24608. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  24609. u32 a,b;
  24610. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  24611. ** by the getVarin32() macro */
  24612. a = *p;
  24613. /* a: p0 (unmasked) */
  24614. #ifndef getVarint32
  24615. if (!(a&0x80))
  24616. {
  24617. /* Values between 0 and 127 */
  24618. *v = a;
  24619. return 1;
  24620. }
  24621. #endif
  24622. /* The 2-byte case */
  24623. p++;
  24624. b = *p;
  24625. /* b: p1 (unmasked) */
  24626. if (!(b&0x80))
  24627. {
  24628. /* Values between 128 and 16383 */
  24629. a &= 0x7f;
  24630. a = a<<7;
  24631. *v = a | b;
  24632. return 2;
  24633. }
  24634. /* The 3-byte case */
  24635. p++;
  24636. a = a<<14;
  24637. a |= *p;
  24638. /* a: p0<<14 | p2 (unmasked) */
  24639. if (!(a&0x80))
  24640. {
  24641. /* Values between 16384 and 2097151 */
  24642. a &= (0x7f<<14)|(0x7f);
  24643. b &= 0x7f;
  24644. b = b<<7;
  24645. *v = a | b;
  24646. return 3;
  24647. }
  24648. /* A 32-bit varint is used to store size information in btrees.
  24649. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  24650. ** A 3-byte varint is sufficient, for example, to record the size
  24651. ** of a 1048569-byte BLOB or string.
  24652. **
  24653. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  24654. ** rare larger cases can be handled by the slower 64-bit varint
  24655. ** routine.
  24656. */
  24657. #if 1
  24658. {
  24659. u64 v64;
  24660. u8 n;
  24661. p -= 2;
  24662. n = sqlite3GetVarint(p, &v64);
  24663. assert( n>3 && n<=9 );
  24664. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  24665. *v = 0xffffffff;
  24666. }else{
  24667. *v = (u32)v64;
  24668. }
  24669. return n;
  24670. }
  24671. #else
  24672. /* For following code (kept for historical record only) shows an
  24673. ** unrolling for the 3- and 4-byte varint cases. This code is
  24674. ** slightly faster, but it is also larger and much harder to test.
  24675. */
  24676. p++;
  24677. b = b<<14;
  24678. b |= *p;
  24679. /* b: p1<<14 | p3 (unmasked) */
  24680. if (!(b&0x80))
  24681. {
  24682. /* Values between 2097152 and 268435455 */
  24683. b &= (0x7f<<14)|(0x7f);
  24684. a &= (0x7f<<14)|(0x7f);
  24685. a = a<<7;
  24686. *v = a | b;
  24687. return 4;
  24688. }
  24689. p++;
  24690. a = a<<14;
  24691. a |= *p;
  24692. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  24693. if (!(a&0x80))
  24694. {
  24695. /* Values between 268435456 and 34359738367 */
  24696. a &= SLOT_4_2_0;
  24697. b &= SLOT_4_2_0;
  24698. b = b<<7;
  24699. *v = a | b;
  24700. return 5;
  24701. }
  24702. /* We can only reach this point when reading a corrupt database
  24703. ** file. In that case we are not in any hurry. Use the (relatively
  24704. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  24705. ** value. */
  24706. {
  24707. u64 v64;
  24708. u8 n;
  24709. p -= 4;
  24710. n = sqlite3GetVarint(p, &v64);
  24711. assert( n>5 && n<=9 );
  24712. *v = (u32)v64;
  24713. return n;
  24714. }
  24715. #endif
  24716. }
  24717. /*
  24718. ** Return the number of bytes that will be needed to store the given
  24719. ** 64-bit integer.
  24720. */
  24721. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  24722. int i;
  24723. for(i=1; (v >>= 7)!=0; i++){ assert( i<9 ); }
  24724. return i;
  24725. }
  24726. /*
  24727. ** Read or write a four-byte big-endian integer value.
  24728. */
  24729. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  24730. #if SQLITE_BYTEORDER==4321
  24731. u32 x;
  24732. memcpy(&x,p,4);
  24733. return x;
  24734. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  24735. && defined(__GNUC__) && GCC_VERSION>=4003000
  24736. u32 x;
  24737. memcpy(&x,p,4);
  24738. return __builtin_bswap32(x);
  24739. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  24740. && defined(_MSC_VER) && _MSC_VER>=1300
  24741. u32 x;
  24742. memcpy(&x,p,4);
  24743. return _byteswap_ulong(x);
  24744. #else
  24745. testcase( p[0]&0x80 );
  24746. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  24747. #endif
  24748. }
  24749. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  24750. #if SQLITE_BYTEORDER==4321
  24751. memcpy(p,&v,4);
  24752. #elif SQLITE_BYTEORDER==1234 && defined(__GNUC__) && GCC_VERSION>=4003000
  24753. u32 x = __builtin_bswap32(v);
  24754. memcpy(p,&x,4);
  24755. #elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
  24756. u32 x = _byteswap_ulong(v);
  24757. memcpy(p,&x,4);
  24758. #else
  24759. p[0] = (u8)(v>>24);
  24760. p[1] = (u8)(v>>16);
  24761. p[2] = (u8)(v>>8);
  24762. p[3] = (u8)v;
  24763. #endif
  24764. }
  24765. /*
  24766. ** Translate a single byte of Hex into an integer.
  24767. ** This routine only works if h really is a valid hexadecimal
  24768. ** character: 0..9a..fA..F
  24769. */
  24770. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  24771. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  24772. #ifdef SQLITE_ASCII
  24773. h += 9*(1&(h>>6));
  24774. #endif
  24775. #ifdef SQLITE_EBCDIC
  24776. h += 9*(1&~(h>>4));
  24777. #endif
  24778. return (u8)(h & 0xf);
  24779. }
  24780. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  24781. /*
  24782. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  24783. ** value. Return a pointer to its binary value. Space to hold the
  24784. ** binary value has been obtained from malloc and must be freed by
  24785. ** the calling routine.
  24786. */
  24787. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  24788. char *zBlob;
  24789. int i;
  24790. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  24791. n--;
  24792. if( zBlob ){
  24793. for(i=0; i<n; i+=2){
  24794. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  24795. }
  24796. zBlob[i/2] = 0;
  24797. }
  24798. return zBlob;
  24799. }
  24800. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  24801. /*
  24802. ** Log an error that is an API call on a connection pointer that should
  24803. ** not have been used. The "type" of connection pointer is given as the
  24804. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  24805. */
  24806. static void logBadConnection(const char *zType){
  24807. sqlite3_log(SQLITE_MISUSE,
  24808. "API call with %s database connection pointer",
  24809. zType
  24810. );
  24811. }
  24812. /*
  24813. ** Check to make sure we have a valid db pointer. This test is not
  24814. ** foolproof but it does provide some measure of protection against
  24815. ** misuse of the interface such as passing in db pointers that are
  24816. ** NULL or which have been previously closed. If this routine returns
  24817. ** 1 it means that the db pointer is valid and 0 if it should not be
  24818. ** dereferenced for any reason. The calling function should invoke
  24819. ** SQLITE_MISUSE immediately.
  24820. **
  24821. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  24822. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  24823. ** open properly and is not fit for general use but which can be
  24824. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  24825. */
  24826. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  24827. u32 magic;
  24828. if( db==0 ){
  24829. logBadConnection("NULL");
  24830. return 0;
  24831. }
  24832. magic = db->magic;
  24833. if( magic!=SQLITE_MAGIC_OPEN ){
  24834. if( sqlite3SafetyCheckSickOrOk(db) ){
  24835. testcase( sqlite3GlobalConfig.xLog!=0 );
  24836. logBadConnection("unopened");
  24837. }
  24838. return 0;
  24839. }else{
  24840. return 1;
  24841. }
  24842. }
  24843. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  24844. u32 magic;
  24845. magic = db->magic;
  24846. if( magic!=SQLITE_MAGIC_SICK &&
  24847. magic!=SQLITE_MAGIC_OPEN &&
  24848. magic!=SQLITE_MAGIC_BUSY ){
  24849. testcase( sqlite3GlobalConfig.xLog!=0 );
  24850. logBadConnection("invalid");
  24851. return 0;
  24852. }else{
  24853. return 1;
  24854. }
  24855. }
  24856. /*
  24857. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  24858. ** the other 64-bit signed integer at *pA and store the result in *pA.
  24859. ** Return 0 on success. Or if the operation would have resulted in an
  24860. ** overflow, leave *pA unchanged and return 1.
  24861. */
  24862. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  24863. i64 iA = *pA;
  24864. testcase( iA==0 ); testcase( iA==1 );
  24865. testcase( iB==-1 ); testcase( iB==0 );
  24866. if( iB>=0 ){
  24867. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  24868. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  24869. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  24870. }else{
  24871. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  24872. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  24873. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  24874. }
  24875. *pA += iB;
  24876. return 0;
  24877. }
  24878. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  24879. testcase( iB==SMALLEST_INT64+1 );
  24880. if( iB==SMALLEST_INT64 ){
  24881. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  24882. if( (*pA)>=0 ) return 1;
  24883. *pA -= iB;
  24884. return 0;
  24885. }else{
  24886. return sqlite3AddInt64(pA, -iB);
  24887. }
  24888. }
  24889. #define TWOPOWER32 (((i64)1)<<32)
  24890. #define TWOPOWER31 (((i64)1)<<31)
  24891. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  24892. i64 iA = *pA;
  24893. i64 iA1, iA0, iB1, iB0, r;
  24894. iA1 = iA/TWOPOWER32;
  24895. iA0 = iA % TWOPOWER32;
  24896. iB1 = iB/TWOPOWER32;
  24897. iB0 = iB % TWOPOWER32;
  24898. if( iA1==0 ){
  24899. if( iB1==0 ){
  24900. *pA *= iB;
  24901. return 0;
  24902. }
  24903. r = iA0*iB1;
  24904. }else if( iB1==0 ){
  24905. r = iA1*iB0;
  24906. }else{
  24907. /* If both iA1 and iB1 are non-zero, overflow will result */
  24908. return 1;
  24909. }
  24910. testcase( r==(-TWOPOWER31)-1 );
  24911. testcase( r==(-TWOPOWER31) );
  24912. testcase( r==TWOPOWER31 );
  24913. testcase( r==TWOPOWER31-1 );
  24914. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  24915. r *= TWOPOWER32;
  24916. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  24917. *pA = r;
  24918. return 0;
  24919. }
  24920. /*
  24921. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  24922. ** if the integer has a value of -2147483648, return +2147483647
  24923. */
  24924. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  24925. if( x>=0 ) return x;
  24926. if( x==(int)0x80000000 ) return 0x7fffffff;
  24927. return -x;
  24928. }
  24929. #ifdef SQLITE_ENABLE_8_3_NAMES
  24930. /*
  24931. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  24932. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  24933. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  24934. ** three characters, then shorten the suffix on z[] to be the last three
  24935. ** characters of the original suffix.
  24936. **
  24937. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  24938. ** do the suffix shortening regardless of URI parameter.
  24939. **
  24940. ** Examples:
  24941. **
  24942. ** test.db-journal => test.nal
  24943. ** test.db-wal => test.wal
  24944. ** test.db-shm => test.shm
  24945. ** test.db-mj7f3319fa => test.9fa
  24946. */
  24947. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  24948. #if SQLITE_ENABLE_8_3_NAMES<2
  24949. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  24950. #endif
  24951. {
  24952. int i, sz;
  24953. sz = sqlite3Strlen30(z);
  24954. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  24955. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  24956. }
  24957. }
  24958. #endif
  24959. /*
  24960. ** Find (an approximate) sum of two LogEst values. This computation is
  24961. ** not a simple "+" operator because LogEst is stored as a logarithmic
  24962. ** value.
  24963. **
  24964. */
  24965. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  24966. static const unsigned char x[] = {
  24967. 10, 10, /* 0,1 */
  24968. 9, 9, /* 2,3 */
  24969. 8, 8, /* 4,5 */
  24970. 7, 7, 7, /* 6,7,8 */
  24971. 6, 6, 6, /* 9,10,11 */
  24972. 5, 5, 5, /* 12-14 */
  24973. 4, 4, 4, 4, /* 15-18 */
  24974. 3, 3, 3, 3, 3, 3, /* 19-24 */
  24975. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  24976. };
  24977. if( a>=b ){
  24978. if( a>b+49 ) return a;
  24979. if( a>b+31 ) return a+1;
  24980. return a+x[a-b];
  24981. }else{
  24982. if( b>a+49 ) return b;
  24983. if( b>a+31 ) return b+1;
  24984. return b+x[b-a];
  24985. }
  24986. }
  24987. /*
  24988. ** Convert an integer into a LogEst. In other words, compute an
  24989. ** approximation for 10*log2(x).
  24990. */
  24991. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  24992. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  24993. LogEst y = 40;
  24994. if( x<8 ){
  24995. if( x<2 ) return 0;
  24996. while( x<8 ){ y -= 10; x <<= 1; }
  24997. }else{
  24998. while( x>255 ){ y += 40; x >>= 4; }
  24999. while( x>15 ){ y += 10; x >>= 1; }
  25000. }
  25001. return a[x&7] + y - 10;
  25002. }
  25003. #ifndef SQLITE_OMIT_VIRTUALTABLE
  25004. /*
  25005. ** Convert a double into a LogEst
  25006. ** In other words, compute an approximation for 10*log2(x).
  25007. */
  25008. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  25009. u64 a;
  25010. LogEst e;
  25011. assert( sizeof(x)==8 && sizeof(a)==8 );
  25012. if( x<=1 ) return 0;
  25013. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  25014. memcpy(&a, &x, 8);
  25015. e = (a>>52) - 1022;
  25016. return e*10;
  25017. }
  25018. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  25019. /*
  25020. ** Convert a LogEst into an integer.
  25021. */
  25022. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  25023. u64 n;
  25024. if( x<10 ) return 1;
  25025. n = x%10;
  25026. x /= 10;
  25027. if( n>=5 ) n -= 2;
  25028. else if( n>=1 ) n -= 1;
  25029. if( x>=3 ){
  25030. return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
  25031. }
  25032. return (n+8)>>(3-x);
  25033. }
  25034. /************** End of util.c ************************************************/
  25035. /************** Begin file hash.c ********************************************/
  25036. /*
  25037. ** 2001 September 22
  25038. **
  25039. ** The author disclaims copyright to this source code. In place of
  25040. ** a legal notice, here is a blessing:
  25041. **
  25042. ** May you do good and not evil.
  25043. ** May you find forgiveness for yourself and forgive others.
  25044. ** May you share freely, never taking more than you give.
  25045. **
  25046. *************************************************************************
  25047. ** This is the implementation of generic hash-tables
  25048. ** used in SQLite.
  25049. */
  25050. /* #include "sqliteInt.h" */
  25051. /* #include <assert.h> */
  25052. /* Turn bulk memory into a hash table object by initializing the
  25053. ** fields of the Hash structure.
  25054. **
  25055. ** "pNew" is a pointer to the hash table that is to be initialized.
  25056. */
  25057. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  25058. assert( pNew!=0 );
  25059. pNew->first = 0;
  25060. pNew->count = 0;
  25061. pNew->htsize = 0;
  25062. pNew->ht = 0;
  25063. }
  25064. /* Remove all entries from a hash table. Reclaim all memory.
  25065. ** Call this routine to delete a hash table or to reset a hash table
  25066. ** to the empty state.
  25067. */
  25068. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  25069. HashElem *elem; /* For looping over all elements of the table */
  25070. assert( pH!=0 );
  25071. elem = pH->first;
  25072. pH->first = 0;
  25073. sqlite3_free(pH->ht);
  25074. pH->ht = 0;
  25075. pH->htsize = 0;
  25076. while( elem ){
  25077. HashElem *next_elem = elem->next;
  25078. sqlite3_free(elem);
  25079. elem = next_elem;
  25080. }
  25081. pH->count = 0;
  25082. }
  25083. /*
  25084. ** The hashing function.
  25085. */
  25086. static unsigned int strHash(const char *z){
  25087. unsigned int h = 0;
  25088. unsigned char c;
  25089. while( (c = (unsigned char)*z++)!=0 ){
  25090. h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
  25091. }
  25092. return h;
  25093. }
  25094. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  25095. ** insert pNew into the pEntry hash bucket.
  25096. */
  25097. static void insertElement(
  25098. Hash *pH, /* The complete hash table */
  25099. struct _ht *pEntry, /* The entry into which pNew is inserted */
  25100. HashElem *pNew /* The element to be inserted */
  25101. ){
  25102. HashElem *pHead; /* First element already in pEntry */
  25103. if( pEntry ){
  25104. pHead = pEntry->count ? pEntry->chain : 0;
  25105. pEntry->count++;
  25106. pEntry->chain = pNew;
  25107. }else{
  25108. pHead = 0;
  25109. }
  25110. if( pHead ){
  25111. pNew->next = pHead;
  25112. pNew->prev = pHead->prev;
  25113. if( pHead->prev ){ pHead->prev->next = pNew; }
  25114. else { pH->first = pNew; }
  25115. pHead->prev = pNew;
  25116. }else{
  25117. pNew->next = pH->first;
  25118. if( pH->first ){ pH->first->prev = pNew; }
  25119. pNew->prev = 0;
  25120. pH->first = pNew;
  25121. }
  25122. }
  25123. /* Resize the hash table so that it cantains "new_size" buckets.
  25124. **
  25125. ** The hash table might fail to resize if sqlite3_malloc() fails or
  25126. ** if the new size is the same as the prior size.
  25127. ** Return TRUE if the resize occurs and false if not.
  25128. */
  25129. static int rehash(Hash *pH, unsigned int new_size){
  25130. struct _ht *new_ht; /* The new hash table */
  25131. HashElem *elem, *next_elem; /* For looping over existing elements */
  25132. #if SQLITE_MALLOC_SOFT_LIMIT>0
  25133. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  25134. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  25135. }
  25136. if( new_size==pH->htsize ) return 0;
  25137. #endif
  25138. /* The inability to allocates space for a larger hash table is
  25139. ** a performance hit but it is not a fatal error. So mark the
  25140. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  25141. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  25142. ** only zeroes the requested number of bytes whereas this module will
  25143. ** use the actual amount of space allocated for the hash table (which
  25144. ** may be larger than the requested amount).
  25145. */
  25146. sqlite3BeginBenignMalloc();
  25147. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  25148. sqlite3EndBenignMalloc();
  25149. if( new_ht==0 ) return 0;
  25150. sqlite3_free(pH->ht);
  25151. pH->ht = new_ht;
  25152. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  25153. memset(new_ht, 0, new_size*sizeof(struct _ht));
  25154. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  25155. unsigned int h = strHash(elem->pKey) % new_size;
  25156. next_elem = elem->next;
  25157. insertElement(pH, &new_ht[h], elem);
  25158. }
  25159. return 1;
  25160. }
  25161. /* This function (for internal use only) locates an element in an
  25162. ** hash table that matches the given key. The hash for this key is
  25163. ** also computed and returned in the *pH parameter.
  25164. */
  25165. static HashElem *findElementWithHash(
  25166. const Hash *pH, /* The pH to be searched */
  25167. const char *pKey, /* The key we are searching for */
  25168. unsigned int *pHash /* Write the hash value here */
  25169. ){
  25170. HashElem *elem; /* Used to loop thru the element list */
  25171. int count; /* Number of elements left to test */
  25172. unsigned int h; /* The computed hash */
  25173. if( pH->ht ){
  25174. struct _ht *pEntry;
  25175. h = strHash(pKey) % pH->htsize;
  25176. pEntry = &pH->ht[h];
  25177. elem = pEntry->chain;
  25178. count = pEntry->count;
  25179. }else{
  25180. h = 0;
  25181. elem = pH->first;
  25182. count = pH->count;
  25183. }
  25184. *pHash = h;
  25185. while( count-- ){
  25186. assert( elem!=0 );
  25187. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  25188. return elem;
  25189. }
  25190. elem = elem->next;
  25191. }
  25192. return 0;
  25193. }
  25194. /* Remove a single entry from the hash table given a pointer to that
  25195. ** element and a hash on the element's key.
  25196. */
  25197. static void removeElementGivenHash(
  25198. Hash *pH, /* The pH containing "elem" */
  25199. HashElem* elem, /* The element to be removed from the pH */
  25200. unsigned int h /* Hash value for the element */
  25201. ){
  25202. struct _ht *pEntry;
  25203. if( elem->prev ){
  25204. elem->prev->next = elem->next;
  25205. }else{
  25206. pH->first = elem->next;
  25207. }
  25208. if( elem->next ){
  25209. elem->next->prev = elem->prev;
  25210. }
  25211. if( pH->ht ){
  25212. pEntry = &pH->ht[h];
  25213. if( pEntry->chain==elem ){
  25214. pEntry->chain = elem->next;
  25215. }
  25216. pEntry->count--;
  25217. assert( pEntry->count>=0 );
  25218. }
  25219. sqlite3_free( elem );
  25220. pH->count--;
  25221. if( pH->count==0 ){
  25222. assert( pH->first==0 );
  25223. assert( pH->count==0 );
  25224. sqlite3HashClear(pH);
  25225. }
  25226. }
  25227. /* Attempt to locate an element of the hash table pH with a key
  25228. ** that matches pKey. Return the data for this element if it is
  25229. ** found, or NULL if there is no match.
  25230. */
  25231. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  25232. HashElem *elem; /* The element that matches key */
  25233. unsigned int h; /* A hash on key */
  25234. assert( pH!=0 );
  25235. assert( pKey!=0 );
  25236. elem = findElementWithHash(pH, pKey, &h);
  25237. return elem ? elem->data : 0;
  25238. }
  25239. /* Insert an element into the hash table pH. The key is pKey
  25240. ** and the data is "data".
  25241. **
  25242. ** If no element exists with a matching key, then a new
  25243. ** element is created and NULL is returned.
  25244. **
  25245. ** If another element already exists with the same key, then the
  25246. ** new data replaces the old data and the old data is returned.
  25247. ** The key is not copied in this instance. If a malloc fails, then
  25248. ** the new data is returned and the hash table is unchanged.
  25249. **
  25250. ** If the "data" parameter to this function is NULL, then the
  25251. ** element corresponding to "key" is removed from the hash table.
  25252. */
  25253. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  25254. unsigned int h; /* the hash of the key modulo hash table size */
  25255. HashElem *elem; /* Used to loop thru the element list */
  25256. HashElem *new_elem; /* New element added to the pH */
  25257. assert( pH!=0 );
  25258. assert( pKey!=0 );
  25259. elem = findElementWithHash(pH,pKey,&h);
  25260. if( elem ){
  25261. void *old_data = elem->data;
  25262. if( data==0 ){
  25263. removeElementGivenHash(pH,elem,h);
  25264. }else{
  25265. elem->data = data;
  25266. elem->pKey = pKey;
  25267. }
  25268. return old_data;
  25269. }
  25270. if( data==0 ) return 0;
  25271. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  25272. if( new_elem==0 ) return data;
  25273. new_elem->pKey = pKey;
  25274. new_elem->data = data;
  25275. pH->count++;
  25276. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  25277. if( rehash(pH, pH->count*2) ){
  25278. assert( pH->htsize>0 );
  25279. h = strHash(pKey) % pH->htsize;
  25280. }
  25281. }
  25282. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  25283. return 0;
  25284. }
  25285. /************** End of hash.c ************************************************/
  25286. /************** Begin file opcodes.c *****************************************/
  25287. /* Automatically generated. Do not edit */
  25288. /* See the tool/mkopcodec.tcl script for details. */
  25289. #if !defined(SQLITE_OMIT_EXPLAIN) \
  25290. || defined(VDBE_PROFILE) \
  25291. || defined(SQLITE_DEBUG)
  25292. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  25293. # define OpHelp(X) "\0" X
  25294. #else
  25295. # define OpHelp(X)
  25296. #endif
  25297. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  25298. static const char *const azName[] = { "?",
  25299. /* 1 */ "Savepoint" OpHelp(""),
  25300. /* 2 */ "AutoCommit" OpHelp(""),
  25301. /* 3 */ "Transaction" OpHelp(""),
  25302. /* 4 */ "SorterNext" OpHelp(""),
  25303. /* 5 */ "PrevIfOpen" OpHelp(""),
  25304. /* 6 */ "NextIfOpen" OpHelp(""),
  25305. /* 7 */ "Prev" OpHelp(""),
  25306. /* 8 */ "Next" OpHelp(""),
  25307. /* 9 */ "Checkpoint" OpHelp(""),
  25308. /* 10 */ "JournalMode" OpHelp(""),
  25309. /* 11 */ "Vacuum" OpHelp(""),
  25310. /* 12 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  25311. /* 13 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  25312. /* 14 */ "Goto" OpHelp(""),
  25313. /* 15 */ "Gosub" OpHelp(""),
  25314. /* 16 */ "Return" OpHelp(""),
  25315. /* 17 */ "InitCoroutine" OpHelp(""),
  25316. /* 18 */ "EndCoroutine" OpHelp(""),
  25317. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  25318. /* 20 */ "Yield" OpHelp(""),
  25319. /* 21 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  25320. /* 22 */ "Halt" OpHelp(""),
  25321. /* 23 */ "Integer" OpHelp("r[P2]=P1"),
  25322. /* 24 */ "Int64" OpHelp("r[P2]=P4"),
  25323. /* 25 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  25324. /* 26 */ "Null" OpHelp("r[P2..P3]=NULL"),
  25325. /* 27 */ "SoftNull" OpHelp("r[P1]=NULL"),
  25326. /* 28 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  25327. /* 29 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  25328. /* 30 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  25329. /* 31 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  25330. /* 32 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  25331. /* 33 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  25332. /* 34 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  25333. /* 35 */ "CollSeq" OpHelp(""),
  25334. /* 36 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  25335. /* 37 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  25336. /* 38 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  25337. /* 39 */ "MustBeInt" OpHelp(""),
  25338. /* 40 */ "RealAffinity" OpHelp(""),
  25339. /* 41 */ "Cast" OpHelp("affinity(r[P1])"),
  25340. /* 42 */ "Permutation" OpHelp(""),
  25341. /* 43 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  25342. /* 44 */ "Jump" OpHelp(""),
  25343. /* 45 */ "Once" OpHelp(""),
  25344. /* 46 */ "If" OpHelp(""),
  25345. /* 47 */ "IfNot" OpHelp(""),
  25346. /* 48 */ "Column" OpHelp("r[P3]=PX"),
  25347. /* 49 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  25348. /* 50 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  25349. /* 51 */ "Count" OpHelp("r[P2]=count()"),
  25350. /* 52 */ "ReadCookie" OpHelp(""),
  25351. /* 53 */ "SetCookie" OpHelp(""),
  25352. /* 54 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  25353. /* 55 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  25354. /* 56 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  25355. /* 57 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  25356. /* 58 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  25357. /* 59 */ "SorterOpen" OpHelp(""),
  25358. /* 60 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  25359. /* 61 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  25360. /* 62 */ "Close" OpHelp(""),
  25361. /* 63 */ "ColumnsUsed" OpHelp(""),
  25362. /* 64 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  25363. /* 65 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  25364. /* 66 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  25365. /* 67 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  25366. /* 68 */ "Seek" OpHelp("intkey=r[P2]"),
  25367. /* 69 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  25368. /* 70 */ "NotFound" OpHelp("key=r[P3@P4]"),
  25369. /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  25370. /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  25371. /* 73 */ "Found" OpHelp("key=r[P3@P4]"),
  25372. /* 74 */ "NotExists" OpHelp("intkey=r[P3]"),
  25373. /* 75 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  25374. /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  25375. /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  25376. /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
  25377. /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
  25378. /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
  25379. /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
  25380. /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
  25381. /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
  25382. /* 84 */ "NewRowid" OpHelp("r[P2]=rowid"),
  25383. /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  25384. /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  25385. /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  25386. /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  25387. /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  25388. /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  25389. /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  25390. /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  25391. /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  25392. /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  25393. /* 95 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  25394. /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  25395. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  25396. /* 98 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  25397. /* 99 */ "Delete" OpHelp(""),
  25398. /* 100 */ "ResetCount" OpHelp(""),
  25399. /* 101 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  25400. /* 102 */ "SorterData" OpHelp("r[P2]=data"),
  25401. /* 103 */ "RowKey" OpHelp("r[P2]=key"),
  25402. /* 104 */ "RowData" OpHelp("r[P2]=data"),
  25403. /* 105 */ "Rowid" OpHelp("r[P2]=rowid"),
  25404. /* 106 */ "NullRow" OpHelp(""),
  25405. /* 107 */ "Last" OpHelp(""),
  25406. /* 108 */ "SorterSort" OpHelp(""),
  25407. /* 109 */ "Sort" OpHelp(""),
  25408. /* 110 */ "Rewind" OpHelp(""),
  25409. /* 111 */ "SorterInsert" OpHelp(""),
  25410. /* 112 */ "IdxInsert" OpHelp("key=r[P2]"),
  25411. /* 113 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  25412. /* 114 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  25413. /* 115 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  25414. /* 116 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  25415. /* 117 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  25416. /* 118 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  25417. /* 119 */ "Destroy" OpHelp(""),
  25418. /* 120 */ "Clear" OpHelp(""),
  25419. /* 121 */ "ResetSorter" OpHelp(""),
  25420. /* 122 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  25421. /* 123 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  25422. /* 124 */ "ParseSchema" OpHelp(""),
  25423. /* 125 */ "LoadAnalysis" OpHelp(""),
  25424. /* 126 */ "DropTable" OpHelp(""),
  25425. /* 127 */ "DropIndex" OpHelp(""),
  25426. /* 128 */ "DropTrigger" OpHelp(""),
  25427. /* 129 */ "IntegrityCk" OpHelp(""),
  25428. /* 130 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  25429. /* 131 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  25430. /* 132 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  25431. /* 133 */ "Real" OpHelp("r[P2]=P4"),
  25432. /* 134 */ "Program" OpHelp(""),
  25433. /* 135 */ "Param" OpHelp(""),
  25434. /* 136 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  25435. /* 137 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  25436. /* 138 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  25437. /* 139 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  25438. /* 140 */ "SetIfNotPos" OpHelp("if r[P1]<=0 then r[P2]=P3"),
  25439. /* 141 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
  25440. /* 142 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  25441. /* 143 */ "JumpZeroIncr" OpHelp("if (r[P1]++)==0 ) goto P2"),
  25442. /* 144 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  25443. /* 145 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  25444. /* 146 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  25445. /* 147 */ "IncrVacuum" OpHelp(""),
  25446. /* 148 */ "Expire" OpHelp(""),
  25447. /* 149 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  25448. /* 150 */ "VBegin" OpHelp(""),
  25449. /* 151 */ "VCreate" OpHelp(""),
  25450. /* 152 */ "VDestroy" OpHelp(""),
  25451. /* 153 */ "VOpen" OpHelp(""),
  25452. /* 154 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  25453. /* 155 */ "VNext" OpHelp(""),
  25454. /* 156 */ "VRename" OpHelp(""),
  25455. /* 157 */ "Pagecount" OpHelp(""),
  25456. /* 158 */ "MaxPgcnt" OpHelp(""),
  25457. /* 159 */ "Init" OpHelp("Start at P2"),
  25458. /* 160 */ "CursorHint" OpHelp(""),
  25459. /* 161 */ "Noop" OpHelp(""),
  25460. /* 162 */ "Explain" OpHelp(""),
  25461. };
  25462. return azName[i];
  25463. }
  25464. #endif
  25465. /************** End of opcodes.c *********************************************/
  25466. /************** Begin file os_unix.c *****************************************/
  25467. /*
  25468. ** 2004 May 22
  25469. **
  25470. ** The author disclaims copyright to this source code. In place of
  25471. ** a legal notice, here is a blessing:
  25472. **
  25473. ** May you do good and not evil.
  25474. ** May you find forgiveness for yourself and forgive others.
  25475. ** May you share freely, never taking more than you give.
  25476. **
  25477. ******************************************************************************
  25478. **
  25479. ** This file contains the VFS implementation for unix-like operating systems
  25480. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  25481. **
  25482. ** There are actually several different VFS implementations in this file.
  25483. ** The differences are in the way that file locking is done. The default
  25484. ** implementation uses Posix Advisory Locks. Alternative implementations
  25485. ** use flock(), dot-files, various proprietary locking schemas, or simply
  25486. ** skip locking all together.
  25487. **
  25488. ** This source file is organized into divisions where the logic for various
  25489. ** subfunctions is contained within the appropriate division. PLEASE
  25490. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  25491. ** in the correct division and should be clearly labeled.
  25492. **
  25493. ** The layout of divisions is as follows:
  25494. **
  25495. ** * General-purpose declarations and utility functions.
  25496. ** * Unique file ID logic used by VxWorks.
  25497. ** * Various locking primitive implementations (all except proxy locking):
  25498. ** + for Posix Advisory Locks
  25499. ** + for no-op locks
  25500. ** + for dot-file locks
  25501. ** + for flock() locking
  25502. ** + for named semaphore locks (VxWorks only)
  25503. ** + for AFP filesystem locks (MacOSX only)
  25504. ** * sqlite3_file methods not associated with locking.
  25505. ** * Definitions of sqlite3_io_methods objects for all locking
  25506. ** methods plus "finder" functions for each locking method.
  25507. ** * sqlite3_vfs method implementations.
  25508. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  25509. ** * Definitions of sqlite3_vfs objects for all locking methods
  25510. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  25511. */
  25512. /* #include "sqliteInt.h" */
  25513. #if SQLITE_OS_UNIX /* This file is used on unix only */
  25514. /*
  25515. ** There are various methods for file locking used for concurrency
  25516. ** control:
  25517. **
  25518. ** 1. POSIX locking (the default),
  25519. ** 2. No locking,
  25520. ** 3. Dot-file locking,
  25521. ** 4. flock() locking,
  25522. ** 5. AFP locking (OSX only),
  25523. ** 6. Named POSIX semaphores (VXWorks only),
  25524. ** 7. proxy locking. (OSX only)
  25525. **
  25526. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  25527. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  25528. ** selection of the appropriate locking style based on the filesystem
  25529. ** where the database is located.
  25530. */
  25531. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  25532. # if defined(__APPLE__)
  25533. # define SQLITE_ENABLE_LOCKING_STYLE 1
  25534. # else
  25535. # define SQLITE_ENABLE_LOCKING_STYLE 0
  25536. # endif
  25537. #endif
  25538. /*
  25539. ** standard include files.
  25540. */
  25541. #include <sys/types.h>
  25542. #include <sys/stat.h>
  25543. #include <fcntl.h>
  25544. #include <unistd.h>
  25545. /* #include <time.h> */
  25546. #include <sys/time.h>
  25547. #include <errno.h>
  25548. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  25549. # include <sys/mman.h>
  25550. #endif
  25551. #if SQLITE_ENABLE_LOCKING_STYLE
  25552. # include <sys/ioctl.h>
  25553. # include <sys/file.h>
  25554. # include <sys/param.h>
  25555. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  25556. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  25557. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  25558. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  25559. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  25560. # define HAVE_GETHOSTUUID 1
  25561. # else
  25562. # warning "gethostuuid() is disabled."
  25563. # endif
  25564. #endif
  25565. #if OS_VXWORKS
  25566. /* # include <sys/ioctl.h> */
  25567. # include <semaphore.h>
  25568. # include <limits.h>
  25569. #endif /* OS_VXWORKS */
  25570. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  25571. # include <sys/mount.h>
  25572. #endif
  25573. #ifdef HAVE_UTIME
  25574. # include <utime.h>
  25575. #endif
  25576. /*
  25577. ** Allowed values of unixFile.fsFlags
  25578. */
  25579. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  25580. /*
  25581. ** If we are to be thread-safe, include the pthreads header and define
  25582. ** the SQLITE_UNIX_THREADS macro.
  25583. */
  25584. #if SQLITE_THREADSAFE
  25585. /* # include <pthread.h> */
  25586. # define SQLITE_UNIX_THREADS 1
  25587. #endif
  25588. /*
  25589. ** Default permissions when creating a new file
  25590. */
  25591. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  25592. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  25593. #endif
  25594. /*
  25595. ** Default permissions when creating auto proxy dir
  25596. */
  25597. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  25598. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  25599. #endif
  25600. /*
  25601. ** Maximum supported path-length.
  25602. */
  25603. #define MAX_PATHNAME 512
  25604. /* Always cast the getpid() return type for compatibility with
  25605. ** kernel modules in VxWorks. */
  25606. #define osGetpid(X) (pid_t)getpid()
  25607. /*
  25608. ** Only set the lastErrno if the error code is a real error and not
  25609. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  25610. */
  25611. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  25612. /* Forward references */
  25613. typedef struct unixShm unixShm; /* Connection shared memory */
  25614. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  25615. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  25616. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  25617. /*
  25618. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  25619. ** cannot be closed immediately. In these cases, instances of the following
  25620. ** structure are used to store the file descriptor while waiting for an
  25621. ** opportunity to either close or reuse it.
  25622. */
  25623. struct UnixUnusedFd {
  25624. int fd; /* File descriptor to close */
  25625. int flags; /* Flags this file descriptor was opened with */
  25626. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  25627. };
  25628. /*
  25629. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  25630. ** VFS implementations.
  25631. */
  25632. typedef struct unixFile unixFile;
  25633. struct unixFile {
  25634. sqlite3_io_methods const *pMethod; /* Always the first entry */
  25635. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  25636. unixInodeInfo *pInode; /* Info about locks on this inode */
  25637. int h; /* The file descriptor */
  25638. unsigned char eFileLock; /* The type of lock held on this fd */
  25639. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  25640. int lastErrno; /* The unix errno from last I/O error */
  25641. void *lockingContext; /* Locking style specific state */
  25642. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  25643. const char *zPath; /* Name of the file */
  25644. unixShm *pShm; /* Shared memory segment information */
  25645. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  25646. #if SQLITE_MAX_MMAP_SIZE>0
  25647. int nFetchOut; /* Number of outstanding xFetch refs */
  25648. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  25649. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  25650. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  25651. void *pMapRegion; /* Memory mapped region */
  25652. #endif
  25653. #ifdef __QNXNTO__
  25654. int sectorSize; /* Device sector size */
  25655. int deviceCharacteristics; /* Precomputed device characteristics */
  25656. #endif
  25657. #if SQLITE_ENABLE_LOCKING_STYLE
  25658. int openFlags; /* The flags specified at open() */
  25659. #endif
  25660. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  25661. unsigned fsFlags; /* cached details from statfs() */
  25662. #endif
  25663. #if OS_VXWORKS
  25664. struct vxworksFileId *pId; /* Unique file ID */
  25665. #endif
  25666. #ifdef SQLITE_DEBUG
  25667. /* The next group of variables are used to track whether or not the
  25668. ** transaction counter in bytes 24-27 of database files are updated
  25669. ** whenever any part of the database changes. An assertion fault will
  25670. ** occur if a file is updated without also updating the transaction
  25671. ** counter. This test is made to avoid new problems similar to the
  25672. ** one described by ticket #3584.
  25673. */
  25674. unsigned char transCntrChng; /* True if the transaction counter changed */
  25675. unsigned char dbUpdate; /* True if any part of database file changed */
  25676. unsigned char inNormalWrite; /* True if in a normal write operation */
  25677. #endif
  25678. #ifdef SQLITE_TEST
  25679. /* In test mode, increase the size of this structure a bit so that
  25680. ** it is larger than the struct CrashFile defined in test6.c.
  25681. */
  25682. char aPadding[32];
  25683. #endif
  25684. };
  25685. /* This variable holds the process id (pid) from when the xRandomness()
  25686. ** method was called. If xOpen() is called from a different process id,
  25687. ** indicating that a fork() has occurred, the PRNG will be reset.
  25688. */
  25689. static pid_t randomnessPid = 0;
  25690. /*
  25691. ** Allowed values for the unixFile.ctrlFlags bitmask:
  25692. */
  25693. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  25694. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  25695. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  25696. #ifndef SQLITE_DISABLE_DIRSYNC
  25697. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  25698. #else
  25699. # define UNIXFILE_DIRSYNC 0x00
  25700. #endif
  25701. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  25702. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  25703. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  25704. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  25705. /*
  25706. ** Include code that is common to all os_*.c files
  25707. */
  25708. /************** Include os_common.h in the middle of os_unix.c ***************/
  25709. /************** Begin file os_common.h ***************************************/
  25710. /*
  25711. ** 2004 May 22
  25712. **
  25713. ** The author disclaims copyright to this source code. In place of
  25714. ** a legal notice, here is a blessing:
  25715. **
  25716. ** May you do good and not evil.
  25717. ** May you find forgiveness for yourself and forgive others.
  25718. ** May you share freely, never taking more than you give.
  25719. **
  25720. ******************************************************************************
  25721. **
  25722. ** This file contains macros and a little bit of code that is common to
  25723. ** all of the platform-specific files (os_*.c) and is #included into those
  25724. ** files.
  25725. **
  25726. ** This file should be #included by the os_*.c files only. It is not a
  25727. ** general purpose header file.
  25728. */
  25729. #ifndef _OS_COMMON_H_
  25730. #define _OS_COMMON_H_
  25731. /*
  25732. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  25733. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  25734. ** switch. The following code should catch this problem at compile-time.
  25735. */
  25736. #ifdef MEMORY_DEBUG
  25737. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  25738. #endif
  25739. /*
  25740. ** Macros for performance tracing. Normally turned off. Only works
  25741. ** on i486 hardware.
  25742. */
  25743. #ifdef SQLITE_PERFORMANCE_TRACE
  25744. /*
  25745. ** hwtime.h contains inline assembler code for implementing
  25746. ** high-performance timing routines.
  25747. */
  25748. /************** Include hwtime.h in the middle of os_common.h ****************/
  25749. /************** Begin file hwtime.h ******************************************/
  25750. /*
  25751. ** 2008 May 27
  25752. **
  25753. ** The author disclaims copyright to this source code. In place of
  25754. ** a legal notice, here is a blessing:
  25755. **
  25756. ** May you do good and not evil.
  25757. ** May you find forgiveness for yourself and forgive others.
  25758. ** May you share freely, never taking more than you give.
  25759. **
  25760. ******************************************************************************
  25761. **
  25762. ** This file contains inline asm code for retrieving "high-performance"
  25763. ** counters for x86 class CPUs.
  25764. */
  25765. #ifndef _HWTIME_H_
  25766. #define _HWTIME_H_
  25767. /*
  25768. ** The following routine only works on pentium-class (or newer) processors.
  25769. ** It uses the RDTSC opcode to read the cycle count value out of the
  25770. ** processor and returns that value. This can be used for high-res
  25771. ** profiling.
  25772. */
  25773. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  25774. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  25775. #if defined(__GNUC__)
  25776. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25777. unsigned int lo, hi;
  25778. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  25779. return (sqlite_uint64)hi << 32 | lo;
  25780. }
  25781. #elif defined(_MSC_VER)
  25782. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  25783. __asm {
  25784. rdtsc
  25785. ret ; return value at EDX:EAX
  25786. }
  25787. }
  25788. #endif
  25789. #elif (defined(__GNUC__) && defined(__x86_64__))
  25790. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25791. unsigned long val;
  25792. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  25793. return val;
  25794. }
  25795. #elif (defined(__GNUC__) && defined(__ppc__))
  25796. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25797. unsigned long long retval;
  25798. unsigned long junk;
  25799. __asm__ __volatile__ ("\n\
  25800. 1: mftbu %1\n\
  25801. mftb %L0\n\
  25802. mftbu %0\n\
  25803. cmpw %0,%1\n\
  25804. bne 1b"
  25805. : "=r" (retval), "=r" (junk));
  25806. return retval;
  25807. }
  25808. #else
  25809. #error Need implementation of sqlite3Hwtime() for your platform.
  25810. /*
  25811. ** To compile without implementing sqlite3Hwtime() for your platform,
  25812. ** you can remove the above #error and use the following
  25813. ** stub function. You will lose timing support for many
  25814. ** of the debugging and testing utilities, but it should at
  25815. ** least compile and run.
  25816. */
  25817. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  25818. #endif
  25819. #endif /* !defined(_HWTIME_H_) */
  25820. /************** End of hwtime.h **********************************************/
  25821. /************** Continuing where we left off in os_common.h ******************/
  25822. static sqlite_uint64 g_start;
  25823. static sqlite_uint64 g_elapsed;
  25824. #define TIMER_START g_start=sqlite3Hwtime()
  25825. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  25826. #define TIMER_ELAPSED g_elapsed
  25827. #else
  25828. #define TIMER_START
  25829. #define TIMER_END
  25830. #define TIMER_ELAPSED ((sqlite_uint64)0)
  25831. #endif
  25832. /*
  25833. ** If we compile with the SQLITE_TEST macro set, then the following block
  25834. ** of code will give us the ability to simulate a disk I/O error. This
  25835. ** is used for testing the I/O recovery logic.
  25836. */
  25837. #ifdef SQLITE_TEST
  25838. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  25839. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  25840. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  25841. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  25842. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  25843. SQLITE_API int sqlite3_diskfull_pending = 0;
  25844. SQLITE_API int sqlite3_diskfull = 0;
  25845. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  25846. #define SimulateIOError(CODE) \
  25847. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  25848. || sqlite3_io_error_pending-- == 1 ) \
  25849. { local_ioerr(); CODE; }
  25850. static void local_ioerr(){
  25851. IOTRACE(("IOERR\n"));
  25852. sqlite3_io_error_hit++;
  25853. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  25854. }
  25855. #define SimulateDiskfullError(CODE) \
  25856. if( sqlite3_diskfull_pending ){ \
  25857. if( sqlite3_diskfull_pending == 1 ){ \
  25858. local_ioerr(); \
  25859. sqlite3_diskfull = 1; \
  25860. sqlite3_io_error_hit = 1; \
  25861. CODE; \
  25862. }else{ \
  25863. sqlite3_diskfull_pending--; \
  25864. } \
  25865. }
  25866. #else
  25867. #define SimulateIOErrorBenign(X)
  25868. #define SimulateIOError(A)
  25869. #define SimulateDiskfullError(A)
  25870. #endif
  25871. /*
  25872. ** When testing, keep a count of the number of open files.
  25873. */
  25874. #ifdef SQLITE_TEST
  25875. SQLITE_API int sqlite3_open_file_count = 0;
  25876. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  25877. #else
  25878. #define OpenCounter(X)
  25879. #endif
  25880. #endif /* !defined(_OS_COMMON_H_) */
  25881. /************** End of os_common.h *******************************************/
  25882. /************** Continuing where we left off in os_unix.c ********************/
  25883. /*
  25884. ** Define various macros that are missing from some systems.
  25885. */
  25886. #ifndef O_LARGEFILE
  25887. # define O_LARGEFILE 0
  25888. #endif
  25889. #ifdef SQLITE_DISABLE_LFS
  25890. # undef O_LARGEFILE
  25891. # define O_LARGEFILE 0
  25892. #endif
  25893. #ifndef O_NOFOLLOW
  25894. # define O_NOFOLLOW 0
  25895. #endif
  25896. #ifndef O_BINARY
  25897. # define O_BINARY 0
  25898. #endif
  25899. /*
  25900. ** The threadid macro resolves to the thread-id or to 0. Used for
  25901. ** testing and debugging only.
  25902. */
  25903. #if SQLITE_THREADSAFE
  25904. #define threadid pthread_self()
  25905. #else
  25906. #define threadid 0
  25907. #endif
  25908. /*
  25909. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  25910. */
  25911. #if !defined(HAVE_MREMAP)
  25912. # if defined(__linux__) && defined(_GNU_SOURCE)
  25913. # define HAVE_MREMAP 1
  25914. # else
  25915. # define HAVE_MREMAP 0
  25916. # endif
  25917. #endif
  25918. /*
  25919. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  25920. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  25921. */
  25922. #ifdef __ANDROID__
  25923. # define lseek lseek64
  25924. #endif
  25925. /*
  25926. ** Different Unix systems declare open() in different ways. Same use
  25927. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  25928. ** The difference is important when using a pointer to the function.
  25929. **
  25930. ** The safest way to deal with the problem is to always use this wrapper
  25931. ** which always has the same well-defined interface.
  25932. */
  25933. static int posixOpen(const char *zFile, int flags, int mode){
  25934. return open(zFile, flags, mode);
  25935. }
  25936. /* Forward reference */
  25937. static int openDirectory(const char*, int*);
  25938. static int unixGetpagesize(void);
  25939. /*
  25940. ** Many system calls are accessed through pointer-to-functions so that
  25941. ** they may be overridden at runtime to facilitate fault injection during
  25942. ** testing and sandboxing. The following array holds the names and pointers
  25943. ** to all overrideable system calls.
  25944. */
  25945. static struct unix_syscall {
  25946. const char *zName; /* Name of the system call */
  25947. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  25948. sqlite3_syscall_ptr pDefault; /* Default value */
  25949. } aSyscall[] = {
  25950. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  25951. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  25952. { "close", (sqlite3_syscall_ptr)close, 0 },
  25953. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  25954. { "access", (sqlite3_syscall_ptr)access, 0 },
  25955. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  25956. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  25957. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  25958. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  25959. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  25960. /*
  25961. ** The DJGPP compiler environment looks mostly like Unix, but it
  25962. ** lacks the fcntl() system call. So redefine fcntl() to be something
  25963. ** that always succeeds. This means that locking does not occur under
  25964. ** DJGPP. But it is DOS - what did you expect?
  25965. */
  25966. #ifdef __DJGPP__
  25967. { "fstat", 0, 0 },
  25968. #define osFstat(a,b,c) 0
  25969. #else
  25970. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  25971. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  25972. #endif
  25973. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  25974. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  25975. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  25976. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  25977. { "read", (sqlite3_syscall_ptr)read, 0 },
  25978. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  25979. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  25980. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  25981. #else
  25982. { "pread", (sqlite3_syscall_ptr)0, 0 },
  25983. #endif
  25984. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  25985. #if defined(USE_PREAD64)
  25986. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  25987. #else
  25988. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  25989. #endif
  25990. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  25991. { "write", (sqlite3_syscall_ptr)write, 0 },
  25992. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  25993. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  25994. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  25995. #else
  25996. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  25997. #endif
  25998. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  25999. aSyscall[12].pCurrent)
  26000. #if defined(USE_PREAD64)
  26001. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  26002. #else
  26003. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  26004. #endif
  26005. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  26006. aSyscall[13].pCurrent)
  26007. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  26008. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  26009. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  26010. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  26011. #else
  26012. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  26013. #endif
  26014. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  26015. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  26016. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  26017. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  26018. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  26019. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  26020. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  26021. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  26022. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  26023. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  26024. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  26025. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  26026. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  26027. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  26028. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  26029. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  26030. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  26031. #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
  26032. #if HAVE_MREMAP
  26033. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  26034. #else
  26035. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  26036. #endif
  26037. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  26038. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  26039. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  26040. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  26041. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  26042. #endif
  26043. }; /* End of the overrideable system calls */
  26044. /*
  26045. ** On some systems, calls to fchown() will trigger a message in a security
  26046. ** log if they come from non-root processes. So avoid calling fchown() if
  26047. ** we are not running as root.
  26048. */
  26049. static int robustFchown(int fd, uid_t uid, gid_t gid){
  26050. #if OS_VXWORKS
  26051. return 0;
  26052. #else
  26053. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  26054. #endif
  26055. }
  26056. /*
  26057. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  26058. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  26059. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  26060. ** system call named zName.
  26061. */
  26062. static int unixSetSystemCall(
  26063. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  26064. const char *zName, /* Name of system call to override */
  26065. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  26066. ){
  26067. unsigned int i;
  26068. int rc = SQLITE_NOTFOUND;
  26069. UNUSED_PARAMETER(pNotUsed);
  26070. if( zName==0 ){
  26071. /* If no zName is given, restore all system calls to their default
  26072. ** settings and return NULL
  26073. */
  26074. rc = SQLITE_OK;
  26075. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  26076. if( aSyscall[i].pDefault ){
  26077. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  26078. }
  26079. }
  26080. }else{
  26081. /* If zName is specified, operate on only the one system call
  26082. ** specified.
  26083. */
  26084. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  26085. if( strcmp(zName, aSyscall[i].zName)==0 ){
  26086. if( aSyscall[i].pDefault==0 ){
  26087. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  26088. }
  26089. rc = SQLITE_OK;
  26090. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  26091. aSyscall[i].pCurrent = pNewFunc;
  26092. break;
  26093. }
  26094. }
  26095. }
  26096. return rc;
  26097. }
  26098. /*
  26099. ** Return the value of a system call. Return NULL if zName is not a
  26100. ** recognized system call name. NULL is also returned if the system call
  26101. ** is currently undefined.
  26102. */
  26103. static sqlite3_syscall_ptr unixGetSystemCall(
  26104. sqlite3_vfs *pNotUsed,
  26105. const char *zName
  26106. ){
  26107. unsigned int i;
  26108. UNUSED_PARAMETER(pNotUsed);
  26109. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  26110. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  26111. }
  26112. return 0;
  26113. }
  26114. /*
  26115. ** Return the name of the first system call after zName. If zName==NULL
  26116. ** then return the name of the first system call. Return NULL if zName
  26117. ** is the last system call or if zName is not the name of a valid
  26118. ** system call.
  26119. */
  26120. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  26121. int i = -1;
  26122. UNUSED_PARAMETER(p);
  26123. if( zName ){
  26124. for(i=0; i<ArraySize(aSyscall)-1; i++){
  26125. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  26126. }
  26127. }
  26128. for(i++; i<ArraySize(aSyscall); i++){
  26129. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  26130. }
  26131. return 0;
  26132. }
  26133. /*
  26134. ** Do not accept any file descriptor less than this value, in order to avoid
  26135. ** opening database file using file descriptors that are commonly used for
  26136. ** standard input, output, and error.
  26137. */
  26138. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  26139. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  26140. #endif
  26141. /*
  26142. ** Invoke open(). Do so multiple times, until it either succeeds or
  26143. ** fails for some reason other than EINTR.
  26144. **
  26145. ** If the file creation mode "m" is 0 then set it to the default for
  26146. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  26147. ** 0644) as modified by the system umask. If m is not 0, then
  26148. ** make the file creation mode be exactly m ignoring the umask.
  26149. **
  26150. ** The m parameter will be non-zero only when creating -wal, -journal,
  26151. ** and -shm files. We want those files to have *exactly* the same
  26152. ** permissions as their original database, unadulterated by the umask.
  26153. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  26154. ** transaction crashes and leaves behind hot journals, then any
  26155. ** process that is able to write to the database will also be able to
  26156. ** recover the hot journals.
  26157. */
  26158. static int robust_open(const char *z, int f, mode_t m){
  26159. int fd;
  26160. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  26161. while(1){
  26162. #if defined(O_CLOEXEC)
  26163. fd = osOpen(z,f|O_CLOEXEC,m2);
  26164. #else
  26165. fd = osOpen(z,f,m2);
  26166. #endif
  26167. if( fd<0 ){
  26168. if( errno==EINTR ) continue;
  26169. break;
  26170. }
  26171. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  26172. osClose(fd);
  26173. sqlite3_log(SQLITE_WARNING,
  26174. "attempt to open \"%s\" as file descriptor %d", z, fd);
  26175. fd = -1;
  26176. if( osOpen("/dev/null", f, m)<0 ) break;
  26177. }
  26178. if( fd>=0 ){
  26179. if( m!=0 ){
  26180. struct stat statbuf;
  26181. if( osFstat(fd, &statbuf)==0
  26182. && statbuf.st_size==0
  26183. && (statbuf.st_mode&0777)!=m
  26184. ){
  26185. osFchmod(fd, m);
  26186. }
  26187. }
  26188. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  26189. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  26190. #endif
  26191. }
  26192. return fd;
  26193. }
  26194. /*
  26195. ** Helper functions to obtain and relinquish the global mutex. The
  26196. ** global mutex is used to protect the unixInodeInfo and
  26197. ** vxworksFileId objects used by this file, all of which may be
  26198. ** shared by multiple threads.
  26199. **
  26200. ** Function unixMutexHeld() is used to assert() that the global mutex
  26201. ** is held when required. This function is only used as part of assert()
  26202. ** statements. e.g.
  26203. **
  26204. ** unixEnterMutex()
  26205. ** assert( unixMutexHeld() );
  26206. ** unixEnterLeave()
  26207. */
  26208. static void unixEnterMutex(void){
  26209. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  26210. }
  26211. static void unixLeaveMutex(void){
  26212. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  26213. }
  26214. #ifdef SQLITE_DEBUG
  26215. static int unixMutexHeld(void) {
  26216. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  26217. }
  26218. #endif
  26219. #ifdef SQLITE_HAVE_OS_TRACE
  26220. /*
  26221. ** Helper function for printing out trace information from debugging
  26222. ** binaries. This returns the string representation of the supplied
  26223. ** integer lock-type.
  26224. */
  26225. static const char *azFileLock(int eFileLock){
  26226. switch( eFileLock ){
  26227. case NO_LOCK: return "NONE";
  26228. case SHARED_LOCK: return "SHARED";
  26229. case RESERVED_LOCK: return "RESERVED";
  26230. case PENDING_LOCK: return "PENDING";
  26231. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  26232. }
  26233. return "ERROR";
  26234. }
  26235. #endif
  26236. #ifdef SQLITE_LOCK_TRACE
  26237. /*
  26238. ** Print out information about all locking operations.
  26239. **
  26240. ** This routine is used for troubleshooting locks on multithreaded
  26241. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  26242. ** command-line option on the compiler. This code is normally
  26243. ** turned off.
  26244. */
  26245. static int lockTrace(int fd, int op, struct flock *p){
  26246. char *zOpName, *zType;
  26247. int s;
  26248. int savedErrno;
  26249. if( op==F_GETLK ){
  26250. zOpName = "GETLK";
  26251. }else if( op==F_SETLK ){
  26252. zOpName = "SETLK";
  26253. }else{
  26254. s = osFcntl(fd, op, p);
  26255. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  26256. return s;
  26257. }
  26258. if( p->l_type==F_RDLCK ){
  26259. zType = "RDLCK";
  26260. }else if( p->l_type==F_WRLCK ){
  26261. zType = "WRLCK";
  26262. }else if( p->l_type==F_UNLCK ){
  26263. zType = "UNLCK";
  26264. }else{
  26265. assert( 0 );
  26266. }
  26267. assert( p->l_whence==SEEK_SET );
  26268. s = osFcntl(fd, op, p);
  26269. savedErrno = errno;
  26270. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  26271. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  26272. (int)p->l_pid, s);
  26273. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  26274. struct flock l2;
  26275. l2 = *p;
  26276. osFcntl(fd, F_GETLK, &l2);
  26277. if( l2.l_type==F_RDLCK ){
  26278. zType = "RDLCK";
  26279. }else if( l2.l_type==F_WRLCK ){
  26280. zType = "WRLCK";
  26281. }else if( l2.l_type==F_UNLCK ){
  26282. zType = "UNLCK";
  26283. }else{
  26284. assert( 0 );
  26285. }
  26286. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  26287. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  26288. }
  26289. errno = savedErrno;
  26290. return s;
  26291. }
  26292. #undef osFcntl
  26293. #define osFcntl lockTrace
  26294. #endif /* SQLITE_LOCK_TRACE */
  26295. /*
  26296. ** Retry ftruncate() calls that fail due to EINTR
  26297. **
  26298. ** All calls to ftruncate() within this file should be made through
  26299. ** this wrapper. On the Android platform, bypassing the logic below
  26300. ** could lead to a corrupt database.
  26301. */
  26302. static int robust_ftruncate(int h, sqlite3_int64 sz){
  26303. int rc;
  26304. #ifdef __ANDROID__
  26305. /* On Android, ftruncate() always uses 32-bit offsets, even if
  26306. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  26307. ** truncate a file to any size larger than 2GiB. Silently ignore any
  26308. ** such attempts. */
  26309. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  26310. rc = SQLITE_OK;
  26311. }else
  26312. #endif
  26313. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  26314. return rc;
  26315. }
  26316. /*
  26317. ** This routine translates a standard POSIX errno code into something
  26318. ** useful to the clients of the sqlite3 functions. Specifically, it is
  26319. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  26320. ** and a variety of "please close the file descriptor NOW" errors into
  26321. ** SQLITE_IOERR
  26322. **
  26323. ** Errors during initialization of locks, or file system support for locks,
  26324. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  26325. */
  26326. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  26327. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  26328. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  26329. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  26330. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  26331. switch (posixError) {
  26332. case EACCES:
  26333. case EAGAIN:
  26334. case ETIMEDOUT:
  26335. case EBUSY:
  26336. case EINTR:
  26337. case ENOLCK:
  26338. /* random NFS retry error, unless during file system support
  26339. * introspection, in which it actually means what it says */
  26340. return SQLITE_BUSY;
  26341. case EPERM:
  26342. return SQLITE_PERM;
  26343. default:
  26344. return sqliteIOErr;
  26345. }
  26346. }
  26347. /******************************************************************************
  26348. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  26349. **
  26350. ** On most versions of unix, we can get a unique ID for a file by concatenating
  26351. ** the device number and the inode number. But this does not work on VxWorks.
  26352. ** On VxWorks, a unique file id must be based on the canonical filename.
  26353. **
  26354. ** A pointer to an instance of the following structure can be used as a
  26355. ** unique file ID in VxWorks. Each instance of this structure contains
  26356. ** a copy of the canonical filename. There is also a reference count.
  26357. ** The structure is reclaimed when the number of pointers to it drops to
  26358. ** zero.
  26359. **
  26360. ** There are never very many files open at one time and lookups are not
  26361. ** a performance-critical path, so it is sufficient to put these
  26362. ** structures on a linked list.
  26363. */
  26364. struct vxworksFileId {
  26365. struct vxworksFileId *pNext; /* Next in a list of them all */
  26366. int nRef; /* Number of references to this one */
  26367. int nName; /* Length of the zCanonicalName[] string */
  26368. char *zCanonicalName; /* Canonical filename */
  26369. };
  26370. #if OS_VXWORKS
  26371. /*
  26372. ** All unique filenames are held on a linked list headed by this
  26373. ** variable:
  26374. */
  26375. static struct vxworksFileId *vxworksFileList = 0;
  26376. /*
  26377. ** Simplify a filename into its canonical form
  26378. ** by making the following changes:
  26379. **
  26380. ** * removing any trailing and duplicate /
  26381. ** * convert /./ into just /
  26382. ** * convert /A/../ where A is any simple name into just /
  26383. **
  26384. ** Changes are made in-place. Return the new name length.
  26385. **
  26386. ** The original filename is in z[0..n-1]. Return the number of
  26387. ** characters in the simplified name.
  26388. */
  26389. static int vxworksSimplifyName(char *z, int n){
  26390. int i, j;
  26391. while( n>1 && z[n-1]=='/' ){ n--; }
  26392. for(i=j=0; i<n; i++){
  26393. if( z[i]=='/' ){
  26394. if( z[i+1]=='/' ) continue;
  26395. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  26396. i += 1;
  26397. continue;
  26398. }
  26399. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  26400. while( j>0 && z[j-1]!='/' ){ j--; }
  26401. if( j>0 ){ j--; }
  26402. i += 2;
  26403. continue;
  26404. }
  26405. }
  26406. z[j++] = z[i];
  26407. }
  26408. z[j] = 0;
  26409. return j;
  26410. }
  26411. /*
  26412. ** Find a unique file ID for the given absolute pathname. Return
  26413. ** a pointer to the vxworksFileId object. This pointer is the unique
  26414. ** file ID.
  26415. **
  26416. ** The nRef field of the vxworksFileId object is incremented before
  26417. ** the object is returned. A new vxworksFileId object is created
  26418. ** and added to the global list if necessary.
  26419. **
  26420. ** If a memory allocation error occurs, return NULL.
  26421. */
  26422. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  26423. struct vxworksFileId *pNew; /* search key and new file ID */
  26424. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  26425. int n; /* Length of zAbsoluteName string */
  26426. assert( zAbsoluteName[0]=='/' );
  26427. n = (int)strlen(zAbsoluteName);
  26428. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  26429. if( pNew==0 ) return 0;
  26430. pNew->zCanonicalName = (char*)&pNew[1];
  26431. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  26432. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  26433. /* Search for an existing entry that matching the canonical name.
  26434. ** If found, increment the reference count and return a pointer to
  26435. ** the existing file ID.
  26436. */
  26437. unixEnterMutex();
  26438. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  26439. if( pCandidate->nName==n
  26440. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  26441. ){
  26442. sqlite3_free(pNew);
  26443. pCandidate->nRef++;
  26444. unixLeaveMutex();
  26445. return pCandidate;
  26446. }
  26447. }
  26448. /* No match was found. We will make a new file ID */
  26449. pNew->nRef = 1;
  26450. pNew->nName = n;
  26451. pNew->pNext = vxworksFileList;
  26452. vxworksFileList = pNew;
  26453. unixLeaveMutex();
  26454. return pNew;
  26455. }
  26456. /*
  26457. ** Decrement the reference count on a vxworksFileId object. Free
  26458. ** the object when the reference count reaches zero.
  26459. */
  26460. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  26461. unixEnterMutex();
  26462. assert( pId->nRef>0 );
  26463. pId->nRef--;
  26464. if( pId->nRef==0 ){
  26465. struct vxworksFileId **pp;
  26466. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  26467. assert( *pp==pId );
  26468. *pp = pId->pNext;
  26469. sqlite3_free(pId);
  26470. }
  26471. unixLeaveMutex();
  26472. }
  26473. #endif /* OS_VXWORKS */
  26474. /*************** End of Unique File ID Utility Used By VxWorks ****************
  26475. ******************************************************************************/
  26476. /******************************************************************************
  26477. *************************** Posix Advisory Locking ****************************
  26478. **
  26479. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  26480. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  26481. ** sets or clears a lock, that operation overrides any prior locks set
  26482. ** by the same process. It does not explicitly say so, but this implies
  26483. ** that it overrides locks set by the same process using a different
  26484. ** file descriptor. Consider this test case:
  26485. **
  26486. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  26487. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  26488. **
  26489. ** Suppose ./file1 and ./file2 are really the same file (because
  26490. ** one is a hard or symbolic link to the other) then if you set
  26491. ** an exclusive lock on fd1, then try to get an exclusive lock
  26492. ** on fd2, it works. I would have expected the second lock to
  26493. ** fail since there was already a lock on the file due to fd1.
  26494. ** But not so. Since both locks came from the same process, the
  26495. ** second overrides the first, even though they were on different
  26496. ** file descriptors opened on different file names.
  26497. **
  26498. ** This means that we cannot use POSIX locks to synchronize file access
  26499. ** among competing threads of the same process. POSIX locks will work fine
  26500. ** to synchronize access for threads in separate processes, but not
  26501. ** threads within the same process.
  26502. **
  26503. ** To work around the problem, SQLite has to manage file locks internally
  26504. ** on its own. Whenever a new database is opened, we have to find the
  26505. ** specific inode of the database file (the inode is determined by the
  26506. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  26507. ** and check for locks already existing on that inode. When locks are
  26508. ** created or removed, we have to look at our own internal record of the
  26509. ** locks to see if another thread has previously set a lock on that same
  26510. ** inode.
  26511. **
  26512. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  26513. ** For VxWorks, we have to use the alternative unique ID system based on
  26514. ** canonical filename and implemented in the previous division.)
  26515. **
  26516. ** The sqlite3_file structure for POSIX is no longer just an integer file
  26517. ** descriptor. It is now a structure that holds the integer file
  26518. ** descriptor and a pointer to a structure that describes the internal
  26519. ** locks on the corresponding inode. There is one locking structure
  26520. ** per inode, so if the same inode is opened twice, both unixFile structures
  26521. ** point to the same locking structure. The locking structure keeps
  26522. ** a reference count (so we will know when to delete it) and a "cnt"
  26523. ** field that tells us its internal lock status. cnt==0 means the
  26524. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  26525. ** cnt>0 means there are cnt shared locks on the file.
  26526. **
  26527. ** Any attempt to lock or unlock a file first checks the locking
  26528. ** structure. The fcntl() system call is only invoked to set a
  26529. ** POSIX lock if the internal lock structure transitions between
  26530. ** a locked and an unlocked state.
  26531. **
  26532. ** But wait: there are yet more problems with POSIX advisory locks.
  26533. **
  26534. ** If you close a file descriptor that points to a file that has locks,
  26535. ** all locks on that file that are owned by the current process are
  26536. ** released. To work around this problem, each unixInodeInfo object
  26537. ** maintains a count of the number of pending locks on tha inode.
  26538. ** When an attempt is made to close an unixFile, if there are
  26539. ** other unixFile open on the same inode that are holding locks, the call
  26540. ** to close() the file descriptor is deferred until all of the locks clear.
  26541. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  26542. ** be closed and that list is walked (and cleared) when the last lock
  26543. ** clears.
  26544. **
  26545. ** Yet another problem: LinuxThreads do not play well with posix locks.
  26546. **
  26547. ** Many older versions of linux use the LinuxThreads library which is
  26548. ** not posix compliant. Under LinuxThreads, a lock created by thread
  26549. ** A cannot be modified or overridden by a different thread B.
  26550. ** Only thread A can modify the lock. Locking behavior is correct
  26551. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  26552. ** on linux - with NPTL a lock created by thread A can override locks
  26553. ** in thread B. But there is no way to know at compile-time which
  26554. ** threading library is being used. So there is no way to know at
  26555. ** compile-time whether or not thread A can override locks on thread B.
  26556. ** One has to do a run-time check to discover the behavior of the
  26557. ** current process.
  26558. **
  26559. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  26560. ** was dropped beginning with version 3.7.0. SQLite will still work with
  26561. ** LinuxThreads provided that (1) there is no more than one connection
  26562. ** per database file in the same process and (2) database connections
  26563. ** do not move across threads.
  26564. */
  26565. /*
  26566. ** An instance of the following structure serves as the key used
  26567. ** to locate a particular unixInodeInfo object.
  26568. */
  26569. struct unixFileId {
  26570. dev_t dev; /* Device number */
  26571. #if OS_VXWORKS
  26572. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  26573. #else
  26574. ino_t ino; /* Inode number */
  26575. #endif
  26576. };
  26577. /*
  26578. ** An instance of the following structure is allocated for each open
  26579. ** inode. Or, on LinuxThreads, there is one of these structures for
  26580. ** each inode opened by each thread.
  26581. **
  26582. ** A single inode can have multiple file descriptors, so each unixFile
  26583. ** structure contains a pointer to an instance of this object and this
  26584. ** object keeps a count of the number of unixFile pointing to it.
  26585. */
  26586. struct unixInodeInfo {
  26587. struct unixFileId fileId; /* The lookup key */
  26588. int nShared; /* Number of SHARED locks held */
  26589. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  26590. unsigned char bProcessLock; /* An exclusive process lock is held */
  26591. int nRef; /* Number of pointers to this structure */
  26592. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  26593. int nLock; /* Number of outstanding file locks */
  26594. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  26595. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  26596. unixInodeInfo *pPrev; /* .... doubly linked */
  26597. #if SQLITE_ENABLE_LOCKING_STYLE
  26598. unsigned long long sharedByte; /* for AFP simulated shared lock */
  26599. #endif
  26600. #if OS_VXWORKS
  26601. sem_t *pSem; /* Named POSIX semaphore */
  26602. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  26603. #endif
  26604. };
  26605. /*
  26606. ** A lists of all unixInodeInfo objects.
  26607. */
  26608. static unixInodeInfo *inodeList = 0;
  26609. /*
  26610. **
  26611. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  26612. ** unixLogError().
  26613. **
  26614. ** It is invoked after an error occurs in an OS function and errno has been
  26615. ** set. It logs a message using sqlite3_log() containing the current value of
  26616. ** errno and, if possible, the human-readable equivalent from strerror() or
  26617. ** strerror_r().
  26618. **
  26619. ** The first argument passed to the macro should be the error code that
  26620. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  26621. ** The two subsequent arguments should be the name of the OS function that
  26622. ** failed (e.g. "unlink", "open") and the associated file-system path,
  26623. ** if any.
  26624. */
  26625. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  26626. static int unixLogErrorAtLine(
  26627. int errcode, /* SQLite error code */
  26628. const char *zFunc, /* Name of OS function that failed */
  26629. const char *zPath, /* File path associated with error */
  26630. int iLine /* Source line number where error occurred */
  26631. ){
  26632. char *zErr; /* Message from strerror() or equivalent */
  26633. int iErrno = errno; /* Saved syscall error number */
  26634. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  26635. ** the strerror() function to obtain the human-readable error message
  26636. ** equivalent to errno. Otherwise, use strerror_r().
  26637. */
  26638. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  26639. char aErr[80];
  26640. memset(aErr, 0, sizeof(aErr));
  26641. zErr = aErr;
  26642. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  26643. ** assume that the system provides the GNU version of strerror_r() that
  26644. ** returns a pointer to a buffer containing the error message. That pointer
  26645. ** may point to aErr[], or it may point to some static storage somewhere.
  26646. ** Otherwise, assume that the system provides the POSIX version of
  26647. ** strerror_r(), which always writes an error message into aErr[].
  26648. **
  26649. ** If the code incorrectly assumes that it is the POSIX version that is
  26650. ** available, the error message will often be an empty string. Not a
  26651. ** huge problem. Incorrectly concluding that the GNU version is available
  26652. ** could lead to a segfault though.
  26653. */
  26654. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  26655. zErr =
  26656. # endif
  26657. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  26658. #elif SQLITE_THREADSAFE
  26659. /* This is a threadsafe build, but strerror_r() is not available. */
  26660. zErr = "";
  26661. #else
  26662. /* Non-threadsafe build, use strerror(). */
  26663. zErr = strerror(iErrno);
  26664. #endif
  26665. if( zPath==0 ) zPath = "";
  26666. sqlite3_log(errcode,
  26667. "os_unix.c:%d: (%d) %s(%s) - %s",
  26668. iLine, iErrno, zFunc, zPath, zErr
  26669. );
  26670. return errcode;
  26671. }
  26672. /*
  26673. ** Close a file descriptor.
  26674. **
  26675. ** We assume that close() almost always works, since it is only in a
  26676. ** very sick application or on a very sick platform that it might fail.
  26677. ** If it does fail, simply leak the file descriptor, but do log the
  26678. ** error.
  26679. **
  26680. ** Note that it is not safe to retry close() after EINTR since the
  26681. ** file descriptor might have already been reused by another thread.
  26682. ** So we don't even try to recover from an EINTR. Just log the error
  26683. ** and move on.
  26684. */
  26685. static void robust_close(unixFile *pFile, int h, int lineno){
  26686. if( osClose(h) ){
  26687. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  26688. pFile ? pFile->zPath : 0, lineno);
  26689. }
  26690. }
  26691. /*
  26692. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  26693. ** a convenient place to set a breakpoint.
  26694. */
  26695. static void storeLastErrno(unixFile *pFile, int error){
  26696. pFile->lastErrno = error;
  26697. }
  26698. /*
  26699. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  26700. */
  26701. static void closePendingFds(unixFile *pFile){
  26702. unixInodeInfo *pInode = pFile->pInode;
  26703. UnixUnusedFd *p;
  26704. UnixUnusedFd *pNext;
  26705. for(p=pInode->pUnused; p; p=pNext){
  26706. pNext = p->pNext;
  26707. robust_close(pFile, p->fd, __LINE__);
  26708. sqlite3_free(p);
  26709. }
  26710. pInode->pUnused = 0;
  26711. }
  26712. /*
  26713. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  26714. **
  26715. ** The mutex entered using the unixEnterMutex() function must be held
  26716. ** when this function is called.
  26717. */
  26718. static void releaseInodeInfo(unixFile *pFile){
  26719. unixInodeInfo *pInode = pFile->pInode;
  26720. assert( unixMutexHeld() );
  26721. if( ALWAYS(pInode) ){
  26722. pInode->nRef--;
  26723. if( pInode->nRef==0 ){
  26724. assert( pInode->pShmNode==0 );
  26725. closePendingFds(pFile);
  26726. if( pInode->pPrev ){
  26727. assert( pInode->pPrev->pNext==pInode );
  26728. pInode->pPrev->pNext = pInode->pNext;
  26729. }else{
  26730. assert( inodeList==pInode );
  26731. inodeList = pInode->pNext;
  26732. }
  26733. if( pInode->pNext ){
  26734. assert( pInode->pNext->pPrev==pInode );
  26735. pInode->pNext->pPrev = pInode->pPrev;
  26736. }
  26737. sqlite3_free(pInode);
  26738. }
  26739. }
  26740. }
  26741. /*
  26742. ** Given a file descriptor, locate the unixInodeInfo object that
  26743. ** describes that file descriptor. Create a new one if necessary. The
  26744. ** return value might be uninitialized if an error occurs.
  26745. **
  26746. ** The mutex entered using the unixEnterMutex() function must be held
  26747. ** when this function is called.
  26748. **
  26749. ** Return an appropriate error code.
  26750. */
  26751. static int findInodeInfo(
  26752. unixFile *pFile, /* Unix file with file desc used in the key */
  26753. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  26754. ){
  26755. int rc; /* System call return code */
  26756. int fd; /* The file descriptor for pFile */
  26757. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  26758. struct stat statbuf; /* Low-level file information */
  26759. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  26760. assert( unixMutexHeld() );
  26761. /* Get low-level information about the file that we can used to
  26762. ** create a unique name for the file.
  26763. */
  26764. fd = pFile->h;
  26765. rc = osFstat(fd, &statbuf);
  26766. if( rc!=0 ){
  26767. storeLastErrno(pFile, errno);
  26768. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  26769. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  26770. #endif
  26771. return SQLITE_IOERR;
  26772. }
  26773. #ifdef __APPLE__
  26774. /* On OS X on an msdos filesystem, the inode number is reported
  26775. ** incorrectly for zero-size files. See ticket #3260. To work
  26776. ** around this problem (we consider it a bug in OS X, not SQLite)
  26777. ** we always increase the file size to 1 by writing a single byte
  26778. ** prior to accessing the inode number. The one byte written is
  26779. ** an ASCII 'S' character which also happens to be the first byte
  26780. ** in the header of every SQLite database. In this way, if there
  26781. ** is a race condition such that another thread has already populated
  26782. ** the first page of the database, no damage is done.
  26783. */
  26784. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  26785. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  26786. if( rc!=1 ){
  26787. storeLastErrno(pFile, errno);
  26788. return SQLITE_IOERR;
  26789. }
  26790. rc = osFstat(fd, &statbuf);
  26791. if( rc!=0 ){
  26792. storeLastErrno(pFile, errno);
  26793. return SQLITE_IOERR;
  26794. }
  26795. }
  26796. #endif
  26797. memset(&fileId, 0, sizeof(fileId));
  26798. fileId.dev = statbuf.st_dev;
  26799. #if OS_VXWORKS
  26800. fileId.pId = pFile->pId;
  26801. #else
  26802. fileId.ino = statbuf.st_ino;
  26803. #endif
  26804. pInode = inodeList;
  26805. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  26806. pInode = pInode->pNext;
  26807. }
  26808. if( pInode==0 ){
  26809. pInode = sqlite3_malloc64( sizeof(*pInode) );
  26810. if( pInode==0 ){
  26811. return SQLITE_NOMEM;
  26812. }
  26813. memset(pInode, 0, sizeof(*pInode));
  26814. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  26815. pInode->nRef = 1;
  26816. pInode->pNext = inodeList;
  26817. pInode->pPrev = 0;
  26818. if( inodeList ) inodeList->pPrev = pInode;
  26819. inodeList = pInode;
  26820. }else{
  26821. pInode->nRef++;
  26822. }
  26823. *ppInode = pInode;
  26824. return SQLITE_OK;
  26825. }
  26826. /*
  26827. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  26828. */
  26829. static int fileHasMoved(unixFile *pFile){
  26830. #if OS_VXWORKS
  26831. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  26832. #else
  26833. struct stat buf;
  26834. return pFile->pInode!=0 &&
  26835. (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
  26836. #endif
  26837. }
  26838. /*
  26839. ** Check a unixFile that is a database. Verify the following:
  26840. **
  26841. ** (1) There is exactly one hard link on the file
  26842. ** (2) The file is not a symbolic link
  26843. ** (3) The file has not been renamed or unlinked
  26844. **
  26845. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  26846. */
  26847. static void verifyDbFile(unixFile *pFile){
  26848. struct stat buf;
  26849. int rc;
  26850. rc = osFstat(pFile->h, &buf);
  26851. if( rc!=0 ){
  26852. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  26853. return;
  26854. }
  26855. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  26856. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  26857. return;
  26858. }
  26859. if( buf.st_nlink>1 ){
  26860. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  26861. return;
  26862. }
  26863. if( fileHasMoved(pFile) ){
  26864. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  26865. return;
  26866. }
  26867. }
  26868. /*
  26869. ** This routine checks if there is a RESERVED lock held on the specified
  26870. ** file by this or any other process. If such a lock is held, set *pResOut
  26871. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26872. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26873. */
  26874. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  26875. int rc = SQLITE_OK;
  26876. int reserved = 0;
  26877. unixFile *pFile = (unixFile*)id;
  26878. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26879. assert( pFile );
  26880. assert( pFile->eFileLock<=SHARED_LOCK );
  26881. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  26882. /* Check if a thread in this process holds such a lock */
  26883. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  26884. reserved = 1;
  26885. }
  26886. /* Otherwise see if some other process holds it.
  26887. */
  26888. #ifndef __DJGPP__
  26889. if( !reserved && !pFile->pInode->bProcessLock ){
  26890. struct flock lock;
  26891. lock.l_whence = SEEK_SET;
  26892. lock.l_start = RESERVED_BYTE;
  26893. lock.l_len = 1;
  26894. lock.l_type = F_WRLCK;
  26895. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  26896. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  26897. storeLastErrno(pFile, errno);
  26898. } else if( lock.l_type!=F_UNLCK ){
  26899. reserved = 1;
  26900. }
  26901. }
  26902. #endif
  26903. unixLeaveMutex();
  26904. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  26905. *pResOut = reserved;
  26906. return rc;
  26907. }
  26908. /*
  26909. ** Attempt to set a system-lock on the file pFile. The lock is
  26910. ** described by pLock.
  26911. **
  26912. ** If the pFile was opened read/write from unix-excl, then the only lock
  26913. ** ever obtained is an exclusive lock, and it is obtained exactly once
  26914. ** the first time any lock is attempted. All subsequent system locking
  26915. ** operations become no-ops. Locking operations still happen internally,
  26916. ** in order to coordinate access between separate database connections
  26917. ** within this process, but all of that is handled in memory and the
  26918. ** operating system does not participate.
  26919. **
  26920. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  26921. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  26922. ** and is read-only.
  26923. **
  26924. ** Zero is returned if the call completes successfully, or -1 if a call
  26925. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  26926. */
  26927. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  26928. int rc;
  26929. unixInodeInfo *pInode = pFile->pInode;
  26930. assert( unixMutexHeld() );
  26931. assert( pInode!=0 );
  26932. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  26933. if( pInode->bProcessLock==0 ){
  26934. struct flock lock;
  26935. assert( pInode->nLock==0 );
  26936. lock.l_whence = SEEK_SET;
  26937. lock.l_start = SHARED_FIRST;
  26938. lock.l_len = SHARED_SIZE;
  26939. lock.l_type = F_WRLCK;
  26940. rc = osFcntl(pFile->h, F_SETLK, &lock);
  26941. if( rc<0 ) return rc;
  26942. pInode->bProcessLock = 1;
  26943. pInode->nLock++;
  26944. }else{
  26945. rc = 0;
  26946. }
  26947. }else{
  26948. rc = osFcntl(pFile->h, F_SETLK, pLock);
  26949. }
  26950. return rc;
  26951. }
  26952. /*
  26953. ** Lock the file with the lock specified by parameter eFileLock - one
  26954. ** of the following:
  26955. **
  26956. ** (1) SHARED_LOCK
  26957. ** (2) RESERVED_LOCK
  26958. ** (3) PENDING_LOCK
  26959. ** (4) EXCLUSIVE_LOCK
  26960. **
  26961. ** Sometimes when requesting one lock state, additional lock states
  26962. ** are inserted in between. The locking might fail on one of the later
  26963. ** transitions leaving the lock state different from what it started but
  26964. ** still short of its goal. The following chart shows the allowed
  26965. ** transitions and the inserted intermediate states:
  26966. **
  26967. ** UNLOCKED -> SHARED
  26968. ** SHARED -> RESERVED
  26969. ** SHARED -> (PENDING) -> EXCLUSIVE
  26970. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26971. ** PENDING -> EXCLUSIVE
  26972. **
  26973. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26974. ** routine to lower a locking level.
  26975. */
  26976. static int unixLock(sqlite3_file *id, int eFileLock){
  26977. /* The following describes the implementation of the various locks and
  26978. ** lock transitions in terms of the POSIX advisory shared and exclusive
  26979. ** lock primitives (called read-locks and write-locks below, to avoid
  26980. ** confusion with SQLite lock names). The algorithms are complicated
  26981. ** slightly in order to be compatible with windows systems simultaneously
  26982. ** accessing the same database file, in case that is ever required.
  26983. **
  26984. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  26985. ** byte', each single bytes at well known offsets, and the 'shared byte
  26986. ** range', a range of 510 bytes at a well known offset.
  26987. **
  26988. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  26989. ** byte'. If this is successful, a random byte from the 'shared byte
  26990. ** range' is read-locked and the lock on the 'pending byte' released.
  26991. **
  26992. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  26993. ** A RESERVED lock is implemented by grabbing a write-lock on the
  26994. ** 'reserved byte'.
  26995. **
  26996. ** A process may only obtain a PENDING lock after it has obtained a
  26997. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  26998. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  26999. ** obtained, but existing SHARED locks are allowed to persist. A process
  27000. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  27001. ** This property is used by the algorithm for rolling back a journal file
  27002. ** after a crash.
  27003. **
  27004. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  27005. ** implemented by obtaining a write-lock on the entire 'shared byte
  27006. ** range'. Since all other locks require a read-lock on one of the bytes
  27007. ** within this range, this ensures that no other locks are held on the
  27008. ** database.
  27009. **
  27010. ** The reason a single byte cannot be used instead of the 'shared byte
  27011. ** range' is that some versions of windows do not support read-locks. By
  27012. ** locking a random byte from a range, concurrent SHARED locks may exist
  27013. ** even if the locking primitive used is always a write-lock.
  27014. */
  27015. int rc = SQLITE_OK;
  27016. unixFile *pFile = (unixFile*)id;
  27017. unixInodeInfo *pInode;
  27018. struct flock lock;
  27019. int tErrno = 0;
  27020. assert( pFile );
  27021. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  27022. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  27023. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  27024. osGetpid(0)));
  27025. /* If there is already a lock of this type or more restrictive on the
  27026. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  27027. ** unixEnterMutex() hasn't been called yet.
  27028. */
  27029. if( pFile->eFileLock>=eFileLock ){
  27030. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  27031. azFileLock(eFileLock)));
  27032. return SQLITE_OK;
  27033. }
  27034. /* Make sure the locking sequence is correct.
  27035. ** (1) We never move from unlocked to anything higher than shared lock.
  27036. ** (2) SQLite never explicitly requests a pendig lock.
  27037. ** (3) A shared lock is always held when a reserve lock is requested.
  27038. */
  27039. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  27040. assert( eFileLock!=PENDING_LOCK );
  27041. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  27042. /* This mutex is needed because pFile->pInode is shared across threads
  27043. */
  27044. unixEnterMutex();
  27045. pInode = pFile->pInode;
  27046. /* If some thread using this PID has a lock via a different unixFile*
  27047. ** handle that precludes the requested lock, return BUSY.
  27048. */
  27049. if( (pFile->eFileLock!=pInode->eFileLock &&
  27050. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  27051. ){
  27052. rc = SQLITE_BUSY;
  27053. goto end_lock;
  27054. }
  27055. /* If a SHARED lock is requested, and some thread using this PID already
  27056. ** has a SHARED or RESERVED lock, then increment reference counts and
  27057. ** return SQLITE_OK.
  27058. */
  27059. if( eFileLock==SHARED_LOCK &&
  27060. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  27061. assert( eFileLock==SHARED_LOCK );
  27062. assert( pFile->eFileLock==0 );
  27063. assert( pInode->nShared>0 );
  27064. pFile->eFileLock = SHARED_LOCK;
  27065. pInode->nShared++;
  27066. pInode->nLock++;
  27067. goto end_lock;
  27068. }
  27069. /* A PENDING lock is needed before acquiring a SHARED lock and before
  27070. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  27071. ** be released.
  27072. */
  27073. lock.l_len = 1L;
  27074. lock.l_whence = SEEK_SET;
  27075. if( eFileLock==SHARED_LOCK
  27076. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  27077. ){
  27078. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  27079. lock.l_start = PENDING_BYTE;
  27080. if( unixFileLock(pFile, &lock) ){
  27081. tErrno = errno;
  27082. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27083. if( rc!=SQLITE_BUSY ){
  27084. storeLastErrno(pFile, tErrno);
  27085. }
  27086. goto end_lock;
  27087. }
  27088. }
  27089. /* If control gets to this point, then actually go ahead and make
  27090. ** operating system calls for the specified lock.
  27091. */
  27092. if( eFileLock==SHARED_LOCK ){
  27093. assert( pInode->nShared==0 );
  27094. assert( pInode->eFileLock==0 );
  27095. assert( rc==SQLITE_OK );
  27096. /* Now get the read-lock */
  27097. lock.l_start = SHARED_FIRST;
  27098. lock.l_len = SHARED_SIZE;
  27099. if( unixFileLock(pFile, &lock) ){
  27100. tErrno = errno;
  27101. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27102. }
  27103. /* Drop the temporary PENDING lock */
  27104. lock.l_start = PENDING_BYTE;
  27105. lock.l_len = 1L;
  27106. lock.l_type = F_UNLCK;
  27107. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  27108. /* This could happen with a network mount */
  27109. tErrno = errno;
  27110. rc = SQLITE_IOERR_UNLOCK;
  27111. }
  27112. if( rc ){
  27113. if( rc!=SQLITE_BUSY ){
  27114. storeLastErrno(pFile, tErrno);
  27115. }
  27116. goto end_lock;
  27117. }else{
  27118. pFile->eFileLock = SHARED_LOCK;
  27119. pInode->nLock++;
  27120. pInode->nShared = 1;
  27121. }
  27122. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  27123. /* We are trying for an exclusive lock but another thread in this
  27124. ** same process is still holding a shared lock. */
  27125. rc = SQLITE_BUSY;
  27126. }else{
  27127. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  27128. ** assumed that there is a SHARED or greater lock on the file
  27129. ** already.
  27130. */
  27131. assert( 0!=pFile->eFileLock );
  27132. lock.l_type = F_WRLCK;
  27133. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  27134. if( eFileLock==RESERVED_LOCK ){
  27135. lock.l_start = RESERVED_BYTE;
  27136. lock.l_len = 1L;
  27137. }else{
  27138. lock.l_start = SHARED_FIRST;
  27139. lock.l_len = SHARED_SIZE;
  27140. }
  27141. if( unixFileLock(pFile, &lock) ){
  27142. tErrno = errno;
  27143. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27144. if( rc!=SQLITE_BUSY ){
  27145. storeLastErrno(pFile, tErrno);
  27146. }
  27147. }
  27148. }
  27149. #ifdef SQLITE_DEBUG
  27150. /* Set up the transaction-counter change checking flags when
  27151. ** transitioning from a SHARED to a RESERVED lock. The change
  27152. ** from SHARED to RESERVED marks the beginning of a normal
  27153. ** write operation (not a hot journal rollback).
  27154. */
  27155. if( rc==SQLITE_OK
  27156. && pFile->eFileLock<=SHARED_LOCK
  27157. && eFileLock==RESERVED_LOCK
  27158. ){
  27159. pFile->transCntrChng = 0;
  27160. pFile->dbUpdate = 0;
  27161. pFile->inNormalWrite = 1;
  27162. }
  27163. #endif
  27164. if( rc==SQLITE_OK ){
  27165. pFile->eFileLock = eFileLock;
  27166. pInode->eFileLock = eFileLock;
  27167. }else if( eFileLock==EXCLUSIVE_LOCK ){
  27168. pFile->eFileLock = PENDING_LOCK;
  27169. pInode->eFileLock = PENDING_LOCK;
  27170. }
  27171. end_lock:
  27172. unixLeaveMutex();
  27173. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  27174. rc==SQLITE_OK ? "ok" : "failed"));
  27175. return rc;
  27176. }
  27177. /*
  27178. ** Add the file descriptor used by file handle pFile to the corresponding
  27179. ** pUnused list.
  27180. */
  27181. static void setPendingFd(unixFile *pFile){
  27182. unixInodeInfo *pInode = pFile->pInode;
  27183. UnixUnusedFd *p = pFile->pUnused;
  27184. p->pNext = pInode->pUnused;
  27185. pInode->pUnused = p;
  27186. pFile->h = -1;
  27187. pFile->pUnused = 0;
  27188. }
  27189. /*
  27190. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27191. ** must be either NO_LOCK or SHARED_LOCK.
  27192. **
  27193. ** If the locking level of the file descriptor is already at or below
  27194. ** the requested locking level, this routine is a no-op.
  27195. **
  27196. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  27197. ** the byte range is divided into 2 parts and the first part is unlocked then
  27198. ** set to a read lock, then the other part is simply unlocked. This works
  27199. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  27200. ** remove the write lock on a region when a read lock is set.
  27201. */
  27202. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  27203. unixFile *pFile = (unixFile*)id;
  27204. unixInodeInfo *pInode;
  27205. struct flock lock;
  27206. int rc = SQLITE_OK;
  27207. assert( pFile );
  27208. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  27209. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  27210. osGetpid(0)));
  27211. assert( eFileLock<=SHARED_LOCK );
  27212. if( pFile->eFileLock<=eFileLock ){
  27213. return SQLITE_OK;
  27214. }
  27215. unixEnterMutex();
  27216. pInode = pFile->pInode;
  27217. assert( pInode->nShared!=0 );
  27218. if( pFile->eFileLock>SHARED_LOCK ){
  27219. assert( pInode->eFileLock==pFile->eFileLock );
  27220. #ifdef SQLITE_DEBUG
  27221. /* When reducing a lock such that other processes can start
  27222. ** reading the database file again, make sure that the
  27223. ** transaction counter was updated if any part of the database
  27224. ** file changed. If the transaction counter is not updated,
  27225. ** other connections to the same file might not realize that
  27226. ** the file has changed and hence might not know to flush their
  27227. ** cache. The use of a stale cache can lead to database corruption.
  27228. */
  27229. pFile->inNormalWrite = 0;
  27230. #endif
  27231. /* downgrading to a shared lock on NFS involves clearing the write lock
  27232. ** before establishing the readlock - to avoid a race condition we downgrade
  27233. ** the lock in 2 blocks, so that part of the range will be covered by a
  27234. ** write lock until the rest is covered by a read lock:
  27235. ** 1: [WWWWW]
  27236. ** 2: [....W]
  27237. ** 3: [RRRRW]
  27238. ** 4: [RRRR.]
  27239. */
  27240. if( eFileLock==SHARED_LOCK ){
  27241. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  27242. (void)handleNFSUnlock;
  27243. assert( handleNFSUnlock==0 );
  27244. #endif
  27245. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27246. if( handleNFSUnlock ){
  27247. int tErrno; /* Error code from system call errors */
  27248. off_t divSize = SHARED_SIZE - 1;
  27249. lock.l_type = F_UNLCK;
  27250. lock.l_whence = SEEK_SET;
  27251. lock.l_start = SHARED_FIRST;
  27252. lock.l_len = divSize;
  27253. if( unixFileLock(pFile, &lock)==(-1) ){
  27254. tErrno = errno;
  27255. rc = SQLITE_IOERR_UNLOCK;
  27256. storeLastErrno(pFile, tErrno);
  27257. goto end_unlock;
  27258. }
  27259. lock.l_type = F_RDLCK;
  27260. lock.l_whence = SEEK_SET;
  27261. lock.l_start = SHARED_FIRST;
  27262. lock.l_len = divSize;
  27263. if( unixFileLock(pFile, &lock)==(-1) ){
  27264. tErrno = errno;
  27265. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  27266. if( IS_LOCK_ERROR(rc) ){
  27267. storeLastErrno(pFile, tErrno);
  27268. }
  27269. goto end_unlock;
  27270. }
  27271. lock.l_type = F_UNLCK;
  27272. lock.l_whence = SEEK_SET;
  27273. lock.l_start = SHARED_FIRST+divSize;
  27274. lock.l_len = SHARED_SIZE-divSize;
  27275. if( unixFileLock(pFile, &lock)==(-1) ){
  27276. tErrno = errno;
  27277. rc = SQLITE_IOERR_UNLOCK;
  27278. storeLastErrno(pFile, tErrno);
  27279. goto end_unlock;
  27280. }
  27281. }else
  27282. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  27283. {
  27284. lock.l_type = F_RDLCK;
  27285. lock.l_whence = SEEK_SET;
  27286. lock.l_start = SHARED_FIRST;
  27287. lock.l_len = SHARED_SIZE;
  27288. if( unixFileLock(pFile, &lock) ){
  27289. /* In theory, the call to unixFileLock() cannot fail because another
  27290. ** process is holding an incompatible lock. If it does, this
  27291. ** indicates that the other process is not following the locking
  27292. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  27293. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  27294. ** an assert to fail). */
  27295. rc = SQLITE_IOERR_RDLOCK;
  27296. storeLastErrno(pFile, errno);
  27297. goto end_unlock;
  27298. }
  27299. }
  27300. }
  27301. lock.l_type = F_UNLCK;
  27302. lock.l_whence = SEEK_SET;
  27303. lock.l_start = PENDING_BYTE;
  27304. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  27305. if( unixFileLock(pFile, &lock)==0 ){
  27306. pInode->eFileLock = SHARED_LOCK;
  27307. }else{
  27308. rc = SQLITE_IOERR_UNLOCK;
  27309. storeLastErrno(pFile, errno);
  27310. goto end_unlock;
  27311. }
  27312. }
  27313. if( eFileLock==NO_LOCK ){
  27314. /* Decrement the shared lock counter. Release the lock using an
  27315. ** OS call only when all threads in this same process have released
  27316. ** the lock.
  27317. */
  27318. pInode->nShared--;
  27319. if( pInode->nShared==0 ){
  27320. lock.l_type = F_UNLCK;
  27321. lock.l_whence = SEEK_SET;
  27322. lock.l_start = lock.l_len = 0L;
  27323. if( unixFileLock(pFile, &lock)==0 ){
  27324. pInode->eFileLock = NO_LOCK;
  27325. }else{
  27326. rc = SQLITE_IOERR_UNLOCK;
  27327. storeLastErrno(pFile, errno);
  27328. pInode->eFileLock = NO_LOCK;
  27329. pFile->eFileLock = NO_LOCK;
  27330. }
  27331. }
  27332. /* Decrement the count of locks against this same file. When the
  27333. ** count reaches zero, close any other file descriptors whose close
  27334. ** was deferred because of outstanding locks.
  27335. */
  27336. pInode->nLock--;
  27337. assert( pInode->nLock>=0 );
  27338. if( pInode->nLock==0 ){
  27339. closePendingFds(pFile);
  27340. }
  27341. }
  27342. end_unlock:
  27343. unixLeaveMutex();
  27344. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  27345. return rc;
  27346. }
  27347. /*
  27348. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27349. ** must be either NO_LOCK or SHARED_LOCK.
  27350. **
  27351. ** If the locking level of the file descriptor is already at or below
  27352. ** the requested locking level, this routine is a no-op.
  27353. */
  27354. static int unixUnlock(sqlite3_file *id, int eFileLock){
  27355. #if SQLITE_MAX_MMAP_SIZE>0
  27356. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  27357. #endif
  27358. return posixUnlock(id, eFileLock, 0);
  27359. }
  27360. #if SQLITE_MAX_MMAP_SIZE>0
  27361. static int unixMapfile(unixFile *pFd, i64 nByte);
  27362. static void unixUnmapfile(unixFile *pFd);
  27363. #endif
  27364. /*
  27365. ** This function performs the parts of the "close file" operation
  27366. ** common to all locking schemes. It closes the directory and file
  27367. ** handles, if they are valid, and sets all fields of the unixFile
  27368. ** structure to 0.
  27369. **
  27370. ** It is *not* necessary to hold the mutex when this routine is called,
  27371. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  27372. ** vxworksReleaseFileId() routine.
  27373. */
  27374. static int closeUnixFile(sqlite3_file *id){
  27375. unixFile *pFile = (unixFile*)id;
  27376. #if SQLITE_MAX_MMAP_SIZE>0
  27377. unixUnmapfile(pFile);
  27378. #endif
  27379. if( pFile->h>=0 ){
  27380. robust_close(pFile, pFile->h, __LINE__);
  27381. pFile->h = -1;
  27382. }
  27383. #if OS_VXWORKS
  27384. if( pFile->pId ){
  27385. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  27386. osUnlink(pFile->pId->zCanonicalName);
  27387. }
  27388. vxworksReleaseFileId(pFile->pId);
  27389. pFile->pId = 0;
  27390. }
  27391. #endif
  27392. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  27393. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  27394. osUnlink(pFile->zPath);
  27395. sqlite3_free(*(char**)&pFile->zPath);
  27396. pFile->zPath = 0;
  27397. }
  27398. #endif
  27399. OSTRACE(("CLOSE %-3d\n", pFile->h));
  27400. OpenCounter(-1);
  27401. sqlite3_free(pFile->pUnused);
  27402. memset(pFile, 0, sizeof(unixFile));
  27403. return SQLITE_OK;
  27404. }
  27405. /*
  27406. ** Close a file.
  27407. */
  27408. static int unixClose(sqlite3_file *id){
  27409. int rc = SQLITE_OK;
  27410. unixFile *pFile = (unixFile *)id;
  27411. verifyDbFile(pFile);
  27412. unixUnlock(id, NO_LOCK);
  27413. unixEnterMutex();
  27414. /* unixFile.pInode is always valid here. Otherwise, a different close
  27415. ** routine (e.g. nolockClose()) would be called instead.
  27416. */
  27417. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  27418. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  27419. /* If there are outstanding locks, do not actually close the file just
  27420. ** yet because that would clear those locks. Instead, add the file
  27421. ** descriptor to pInode->pUnused list. It will be automatically closed
  27422. ** when the last lock is cleared.
  27423. */
  27424. setPendingFd(pFile);
  27425. }
  27426. releaseInodeInfo(pFile);
  27427. rc = closeUnixFile(id);
  27428. unixLeaveMutex();
  27429. return rc;
  27430. }
  27431. /************** End of the posix advisory lock implementation *****************
  27432. ******************************************************************************/
  27433. /******************************************************************************
  27434. ****************************** No-op Locking **********************************
  27435. **
  27436. ** Of the various locking implementations available, this is by far the
  27437. ** simplest: locking is ignored. No attempt is made to lock the database
  27438. ** file for reading or writing.
  27439. **
  27440. ** This locking mode is appropriate for use on read-only databases
  27441. ** (ex: databases that are burned into CD-ROM, for example.) It can
  27442. ** also be used if the application employs some external mechanism to
  27443. ** prevent simultaneous access of the same database by two or more
  27444. ** database connections. But there is a serious risk of database
  27445. ** corruption if this locking mode is used in situations where multiple
  27446. ** database connections are accessing the same database file at the same
  27447. ** time and one or more of those connections are writing.
  27448. */
  27449. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  27450. UNUSED_PARAMETER(NotUsed);
  27451. *pResOut = 0;
  27452. return SQLITE_OK;
  27453. }
  27454. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  27455. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  27456. return SQLITE_OK;
  27457. }
  27458. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  27459. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  27460. return SQLITE_OK;
  27461. }
  27462. /*
  27463. ** Close the file.
  27464. */
  27465. static int nolockClose(sqlite3_file *id) {
  27466. return closeUnixFile(id);
  27467. }
  27468. /******************* End of the no-op lock implementation *********************
  27469. ******************************************************************************/
  27470. /******************************************************************************
  27471. ************************* Begin dot-file Locking ******************************
  27472. **
  27473. ** The dotfile locking implementation uses the existence of separate lock
  27474. ** files (really a directory) to control access to the database. This works
  27475. ** on just about every filesystem imaginable. But there are serious downsides:
  27476. **
  27477. ** (1) There is zero concurrency. A single reader blocks all other
  27478. ** connections from reading or writing the database.
  27479. **
  27480. ** (2) An application crash or power loss can leave stale lock files
  27481. ** sitting around that need to be cleared manually.
  27482. **
  27483. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  27484. ** other locking strategy is available.
  27485. **
  27486. ** Dotfile locking works by creating a subdirectory in the same directory as
  27487. ** the database and with the same name but with a ".lock" extension added.
  27488. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  27489. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  27490. */
  27491. /*
  27492. ** The file suffix added to the data base filename in order to create the
  27493. ** lock directory.
  27494. */
  27495. #define DOTLOCK_SUFFIX ".lock"
  27496. /*
  27497. ** This routine checks if there is a RESERVED lock held on the specified
  27498. ** file by this or any other process. If such a lock is held, set *pResOut
  27499. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27500. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27501. **
  27502. ** In dotfile locking, either a lock exists or it does not. So in this
  27503. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  27504. ** is held on the file and false if the file is unlocked.
  27505. */
  27506. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  27507. int rc = SQLITE_OK;
  27508. int reserved = 0;
  27509. unixFile *pFile = (unixFile*)id;
  27510. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27511. assert( pFile );
  27512. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  27513. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  27514. *pResOut = reserved;
  27515. return rc;
  27516. }
  27517. /*
  27518. ** Lock the file with the lock specified by parameter eFileLock - one
  27519. ** of the following:
  27520. **
  27521. ** (1) SHARED_LOCK
  27522. ** (2) RESERVED_LOCK
  27523. ** (3) PENDING_LOCK
  27524. ** (4) EXCLUSIVE_LOCK
  27525. **
  27526. ** Sometimes when requesting one lock state, additional lock states
  27527. ** are inserted in between. The locking might fail on one of the later
  27528. ** transitions leaving the lock state different from what it started but
  27529. ** still short of its goal. The following chart shows the allowed
  27530. ** transitions and the inserted intermediate states:
  27531. **
  27532. ** UNLOCKED -> SHARED
  27533. ** SHARED -> RESERVED
  27534. ** SHARED -> (PENDING) -> EXCLUSIVE
  27535. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27536. ** PENDING -> EXCLUSIVE
  27537. **
  27538. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27539. ** routine to lower a locking level.
  27540. **
  27541. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  27542. ** But we track the other locking levels internally.
  27543. */
  27544. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  27545. unixFile *pFile = (unixFile*)id;
  27546. char *zLockFile = (char *)pFile->lockingContext;
  27547. int rc = SQLITE_OK;
  27548. /* If we have any lock, then the lock file already exists. All we have
  27549. ** to do is adjust our internal record of the lock level.
  27550. */
  27551. if( pFile->eFileLock > NO_LOCK ){
  27552. pFile->eFileLock = eFileLock;
  27553. /* Always update the timestamp on the old file */
  27554. #ifdef HAVE_UTIME
  27555. utime(zLockFile, NULL);
  27556. #else
  27557. utimes(zLockFile, NULL);
  27558. #endif
  27559. return SQLITE_OK;
  27560. }
  27561. /* grab an exclusive lock */
  27562. rc = osMkdir(zLockFile, 0777);
  27563. if( rc<0 ){
  27564. /* failed to open/create the lock directory */
  27565. int tErrno = errno;
  27566. if( EEXIST == tErrno ){
  27567. rc = SQLITE_BUSY;
  27568. } else {
  27569. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27570. if( rc!=SQLITE_BUSY ){
  27571. storeLastErrno(pFile, tErrno);
  27572. }
  27573. }
  27574. return rc;
  27575. }
  27576. /* got it, set the type and return ok */
  27577. pFile->eFileLock = eFileLock;
  27578. return rc;
  27579. }
  27580. /*
  27581. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27582. ** must be either NO_LOCK or SHARED_LOCK.
  27583. **
  27584. ** If the locking level of the file descriptor is already at or below
  27585. ** the requested locking level, this routine is a no-op.
  27586. **
  27587. ** When the locking level reaches NO_LOCK, delete the lock file.
  27588. */
  27589. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  27590. unixFile *pFile = (unixFile*)id;
  27591. char *zLockFile = (char *)pFile->lockingContext;
  27592. int rc;
  27593. assert( pFile );
  27594. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  27595. pFile->eFileLock, osGetpid(0)));
  27596. assert( eFileLock<=SHARED_LOCK );
  27597. /* no-op if possible */
  27598. if( pFile->eFileLock==eFileLock ){
  27599. return SQLITE_OK;
  27600. }
  27601. /* To downgrade to shared, simply update our internal notion of the
  27602. ** lock state. No need to mess with the file on disk.
  27603. */
  27604. if( eFileLock==SHARED_LOCK ){
  27605. pFile->eFileLock = SHARED_LOCK;
  27606. return SQLITE_OK;
  27607. }
  27608. /* To fully unlock the database, delete the lock file */
  27609. assert( eFileLock==NO_LOCK );
  27610. rc = osRmdir(zLockFile);
  27611. if( rc<0 ){
  27612. int tErrno = errno;
  27613. if( tErrno==ENOENT ){
  27614. rc = SQLITE_OK;
  27615. }else{
  27616. rc = SQLITE_IOERR_UNLOCK;
  27617. storeLastErrno(pFile, tErrno);
  27618. }
  27619. return rc;
  27620. }
  27621. pFile->eFileLock = NO_LOCK;
  27622. return SQLITE_OK;
  27623. }
  27624. /*
  27625. ** Close a file. Make sure the lock has been released before closing.
  27626. */
  27627. static int dotlockClose(sqlite3_file *id) {
  27628. unixFile *pFile = (unixFile*)id;
  27629. assert( id!=0 );
  27630. dotlockUnlock(id, NO_LOCK);
  27631. sqlite3_free(pFile->lockingContext);
  27632. return closeUnixFile(id);
  27633. }
  27634. /****************** End of the dot-file lock implementation *******************
  27635. ******************************************************************************/
  27636. /******************************************************************************
  27637. ************************** Begin flock Locking ********************************
  27638. **
  27639. ** Use the flock() system call to do file locking.
  27640. **
  27641. ** flock() locking is like dot-file locking in that the various
  27642. ** fine-grain locking levels supported by SQLite are collapsed into
  27643. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  27644. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  27645. ** still works when you do this, but concurrency is reduced since
  27646. ** only a single process can be reading the database at a time.
  27647. **
  27648. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  27649. */
  27650. #if SQLITE_ENABLE_LOCKING_STYLE
  27651. /*
  27652. ** Retry flock() calls that fail with EINTR
  27653. */
  27654. #ifdef EINTR
  27655. static int robust_flock(int fd, int op){
  27656. int rc;
  27657. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  27658. return rc;
  27659. }
  27660. #else
  27661. # define robust_flock(a,b) flock(a,b)
  27662. #endif
  27663. /*
  27664. ** This routine checks if there is a RESERVED lock held on the specified
  27665. ** file by this or any other process. If such a lock is held, set *pResOut
  27666. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27667. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27668. */
  27669. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  27670. int rc = SQLITE_OK;
  27671. int reserved = 0;
  27672. unixFile *pFile = (unixFile*)id;
  27673. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27674. assert( pFile );
  27675. /* Check if a thread in this process holds such a lock */
  27676. if( pFile->eFileLock>SHARED_LOCK ){
  27677. reserved = 1;
  27678. }
  27679. /* Otherwise see if some other process holds it. */
  27680. if( !reserved ){
  27681. /* attempt to get the lock */
  27682. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  27683. if( !lrc ){
  27684. /* got the lock, unlock it */
  27685. lrc = robust_flock(pFile->h, LOCK_UN);
  27686. if ( lrc ) {
  27687. int tErrno = errno;
  27688. /* unlock failed with an error */
  27689. lrc = SQLITE_IOERR_UNLOCK;
  27690. storeLastErrno(pFile, tErrno);
  27691. rc = lrc;
  27692. }
  27693. } else {
  27694. int tErrno = errno;
  27695. reserved = 1;
  27696. /* someone else might have it reserved */
  27697. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27698. if( IS_LOCK_ERROR(lrc) ){
  27699. storeLastErrno(pFile, tErrno);
  27700. rc = lrc;
  27701. }
  27702. }
  27703. }
  27704. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  27705. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  27706. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  27707. rc = SQLITE_OK;
  27708. reserved=1;
  27709. }
  27710. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  27711. *pResOut = reserved;
  27712. return rc;
  27713. }
  27714. /*
  27715. ** Lock the file with the lock specified by parameter eFileLock - one
  27716. ** of the following:
  27717. **
  27718. ** (1) SHARED_LOCK
  27719. ** (2) RESERVED_LOCK
  27720. ** (3) PENDING_LOCK
  27721. ** (4) EXCLUSIVE_LOCK
  27722. **
  27723. ** Sometimes when requesting one lock state, additional lock states
  27724. ** are inserted in between. The locking might fail on one of the later
  27725. ** transitions leaving the lock state different from what it started but
  27726. ** still short of its goal. The following chart shows the allowed
  27727. ** transitions and the inserted intermediate states:
  27728. **
  27729. ** UNLOCKED -> SHARED
  27730. ** SHARED -> RESERVED
  27731. ** SHARED -> (PENDING) -> EXCLUSIVE
  27732. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27733. ** PENDING -> EXCLUSIVE
  27734. **
  27735. ** flock() only really support EXCLUSIVE locks. We track intermediate
  27736. ** lock states in the sqlite3_file structure, but all locks SHARED or
  27737. ** above are really EXCLUSIVE locks and exclude all other processes from
  27738. ** access the file.
  27739. **
  27740. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27741. ** routine to lower a locking level.
  27742. */
  27743. static int flockLock(sqlite3_file *id, int eFileLock) {
  27744. int rc = SQLITE_OK;
  27745. unixFile *pFile = (unixFile*)id;
  27746. assert( pFile );
  27747. /* if we already have a lock, it is exclusive.
  27748. ** Just adjust level and punt on outta here. */
  27749. if (pFile->eFileLock > NO_LOCK) {
  27750. pFile->eFileLock = eFileLock;
  27751. return SQLITE_OK;
  27752. }
  27753. /* grab an exclusive lock */
  27754. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  27755. int tErrno = errno;
  27756. /* didn't get, must be busy */
  27757. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  27758. if( IS_LOCK_ERROR(rc) ){
  27759. storeLastErrno(pFile, tErrno);
  27760. }
  27761. } else {
  27762. /* got it, set the type and return ok */
  27763. pFile->eFileLock = eFileLock;
  27764. }
  27765. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  27766. rc==SQLITE_OK ? "ok" : "failed"));
  27767. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  27768. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  27769. rc = SQLITE_BUSY;
  27770. }
  27771. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  27772. return rc;
  27773. }
  27774. /*
  27775. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27776. ** must be either NO_LOCK or SHARED_LOCK.
  27777. **
  27778. ** If the locking level of the file descriptor is already at or below
  27779. ** the requested locking level, this routine is a no-op.
  27780. */
  27781. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  27782. unixFile *pFile = (unixFile*)id;
  27783. assert( pFile );
  27784. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  27785. pFile->eFileLock, osGetpid(0)));
  27786. assert( eFileLock<=SHARED_LOCK );
  27787. /* no-op if possible */
  27788. if( pFile->eFileLock==eFileLock ){
  27789. return SQLITE_OK;
  27790. }
  27791. /* shared can just be set because we always have an exclusive */
  27792. if (eFileLock==SHARED_LOCK) {
  27793. pFile->eFileLock = eFileLock;
  27794. return SQLITE_OK;
  27795. }
  27796. /* no, really, unlock. */
  27797. if( robust_flock(pFile->h, LOCK_UN) ){
  27798. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  27799. return SQLITE_OK;
  27800. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  27801. return SQLITE_IOERR_UNLOCK;
  27802. }else{
  27803. pFile->eFileLock = NO_LOCK;
  27804. return SQLITE_OK;
  27805. }
  27806. }
  27807. /*
  27808. ** Close a file.
  27809. */
  27810. static int flockClose(sqlite3_file *id) {
  27811. assert( id!=0 );
  27812. flockUnlock(id, NO_LOCK);
  27813. return closeUnixFile(id);
  27814. }
  27815. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  27816. /******************* End of the flock lock implementation *********************
  27817. ******************************************************************************/
  27818. /******************************************************************************
  27819. ************************ Begin Named Semaphore Locking ************************
  27820. **
  27821. ** Named semaphore locking is only supported on VxWorks.
  27822. **
  27823. ** Semaphore locking is like dot-lock and flock in that it really only
  27824. ** supports EXCLUSIVE locking. Only a single process can read or write
  27825. ** the database file at a time. This reduces potential concurrency, but
  27826. ** makes the lock implementation much easier.
  27827. */
  27828. #if OS_VXWORKS
  27829. /*
  27830. ** This routine checks if there is a RESERVED lock held on the specified
  27831. ** file by this or any other process. If such a lock is held, set *pResOut
  27832. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27833. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27834. */
  27835. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  27836. int rc = SQLITE_OK;
  27837. int reserved = 0;
  27838. unixFile *pFile = (unixFile*)id;
  27839. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27840. assert( pFile );
  27841. /* Check if a thread in this process holds such a lock */
  27842. if( pFile->eFileLock>SHARED_LOCK ){
  27843. reserved = 1;
  27844. }
  27845. /* Otherwise see if some other process holds it. */
  27846. if( !reserved ){
  27847. sem_t *pSem = pFile->pInode->pSem;
  27848. if( sem_trywait(pSem)==-1 ){
  27849. int tErrno = errno;
  27850. if( EAGAIN != tErrno ){
  27851. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  27852. storeLastErrno(pFile, tErrno);
  27853. } else {
  27854. /* someone else has the lock when we are in NO_LOCK */
  27855. reserved = (pFile->eFileLock < SHARED_LOCK);
  27856. }
  27857. }else{
  27858. /* we could have it if we want it */
  27859. sem_post(pSem);
  27860. }
  27861. }
  27862. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  27863. *pResOut = reserved;
  27864. return rc;
  27865. }
  27866. /*
  27867. ** Lock the file with the lock specified by parameter eFileLock - one
  27868. ** of the following:
  27869. **
  27870. ** (1) SHARED_LOCK
  27871. ** (2) RESERVED_LOCK
  27872. ** (3) PENDING_LOCK
  27873. ** (4) EXCLUSIVE_LOCK
  27874. **
  27875. ** Sometimes when requesting one lock state, additional lock states
  27876. ** are inserted in between. The locking might fail on one of the later
  27877. ** transitions leaving the lock state different from what it started but
  27878. ** still short of its goal. The following chart shows the allowed
  27879. ** transitions and the inserted intermediate states:
  27880. **
  27881. ** UNLOCKED -> SHARED
  27882. ** SHARED -> RESERVED
  27883. ** SHARED -> (PENDING) -> EXCLUSIVE
  27884. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27885. ** PENDING -> EXCLUSIVE
  27886. **
  27887. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  27888. ** lock states in the sqlite3_file structure, but all locks SHARED or
  27889. ** above are really EXCLUSIVE locks and exclude all other processes from
  27890. ** access the file.
  27891. **
  27892. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27893. ** routine to lower a locking level.
  27894. */
  27895. static int semXLock(sqlite3_file *id, int eFileLock) {
  27896. unixFile *pFile = (unixFile*)id;
  27897. sem_t *pSem = pFile->pInode->pSem;
  27898. int rc = SQLITE_OK;
  27899. /* if we already have a lock, it is exclusive.
  27900. ** Just adjust level and punt on outta here. */
  27901. if (pFile->eFileLock > NO_LOCK) {
  27902. pFile->eFileLock = eFileLock;
  27903. rc = SQLITE_OK;
  27904. goto sem_end_lock;
  27905. }
  27906. /* lock semaphore now but bail out when already locked. */
  27907. if( sem_trywait(pSem)==-1 ){
  27908. rc = SQLITE_BUSY;
  27909. goto sem_end_lock;
  27910. }
  27911. /* got it, set the type and return ok */
  27912. pFile->eFileLock = eFileLock;
  27913. sem_end_lock:
  27914. return rc;
  27915. }
  27916. /*
  27917. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27918. ** must be either NO_LOCK or SHARED_LOCK.
  27919. **
  27920. ** If the locking level of the file descriptor is already at or below
  27921. ** the requested locking level, this routine is a no-op.
  27922. */
  27923. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  27924. unixFile *pFile = (unixFile*)id;
  27925. sem_t *pSem = pFile->pInode->pSem;
  27926. assert( pFile );
  27927. assert( pSem );
  27928. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  27929. pFile->eFileLock, osGetpid(0)));
  27930. assert( eFileLock<=SHARED_LOCK );
  27931. /* no-op if possible */
  27932. if( pFile->eFileLock==eFileLock ){
  27933. return SQLITE_OK;
  27934. }
  27935. /* shared can just be set because we always have an exclusive */
  27936. if (eFileLock==SHARED_LOCK) {
  27937. pFile->eFileLock = eFileLock;
  27938. return SQLITE_OK;
  27939. }
  27940. /* no, really unlock. */
  27941. if ( sem_post(pSem)==-1 ) {
  27942. int rc, tErrno = errno;
  27943. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  27944. if( IS_LOCK_ERROR(rc) ){
  27945. storeLastErrno(pFile, tErrno);
  27946. }
  27947. return rc;
  27948. }
  27949. pFile->eFileLock = NO_LOCK;
  27950. return SQLITE_OK;
  27951. }
  27952. /*
  27953. ** Close a file.
  27954. */
  27955. static int semXClose(sqlite3_file *id) {
  27956. if( id ){
  27957. unixFile *pFile = (unixFile*)id;
  27958. semXUnlock(id, NO_LOCK);
  27959. assert( pFile );
  27960. unixEnterMutex();
  27961. releaseInodeInfo(pFile);
  27962. unixLeaveMutex();
  27963. closeUnixFile(id);
  27964. }
  27965. return SQLITE_OK;
  27966. }
  27967. #endif /* OS_VXWORKS */
  27968. /*
  27969. ** Named semaphore locking is only available on VxWorks.
  27970. **
  27971. *************** End of the named semaphore lock implementation ****************
  27972. ******************************************************************************/
  27973. /******************************************************************************
  27974. *************************** Begin AFP Locking *********************************
  27975. **
  27976. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  27977. ** on Apple Macintosh computers - both OS9 and OSX.
  27978. **
  27979. ** Third-party implementations of AFP are available. But this code here
  27980. ** only works on OSX.
  27981. */
  27982. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27983. /*
  27984. ** The afpLockingContext structure contains all afp lock specific state
  27985. */
  27986. typedef struct afpLockingContext afpLockingContext;
  27987. struct afpLockingContext {
  27988. int reserved;
  27989. const char *dbPath; /* Name of the open file */
  27990. };
  27991. struct ByteRangeLockPB2
  27992. {
  27993. unsigned long long offset; /* offset to first byte to lock */
  27994. unsigned long long length; /* nbr of bytes to lock */
  27995. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  27996. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  27997. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  27998. int fd; /* file desc to assoc this lock with */
  27999. };
  28000. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  28001. /*
  28002. ** This is a utility for setting or clearing a bit-range lock on an
  28003. ** AFP filesystem.
  28004. **
  28005. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  28006. */
  28007. static int afpSetLock(
  28008. const char *path, /* Name of the file to be locked or unlocked */
  28009. unixFile *pFile, /* Open file descriptor on path */
  28010. unsigned long long offset, /* First byte to be locked */
  28011. unsigned long long length, /* Number of bytes to lock */
  28012. int setLockFlag /* True to set lock. False to clear lock */
  28013. ){
  28014. struct ByteRangeLockPB2 pb;
  28015. int err;
  28016. pb.unLockFlag = setLockFlag ? 0 : 1;
  28017. pb.startEndFlag = 0;
  28018. pb.offset = offset;
  28019. pb.length = length;
  28020. pb.fd = pFile->h;
  28021. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  28022. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  28023. offset, length));
  28024. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  28025. if ( err==-1 ) {
  28026. int rc;
  28027. int tErrno = errno;
  28028. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  28029. path, tErrno, strerror(tErrno)));
  28030. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  28031. rc = SQLITE_BUSY;
  28032. #else
  28033. rc = sqliteErrorFromPosixError(tErrno,
  28034. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  28035. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  28036. if( IS_LOCK_ERROR(rc) ){
  28037. storeLastErrno(pFile, tErrno);
  28038. }
  28039. return rc;
  28040. } else {
  28041. return SQLITE_OK;
  28042. }
  28043. }
  28044. /*
  28045. ** This routine checks if there is a RESERVED lock held on the specified
  28046. ** file by this or any other process. If such a lock is held, set *pResOut
  28047. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28048. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28049. */
  28050. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  28051. int rc = SQLITE_OK;
  28052. int reserved = 0;
  28053. unixFile *pFile = (unixFile*)id;
  28054. afpLockingContext *context;
  28055. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  28056. assert( pFile );
  28057. context = (afpLockingContext *) pFile->lockingContext;
  28058. if( context->reserved ){
  28059. *pResOut = 1;
  28060. return SQLITE_OK;
  28061. }
  28062. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  28063. /* Check if a thread in this process holds such a lock */
  28064. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  28065. reserved = 1;
  28066. }
  28067. /* Otherwise see if some other process holds it.
  28068. */
  28069. if( !reserved ){
  28070. /* lock the RESERVED byte */
  28071. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  28072. if( SQLITE_OK==lrc ){
  28073. /* if we succeeded in taking the reserved lock, unlock it to restore
  28074. ** the original state */
  28075. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  28076. } else {
  28077. /* if we failed to get the lock then someone else must have it */
  28078. reserved = 1;
  28079. }
  28080. if( IS_LOCK_ERROR(lrc) ){
  28081. rc=lrc;
  28082. }
  28083. }
  28084. unixLeaveMutex();
  28085. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  28086. *pResOut = reserved;
  28087. return rc;
  28088. }
  28089. /*
  28090. ** Lock the file with the lock specified by parameter eFileLock - one
  28091. ** of the following:
  28092. **
  28093. ** (1) SHARED_LOCK
  28094. ** (2) RESERVED_LOCK
  28095. ** (3) PENDING_LOCK
  28096. ** (4) EXCLUSIVE_LOCK
  28097. **
  28098. ** Sometimes when requesting one lock state, additional lock states
  28099. ** are inserted in between. The locking might fail on one of the later
  28100. ** transitions leaving the lock state different from what it started but
  28101. ** still short of its goal. The following chart shows the allowed
  28102. ** transitions and the inserted intermediate states:
  28103. **
  28104. ** UNLOCKED -> SHARED
  28105. ** SHARED -> RESERVED
  28106. ** SHARED -> (PENDING) -> EXCLUSIVE
  28107. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28108. ** PENDING -> EXCLUSIVE
  28109. **
  28110. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28111. ** routine to lower a locking level.
  28112. */
  28113. static int afpLock(sqlite3_file *id, int eFileLock){
  28114. int rc = SQLITE_OK;
  28115. unixFile *pFile = (unixFile*)id;
  28116. unixInodeInfo *pInode = pFile->pInode;
  28117. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  28118. assert( pFile );
  28119. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  28120. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  28121. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  28122. /* If there is already a lock of this type or more restrictive on the
  28123. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  28124. ** unixEnterMutex() hasn't been called yet.
  28125. */
  28126. if( pFile->eFileLock>=eFileLock ){
  28127. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  28128. azFileLock(eFileLock)));
  28129. return SQLITE_OK;
  28130. }
  28131. /* Make sure the locking sequence is correct
  28132. ** (1) We never move from unlocked to anything higher than shared lock.
  28133. ** (2) SQLite never explicitly requests a pendig lock.
  28134. ** (3) A shared lock is always held when a reserve lock is requested.
  28135. */
  28136. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  28137. assert( eFileLock!=PENDING_LOCK );
  28138. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  28139. /* This mutex is needed because pFile->pInode is shared across threads
  28140. */
  28141. unixEnterMutex();
  28142. pInode = pFile->pInode;
  28143. /* If some thread using this PID has a lock via a different unixFile*
  28144. ** handle that precludes the requested lock, return BUSY.
  28145. */
  28146. if( (pFile->eFileLock!=pInode->eFileLock &&
  28147. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  28148. ){
  28149. rc = SQLITE_BUSY;
  28150. goto afp_end_lock;
  28151. }
  28152. /* If a SHARED lock is requested, and some thread using this PID already
  28153. ** has a SHARED or RESERVED lock, then increment reference counts and
  28154. ** return SQLITE_OK.
  28155. */
  28156. if( eFileLock==SHARED_LOCK &&
  28157. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  28158. assert( eFileLock==SHARED_LOCK );
  28159. assert( pFile->eFileLock==0 );
  28160. assert( pInode->nShared>0 );
  28161. pFile->eFileLock = SHARED_LOCK;
  28162. pInode->nShared++;
  28163. pInode->nLock++;
  28164. goto afp_end_lock;
  28165. }
  28166. /* A PENDING lock is needed before acquiring a SHARED lock and before
  28167. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  28168. ** be released.
  28169. */
  28170. if( eFileLock==SHARED_LOCK
  28171. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  28172. ){
  28173. int failed;
  28174. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  28175. if (failed) {
  28176. rc = failed;
  28177. goto afp_end_lock;
  28178. }
  28179. }
  28180. /* If control gets to this point, then actually go ahead and make
  28181. ** operating system calls for the specified lock.
  28182. */
  28183. if( eFileLock==SHARED_LOCK ){
  28184. int lrc1, lrc2, lrc1Errno = 0;
  28185. long lk, mask;
  28186. assert( pInode->nShared==0 );
  28187. assert( pInode->eFileLock==0 );
  28188. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  28189. /* Now get the read-lock SHARED_LOCK */
  28190. /* note that the quality of the randomness doesn't matter that much */
  28191. lk = random();
  28192. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  28193. lrc1 = afpSetLock(context->dbPath, pFile,
  28194. SHARED_FIRST+pInode->sharedByte, 1, 1);
  28195. if( IS_LOCK_ERROR(lrc1) ){
  28196. lrc1Errno = pFile->lastErrno;
  28197. }
  28198. /* Drop the temporary PENDING lock */
  28199. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  28200. if( IS_LOCK_ERROR(lrc1) ) {
  28201. storeLastErrno(pFile, lrc1Errno);
  28202. rc = lrc1;
  28203. goto afp_end_lock;
  28204. } else if( IS_LOCK_ERROR(lrc2) ){
  28205. rc = lrc2;
  28206. goto afp_end_lock;
  28207. } else if( lrc1 != SQLITE_OK ) {
  28208. rc = lrc1;
  28209. } else {
  28210. pFile->eFileLock = SHARED_LOCK;
  28211. pInode->nLock++;
  28212. pInode->nShared = 1;
  28213. }
  28214. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  28215. /* We are trying for an exclusive lock but another thread in this
  28216. ** same process is still holding a shared lock. */
  28217. rc = SQLITE_BUSY;
  28218. }else{
  28219. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  28220. ** assumed that there is a SHARED or greater lock on the file
  28221. ** already.
  28222. */
  28223. int failed = 0;
  28224. assert( 0!=pFile->eFileLock );
  28225. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  28226. /* Acquire a RESERVED lock */
  28227. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  28228. if( !failed ){
  28229. context->reserved = 1;
  28230. }
  28231. }
  28232. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  28233. /* Acquire an EXCLUSIVE lock */
  28234. /* Remove the shared lock before trying the range. we'll need to
  28235. ** reestablish the shared lock if we can't get the afpUnlock
  28236. */
  28237. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  28238. pInode->sharedByte, 1, 0)) ){
  28239. int failed2 = SQLITE_OK;
  28240. /* now attemmpt to get the exclusive lock range */
  28241. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  28242. SHARED_SIZE, 1);
  28243. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  28244. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  28245. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  28246. ** a critical I/O error
  28247. */
  28248. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  28249. SQLITE_IOERR_LOCK;
  28250. goto afp_end_lock;
  28251. }
  28252. }else{
  28253. rc = failed;
  28254. }
  28255. }
  28256. if( failed ){
  28257. rc = failed;
  28258. }
  28259. }
  28260. if( rc==SQLITE_OK ){
  28261. pFile->eFileLock = eFileLock;
  28262. pInode->eFileLock = eFileLock;
  28263. }else if( eFileLock==EXCLUSIVE_LOCK ){
  28264. pFile->eFileLock = PENDING_LOCK;
  28265. pInode->eFileLock = PENDING_LOCK;
  28266. }
  28267. afp_end_lock:
  28268. unixLeaveMutex();
  28269. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  28270. rc==SQLITE_OK ? "ok" : "failed"));
  28271. return rc;
  28272. }
  28273. /*
  28274. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28275. ** must be either NO_LOCK or SHARED_LOCK.
  28276. **
  28277. ** If the locking level of the file descriptor is already at or below
  28278. ** the requested locking level, this routine is a no-op.
  28279. */
  28280. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  28281. int rc = SQLITE_OK;
  28282. unixFile *pFile = (unixFile*)id;
  28283. unixInodeInfo *pInode;
  28284. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  28285. int skipShared = 0;
  28286. #ifdef SQLITE_TEST
  28287. int h = pFile->h;
  28288. #endif
  28289. assert( pFile );
  28290. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  28291. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  28292. osGetpid(0)));
  28293. assert( eFileLock<=SHARED_LOCK );
  28294. if( pFile->eFileLock<=eFileLock ){
  28295. return SQLITE_OK;
  28296. }
  28297. unixEnterMutex();
  28298. pInode = pFile->pInode;
  28299. assert( pInode->nShared!=0 );
  28300. if( pFile->eFileLock>SHARED_LOCK ){
  28301. assert( pInode->eFileLock==pFile->eFileLock );
  28302. SimulateIOErrorBenign(1);
  28303. SimulateIOError( h=(-1) )
  28304. SimulateIOErrorBenign(0);
  28305. #ifdef SQLITE_DEBUG
  28306. /* When reducing a lock such that other processes can start
  28307. ** reading the database file again, make sure that the
  28308. ** transaction counter was updated if any part of the database
  28309. ** file changed. If the transaction counter is not updated,
  28310. ** other connections to the same file might not realize that
  28311. ** the file has changed and hence might not know to flush their
  28312. ** cache. The use of a stale cache can lead to database corruption.
  28313. */
  28314. assert( pFile->inNormalWrite==0
  28315. || pFile->dbUpdate==0
  28316. || pFile->transCntrChng==1 );
  28317. pFile->inNormalWrite = 0;
  28318. #endif
  28319. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  28320. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  28321. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  28322. /* only re-establish the shared lock if necessary */
  28323. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  28324. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  28325. } else {
  28326. skipShared = 1;
  28327. }
  28328. }
  28329. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  28330. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  28331. }
  28332. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  28333. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  28334. if( !rc ){
  28335. context->reserved = 0;
  28336. }
  28337. }
  28338. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  28339. pInode->eFileLock = SHARED_LOCK;
  28340. }
  28341. }
  28342. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  28343. /* Decrement the shared lock counter. Release the lock using an
  28344. ** OS call only when all threads in this same process have released
  28345. ** the lock.
  28346. */
  28347. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  28348. pInode->nShared--;
  28349. if( pInode->nShared==0 ){
  28350. SimulateIOErrorBenign(1);
  28351. SimulateIOError( h=(-1) )
  28352. SimulateIOErrorBenign(0);
  28353. if( !skipShared ){
  28354. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  28355. }
  28356. if( !rc ){
  28357. pInode->eFileLock = NO_LOCK;
  28358. pFile->eFileLock = NO_LOCK;
  28359. }
  28360. }
  28361. if( rc==SQLITE_OK ){
  28362. pInode->nLock--;
  28363. assert( pInode->nLock>=0 );
  28364. if( pInode->nLock==0 ){
  28365. closePendingFds(pFile);
  28366. }
  28367. }
  28368. }
  28369. unixLeaveMutex();
  28370. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  28371. return rc;
  28372. }
  28373. /*
  28374. ** Close a file & cleanup AFP specific locking context
  28375. */
  28376. static int afpClose(sqlite3_file *id) {
  28377. int rc = SQLITE_OK;
  28378. unixFile *pFile = (unixFile*)id;
  28379. assert( id!=0 );
  28380. afpUnlock(id, NO_LOCK);
  28381. unixEnterMutex();
  28382. if( pFile->pInode && pFile->pInode->nLock ){
  28383. /* If there are outstanding locks, do not actually close the file just
  28384. ** yet because that would clear those locks. Instead, add the file
  28385. ** descriptor to pInode->aPending. It will be automatically closed when
  28386. ** the last lock is cleared.
  28387. */
  28388. setPendingFd(pFile);
  28389. }
  28390. releaseInodeInfo(pFile);
  28391. sqlite3_free(pFile->lockingContext);
  28392. rc = closeUnixFile(id);
  28393. unixLeaveMutex();
  28394. return rc;
  28395. }
  28396. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28397. /*
  28398. ** The code above is the AFP lock implementation. The code is specific
  28399. ** to MacOSX and does not work on other unix platforms. No alternative
  28400. ** is available. If you don't compile for a mac, then the "unix-afp"
  28401. ** VFS is not available.
  28402. **
  28403. ********************* End of the AFP lock implementation **********************
  28404. ******************************************************************************/
  28405. /******************************************************************************
  28406. *************************** Begin NFS Locking ********************************/
  28407. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28408. /*
  28409. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28410. ** must be either NO_LOCK or SHARED_LOCK.
  28411. **
  28412. ** If the locking level of the file descriptor is already at or below
  28413. ** the requested locking level, this routine is a no-op.
  28414. */
  28415. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  28416. return posixUnlock(id, eFileLock, 1);
  28417. }
  28418. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28419. /*
  28420. ** The code above is the NFS lock implementation. The code is specific
  28421. ** to MacOSX and does not work on other unix platforms. No alternative
  28422. ** is available.
  28423. **
  28424. ********************* End of the NFS lock implementation **********************
  28425. ******************************************************************************/
  28426. /******************************************************************************
  28427. **************** Non-locking sqlite3_file methods *****************************
  28428. **
  28429. ** The next division contains implementations for all methods of the
  28430. ** sqlite3_file object other than the locking methods. The locking
  28431. ** methods were defined in divisions above (one locking method per
  28432. ** division). Those methods that are common to all locking modes
  28433. ** are gather together into this division.
  28434. */
  28435. /*
  28436. ** Seek to the offset passed as the second argument, then read cnt
  28437. ** bytes into pBuf. Return the number of bytes actually read.
  28438. **
  28439. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  28440. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  28441. ** one system to another. Since SQLite does not define USE_PREAD
  28442. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  28443. ** See tickets #2741 and #2681.
  28444. **
  28445. ** To avoid stomping the errno value on a failed read the lastErrno value
  28446. ** is set before returning.
  28447. */
  28448. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  28449. int got;
  28450. int prior = 0;
  28451. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  28452. i64 newOffset;
  28453. #endif
  28454. TIMER_START;
  28455. assert( cnt==(cnt&0x1ffff) );
  28456. assert( id->h>2 );
  28457. do{
  28458. #if defined(USE_PREAD)
  28459. got = osPread(id->h, pBuf, cnt, offset);
  28460. SimulateIOError( got = -1 );
  28461. #elif defined(USE_PREAD64)
  28462. got = osPread64(id->h, pBuf, cnt, offset);
  28463. SimulateIOError( got = -1 );
  28464. #else
  28465. newOffset = lseek(id->h, offset, SEEK_SET);
  28466. SimulateIOError( newOffset = -1 );
  28467. if( newOffset<0 ){
  28468. storeLastErrno((unixFile*)id, errno);
  28469. return -1;
  28470. }
  28471. got = osRead(id->h, pBuf, cnt);
  28472. #endif
  28473. if( got==cnt ) break;
  28474. if( got<0 ){
  28475. if( errno==EINTR ){ got = 1; continue; }
  28476. prior = 0;
  28477. storeLastErrno((unixFile*)id, errno);
  28478. break;
  28479. }else if( got>0 ){
  28480. cnt -= got;
  28481. offset += got;
  28482. prior += got;
  28483. pBuf = (void*)(got + (char*)pBuf);
  28484. }
  28485. }while( got>0 );
  28486. TIMER_END;
  28487. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  28488. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  28489. return got+prior;
  28490. }
  28491. /*
  28492. ** Read data from a file into a buffer. Return SQLITE_OK if all
  28493. ** bytes were read successfully and SQLITE_IOERR if anything goes
  28494. ** wrong.
  28495. */
  28496. static int unixRead(
  28497. sqlite3_file *id,
  28498. void *pBuf,
  28499. int amt,
  28500. sqlite3_int64 offset
  28501. ){
  28502. unixFile *pFile = (unixFile *)id;
  28503. int got;
  28504. assert( id );
  28505. assert( offset>=0 );
  28506. assert( amt>0 );
  28507. /* If this is a database file (not a journal, master-journal or temp
  28508. ** file), the bytes in the locking range should never be read or written. */
  28509. #if 0
  28510. assert( pFile->pUnused==0
  28511. || offset>=PENDING_BYTE+512
  28512. || offset+amt<=PENDING_BYTE
  28513. );
  28514. #endif
  28515. #if SQLITE_MAX_MMAP_SIZE>0
  28516. /* Deal with as much of this read request as possible by transfering
  28517. ** data from the memory mapping using memcpy(). */
  28518. if( offset<pFile->mmapSize ){
  28519. if( offset+amt <= pFile->mmapSize ){
  28520. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  28521. return SQLITE_OK;
  28522. }else{
  28523. int nCopy = pFile->mmapSize - offset;
  28524. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  28525. pBuf = &((u8 *)pBuf)[nCopy];
  28526. amt -= nCopy;
  28527. offset += nCopy;
  28528. }
  28529. }
  28530. #endif
  28531. got = seekAndRead(pFile, offset, pBuf, amt);
  28532. if( got==amt ){
  28533. return SQLITE_OK;
  28534. }else if( got<0 ){
  28535. /* lastErrno set by seekAndRead */
  28536. return SQLITE_IOERR_READ;
  28537. }else{
  28538. storeLastErrno(pFile, 0); /* not a system error */
  28539. /* Unread parts of the buffer must be zero-filled */
  28540. memset(&((char*)pBuf)[got], 0, amt-got);
  28541. return SQLITE_IOERR_SHORT_READ;
  28542. }
  28543. }
  28544. /*
  28545. ** Attempt to seek the file-descriptor passed as the first argument to
  28546. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  28547. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  28548. ** return the actual number of bytes written (which may be less than
  28549. ** nBuf).
  28550. */
  28551. static int seekAndWriteFd(
  28552. int fd, /* File descriptor to write to */
  28553. i64 iOff, /* File offset to begin writing at */
  28554. const void *pBuf, /* Copy data from this buffer to the file */
  28555. int nBuf, /* Size of buffer pBuf in bytes */
  28556. int *piErrno /* OUT: Error number if error occurs */
  28557. ){
  28558. int rc = 0; /* Value returned by system call */
  28559. assert( nBuf==(nBuf&0x1ffff) );
  28560. assert( fd>2 );
  28561. assert( piErrno!=0 );
  28562. nBuf &= 0x1ffff;
  28563. TIMER_START;
  28564. #if defined(USE_PREAD)
  28565. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  28566. #elif defined(USE_PREAD64)
  28567. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  28568. #else
  28569. do{
  28570. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  28571. SimulateIOError( iSeek = -1 );
  28572. if( iSeek<0 ){
  28573. rc = -1;
  28574. break;
  28575. }
  28576. rc = osWrite(fd, pBuf, nBuf);
  28577. }while( rc<0 && errno==EINTR );
  28578. #endif
  28579. TIMER_END;
  28580. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  28581. if( rc<0 ) *piErrno = errno;
  28582. return rc;
  28583. }
  28584. /*
  28585. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  28586. ** Return the number of bytes actually read. Update the offset.
  28587. **
  28588. ** To avoid stomping the errno value on a failed write the lastErrno value
  28589. ** is set before returning.
  28590. */
  28591. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  28592. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  28593. }
  28594. /*
  28595. ** Write data from a buffer into a file. Return SQLITE_OK on success
  28596. ** or some other error code on failure.
  28597. */
  28598. static int unixWrite(
  28599. sqlite3_file *id,
  28600. const void *pBuf,
  28601. int amt,
  28602. sqlite3_int64 offset
  28603. ){
  28604. unixFile *pFile = (unixFile*)id;
  28605. int wrote = 0;
  28606. assert( id );
  28607. assert( amt>0 );
  28608. /* If this is a database file (not a journal, master-journal or temp
  28609. ** file), the bytes in the locking range should never be read or written. */
  28610. #if 0
  28611. assert( pFile->pUnused==0
  28612. || offset>=PENDING_BYTE+512
  28613. || offset+amt<=PENDING_BYTE
  28614. );
  28615. #endif
  28616. #ifdef SQLITE_DEBUG
  28617. /* If we are doing a normal write to a database file (as opposed to
  28618. ** doing a hot-journal rollback or a write to some file other than a
  28619. ** normal database file) then record the fact that the database
  28620. ** has changed. If the transaction counter is modified, record that
  28621. ** fact too.
  28622. */
  28623. if( pFile->inNormalWrite ){
  28624. pFile->dbUpdate = 1; /* The database has been modified */
  28625. if( offset<=24 && offset+amt>=27 ){
  28626. int rc;
  28627. char oldCntr[4];
  28628. SimulateIOErrorBenign(1);
  28629. rc = seekAndRead(pFile, 24, oldCntr, 4);
  28630. SimulateIOErrorBenign(0);
  28631. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  28632. pFile->transCntrChng = 1; /* The transaction counter has changed */
  28633. }
  28634. }
  28635. }
  28636. #endif
  28637. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  28638. /* Deal with as much of this write request as possible by transfering
  28639. ** data from the memory mapping using memcpy(). */
  28640. if( offset<pFile->mmapSize ){
  28641. if( offset+amt <= pFile->mmapSize ){
  28642. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  28643. return SQLITE_OK;
  28644. }else{
  28645. int nCopy = pFile->mmapSize - offset;
  28646. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  28647. pBuf = &((u8 *)pBuf)[nCopy];
  28648. amt -= nCopy;
  28649. offset += nCopy;
  28650. }
  28651. }
  28652. #endif
  28653. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  28654. amt -= wrote;
  28655. offset += wrote;
  28656. pBuf = &((char*)pBuf)[wrote];
  28657. }
  28658. SimulateIOError(( wrote=(-1), amt=1 ));
  28659. SimulateDiskfullError(( wrote=0, amt=1 ));
  28660. if( amt>wrote ){
  28661. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  28662. /* lastErrno set by seekAndWrite */
  28663. return SQLITE_IOERR_WRITE;
  28664. }else{
  28665. storeLastErrno(pFile, 0); /* not a system error */
  28666. return SQLITE_FULL;
  28667. }
  28668. }
  28669. return SQLITE_OK;
  28670. }
  28671. #ifdef SQLITE_TEST
  28672. /*
  28673. ** Count the number of fullsyncs and normal syncs. This is used to test
  28674. ** that syncs and fullsyncs are occurring at the right times.
  28675. */
  28676. SQLITE_API int sqlite3_sync_count = 0;
  28677. SQLITE_API int sqlite3_fullsync_count = 0;
  28678. #endif
  28679. /*
  28680. ** We do not trust systems to provide a working fdatasync(). Some do.
  28681. ** Others do no. To be safe, we will stick with the (slightly slower)
  28682. ** fsync(). If you know that your system does support fdatasync() correctly,
  28683. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  28684. */
  28685. #if !defined(fdatasync) && !HAVE_FDATASYNC
  28686. # define fdatasync fsync
  28687. #endif
  28688. /*
  28689. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  28690. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  28691. ** only available on Mac OS X. But that could change.
  28692. */
  28693. #ifdef F_FULLFSYNC
  28694. # define HAVE_FULLFSYNC 1
  28695. #else
  28696. # define HAVE_FULLFSYNC 0
  28697. #endif
  28698. /*
  28699. ** The fsync() system call does not work as advertised on many
  28700. ** unix systems. The following procedure is an attempt to make
  28701. ** it work better.
  28702. **
  28703. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  28704. ** for testing when we want to run through the test suite quickly.
  28705. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  28706. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  28707. ** or power failure will likely corrupt the database file.
  28708. **
  28709. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  28710. ** The idea behind dataOnly is that it should only write the file content
  28711. ** to disk, not the inode. We only set dataOnly if the file size is
  28712. ** unchanged since the file size is part of the inode. However,
  28713. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  28714. ** file size has changed. The only real difference between fdatasync()
  28715. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  28716. ** inode if the mtime or owner or other inode attributes have changed.
  28717. ** We only care about the file size, not the other file attributes, so
  28718. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  28719. ** So, we always use fdatasync() if it is available, regardless of
  28720. ** the value of the dataOnly flag.
  28721. */
  28722. static int full_fsync(int fd, int fullSync, int dataOnly){
  28723. int rc;
  28724. /* The following "ifdef/elif/else/" block has the same structure as
  28725. ** the one below. It is replicated here solely to avoid cluttering
  28726. ** up the real code with the UNUSED_PARAMETER() macros.
  28727. */
  28728. #ifdef SQLITE_NO_SYNC
  28729. UNUSED_PARAMETER(fd);
  28730. UNUSED_PARAMETER(fullSync);
  28731. UNUSED_PARAMETER(dataOnly);
  28732. #elif HAVE_FULLFSYNC
  28733. UNUSED_PARAMETER(dataOnly);
  28734. #else
  28735. UNUSED_PARAMETER(fullSync);
  28736. UNUSED_PARAMETER(dataOnly);
  28737. #endif
  28738. /* Record the number of times that we do a normal fsync() and
  28739. ** FULLSYNC. This is used during testing to verify that this procedure
  28740. ** gets called with the correct arguments.
  28741. */
  28742. #ifdef SQLITE_TEST
  28743. if( fullSync ) sqlite3_fullsync_count++;
  28744. sqlite3_sync_count++;
  28745. #endif
  28746. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  28747. ** no-op. But go ahead and call fstat() to validate the file
  28748. ** descriptor as we need a method to provoke a failure during
  28749. ** coverate testing.
  28750. */
  28751. #ifdef SQLITE_NO_SYNC
  28752. {
  28753. struct stat buf;
  28754. rc = osFstat(fd, &buf);
  28755. }
  28756. #elif HAVE_FULLFSYNC
  28757. if( fullSync ){
  28758. rc = osFcntl(fd, F_FULLFSYNC, 0);
  28759. }else{
  28760. rc = 1;
  28761. }
  28762. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  28763. ** It shouldn't be possible for fullfsync to fail on the local
  28764. ** file system (on OSX), so failure indicates that FULLFSYNC
  28765. ** isn't supported for this file system. So, attempt an fsync
  28766. ** and (for now) ignore the overhead of a superfluous fcntl call.
  28767. ** It'd be better to detect fullfsync support once and avoid
  28768. ** the fcntl call every time sync is called.
  28769. */
  28770. if( rc ) rc = fsync(fd);
  28771. #elif defined(__APPLE__)
  28772. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  28773. ** so currently we default to the macro that redefines fdatasync to fsync
  28774. */
  28775. rc = fsync(fd);
  28776. #else
  28777. rc = fdatasync(fd);
  28778. #if OS_VXWORKS
  28779. if( rc==-1 && errno==ENOTSUP ){
  28780. rc = fsync(fd);
  28781. }
  28782. #endif /* OS_VXWORKS */
  28783. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  28784. if( OS_VXWORKS && rc!= -1 ){
  28785. rc = 0;
  28786. }
  28787. return rc;
  28788. }
  28789. /*
  28790. ** Open a file descriptor to the directory containing file zFilename.
  28791. ** If successful, *pFd is set to the opened file descriptor and
  28792. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  28793. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  28794. ** value.
  28795. **
  28796. ** The directory file descriptor is used for only one thing - to
  28797. ** fsync() a directory to make sure file creation and deletion events
  28798. ** are flushed to disk. Such fsyncs are not needed on newer
  28799. ** journaling filesystems, but are required on older filesystems.
  28800. **
  28801. ** This routine can be overridden using the xSetSysCall interface.
  28802. ** The ability to override this routine was added in support of the
  28803. ** chromium sandbox. Opening a directory is a security risk (we are
  28804. ** told) so making it overrideable allows the chromium sandbox to
  28805. ** replace this routine with a harmless no-op. To make this routine
  28806. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  28807. ** *pFd set to a negative number.
  28808. **
  28809. ** If SQLITE_OK is returned, the caller is responsible for closing
  28810. ** the file descriptor *pFd using close().
  28811. */
  28812. static int openDirectory(const char *zFilename, int *pFd){
  28813. int ii;
  28814. int fd = -1;
  28815. char zDirname[MAX_PATHNAME+1];
  28816. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  28817. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  28818. if( ii>0 ){
  28819. zDirname[ii] = '\0';
  28820. }else{
  28821. if( zDirname[0]!='/' ) zDirname[0] = '.';
  28822. zDirname[1] = 0;
  28823. }
  28824. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  28825. if( fd>=0 ){
  28826. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  28827. }
  28828. *pFd = fd;
  28829. if( fd>=0 ) return SQLITE_OK;
  28830. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  28831. }
  28832. /*
  28833. ** Make sure all writes to a particular file are committed to disk.
  28834. **
  28835. ** If dataOnly==0 then both the file itself and its metadata (file
  28836. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  28837. ** file data is synced.
  28838. **
  28839. ** Under Unix, also make sure that the directory entry for the file
  28840. ** has been created by fsync-ing the directory that contains the file.
  28841. ** If we do not do this and we encounter a power failure, the directory
  28842. ** entry for the journal might not exist after we reboot. The next
  28843. ** SQLite to access the file will not know that the journal exists (because
  28844. ** the directory entry for the journal was never created) and the transaction
  28845. ** will not roll back - possibly leading to database corruption.
  28846. */
  28847. static int unixSync(sqlite3_file *id, int flags){
  28848. int rc;
  28849. unixFile *pFile = (unixFile*)id;
  28850. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  28851. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  28852. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  28853. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  28854. || (flags&0x0F)==SQLITE_SYNC_FULL
  28855. );
  28856. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  28857. ** line is to test that doing so does not cause any problems.
  28858. */
  28859. SimulateDiskfullError( return SQLITE_FULL );
  28860. assert( pFile );
  28861. OSTRACE(("SYNC %-3d\n", pFile->h));
  28862. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  28863. SimulateIOError( rc=1 );
  28864. if( rc ){
  28865. storeLastErrno(pFile, errno);
  28866. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  28867. }
  28868. /* Also fsync the directory containing the file if the DIRSYNC flag
  28869. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  28870. ** are unable to fsync a directory, so ignore errors on the fsync.
  28871. */
  28872. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  28873. int dirfd;
  28874. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  28875. HAVE_FULLFSYNC, isFullsync));
  28876. rc = osOpenDirectory(pFile->zPath, &dirfd);
  28877. if( rc==SQLITE_OK ){
  28878. full_fsync(dirfd, 0, 0);
  28879. robust_close(pFile, dirfd, __LINE__);
  28880. }else{
  28881. assert( rc==SQLITE_CANTOPEN );
  28882. rc = SQLITE_OK;
  28883. }
  28884. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  28885. }
  28886. return rc;
  28887. }
  28888. /*
  28889. ** Truncate an open file to a specified size
  28890. */
  28891. static int unixTruncate(sqlite3_file *id, i64 nByte){
  28892. unixFile *pFile = (unixFile *)id;
  28893. int rc;
  28894. assert( pFile );
  28895. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  28896. /* If the user has configured a chunk-size for this file, truncate the
  28897. ** file so that it consists of an integer number of chunks (i.e. the
  28898. ** actual file size after the operation may be larger than the requested
  28899. ** size).
  28900. */
  28901. if( pFile->szChunk>0 ){
  28902. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  28903. }
  28904. rc = robust_ftruncate(pFile->h, nByte);
  28905. if( rc ){
  28906. storeLastErrno(pFile, errno);
  28907. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  28908. }else{
  28909. #ifdef SQLITE_DEBUG
  28910. /* If we are doing a normal write to a database file (as opposed to
  28911. ** doing a hot-journal rollback or a write to some file other than a
  28912. ** normal database file) and we truncate the file to zero length,
  28913. ** that effectively updates the change counter. This might happen
  28914. ** when restoring a database using the backup API from a zero-length
  28915. ** source.
  28916. */
  28917. if( pFile->inNormalWrite && nByte==0 ){
  28918. pFile->transCntrChng = 1;
  28919. }
  28920. #endif
  28921. #if SQLITE_MAX_MMAP_SIZE>0
  28922. /* If the file was just truncated to a size smaller than the currently
  28923. ** mapped region, reduce the effective mapping size as well. SQLite will
  28924. ** use read() and write() to access data beyond this point from now on.
  28925. */
  28926. if( nByte<pFile->mmapSize ){
  28927. pFile->mmapSize = nByte;
  28928. }
  28929. #endif
  28930. return SQLITE_OK;
  28931. }
  28932. }
  28933. /*
  28934. ** Determine the current size of a file in bytes
  28935. */
  28936. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  28937. int rc;
  28938. struct stat buf;
  28939. assert( id );
  28940. rc = osFstat(((unixFile*)id)->h, &buf);
  28941. SimulateIOError( rc=1 );
  28942. if( rc!=0 ){
  28943. storeLastErrno((unixFile*)id, errno);
  28944. return SQLITE_IOERR_FSTAT;
  28945. }
  28946. *pSize = buf.st_size;
  28947. /* When opening a zero-size database, the findInodeInfo() procedure
  28948. ** writes a single byte into that file in order to work around a bug
  28949. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  28950. ** layers, we need to report this file size as zero even though it is
  28951. ** really 1. Ticket #3260.
  28952. */
  28953. if( *pSize==1 ) *pSize = 0;
  28954. return SQLITE_OK;
  28955. }
  28956. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28957. /*
  28958. ** Handler for proxy-locking file-control verbs. Defined below in the
  28959. ** proxying locking division.
  28960. */
  28961. static int proxyFileControl(sqlite3_file*,int,void*);
  28962. #endif
  28963. /*
  28964. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  28965. ** file-control operation. Enlarge the database to nBytes in size
  28966. ** (rounded up to the next chunk-size). If the database is already
  28967. ** nBytes or larger, this routine is a no-op.
  28968. */
  28969. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  28970. if( pFile->szChunk>0 ){
  28971. i64 nSize; /* Required file size */
  28972. struct stat buf; /* Used to hold return values of fstat() */
  28973. if( osFstat(pFile->h, &buf) ){
  28974. return SQLITE_IOERR_FSTAT;
  28975. }
  28976. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  28977. if( nSize>(i64)buf.st_size ){
  28978. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  28979. /* The code below is handling the return value of osFallocate()
  28980. ** correctly. posix_fallocate() is defined to "returns zero on success,
  28981. ** or an error number on failure". See the manpage for details. */
  28982. int err;
  28983. do{
  28984. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  28985. }while( err==EINTR );
  28986. if( err ) return SQLITE_IOERR_WRITE;
  28987. #else
  28988. /* If the OS does not have posix_fallocate(), fake it. Write a
  28989. ** single byte to the last byte in each block that falls entirely
  28990. ** within the extended region. Then, if required, a single byte
  28991. ** at offset (nSize-1), to set the size of the file correctly.
  28992. ** This is a similar technique to that used by glibc on systems
  28993. ** that do not have a real fallocate() call.
  28994. */
  28995. int nBlk = buf.st_blksize; /* File-system block size */
  28996. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  28997. i64 iWrite; /* Next offset to write to */
  28998. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  28999. assert( iWrite>=buf.st_size );
  29000. assert( ((iWrite+1)%nBlk)==0 );
  29001. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  29002. if( iWrite>=nSize ) iWrite = nSize - 1;
  29003. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  29004. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  29005. }
  29006. #endif
  29007. }
  29008. }
  29009. #if SQLITE_MAX_MMAP_SIZE>0
  29010. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  29011. int rc;
  29012. if( pFile->szChunk<=0 ){
  29013. if( robust_ftruncate(pFile->h, nByte) ){
  29014. storeLastErrno(pFile, errno);
  29015. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  29016. }
  29017. }
  29018. rc = unixMapfile(pFile, nByte);
  29019. return rc;
  29020. }
  29021. #endif
  29022. return SQLITE_OK;
  29023. }
  29024. /*
  29025. ** If *pArg is initially negative then this is a query. Set *pArg to
  29026. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  29027. **
  29028. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  29029. */
  29030. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  29031. if( *pArg<0 ){
  29032. *pArg = (pFile->ctrlFlags & mask)!=0;
  29033. }else if( (*pArg)==0 ){
  29034. pFile->ctrlFlags &= ~mask;
  29035. }else{
  29036. pFile->ctrlFlags |= mask;
  29037. }
  29038. }
  29039. /* Forward declaration */
  29040. static int unixGetTempname(int nBuf, char *zBuf);
  29041. /*
  29042. ** Information and control of an open file handle.
  29043. */
  29044. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  29045. unixFile *pFile = (unixFile*)id;
  29046. switch( op ){
  29047. case SQLITE_FCNTL_LOCKSTATE: {
  29048. *(int*)pArg = pFile->eFileLock;
  29049. return SQLITE_OK;
  29050. }
  29051. case SQLITE_FCNTL_LAST_ERRNO: {
  29052. *(int*)pArg = pFile->lastErrno;
  29053. return SQLITE_OK;
  29054. }
  29055. case SQLITE_FCNTL_CHUNK_SIZE: {
  29056. pFile->szChunk = *(int *)pArg;
  29057. return SQLITE_OK;
  29058. }
  29059. case SQLITE_FCNTL_SIZE_HINT: {
  29060. int rc;
  29061. SimulateIOErrorBenign(1);
  29062. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  29063. SimulateIOErrorBenign(0);
  29064. return rc;
  29065. }
  29066. case SQLITE_FCNTL_PERSIST_WAL: {
  29067. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  29068. return SQLITE_OK;
  29069. }
  29070. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  29071. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  29072. return SQLITE_OK;
  29073. }
  29074. case SQLITE_FCNTL_VFSNAME: {
  29075. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  29076. return SQLITE_OK;
  29077. }
  29078. case SQLITE_FCNTL_TEMPFILENAME: {
  29079. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  29080. if( zTFile ){
  29081. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  29082. *(char**)pArg = zTFile;
  29083. }
  29084. return SQLITE_OK;
  29085. }
  29086. case SQLITE_FCNTL_HAS_MOVED: {
  29087. *(int*)pArg = fileHasMoved(pFile);
  29088. return SQLITE_OK;
  29089. }
  29090. #if SQLITE_MAX_MMAP_SIZE>0
  29091. case SQLITE_FCNTL_MMAP_SIZE: {
  29092. i64 newLimit = *(i64*)pArg;
  29093. int rc = SQLITE_OK;
  29094. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  29095. newLimit = sqlite3GlobalConfig.mxMmap;
  29096. }
  29097. *(i64*)pArg = pFile->mmapSizeMax;
  29098. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  29099. pFile->mmapSizeMax = newLimit;
  29100. if( pFile->mmapSize>0 ){
  29101. unixUnmapfile(pFile);
  29102. rc = unixMapfile(pFile, -1);
  29103. }
  29104. }
  29105. return rc;
  29106. }
  29107. #endif
  29108. #ifdef SQLITE_DEBUG
  29109. /* The pager calls this method to signal that it has done
  29110. ** a rollback and that the database is therefore unchanged and
  29111. ** it hence it is OK for the transaction change counter to be
  29112. ** unchanged.
  29113. */
  29114. case SQLITE_FCNTL_DB_UNCHANGED: {
  29115. ((unixFile*)id)->dbUpdate = 0;
  29116. return SQLITE_OK;
  29117. }
  29118. #endif
  29119. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29120. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  29121. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  29122. return proxyFileControl(id,op,pArg);
  29123. }
  29124. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  29125. }
  29126. return SQLITE_NOTFOUND;
  29127. }
  29128. /*
  29129. ** Return the sector size in bytes of the underlying block device for
  29130. ** the specified file. This is almost always 512 bytes, but may be
  29131. ** larger for some devices.
  29132. **
  29133. ** SQLite code assumes this function cannot fail. It also assumes that
  29134. ** if two files are created in the same file-system directory (i.e.
  29135. ** a database and its journal file) that the sector size will be the
  29136. ** same for both.
  29137. */
  29138. #ifndef __QNXNTO__
  29139. static int unixSectorSize(sqlite3_file *NotUsed){
  29140. UNUSED_PARAMETER(NotUsed);
  29141. return SQLITE_DEFAULT_SECTOR_SIZE;
  29142. }
  29143. #endif
  29144. /*
  29145. ** The following version of unixSectorSize() is optimized for QNX.
  29146. */
  29147. #ifdef __QNXNTO__
  29148. #include <sys/dcmd_blk.h>
  29149. #include <sys/statvfs.h>
  29150. static int unixSectorSize(sqlite3_file *id){
  29151. unixFile *pFile = (unixFile*)id;
  29152. if( pFile->sectorSize == 0 ){
  29153. struct statvfs fsInfo;
  29154. /* Set defaults for non-supported filesystems */
  29155. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  29156. pFile->deviceCharacteristics = 0;
  29157. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  29158. return pFile->sectorSize;
  29159. }
  29160. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  29161. pFile->sectorSize = fsInfo.f_bsize;
  29162. pFile->deviceCharacteristics =
  29163. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  29164. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  29165. ** the write succeeds */
  29166. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29167. ** so it is ordered */
  29168. 0;
  29169. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  29170. pFile->sectorSize = fsInfo.f_bsize;
  29171. pFile->deviceCharacteristics =
  29172. /* etfs cluster size writes are atomic */
  29173. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  29174. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  29175. ** the write succeeds */
  29176. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29177. ** so it is ordered */
  29178. 0;
  29179. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  29180. pFile->sectorSize = fsInfo.f_bsize;
  29181. pFile->deviceCharacteristics =
  29182. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  29183. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  29184. ** the write succeeds */
  29185. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29186. ** so it is ordered */
  29187. 0;
  29188. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  29189. pFile->sectorSize = fsInfo.f_bsize;
  29190. pFile->deviceCharacteristics =
  29191. /* full bitset of atomics from max sector size and smaller */
  29192. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  29193. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29194. ** so it is ordered */
  29195. 0;
  29196. }else if( strstr(fsInfo.f_basetype, "dos") ){
  29197. pFile->sectorSize = fsInfo.f_bsize;
  29198. pFile->deviceCharacteristics =
  29199. /* full bitset of atomics from max sector size and smaller */
  29200. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  29201. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  29202. ** so it is ordered */
  29203. 0;
  29204. }else{
  29205. pFile->deviceCharacteristics =
  29206. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  29207. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  29208. ** the write succeeds */
  29209. 0;
  29210. }
  29211. }
  29212. /* Last chance verification. If the sector size isn't a multiple of 512
  29213. ** then it isn't valid.*/
  29214. if( pFile->sectorSize % 512 != 0 ){
  29215. pFile->deviceCharacteristics = 0;
  29216. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  29217. }
  29218. return pFile->sectorSize;
  29219. }
  29220. #endif /* __QNXNTO__ */
  29221. /*
  29222. ** Return the device characteristics for the file.
  29223. **
  29224. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  29225. ** However, that choice is controversial since technically the underlying
  29226. ** file system does not always provide powersafe overwrites. (In other
  29227. ** words, after a power-loss event, parts of the file that were never
  29228. ** written might end up being altered.) However, non-PSOW behavior is very,
  29229. ** very rare. And asserting PSOW makes a large reduction in the amount
  29230. ** of required I/O for journaling, since a lot of padding is eliminated.
  29231. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  29232. ** available to turn it off and URI query parameter available to turn it off.
  29233. */
  29234. static int unixDeviceCharacteristics(sqlite3_file *id){
  29235. unixFile *p = (unixFile*)id;
  29236. int rc = 0;
  29237. #ifdef __QNXNTO__
  29238. if( p->sectorSize==0 ) unixSectorSize(id);
  29239. rc = p->deviceCharacteristics;
  29240. #endif
  29241. if( p->ctrlFlags & UNIXFILE_PSOW ){
  29242. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  29243. }
  29244. return rc;
  29245. }
  29246. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  29247. /*
  29248. ** Return the system page size.
  29249. **
  29250. ** This function should not be called directly by other code in this file.
  29251. ** Instead, it should be called via macro osGetpagesize().
  29252. */
  29253. static int unixGetpagesize(void){
  29254. #if OS_VXWORKS
  29255. return 1024;
  29256. #elif defined(_BSD_SOURCE)
  29257. return getpagesize();
  29258. #else
  29259. return (int)sysconf(_SC_PAGESIZE);
  29260. #endif
  29261. }
  29262. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  29263. #ifndef SQLITE_OMIT_WAL
  29264. /*
  29265. ** Object used to represent an shared memory buffer.
  29266. **
  29267. ** When multiple threads all reference the same wal-index, each thread
  29268. ** has its own unixShm object, but they all point to a single instance
  29269. ** of this unixShmNode object. In other words, each wal-index is opened
  29270. ** only once per process.
  29271. **
  29272. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  29273. ** We could coalesce this object into unixInodeInfo, but that would mean
  29274. ** every open file that does not use shared memory (in other words, most
  29275. ** open files) would have to carry around this extra information. So
  29276. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  29277. ** and the unixShmNode object is created only when needed.
  29278. **
  29279. ** unixMutexHeld() must be true when creating or destroying
  29280. ** this object or while reading or writing the following fields:
  29281. **
  29282. ** nRef
  29283. **
  29284. ** The following fields are read-only after the object is created:
  29285. **
  29286. ** fid
  29287. ** zFilename
  29288. **
  29289. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  29290. ** unixMutexHeld() is true when reading or writing any other field
  29291. ** in this structure.
  29292. */
  29293. struct unixShmNode {
  29294. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  29295. sqlite3_mutex *mutex; /* Mutex to access this object */
  29296. char *zFilename; /* Name of the mmapped file */
  29297. int h; /* Open file descriptor */
  29298. int szRegion; /* Size of shared-memory regions */
  29299. u16 nRegion; /* Size of array apRegion */
  29300. u8 isReadonly; /* True if read-only */
  29301. char **apRegion; /* Array of mapped shared-memory regions */
  29302. int nRef; /* Number of unixShm objects pointing to this */
  29303. unixShm *pFirst; /* All unixShm objects pointing to this */
  29304. #ifdef SQLITE_DEBUG
  29305. u8 exclMask; /* Mask of exclusive locks held */
  29306. u8 sharedMask; /* Mask of shared locks held */
  29307. u8 nextShmId; /* Next available unixShm.id value */
  29308. #endif
  29309. };
  29310. /*
  29311. ** Structure used internally by this VFS to record the state of an
  29312. ** open shared memory connection.
  29313. **
  29314. ** The following fields are initialized when this object is created and
  29315. ** are read-only thereafter:
  29316. **
  29317. ** unixShm.pFile
  29318. ** unixShm.id
  29319. **
  29320. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  29321. ** while accessing any read/write fields.
  29322. */
  29323. struct unixShm {
  29324. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  29325. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  29326. u8 hasMutex; /* True if holding the unixShmNode mutex */
  29327. u8 id; /* Id of this connection within its unixShmNode */
  29328. u16 sharedMask; /* Mask of shared locks held */
  29329. u16 exclMask; /* Mask of exclusive locks held */
  29330. };
  29331. /*
  29332. ** Constants used for locking
  29333. */
  29334. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  29335. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  29336. /*
  29337. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  29338. **
  29339. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  29340. ** otherwise.
  29341. */
  29342. static int unixShmSystemLock(
  29343. unixFile *pFile, /* Open connection to the WAL file */
  29344. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  29345. int ofst, /* First byte of the locking range */
  29346. int n /* Number of bytes to lock */
  29347. ){
  29348. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  29349. struct flock f; /* The posix advisory locking structure */
  29350. int rc = SQLITE_OK; /* Result code form fcntl() */
  29351. /* Access to the unixShmNode object is serialized by the caller */
  29352. pShmNode = pFile->pInode->pShmNode;
  29353. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  29354. /* Shared locks never span more than one byte */
  29355. assert( n==1 || lockType!=F_RDLCK );
  29356. /* Locks are within range */
  29357. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  29358. if( pShmNode->h>=0 ){
  29359. /* Initialize the locking parameters */
  29360. memset(&f, 0, sizeof(f));
  29361. f.l_type = lockType;
  29362. f.l_whence = SEEK_SET;
  29363. f.l_start = ofst;
  29364. f.l_len = n;
  29365. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  29366. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  29367. }
  29368. /* Update the global lock state and do debug tracing */
  29369. #ifdef SQLITE_DEBUG
  29370. { u16 mask;
  29371. OSTRACE(("SHM-LOCK "));
  29372. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  29373. if( rc==SQLITE_OK ){
  29374. if( lockType==F_UNLCK ){
  29375. OSTRACE(("unlock %d ok", ofst));
  29376. pShmNode->exclMask &= ~mask;
  29377. pShmNode->sharedMask &= ~mask;
  29378. }else if( lockType==F_RDLCK ){
  29379. OSTRACE(("read-lock %d ok", ofst));
  29380. pShmNode->exclMask &= ~mask;
  29381. pShmNode->sharedMask |= mask;
  29382. }else{
  29383. assert( lockType==F_WRLCK );
  29384. OSTRACE(("write-lock %d ok", ofst));
  29385. pShmNode->exclMask |= mask;
  29386. pShmNode->sharedMask &= ~mask;
  29387. }
  29388. }else{
  29389. if( lockType==F_UNLCK ){
  29390. OSTRACE(("unlock %d failed", ofst));
  29391. }else if( lockType==F_RDLCK ){
  29392. OSTRACE(("read-lock failed"));
  29393. }else{
  29394. assert( lockType==F_WRLCK );
  29395. OSTRACE(("write-lock %d failed", ofst));
  29396. }
  29397. }
  29398. OSTRACE((" - afterwards %03x,%03x\n",
  29399. pShmNode->sharedMask, pShmNode->exclMask));
  29400. }
  29401. #endif
  29402. return rc;
  29403. }
  29404. /*
  29405. ** Return the minimum number of 32KB shm regions that should be mapped at
  29406. ** a time, assuming that each mapping must be an integer multiple of the
  29407. ** current system page-size.
  29408. **
  29409. ** Usually, this is 1. The exception seems to be systems that are configured
  29410. ** to use 64KB pages - in this case each mapping must cover at least two
  29411. ** shm regions.
  29412. */
  29413. static int unixShmRegionPerMap(void){
  29414. int shmsz = 32*1024; /* SHM region size */
  29415. int pgsz = osGetpagesize(); /* System page size */
  29416. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  29417. if( pgsz<shmsz ) return 1;
  29418. return pgsz/shmsz;
  29419. }
  29420. /*
  29421. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  29422. **
  29423. ** This is not a VFS shared-memory method; it is a utility function called
  29424. ** by VFS shared-memory methods.
  29425. */
  29426. static void unixShmPurge(unixFile *pFd){
  29427. unixShmNode *p = pFd->pInode->pShmNode;
  29428. assert( unixMutexHeld() );
  29429. if( p && ALWAYS(p->nRef==0) ){
  29430. int nShmPerMap = unixShmRegionPerMap();
  29431. int i;
  29432. assert( p->pInode==pFd->pInode );
  29433. sqlite3_mutex_free(p->mutex);
  29434. for(i=0; i<p->nRegion; i+=nShmPerMap){
  29435. if( p->h>=0 ){
  29436. osMunmap(p->apRegion[i], p->szRegion);
  29437. }else{
  29438. sqlite3_free(p->apRegion[i]);
  29439. }
  29440. }
  29441. sqlite3_free(p->apRegion);
  29442. if( p->h>=0 ){
  29443. robust_close(pFd, p->h, __LINE__);
  29444. p->h = -1;
  29445. }
  29446. p->pInode->pShmNode = 0;
  29447. sqlite3_free(p);
  29448. }
  29449. }
  29450. /*
  29451. ** Open a shared-memory area associated with open database file pDbFd.
  29452. ** This particular implementation uses mmapped files.
  29453. **
  29454. ** The file used to implement shared-memory is in the same directory
  29455. ** as the open database file and has the same name as the open database
  29456. ** file with the "-shm" suffix added. For example, if the database file
  29457. ** is "/home/user1/config.db" then the file that is created and mmapped
  29458. ** for shared memory will be called "/home/user1/config.db-shm".
  29459. **
  29460. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  29461. ** some other tmpfs mount. But if a file in a different directory
  29462. ** from the database file is used, then differing access permissions
  29463. ** or a chroot() might cause two different processes on the same
  29464. ** database to end up using different files for shared memory -
  29465. ** meaning that their memory would not really be shared - resulting
  29466. ** in database corruption. Nevertheless, this tmpfs file usage
  29467. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  29468. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  29469. ** option results in an incompatible build of SQLite; builds of SQLite
  29470. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  29471. ** same database file at the same time, database corruption will likely
  29472. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  29473. ** "unsupported" and may go away in a future SQLite release.
  29474. **
  29475. ** When opening a new shared-memory file, if no other instances of that
  29476. ** file are currently open, in this process or in other processes, then
  29477. ** the file must be truncated to zero length or have its header cleared.
  29478. **
  29479. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  29480. ** that means that an exclusive lock is held on the database file and
  29481. ** that no other processes are able to read or write the database. In
  29482. ** that case, we do not really need shared memory. No shared memory
  29483. ** file is created. The shared memory will be simulated with heap memory.
  29484. */
  29485. static int unixOpenSharedMemory(unixFile *pDbFd){
  29486. struct unixShm *p = 0; /* The connection to be opened */
  29487. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  29488. int rc; /* Result code */
  29489. unixInodeInfo *pInode; /* The inode of fd */
  29490. char *zShmFilename; /* Name of the file used for SHM */
  29491. int nShmFilename; /* Size of the SHM filename in bytes */
  29492. /* Allocate space for the new unixShm object. */
  29493. p = sqlite3_malloc64( sizeof(*p) );
  29494. if( p==0 ) return SQLITE_NOMEM;
  29495. memset(p, 0, sizeof(*p));
  29496. assert( pDbFd->pShm==0 );
  29497. /* Check to see if a unixShmNode object already exists. Reuse an existing
  29498. ** one if present. Create a new one if necessary.
  29499. */
  29500. unixEnterMutex();
  29501. pInode = pDbFd->pInode;
  29502. pShmNode = pInode->pShmNode;
  29503. if( pShmNode==0 ){
  29504. struct stat sStat; /* fstat() info for database file */
  29505. #ifndef SQLITE_SHM_DIRECTORY
  29506. const char *zBasePath = pDbFd->zPath;
  29507. #endif
  29508. /* Call fstat() to figure out the permissions on the database file. If
  29509. ** a new *-shm file is created, an attempt will be made to create it
  29510. ** with the same permissions.
  29511. */
  29512. if( osFstat(pDbFd->h, &sStat) ){
  29513. rc = SQLITE_IOERR_FSTAT;
  29514. goto shm_open_err;
  29515. }
  29516. #ifdef SQLITE_SHM_DIRECTORY
  29517. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  29518. #else
  29519. nShmFilename = 6 + (int)strlen(zBasePath);
  29520. #endif
  29521. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  29522. if( pShmNode==0 ){
  29523. rc = SQLITE_NOMEM;
  29524. goto shm_open_err;
  29525. }
  29526. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  29527. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  29528. #ifdef SQLITE_SHM_DIRECTORY
  29529. sqlite3_snprintf(nShmFilename, zShmFilename,
  29530. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  29531. (u32)sStat.st_ino, (u32)sStat.st_dev);
  29532. #else
  29533. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
  29534. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  29535. #endif
  29536. pShmNode->h = -1;
  29537. pDbFd->pInode->pShmNode = pShmNode;
  29538. pShmNode->pInode = pDbFd->pInode;
  29539. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  29540. if( pShmNode->mutex==0 ){
  29541. rc = SQLITE_NOMEM;
  29542. goto shm_open_err;
  29543. }
  29544. if( pInode->bProcessLock==0 ){
  29545. int openFlags = O_RDWR | O_CREAT;
  29546. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  29547. openFlags = O_RDONLY;
  29548. pShmNode->isReadonly = 1;
  29549. }
  29550. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  29551. if( pShmNode->h<0 ){
  29552. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  29553. goto shm_open_err;
  29554. }
  29555. /* If this process is running as root, make sure that the SHM file
  29556. ** is owned by the same user that owns the original database. Otherwise,
  29557. ** the original owner will not be able to connect.
  29558. */
  29559. robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  29560. /* Check to see if another process is holding the dead-man switch.
  29561. ** If not, truncate the file to zero length.
  29562. */
  29563. rc = SQLITE_OK;
  29564. if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  29565. if( robust_ftruncate(pShmNode->h, 0) ){
  29566. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  29567. }
  29568. }
  29569. if( rc==SQLITE_OK ){
  29570. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  29571. }
  29572. if( rc ) goto shm_open_err;
  29573. }
  29574. }
  29575. /* Make the new connection a child of the unixShmNode */
  29576. p->pShmNode = pShmNode;
  29577. #ifdef SQLITE_DEBUG
  29578. p->id = pShmNode->nextShmId++;
  29579. #endif
  29580. pShmNode->nRef++;
  29581. pDbFd->pShm = p;
  29582. unixLeaveMutex();
  29583. /* The reference count on pShmNode has already been incremented under
  29584. ** the cover of the unixEnterMutex() mutex and the pointer from the
  29585. ** new (struct unixShm) object to the pShmNode has been set. All that is
  29586. ** left to do is to link the new object into the linked list starting
  29587. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  29588. ** mutex.
  29589. */
  29590. sqlite3_mutex_enter(pShmNode->mutex);
  29591. p->pNext = pShmNode->pFirst;
  29592. pShmNode->pFirst = p;
  29593. sqlite3_mutex_leave(pShmNode->mutex);
  29594. return SQLITE_OK;
  29595. /* Jump here on any error */
  29596. shm_open_err:
  29597. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  29598. sqlite3_free(p);
  29599. unixLeaveMutex();
  29600. return rc;
  29601. }
  29602. /*
  29603. ** This function is called to obtain a pointer to region iRegion of the
  29604. ** shared-memory associated with the database file fd. Shared-memory regions
  29605. ** are numbered starting from zero. Each shared-memory region is szRegion
  29606. ** bytes in size.
  29607. **
  29608. ** If an error occurs, an error code is returned and *pp is set to NULL.
  29609. **
  29610. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  29611. ** region has not been allocated (by any client, including one running in a
  29612. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  29613. ** bExtend is non-zero and the requested shared-memory region has not yet
  29614. ** been allocated, it is allocated by this function.
  29615. **
  29616. ** If the shared-memory region has already been allocated or is allocated by
  29617. ** this call as described above, then it is mapped into this processes
  29618. ** address space (if it is not already), *pp is set to point to the mapped
  29619. ** memory and SQLITE_OK returned.
  29620. */
  29621. static int unixShmMap(
  29622. sqlite3_file *fd, /* Handle open on database file */
  29623. int iRegion, /* Region to retrieve */
  29624. int szRegion, /* Size of regions */
  29625. int bExtend, /* True to extend file if necessary */
  29626. void volatile **pp /* OUT: Mapped memory */
  29627. ){
  29628. unixFile *pDbFd = (unixFile*)fd;
  29629. unixShm *p;
  29630. unixShmNode *pShmNode;
  29631. int rc = SQLITE_OK;
  29632. int nShmPerMap = unixShmRegionPerMap();
  29633. int nReqRegion;
  29634. /* If the shared-memory file has not yet been opened, open it now. */
  29635. if( pDbFd->pShm==0 ){
  29636. rc = unixOpenSharedMemory(pDbFd);
  29637. if( rc!=SQLITE_OK ) return rc;
  29638. }
  29639. p = pDbFd->pShm;
  29640. pShmNode = p->pShmNode;
  29641. sqlite3_mutex_enter(pShmNode->mutex);
  29642. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  29643. assert( pShmNode->pInode==pDbFd->pInode );
  29644. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  29645. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  29646. /* Minimum number of regions required to be mapped. */
  29647. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  29648. if( pShmNode->nRegion<nReqRegion ){
  29649. char **apNew; /* New apRegion[] array */
  29650. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  29651. struct stat sStat; /* Used by fstat() */
  29652. pShmNode->szRegion = szRegion;
  29653. if( pShmNode->h>=0 ){
  29654. /* The requested region is not mapped into this processes address space.
  29655. ** Check to see if it has been allocated (i.e. if the wal-index file is
  29656. ** large enough to contain the requested region).
  29657. */
  29658. if( osFstat(pShmNode->h, &sStat) ){
  29659. rc = SQLITE_IOERR_SHMSIZE;
  29660. goto shmpage_out;
  29661. }
  29662. if( sStat.st_size<nByte ){
  29663. /* The requested memory region does not exist. If bExtend is set to
  29664. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  29665. */
  29666. if( !bExtend ){
  29667. goto shmpage_out;
  29668. }
  29669. /* Alternatively, if bExtend is true, extend the file. Do this by
  29670. ** writing a single byte to the end of each (OS) page being
  29671. ** allocated or extended. Technically, we need only write to the
  29672. ** last page in order to extend the file. But writing to all new
  29673. ** pages forces the OS to allocate them immediately, which reduces
  29674. ** the chances of SIGBUS while accessing the mapped region later on.
  29675. */
  29676. else{
  29677. static const int pgsz = 4096;
  29678. int iPg;
  29679. /* Write to the last byte of each newly allocated or extended page */
  29680. assert( (nByte % pgsz)==0 );
  29681. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  29682. int x = 0;
  29683. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
  29684. const char *zFile = pShmNode->zFilename;
  29685. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  29686. goto shmpage_out;
  29687. }
  29688. }
  29689. }
  29690. }
  29691. }
  29692. /* Map the requested memory region into this processes address space. */
  29693. apNew = (char **)sqlite3_realloc(
  29694. pShmNode->apRegion, nReqRegion*sizeof(char *)
  29695. );
  29696. if( !apNew ){
  29697. rc = SQLITE_IOERR_NOMEM;
  29698. goto shmpage_out;
  29699. }
  29700. pShmNode->apRegion = apNew;
  29701. while( pShmNode->nRegion<nReqRegion ){
  29702. int nMap = szRegion*nShmPerMap;
  29703. int i;
  29704. void *pMem;
  29705. if( pShmNode->h>=0 ){
  29706. pMem = osMmap(0, nMap,
  29707. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  29708. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  29709. );
  29710. if( pMem==MAP_FAILED ){
  29711. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  29712. goto shmpage_out;
  29713. }
  29714. }else{
  29715. pMem = sqlite3_malloc64(szRegion);
  29716. if( pMem==0 ){
  29717. rc = SQLITE_NOMEM;
  29718. goto shmpage_out;
  29719. }
  29720. memset(pMem, 0, szRegion);
  29721. }
  29722. for(i=0; i<nShmPerMap; i++){
  29723. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  29724. }
  29725. pShmNode->nRegion += nShmPerMap;
  29726. }
  29727. }
  29728. shmpage_out:
  29729. if( pShmNode->nRegion>iRegion ){
  29730. *pp = pShmNode->apRegion[iRegion];
  29731. }else{
  29732. *pp = 0;
  29733. }
  29734. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  29735. sqlite3_mutex_leave(pShmNode->mutex);
  29736. return rc;
  29737. }
  29738. /*
  29739. ** Change the lock state for a shared-memory segment.
  29740. **
  29741. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  29742. ** different here than in posix. In xShmLock(), one can go from unlocked
  29743. ** to shared and back or from unlocked to exclusive and back. But one may
  29744. ** not go from shared to exclusive or from exclusive to shared.
  29745. */
  29746. static int unixShmLock(
  29747. sqlite3_file *fd, /* Database file holding the shared memory */
  29748. int ofst, /* First lock to acquire or release */
  29749. int n, /* Number of locks to acquire or release */
  29750. int flags /* What to do with the lock */
  29751. ){
  29752. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  29753. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  29754. unixShm *pX; /* For looping over all siblings */
  29755. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  29756. int rc = SQLITE_OK; /* Result code */
  29757. u16 mask; /* Mask of locks to take or release */
  29758. assert( pShmNode==pDbFd->pInode->pShmNode );
  29759. assert( pShmNode->pInode==pDbFd->pInode );
  29760. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  29761. assert( n>=1 );
  29762. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  29763. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  29764. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  29765. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  29766. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  29767. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  29768. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  29769. mask = (1<<(ofst+n)) - (1<<ofst);
  29770. assert( n>1 || mask==(1<<ofst) );
  29771. sqlite3_mutex_enter(pShmNode->mutex);
  29772. if( flags & SQLITE_SHM_UNLOCK ){
  29773. u16 allMask = 0; /* Mask of locks held by siblings */
  29774. /* See if any siblings hold this same lock */
  29775. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  29776. if( pX==p ) continue;
  29777. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  29778. allMask |= pX->sharedMask;
  29779. }
  29780. /* Unlock the system-level locks */
  29781. if( (mask & allMask)==0 ){
  29782. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  29783. }else{
  29784. rc = SQLITE_OK;
  29785. }
  29786. /* Undo the local locks */
  29787. if( rc==SQLITE_OK ){
  29788. p->exclMask &= ~mask;
  29789. p->sharedMask &= ~mask;
  29790. }
  29791. }else if( flags & SQLITE_SHM_SHARED ){
  29792. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  29793. /* Find out which shared locks are already held by sibling connections.
  29794. ** If any sibling already holds an exclusive lock, go ahead and return
  29795. ** SQLITE_BUSY.
  29796. */
  29797. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  29798. if( (pX->exclMask & mask)!=0 ){
  29799. rc = SQLITE_BUSY;
  29800. break;
  29801. }
  29802. allShared |= pX->sharedMask;
  29803. }
  29804. /* Get shared locks at the system level, if necessary */
  29805. if( rc==SQLITE_OK ){
  29806. if( (allShared & mask)==0 ){
  29807. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  29808. }else{
  29809. rc = SQLITE_OK;
  29810. }
  29811. }
  29812. /* Get the local shared locks */
  29813. if( rc==SQLITE_OK ){
  29814. p->sharedMask |= mask;
  29815. }
  29816. }else{
  29817. /* Make sure no sibling connections hold locks that will block this
  29818. ** lock. If any do, return SQLITE_BUSY right away.
  29819. */
  29820. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  29821. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  29822. rc = SQLITE_BUSY;
  29823. break;
  29824. }
  29825. }
  29826. /* Get the exclusive locks at the system level. Then if successful
  29827. ** also mark the local connection as being locked.
  29828. */
  29829. if( rc==SQLITE_OK ){
  29830. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  29831. if( rc==SQLITE_OK ){
  29832. assert( (p->sharedMask & mask)==0 );
  29833. p->exclMask |= mask;
  29834. }
  29835. }
  29836. }
  29837. sqlite3_mutex_leave(pShmNode->mutex);
  29838. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  29839. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  29840. return rc;
  29841. }
  29842. /*
  29843. ** Implement a memory barrier or memory fence on shared memory.
  29844. **
  29845. ** All loads and stores begun before the barrier must complete before
  29846. ** any load or store begun after the barrier.
  29847. */
  29848. static void unixShmBarrier(
  29849. sqlite3_file *fd /* Database file holding the shared memory */
  29850. ){
  29851. UNUSED_PARAMETER(fd);
  29852. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  29853. unixEnterMutex(); /* Also mutex, for redundancy */
  29854. unixLeaveMutex();
  29855. }
  29856. /*
  29857. ** Close a connection to shared-memory. Delete the underlying
  29858. ** storage if deleteFlag is true.
  29859. **
  29860. ** If there is no shared memory associated with the connection then this
  29861. ** routine is a harmless no-op.
  29862. */
  29863. static int unixShmUnmap(
  29864. sqlite3_file *fd, /* The underlying database file */
  29865. int deleteFlag /* Delete shared-memory if true */
  29866. ){
  29867. unixShm *p; /* The connection to be closed */
  29868. unixShmNode *pShmNode; /* The underlying shared-memory file */
  29869. unixShm **pp; /* For looping over sibling connections */
  29870. unixFile *pDbFd; /* The underlying database file */
  29871. pDbFd = (unixFile*)fd;
  29872. p = pDbFd->pShm;
  29873. if( p==0 ) return SQLITE_OK;
  29874. pShmNode = p->pShmNode;
  29875. assert( pShmNode==pDbFd->pInode->pShmNode );
  29876. assert( pShmNode->pInode==pDbFd->pInode );
  29877. /* Remove connection p from the set of connections associated
  29878. ** with pShmNode */
  29879. sqlite3_mutex_enter(pShmNode->mutex);
  29880. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  29881. *pp = p->pNext;
  29882. /* Free the connection p */
  29883. sqlite3_free(p);
  29884. pDbFd->pShm = 0;
  29885. sqlite3_mutex_leave(pShmNode->mutex);
  29886. /* If pShmNode->nRef has reached 0, then close the underlying
  29887. ** shared-memory file, too */
  29888. unixEnterMutex();
  29889. assert( pShmNode->nRef>0 );
  29890. pShmNode->nRef--;
  29891. if( pShmNode->nRef==0 ){
  29892. if( deleteFlag && pShmNode->h>=0 ){
  29893. osUnlink(pShmNode->zFilename);
  29894. }
  29895. unixShmPurge(pDbFd);
  29896. }
  29897. unixLeaveMutex();
  29898. return SQLITE_OK;
  29899. }
  29900. #else
  29901. # define unixShmMap 0
  29902. # define unixShmLock 0
  29903. # define unixShmBarrier 0
  29904. # define unixShmUnmap 0
  29905. #endif /* #ifndef SQLITE_OMIT_WAL */
  29906. #if SQLITE_MAX_MMAP_SIZE>0
  29907. /*
  29908. ** If it is currently memory mapped, unmap file pFd.
  29909. */
  29910. static void unixUnmapfile(unixFile *pFd){
  29911. assert( pFd->nFetchOut==0 );
  29912. if( pFd->pMapRegion ){
  29913. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  29914. pFd->pMapRegion = 0;
  29915. pFd->mmapSize = 0;
  29916. pFd->mmapSizeActual = 0;
  29917. }
  29918. }
  29919. /*
  29920. ** Attempt to set the size of the memory mapping maintained by file
  29921. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  29922. **
  29923. ** If successful, this function sets the following variables:
  29924. **
  29925. ** unixFile.pMapRegion
  29926. ** unixFile.mmapSize
  29927. ** unixFile.mmapSizeActual
  29928. **
  29929. ** If unsuccessful, an error message is logged via sqlite3_log() and
  29930. ** the three variables above are zeroed. In this case SQLite should
  29931. ** continue accessing the database using the xRead() and xWrite()
  29932. ** methods.
  29933. */
  29934. static void unixRemapfile(
  29935. unixFile *pFd, /* File descriptor object */
  29936. i64 nNew /* Required mapping size */
  29937. ){
  29938. const char *zErr = "mmap";
  29939. int h = pFd->h; /* File descriptor open on db file */
  29940. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  29941. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  29942. u8 *pNew = 0; /* Location of new mapping */
  29943. int flags = PROT_READ; /* Flags to pass to mmap() */
  29944. assert( pFd->nFetchOut==0 );
  29945. assert( nNew>pFd->mmapSize );
  29946. assert( nNew<=pFd->mmapSizeMax );
  29947. assert( nNew>0 );
  29948. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  29949. assert( MAP_FAILED!=0 );
  29950. #ifdef SQLITE_MMAP_READWRITE
  29951. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  29952. #endif
  29953. if( pOrig ){
  29954. #if HAVE_MREMAP
  29955. i64 nReuse = pFd->mmapSize;
  29956. #else
  29957. const int szSyspage = osGetpagesize();
  29958. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  29959. #endif
  29960. u8 *pReq = &pOrig[nReuse];
  29961. /* Unmap any pages of the existing mapping that cannot be reused. */
  29962. if( nReuse!=nOrig ){
  29963. osMunmap(pReq, nOrig-nReuse);
  29964. }
  29965. #if HAVE_MREMAP
  29966. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  29967. zErr = "mremap";
  29968. #else
  29969. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  29970. if( pNew!=MAP_FAILED ){
  29971. if( pNew!=pReq ){
  29972. osMunmap(pNew, nNew - nReuse);
  29973. pNew = 0;
  29974. }else{
  29975. pNew = pOrig;
  29976. }
  29977. }
  29978. #endif
  29979. /* The attempt to extend the existing mapping failed. Free it. */
  29980. if( pNew==MAP_FAILED || pNew==0 ){
  29981. osMunmap(pOrig, nReuse);
  29982. }
  29983. }
  29984. /* If pNew is still NULL, try to create an entirely new mapping. */
  29985. if( pNew==0 ){
  29986. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  29987. }
  29988. if( pNew==MAP_FAILED ){
  29989. pNew = 0;
  29990. nNew = 0;
  29991. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  29992. /* If the mmap() above failed, assume that all subsequent mmap() calls
  29993. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  29994. ** in this case. */
  29995. pFd->mmapSizeMax = 0;
  29996. }
  29997. pFd->pMapRegion = (void *)pNew;
  29998. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  29999. }
  30000. /*
  30001. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  30002. ** is already mapped, the existing mapping is replaced by the new). Or, if
  30003. ** there already exists a mapping for this file, and there are still
  30004. ** outstanding xFetch() references to it, this function is a no-op.
  30005. **
  30006. ** If parameter nByte is non-negative, then it is the requested size of
  30007. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  30008. ** requested size is the size of the file on disk. The actual size of the
  30009. ** created mapping is either the requested size or the value configured
  30010. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  30011. **
  30012. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  30013. ** recreated as a result of outstanding references) or an SQLite error
  30014. ** code otherwise.
  30015. */
  30016. static int unixMapfile(unixFile *pFd, i64 nMap){
  30017. assert( nMap>=0 || pFd->nFetchOut==0 );
  30018. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  30019. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  30020. if( nMap<0 ){
  30021. struct stat statbuf; /* Low-level file information */
  30022. if( osFstat(pFd->h, &statbuf) ){
  30023. return SQLITE_IOERR_FSTAT;
  30024. }
  30025. nMap = statbuf.st_size;
  30026. }
  30027. if( nMap>pFd->mmapSizeMax ){
  30028. nMap = pFd->mmapSizeMax;
  30029. }
  30030. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  30031. if( nMap!=pFd->mmapSize ){
  30032. unixRemapfile(pFd, nMap);
  30033. }
  30034. return SQLITE_OK;
  30035. }
  30036. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  30037. /*
  30038. ** If possible, return a pointer to a mapping of file fd starting at offset
  30039. ** iOff. The mapping must be valid for at least nAmt bytes.
  30040. **
  30041. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  30042. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  30043. ** Finally, if an error does occur, return an SQLite error code. The final
  30044. ** value of *pp is undefined in this case.
  30045. **
  30046. ** If this function does return a pointer, the caller must eventually
  30047. ** release the reference by calling unixUnfetch().
  30048. */
  30049. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  30050. #if SQLITE_MAX_MMAP_SIZE>0
  30051. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  30052. #endif
  30053. *pp = 0;
  30054. #if SQLITE_MAX_MMAP_SIZE>0
  30055. if( pFd->mmapSizeMax>0 ){
  30056. if( pFd->pMapRegion==0 ){
  30057. int rc = unixMapfile(pFd, -1);
  30058. if( rc!=SQLITE_OK ) return rc;
  30059. }
  30060. if( pFd->mmapSize >= iOff+nAmt ){
  30061. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  30062. pFd->nFetchOut++;
  30063. }
  30064. }
  30065. #endif
  30066. return SQLITE_OK;
  30067. }
  30068. /*
  30069. ** If the third argument is non-NULL, then this function releases a
  30070. ** reference obtained by an earlier call to unixFetch(). The second
  30071. ** argument passed to this function must be the same as the corresponding
  30072. ** argument that was passed to the unixFetch() invocation.
  30073. **
  30074. ** Or, if the third argument is NULL, then this function is being called
  30075. ** to inform the VFS layer that, according to POSIX, any existing mapping
  30076. ** may now be invalid and should be unmapped.
  30077. */
  30078. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  30079. #if SQLITE_MAX_MMAP_SIZE>0
  30080. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  30081. UNUSED_PARAMETER(iOff);
  30082. /* If p==0 (unmap the entire file) then there must be no outstanding
  30083. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  30084. ** then there must be at least one outstanding. */
  30085. assert( (p==0)==(pFd->nFetchOut==0) );
  30086. /* If p!=0, it must match the iOff value. */
  30087. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  30088. if( p ){
  30089. pFd->nFetchOut--;
  30090. }else{
  30091. unixUnmapfile(pFd);
  30092. }
  30093. assert( pFd->nFetchOut>=0 );
  30094. #else
  30095. UNUSED_PARAMETER(fd);
  30096. UNUSED_PARAMETER(p);
  30097. UNUSED_PARAMETER(iOff);
  30098. #endif
  30099. return SQLITE_OK;
  30100. }
  30101. /*
  30102. ** Here ends the implementation of all sqlite3_file methods.
  30103. **
  30104. ********************** End sqlite3_file Methods *******************************
  30105. ******************************************************************************/
  30106. /*
  30107. ** This division contains definitions of sqlite3_io_methods objects that
  30108. ** implement various file locking strategies. It also contains definitions
  30109. ** of "finder" functions. A finder-function is used to locate the appropriate
  30110. ** sqlite3_io_methods object for a particular database file. The pAppData
  30111. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  30112. ** the correct finder-function for that VFS.
  30113. **
  30114. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  30115. ** object. The only interesting finder-function is autolockIoFinder, which
  30116. ** looks at the filesystem type and tries to guess the best locking
  30117. ** strategy from that.
  30118. **
  30119. ** For finder-function F, two objects are created:
  30120. **
  30121. ** (1) The real finder-function named "FImpt()".
  30122. **
  30123. ** (2) A constant pointer to this function named just "F".
  30124. **
  30125. **
  30126. ** A pointer to the F pointer is used as the pAppData value for VFS
  30127. ** objects. We have to do this instead of letting pAppData point
  30128. ** directly at the finder-function since C90 rules prevent a void*
  30129. ** from be cast into a function pointer.
  30130. **
  30131. **
  30132. ** Each instance of this macro generates two objects:
  30133. **
  30134. ** * A constant sqlite3_io_methods object call METHOD that has locking
  30135. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  30136. **
  30137. ** * An I/O method finder function called FINDER that returns a pointer
  30138. ** to the METHOD object in the previous bullet.
  30139. */
  30140. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  30141. static const sqlite3_io_methods METHOD = { \
  30142. VERSION, /* iVersion */ \
  30143. CLOSE, /* xClose */ \
  30144. unixRead, /* xRead */ \
  30145. unixWrite, /* xWrite */ \
  30146. unixTruncate, /* xTruncate */ \
  30147. unixSync, /* xSync */ \
  30148. unixFileSize, /* xFileSize */ \
  30149. LOCK, /* xLock */ \
  30150. UNLOCK, /* xUnlock */ \
  30151. CKLOCK, /* xCheckReservedLock */ \
  30152. unixFileControl, /* xFileControl */ \
  30153. unixSectorSize, /* xSectorSize */ \
  30154. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  30155. SHMMAP, /* xShmMap */ \
  30156. unixShmLock, /* xShmLock */ \
  30157. unixShmBarrier, /* xShmBarrier */ \
  30158. unixShmUnmap, /* xShmUnmap */ \
  30159. unixFetch, /* xFetch */ \
  30160. unixUnfetch, /* xUnfetch */ \
  30161. }; \
  30162. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  30163. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  30164. return &METHOD; \
  30165. } \
  30166. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  30167. = FINDER##Impl;
  30168. /*
  30169. ** Here are all of the sqlite3_io_methods objects for each of the
  30170. ** locking strategies. Functions that return pointers to these methods
  30171. ** are also created.
  30172. */
  30173. IOMETHODS(
  30174. posixIoFinder, /* Finder function name */
  30175. posixIoMethods, /* sqlite3_io_methods object name */
  30176. 3, /* shared memory and mmap are enabled */
  30177. unixClose, /* xClose method */
  30178. unixLock, /* xLock method */
  30179. unixUnlock, /* xUnlock method */
  30180. unixCheckReservedLock, /* xCheckReservedLock method */
  30181. unixShmMap /* xShmMap method */
  30182. )
  30183. IOMETHODS(
  30184. nolockIoFinder, /* Finder function name */
  30185. nolockIoMethods, /* sqlite3_io_methods object name */
  30186. 3, /* shared memory is disabled */
  30187. nolockClose, /* xClose method */
  30188. nolockLock, /* xLock method */
  30189. nolockUnlock, /* xUnlock method */
  30190. nolockCheckReservedLock, /* xCheckReservedLock method */
  30191. 0 /* xShmMap method */
  30192. )
  30193. IOMETHODS(
  30194. dotlockIoFinder, /* Finder function name */
  30195. dotlockIoMethods, /* sqlite3_io_methods object name */
  30196. 1, /* shared memory is disabled */
  30197. dotlockClose, /* xClose method */
  30198. dotlockLock, /* xLock method */
  30199. dotlockUnlock, /* xUnlock method */
  30200. dotlockCheckReservedLock, /* xCheckReservedLock method */
  30201. 0 /* xShmMap method */
  30202. )
  30203. #if SQLITE_ENABLE_LOCKING_STYLE
  30204. IOMETHODS(
  30205. flockIoFinder, /* Finder function name */
  30206. flockIoMethods, /* sqlite3_io_methods object name */
  30207. 1, /* shared memory is disabled */
  30208. flockClose, /* xClose method */
  30209. flockLock, /* xLock method */
  30210. flockUnlock, /* xUnlock method */
  30211. flockCheckReservedLock, /* xCheckReservedLock method */
  30212. 0 /* xShmMap method */
  30213. )
  30214. #endif
  30215. #if OS_VXWORKS
  30216. IOMETHODS(
  30217. semIoFinder, /* Finder function name */
  30218. semIoMethods, /* sqlite3_io_methods object name */
  30219. 1, /* shared memory is disabled */
  30220. semXClose, /* xClose method */
  30221. semXLock, /* xLock method */
  30222. semXUnlock, /* xUnlock method */
  30223. semXCheckReservedLock, /* xCheckReservedLock method */
  30224. 0 /* xShmMap method */
  30225. )
  30226. #endif
  30227. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30228. IOMETHODS(
  30229. afpIoFinder, /* Finder function name */
  30230. afpIoMethods, /* sqlite3_io_methods object name */
  30231. 1, /* shared memory is disabled */
  30232. afpClose, /* xClose method */
  30233. afpLock, /* xLock method */
  30234. afpUnlock, /* xUnlock method */
  30235. afpCheckReservedLock, /* xCheckReservedLock method */
  30236. 0 /* xShmMap method */
  30237. )
  30238. #endif
  30239. /*
  30240. ** The proxy locking method is a "super-method" in the sense that it
  30241. ** opens secondary file descriptors for the conch and lock files and
  30242. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  30243. ** secondary files. For this reason, the division that implements
  30244. ** proxy locking is located much further down in the file. But we need
  30245. ** to go ahead and define the sqlite3_io_methods and finder function
  30246. ** for proxy locking here. So we forward declare the I/O methods.
  30247. */
  30248. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30249. static int proxyClose(sqlite3_file*);
  30250. static int proxyLock(sqlite3_file*, int);
  30251. static int proxyUnlock(sqlite3_file*, int);
  30252. static int proxyCheckReservedLock(sqlite3_file*, int*);
  30253. IOMETHODS(
  30254. proxyIoFinder, /* Finder function name */
  30255. proxyIoMethods, /* sqlite3_io_methods object name */
  30256. 1, /* shared memory is disabled */
  30257. proxyClose, /* xClose method */
  30258. proxyLock, /* xLock method */
  30259. proxyUnlock, /* xUnlock method */
  30260. proxyCheckReservedLock, /* xCheckReservedLock method */
  30261. 0 /* xShmMap method */
  30262. )
  30263. #endif
  30264. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  30265. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30266. IOMETHODS(
  30267. nfsIoFinder, /* Finder function name */
  30268. nfsIoMethods, /* sqlite3_io_methods object name */
  30269. 1, /* shared memory is disabled */
  30270. unixClose, /* xClose method */
  30271. unixLock, /* xLock method */
  30272. nfsUnlock, /* xUnlock method */
  30273. unixCheckReservedLock, /* xCheckReservedLock method */
  30274. 0 /* xShmMap method */
  30275. )
  30276. #endif
  30277. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30278. /*
  30279. ** This "finder" function attempts to determine the best locking strategy
  30280. ** for the database file "filePath". It then returns the sqlite3_io_methods
  30281. ** object that implements that strategy.
  30282. **
  30283. ** This is for MacOSX only.
  30284. */
  30285. static const sqlite3_io_methods *autolockIoFinderImpl(
  30286. const char *filePath, /* name of the database file */
  30287. unixFile *pNew /* open file object for the database file */
  30288. ){
  30289. static const struct Mapping {
  30290. const char *zFilesystem; /* Filesystem type name */
  30291. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  30292. } aMap[] = {
  30293. { "hfs", &posixIoMethods },
  30294. { "ufs", &posixIoMethods },
  30295. { "afpfs", &afpIoMethods },
  30296. { "smbfs", &afpIoMethods },
  30297. { "webdav", &nolockIoMethods },
  30298. { 0, 0 }
  30299. };
  30300. int i;
  30301. struct statfs fsInfo;
  30302. struct flock lockInfo;
  30303. if( !filePath ){
  30304. /* If filePath==NULL that means we are dealing with a transient file
  30305. ** that does not need to be locked. */
  30306. return &nolockIoMethods;
  30307. }
  30308. if( statfs(filePath, &fsInfo) != -1 ){
  30309. if( fsInfo.f_flags & MNT_RDONLY ){
  30310. return &nolockIoMethods;
  30311. }
  30312. for(i=0; aMap[i].zFilesystem; i++){
  30313. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  30314. return aMap[i].pMethods;
  30315. }
  30316. }
  30317. }
  30318. /* Default case. Handles, amongst others, "nfs".
  30319. ** Test byte-range lock using fcntl(). If the call succeeds,
  30320. ** assume that the file-system supports POSIX style locks.
  30321. */
  30322. lockInfo.l_len = 1;
  30323. lockInfo.l_start = 0;
  30324. lockInfo.l_whence = SEEK_SET;
  30325. lockInfo.l_type = F_RDLCK;
  30326. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  30327. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  30328. return &nfsIoMethods;
  30329. } else {
  30330. return &posixIoMethods;
  30331. }
  30332. }else{
  30333. return &dotlockIoMethods;
  30334. }
  30335. }
  30336. static const sqlite3_io_methods
  30337. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  30338. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  30339. #if OS_VXWORKS
  30340. /*
  30341. ** This "finder" function for VxWorks checks to see if posix advisory
  30342. ** locking works. If it does, then that is what is used. If it does not
  30343. ** work, then fallback to named semaphore locking.
  30344. */
  30345. static const sqlite3_io_methods *vxworksIoFinderImpl(
  30346. const char *filePath, /* name of the database file */
  30347. unixFile *pNew /* the open file object */
  30348. ){
  30349. struct flock lockInfo;
  30350. if( !filePath ){
  30351. /* If filePath==NULL that means we are dealing with a transient file
  30352. ** that does not need to be locked. */
  30353. return &nolockIoMethods;
  30354. }
  30355. /* Test if fcntl() is supported and use POSIX style locks.
  30356. ** Otherwise fall back to the named semaphore method.
  30357. */
  30358. lockInfo.l_len = 1;
  30359. lockInfo.l_start = 0;
  30360. lockInfo.l_whence = SEEK_SET;
  30361. lockInfo.l_type = F_RDLCK;
  30362. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  30363. return &posixIoMethods;
  30364. }else{
  30365. return &semIoMethods;
  30366. }
  30367. }
  30368. static const sqlite3_io_methods
  30369. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  30370. #endif /* OS_VXWORKS */
  30371. /*
  30372. ** An abstract type for a pointer to an IO method finder function:
  30373. */
  30374. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  30375. /****************************************************************************
  30376. **************************** sqlite3_vfs methods ****************************
  30377. **
  30378. ** This division contains the implementation of methods on the
  30379. ** sqlite3_vfs object.
  30380. */
  30381. /*
  30382. ** Initialize the contents of the unixFile structure pointed to by pId.
  30383. */
  30384. static int fillInUnixFile(
  30385. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  30386. int h, /* Open file descriptor of file being opened */
  30387. sqlite3_file *pId, /* Write to the unixFile structure here */
  30388. const char *zFilename, /* Name of the file being opened */
  30389. int ctrlFlags /* Zero or more UNIXFILE_* values */
  30390. ){
  30391. const sqlite3_io_methods *pLockingStyle;
  30392. unixFile *pNew = (unixFile *)pId;
  30393. int rc = SQLITE_OK;
  30394. assert( pNew->pInode==NULL );
  30395. /* Usually the path zFilename should not be a relative pathname. The
  30396. ** exception is when opening the proxy "conch" file in builds that
  30397. ** include the special Apple locking styles.
  30398. */
  30399. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30400. assert( zFilename==0 || zFilename[0]=='/'
  30401. || pVfs->pAppData==(void*)&autolockIoFinder );
  30402. #else
  30403. assert( zFilename==0 || zFilename[0]=='/' );
  30404. #endif
  30405. /* No locking occurs in temporary files */
  30406. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  30407. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  30408. pNew->h = h;
  30409. pNew->pVfs = pVfs;
  30410. pNew->zPath = zFilename;
  30411. pNew->ctrlFlags = (u8)ctrlFlags;
  30412. #if SQLITE_MAX_MMAP_SIZE>0
  30413. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  30414. #endif
  30415. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  30416. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  30417. pNew->ctrlFlags |= UNIXFILE_PSOW;
  30418. }
  30419. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  30420. pNew->ctrlFlags |= UNIXFILE_EXCL;
  30421. }
  30422. #if OS_VXWORKS
  30423. pNew->pId = vxworksFindFileId(zFilename);
  30424. if( pNew->pId==0 ){
  30425. ctrlFlags |= UNIXFILE_NOLOCK;
  30426. rc = SQLITE_NOMEM;
  30427. }
  30428. #endif
  30429. if( ctrlFlags & UNIXFILE_NOLOCK ){
  30430. pLockingStyle = &nolockIoMethods;
  30431. }else{
  30432. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  30433. #if SQLITE_ENABLE_LOCKING_STYLE
  30434. /* Cache zFilename in the locking context (AFP and dotlock override) for
  30435. ** proxyLock activation is possible (remote proxy is based on db name)
  30436. ** zFilename remains valid until file is closed, to support */
  30437. pNew->lockingContext = (void*)zFilename;
  30438. #endif
  30439. }
  30440. if( pLockingStyle == &posixIoMethods
  30441. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30442. || pLockingStyle == &nfsIoMethods
  30443. #endif
  30444. ){
  30445. unixEnterMutex();
  30446. rc = findInodeInfo(pNew, &pNew->pInode);
  30447. if( rc!=SQLITE_OK ){
  30448. /* If an error occurred in findInodeInfo(), close the file descriptor
  30449. ** immediately, before releasing the mutex. findInodeInfo() may fail
  30450. ** in two scenarios:
  30451. **
  30452. ** (a) A call to fstat() failed.
  30453. ** (b) A malloc failed.
  30454. **
  30455. ** Scenario (b) may only occur if the process is holding no other
  30456. ** file descriptors open on the same file. If there were other file
  30457. ** descriptors on this file, then no malloc would be required by
  30458. ** findInodeInfo(). If this is the case, it is quite safe to close
  30459. ** handle h - as it is guaranteed that no posix locks will be released
  30460. ** by doing so.
  30461. **
  30462. ** If scenario (a) caused the error then things are not so safe. The
  30463. ** implicit assumption here is that if fstat() fails, things are in
  30464. ** such bad shape that dropping a lock or two doesn't matter much.
  30465. */
  30466. robust_close(pNew, h, __LINE__);
  30467. h = -1;
  30468. }
  30469. unixLeaveMutex();
  30470. }
  30471. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  30472. else if( pLockingStyle == &afpIoMethods ){
  30473. /* AFP locking uses the file path so it needs to be included in
  30474. ** the afpLockingContext.
  30475. */
  30476. afpLockingContext *pCtx;
  30477. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  30478. if( pCtx==0 ){
  30479. rc = SQLITE_NOMEM;
  30480. }else{
  30481. /* NB: zFilename exists and remains valid until the file is closed
  30482. ** according to requirement F11141. So we do not need to make a
  30483. ** copy of the filename. */
  30484. pCtx->dbPath = zFilename;
  30485. pCtx->reserved = 0;
  30486. srandomdev();
  30487. unixEnterMutex();
  30488. rc = findInodeInfo(pNew, &pNew->pInode);
  30489. if( rc!=SQLITE_OK ){
  30490. sqlite3_free(pNew->lockingContext);
  30491. robust_close(pNew, h, __LINE__);
  30492. h = -1;
  30493. }
  30494. unixLeaveMutex();
  30495. }
  30496. }
  30497. #endif
  30498. else if( pLockingStyle == &dotlockIoMethods ){
  30499. /* Dotfile locking uses the file path so it needs to be included in
  30500. ** the dotlockLockingContext
  30501. */
  30502. char *zLockFile;
  30503. int nFilename;
  30504. assert( zFilename!=0 );
  30505. nFilename = (int)strlen(zFilename) + 6;
  30506. zLockFile = (char *)sqlite3_malloc64(nFilename);
  30507. if( zLockFile==0 ){
  30508. rc = SQLITE_NOMEM;
  30509. }else{
  30510. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  30511. }
  30512. pNew->lockingContext = zLockFile;
  30513. }
  30514. #if OS_VXWORKS
  30515. else if( pLockingStyle == &semIoMethods ){
  30516. /* Named semaphore locking uses the file path so it needs to be
  30517. ** included in the semLockingContext
  30518. */
  30519. unixEnterMutex();
  30520. rc = findInodeInfo(pNew, &pNew->pInode);
  30521. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  30522. char *zSemName = pNew->pInode->aSemName;
  30523. int n;
  30524. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  30525. pNew->pId->zCanonicalName);
  30526. for( n=1; zSemName[n]; n++ )
  30527. if( zSemName[n]=='/' ) zSemName[n] = '_';
  30528. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  30529. if( pNew->pInode->pSem == SEM_FAILED ){
  30530. rc = SQLITE_NOMEM;
  30531. pNew->pInode->aSemName[0] = '\0';
  30532. }
  30533. }
  30534. unixLeaveMutex();
  30535. }
  30536. #endif
  30537. storeLastErrno(pNew, 0);
  30538. #if OS_VXWORKS
  30539. if( rc!=SQLITE_OK ){
  30540. if( h>=0 ) robust_close(pNew, h, __LINE__);
  30541. h = -1;
  30542. osUnlink(zFilename);
  30543. pNew->ctrlFlags |= UNIXFILE_DELETE;
  30544. }
  30545. #endif
  30546. if( rc!=SQLITE_OK ){
  30547. if( h>=0 ) robust_close(pNew, h, __LINE__);
  30548. }else{
  30549. pNew->pMethod = pLockingStyle;
  30550. OpenCounter(+1);
  30551. verifyDbFile(pNew);
  30552. }
  30553. return rc;
  30554. }
  30555. /*
  30556. ** Return the name of a directory in which to put temporary files.
  30557. ** If no suitable temporary file directory can be found, return NULL.
  30558. */
  30559. static const char *unixTempFileDir(void){
  30560. static const char *azDirs[] = {
  30561. 0,
  30562. 0,
  30563. "/var/tmp",
  30564. "/usr/tmp",
  30565. "/tmp",
  30566. "."
  30567. };
  30568. unsigned int i;
  30569. struct stat buf;
  30570. const char *zDir = sqlite3_temp_directory;
  30571. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  30572. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  30573. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  30574. if( zDir==0 ) continue;
  30575. if( osStat(zDir, &buf) ) continue;
  30576. if( !S_ISDIR(buf.st_mode) ) continue;
  30577. if( osAccess(zDir, 07) ) continue;
  30578. break;
  30579. }
  30580. return zDir;
  30581. }
  30582. /*
  30583. ** Create a temporary file name in zBuf. zBuf must be allocated
  30584. ** by the calling process and must be big enough to hold at least
  30585. ** pVfs->mxPathname bytes.
  30586. */
  30587. static int unixGetTempname(int nBuf, char *zBuf){
  30588. const char *zDir;
  30589. int iLimit = 0;
  30590. /* It's odd to simulate an io-error here, but really this is just
  30591. ** using the io-error infrastructure to test that SQLite handles this
  30592. ** function failing.
  30593. */
  30594. SimulateIOError( return SQLITE_IOERR );
  30595. zDir = unixTempFileDir();
  30596. do{
  30597. u64 r;
  30598. sqlite3_randomness(sizeof(r), &r);
  30599. assert( nBuf>2 );
  30600. zBuf[nBuf-2] = 0;
  30601. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  30602. zDir, r, 0);
  30603. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  30604. }while( osAccess(zBuf,0)==0 );
  30605. return SQLITE_OK;
  30606. }
  30607. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  30608. /*
  30609. ** Routine to transform a unixFile into a proxy-locking unixFile.
  30610. ** Implementation in the proxy-lock division, but used by unixOpen()
  30611. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  30612. */
  30613. static int proxyTransformUnixFile(unixFile*, const char*);
  30614. #endif
  30615. /*
  30616. ** Search for an unused file descriptor that was opened on the database
  30617. ** file (not a journal or master-journal file) identified by pathname
  30618. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  30619. ** argument to this function.
  30620. **
  30621. ** Such a file descriptor may exist if a database connection was closed
  30622. ** but the associated file descriptor could not be closed because some
  30623. ** other file descriptor open on the same file is holding a file-lock.
  30624. ** Refer to comments in the unixClose() function and the lengthy comment
  30625. ** describing "Posix Advisory Locking" at the start of this file for
  30626. ** further details. Also, ticket #4018.
  30627. **
  30628. ** If a suitable file descriptor is found, then it is returned. If no
  30629. ** such file descriptor is located, -1 is returned.
  30630. */
  30631. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  30632. UnixUnusedFd *pUnused = 0;
  30633. /* Do not search for an unused file descriptor on vxworks. Not because
  30634. ** vxworks would not benefit from the change (it might, we're not sure),
  30635. ** but because no way to test it is currently available. It is better
  30636. ** not to risk breaking vxworks support for the sake of such an obscure
  30637. ** feature. */
  30638. #if !OS_VXWORKS
  30639. struct stat sStat; /* Results of stat() call */
  30640. /* A stat() call may fail for various reasons. If this happens, it is
  30641. ** almost certain that an open() call on the same path will also fail.
  30642. ** For this reason, if an error occurs in the stat() call here, it is
  30643. ** ignored and -1 is returned. The caller will try to open a new file
  30644. ** descriptor on the same path, fail, and return an error to SQLite.
  30645. **
  30646. ** Even if a subsequent open() call does succeed, the consequences of
  30647. ** not searching for a reusable file descriptor are not dire. */
  30648. if( 0==osStat(zPath, &sStat) ){
  30649. unixInodeInfo *pInode;
  30650. unixEnterMutex();
  30651. pInode = inodeList;
  30652. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  30653. || pInode->fileId.ino!=sStat.st_ino) ){
  30654. pInode = pInode->pNext;
  30655. }
  30656. if( pInode ){
  30657. UnixUnusedFd **pp;
  30658. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  30659. pUnused = *pp;
  30660. if( pUnused ){
  30661. *pp = pUnused->pNext;
  30662. }
  30663. }
  30664. unixLeaveMutex();
  30665. }
  30666. #endif /* if !OS_VXWORKS */
  30667. return pUnused;
  30668. }
  30669. /*
  30670. ** This function is called by unixOpen() to determine the unix permissions
  30671. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  30672. ** and a value suitable for passing as the third argument to open(2) is
  30673. ** written to *pMode. If an IO error occurs, an SQLite error code is
  30674. ** returned and the value of *pMode is not modified.
  30675. **
  30676. ** In most cases, this routine sets *pMode to 0, which will become
  30677. ** an indication to robust_open() to create the file using
  30678. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  30679. ** But if the file being opened is a WAL or regular journal file, then
  30680. ** this function queries the file-system for the permissions on the
  30681. ** corresponding database file and sets *pMode to this value. Whenever
  30682. ** possible, WAL and journal files are created using the same permissions
  30683. ** as the associated database file.
  30684. **
  30685. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  30686. ** original filename is unavailable. But 8_3_NAMES is only used for
  30687. ** FAT filesystems and permissions do not matter there, so just use
  30688. ** the default permissions.
  30689. */
  30690. static int findCreateFileMode(
  30691. const char *zPath, /* Path of file (possibly) being created */
  30692. int flags, /* Flags passed as 4th argument to xOpen() */
  30693. mode_t *pMode, /* OUT: Permissions to open file with */
  30694. uid_t *pUid, /* OUT: uid to set on the file */
  30695. gid_t *pGid /* OUT: gid to set on the file */
  30696. ){
  30697. int rc = SQLITE_OK; /* Return Code */
  30698. *pMode = 0;
  30699. *pUid = 0;
  30700. *pGid = 0;
  30701. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  30702. char zDb[MAX_PATHNAME+1]; /* Database file path */
  30703. int nDb; /* Number of valid bytes in zDb */
  30704. struct stat sStat; /* Output of stat() on database file */
  30705. /* zPath is a path to a WAL or journal file. The following block derives
  30706. ** the path to the associated database file from zPath. This block handles
  30707. ** the following naming conventions:
  30708. **
  30709. ** "<path to db>-journal"
  30710. ** "<path to db>-wal"
  30711. ** "<path to db>-journalNN"
  30712. ** "<path to db>-walNN"
  30713. **
  30714. ** where NN is a decimal number. The NN naming schemes are
  30715. ** used by the test_multiplex.c module.
  30716. */
  30717. nDb = sqlite3Strlen30(zPath) - 1;
  30718. while( zPath[nDb]!='-' ){
  30719. #ifndef SQLITE_ENABLE_8_3_NAMES
  30720. /* In the normal case (8+3 filenames disabled) the journal filename
  30721. ** is guaranteed to contain a '-' character. */
  30722. assert( nDb>0 );
  30723. assert( sqlite3Isalnum(zPath[nDb]) );
  30724. #else
  30725. /* If 8+3 names are possible, then the journal file might not contain
  30726. ** a '-' character. So check for that case and return early. */
  30727. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  30728. #endif
  30729. nDb--;
  30730. }
  30731. memcpy(zDb, zPath, nDb);
  30732. zDb[nDb] = '\0';
  30733. if( 0==osStat(zDb, &sStat) ){
  30734. *pMode = sStat.st_mode & 0777;
  30735. *pUid = sStat.st_uid;
  30736. *pGid = sStat.st_gid;
  30737. }else{
  30738. rc = SQLITE_IOERR_FSTAT;
  30739. }
  30740. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  30741. *pMode = 0600;
  30742. }
  30743. return rc;
  30744. }
  30745. /*
  30746. ** Open the file zPath.
  30747. **
  30748. ** Previously, the SQLite OS layer used three functions in place of this
  30749. ** one:
  30750. **
  30751. ** sqlite3OsOpenReadWrite();
  30752. ** sqlite3OsOpenReadOnly();
  30753. ** sqlite3OsOpenExclusive();
  30754. **
  30755. ** These calls correspond to the following combinations of flags:
  30756. **
  30757. ** ReadWrite() -> (READWRITE | CREATE)
  30758. ** ReadOnly() -> (READONLY)
  30759. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  30760. **
  30761. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  30762. ** true, the file was configured to be automatically deleted when the
  30763. ** file handle closed. To achieve the same effect using this new
  30764. ** interface, add the DELETEONCLOSE flag to those specified above for
  30765. ** OpenExclusive().
  30766. */
  30767. static int unixOpen(
  30768. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  30769. const char *zPath, /* Pathname of file to be opened */
  30770. sqlite3_file *pFile, /* The file descriptor to be filled in */
  30771. int flags, /* Input flags to control the opening */
  30772. int *pOutFlags /* Output flags returned to SQLite core */
  30773. ){
  30774. unixFile *p = (unixFile *)pFile;
  30775. int fd = -1; /* File descriptor returned by open() */
  30776. int openFlags = 0; /* Flags to pass to open() */
  30777. int eType = flags&0xFFFFFF00; /* Type of file to open */
  30778. int noLock; /* True to omit locking primitives */
  30779. int rc = SQLITE_OK; /* Function Return Code */
  30780. int ctrlFlags = 0; /* UNIXFILE_* flags */
  30781. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  30782. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  30783. int isCreate = (flags & SQLITE_OPEN_CREATE);
  30784. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  30785. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  30786. #if SQLITE_ENABLE_LOCKING_STYLE
  30787. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  30788. #endif
  30789. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  30790. struct statfs fsInfo;
  30791. #endif
  30792. /* If creating a master or main-file journal, this function will open
  30793. ** a file-descriptor on the directory too. The first time unixSync()
  30794. ** is called the directory file descriptor will be fsync()ed and close()d.
  30795. */
  30796. int syncDir = (isCreate && (
  30797. eType==SQLITE_OPEN_MASTER_JOURNAL
  30798. || eType==SQLITE_OPEN_MAIN_JOURNAL
  30799. || eType==SQLITE_OPEN_WAL
  30800. ));
  30801. /* If argument zPath is a NULL pointer, this function is required to open
  30802. ** a temporary file. Use this buffer to store the file name in.
  30803. */
  30804. char zTmpname[MAX_PATHNAME+2];
  30805. const char *zName = zPath;
  30806. /* Check the following statements are true:
  30807. **
  30808. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  30809. ** (b) if CREATE is set, then READWRITE must also be set, and
  30810. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  30811. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  30812. */
  30813. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  30814. assert(isCreate==0 || isReadWrite);
  30815. assert(isExclusive==0 || isCreate);
  30816. assert(isDelete==0 || isCreate);
  30817. /* The main DB, main journal, WAL file and master journal are never
  30818. ** automatically deleted. Nor are they ever temporary files. */
  30819. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  30820. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  30821. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  30822. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  30823. /* Assert that the upper layer has set one of the "file-type" flags. */
  30824. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  30825. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  30826. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  30827. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  30828. );
  30829. /* Detect a pid change and reset the PRNG. There is a race condition
  30830. ** here such that two or more threads all trying to open databases at
  30831. ** the same instant might all reset the PRNG. But multiple resets
  30832. ** are harmless.
  30833. */
  30834. if( randomnessPid!=osGetpid(0) ){
  30835. randomnessPid = osGetpid(0);
  30836. sqlite3_randomness(0,0);
  30837. }
  30838. memset(p, 0, sizeof(unixFile));
  30839. if( eType==SQLITE_OPEN_MAIN_DB ){
  30840. UnixUnusedFd *pUnused;
  30841. pUnused = findReusableFd(zName, flags);
  30842. if( pUnused ){
  30843. fd = pUnused->fd;
  30844. }else{
  30845. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  30846. if( !pUnused ){
  30847. return SQLITE_NOMEM;
  30848. }
  30849. }
  30850. p->pUnused = pUnused;
  30851. /* Database filenames are double-zero terminated if they are not
  30852. ** URIs with parameters. Hence, they can always be passed into
  30853. ** sqlite3_uri_parameter(). */
  30854. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  30855. }else if( !zName ){
  30856. /* If zName is NULL, the upper layer is requesting a temp file. */
  30857. assert(isDelete && !syncDir);
  30858. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  30859. if( rc!=SQLITE_OK ){
  30860. return rc;
  30861. }
  30862. zName = zTmpname;
  30863. /* Generated temporary filenames are always double-zero terminated
  30864. ** for use by sqlite3_uri_parameter(). */
  30865. assert( zName[strlen(zName)+1]==0 );
  30866. }
  30867. /* Determine the value of the flags parameter passed to POSIX function
  30868. ** open(). These must be calculated even if open() is not called, as
  30869. ** they may be stored as part of the file handle and used by the
  30870. ** 'conch file' locking functions later on. */
  30871. if( isReadonly ) openFlags |= O_RDONLY;
  30872. if( isReadWrite ) openFlags |= O_RDWR;
  30873. if( isCreate ) openFlags |= O_CREAT;
  30874. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  30875. openFlags |= (O_LARGEFILE|O_BINARY);
  30876. if( fd<0 ){
  30877. mode_t openMode; /* Permissions to create file with */
  30878. uid_t uid; /* Userid for the file */
  30879. gid_t gid; /* Groupid for the file */
  30880. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  30881. if( rc!=SQLITE_OK ){
  30882. assert( !p->pUnused );
  30883. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  30884. return rc;
  30885. }
  30886. fd = robust_open(zName, openFlags, openMode);
  30887. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  30888. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  30889. if( fd<0 && errno!=EISDIR && isReadWrite ){
  30890. /* Failed to open the file for read/write access. Try read-only. */
  30891. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  30892. openFlags &= ~(O_RDWR|O_CREAT);
  30893. flags |= SQLITE_OPEN_READONLY;
  30894. openFlags |= O_RDONLY;
  30895. isReadonly = 1;
  30896. fd = robust_open(zName, openFlags, openMode);
  30897. }
  30898. if( fd<0 ){
  30899. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  30900. goto open_finished;
  30901. }
  30902. /* If this process is running as root and if creating a new rollback
  30903. ** journal or WAL file, set the ownership of the journal or WAL to be
  30904. ** the same as the original database.
  30905. */
  30906. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  30907. robustFchown(fd, uid, gid);
  30908. }
  30909. }
  30910. assert( fd>=0 );
  30911. if( pOutFlags ){
  30912. *pOutFlags = flags;
  30913. }
  30914. if( p->pUnused ){
  30915. p->pUnused->fd = fd;
  30916. p->pUnused->flags = flags;
  30917. }
  30918. if( isDelete ){
  30919. #if OS_VXWORKS
  30920. zPath = zName;
  30921. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  30922. zPath = sqlite3_mprintf("%s", zName);
  30923. if( zPath==0 ){
  30924. robust_close(p, fd, __LINE__);
  30925. return SQLITE_NOMEM;
  30926. }
  30927. #else
  30928. osUnlink(zName);
  30929. #endif
  30930. }
  30931. #if SQLITE_ENABLE_LOCKING_STYLE
  30932. else{
  30933. p->openFlags = openFlags;
  30934. }
  30935. #endif
  30936. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  30937. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  30938. if( fstatfs(fd, &fsInfo) == -1 ){
  30939. storeLastErrno(p, errno);
  30940. robust_close(p, fd, __LINE__);
  30941. return SQLITE_IOERR_ACCESS;
  30942. }
  30943. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  30944. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  30945. }
  30946. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  30947. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  30948. }
  30949. #endif
  30950. /* Set up appropriate ctrlFlags */
  30951. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  30952. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  30953. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  30954. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  30955. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  30956. #if SQLITE_ENABLE_LOCKING_STYLE
  30957. #if SQLITE_PREFER_PROXY_LOCKING
  30958. isAutoProxy = 1;
  30959. #endif
  30960. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  30961. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  30962. int useProxy = 0;
  30963. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  30964. ** never use proxy, NULL means use proxy for non-local files only. */
  30965. if( envforce!=NULL ){
  30966. useProxy = atoi(envforce)>0;
  30967. }else{
  30968. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  30969. }
  30970. if( useProxy ){
  30971. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  30972. if( rc==SQLITE_OK ){
  30973. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  30974. if( rc!=SQLITE_OK ){
  30975. /* Use unixClose to clean up the resources added in fillInUnixFile
  30976. ** and clear all the structure's references. Specifically,
  30977. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  30978. */
  30979. unixClose(pFile);
  30980. return rc;
  30981. }
  30982. }
  30983. goto open_finished;
  30984. }
  30985. }
  30986. #endif
  30987. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  30988. open_finished:
  30989. if( rc!=SQLITE_OK ){
  30990. sqlite3_free(p->pUnused);
  30991. }
  30992. return rc;
  30993. }
  30994. /*
  30995. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  30996. ** the directory after deleting the file.
  30997. */
  30998. static int unixDelete(
  30999. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  31000. const char *zPath, /* Name of file to be deleted */
  31001. int dirSync /* If true, fsync() directory after deleting file */
  31002. ){
  31003. int rc = SQLITE_OK;
  31004. UNUSED_PARAMETER(NotUsed);
  31005. SimulateIOError(return SQLITE_IOERR_DELETE);
  31006. if( osUnlink(zPath)==(-1) ){
  31007. if( errno==ENOENT
  31008. #if OS_VXWORKS
  31009. || osAccess(zPath,0)!=0
  31010. #endif
  31011. ){
  31012. rc = SQLITE_IOERR_DELETE_NOENT;
  31013. }else{
  31014. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  31015. }
  31016. return rc;
  31017. }
  31018. #ifndef SQLITE_DISABLE_DIRSYNC
  31019. if( (dirSync & 1)!=0 ){
  31020. int fd;
  31021. rc = osOpenDirectory(zPath, &fd);
  31022. if( rc==SQLITE_OK ){
  31023. #if OS_VXWORKS
  31024. if( fsync(fd)==-1 )
  31025. #else
  31026. if( fsync(fd) )
  31027. #endif
  31028. {
  31029. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  31030. }
  31031. robust_close(0, fd, __LINE__);
  31032. }else{
  31033. assert( rc==SQLITE_CANTOPEN );
  31034. rc = SQLITE_OK;
  31035. }
  31036. }
  31037. #endif
  31038. return rc;
  31039. }
  31040. /*
  31041. ** Test the existence of or access permissions of file zPath. The
  31042. ** test performed depends on the value of flags:
  31043. **
  31044. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  31045. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  31046. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  31047. **
  31048. ** Otherwise return 0.
  31049. */
  31050. static int unixAccess(
  31051. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  31052. const char *zPath, /* Path of the file to examine */
  31053. int flags, /* What do we want to learn about the zPath file? */
  31054. int *pResOut /* Write result boolean here */
  31055. ){
  31056. UNUSED_PARAMETER(NotUsed);
  31057. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  31058. assert( pResOut!=0 );
  31059. /* The spec says there are three possible values for flags. But only
  31060. ** two of them are actually used */
  31061. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  31062. if( flags==SQLITE_ACCESS_EXISTS ){
  31063. struct stat buf;
  31064. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  31065. }else{
  31066. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  31067. }
  31068. return SQLITE_OK;
  31069. }
  31070. /*
  31071. ** Turn a relative pathname into a full pathname. The relative path
  31072. ** is stored as a nul-terminated string in the buffer pointed to by
  31073. ** zPath.
  31074. **
  31075. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  31076. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  31077. ** this buffer before returning.
  31078. */
  31079. static int unixFullPathname(
  31080. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  31081. const char *zPath, /* Possibly relative input path */
  31082. int nOut, /* Size of output buffer in bytes */
  31083. char *zOut /* Output buffer */
  31084. ){
  31085. int nByte;
  31086. /* It's odd to simulate an io-error here, but really this is just
  31087. ** using the io-error infrastructure to test that SQLite handles this
  31088. ** function failing. This function could fail if, for example, the
  31089. ** current working directory has been unlinked.
  31090. */
  31091. SimulateIOError( return SQLITE_ERROR );
  31092. assert( pVfs->mxPathname==MAX_PATHNAME );
  31093. UNUSED_PARAMETER(pVfs);
  31094. /* Attempt to resolve the path as if it were a symbolic link. If it is
  31095. ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
  31096. ** the identified file is not a symbolic link or does not exist, then
  31097. ** zPath is copied directly into zOut. Either way, nByte is left set to
  31098. ** the size of the string copied into zOut[] in bytes. */
  31099. nByte = osReadlink(zPath, zOut, nOut-1);
  31100. if( nByte<0 ){
  31101. if( errno!=EINVAL && errno!=ENOENT ){
  31102. return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
  31103. }
  31104. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  31105. nByte = sqlite3Strlen30(zOut);
  31106. }else{
  31107. zOut[nByte] = '\0';
  31108. }
  31109. /* If buffer zOut[] now contains an absolute path there is nothing more
  31110. ** to do. If it contains a relative path, do the following:
  31111. **
  31112. ** * move the relative path string so that it is at the end of th
  31113. ** zOut[] buffer.
  31114. ** * Call getcwd() to read the path of the current working directory
  31115. ** into the start of the zOut[] buffer.
  31116. ** * Append a '/' character to the cwd string and move the
  31117. ** relative path back within the buffer so that it immediately
  31118. ** follows the '/'.
  31119. **
  31120. ** This code is written so that if the combination of the CWD and relative
  31121. ** path are larger than the allocated size of zOut[] the CWD is silently
  31122. ** truncated to make it fit. This is Ok, as SQLite refuses to open any
  31123. ** file for which this function returns a full path larger than (nOut-8)
  31124. ** bytes in size. */
  31125. testcase( nByte==nOut-5 );
  31126. testcase( nByte==nOut-4 );
  31127. if( zOut[0]!='/' && nByte<nOut-4 ){
  31128. int nCwd;
  31129. int nRem = nOut-nByte-1;
  31130. memmove(&zOut[nRem], zOut, nByte+1);
  31131. zOut[nRem-1] = '\0';
  31132. if( osGetcwd(zOut, nRem-1)==0 ){
  31133. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  31134. }
  31135. nCwd = sqlite3Strlen30(zOut);
  31136. assert( nCwd<=nRem-1 );
  31137. zOut[nCwd] = '/';
  31138. memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
  31139. }
  31140. return SQLITE_OK;
  31141. }
  31142. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  31143. /*
  31144. ** Interfaces for opening a shared library, finding entry points
  31145. ** within the shared library, and closing the shared library.
  31146. */
  31147. #include <dlfcn.h>
  31148. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  31149. UNUSED_PARAMETER(NotUsed);
  31150. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  31151. }
  31152. /*
  31153. ** SQLite calls this function immediately after a call to unixDlSym() or
  31154. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  31155. ** message is available, it is written to zBufOut. If no error message
  31156. ** is available, zBufOut is left unmodified and SQLite uses a default
  31157. ** error message.
  31158. */
  31159. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  31160. const char *zErr;
  31161. UNUSED_PARAMETER(NotUsed);
  31162. unixEnterMutex();
  31163. zErr = dlerror();
  31164. if( zErr ){
  31165. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  31166. }
  31167. unixLeaveMutex();
  31168. }
  31169. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  31170. /*
  31171. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  31172. ** cast into a pointer to a function. And yet the library dlsym() routine
  31173. ** returns a void* which is really a pointer to a function. So how do we
  31174. ** use dlsym() with -pedantic-errors?
  31175. **
  31176. ** Variable x below is defined to be a pointer to a function taking
  31177. ** parameters void* and const char* and returning a pointer to a function.
  31178. ** We initialize x by assigning it a pointer to the dlsym() function.
  31179. ** (That assignment requires a cast.) Then we call the function that
  31180. ** x points to.
  31181. **
  31182. ** This work-around is unlikely to work correctly on any system where
  31183. ** you really cannot cast a function pointer into void*. But then, on the
  31184. ** other hand, dlsym() will not work on such a system either, so we have
  31185. ** not really lost anything.
  31186. */
  31187. void (*(*x)(void*,const char*))(void);
  31188. UNUSED_PARAMETER(NotUsed);
  31189. x = (void(*(*)(void*,const char*))(void))dlsym;
  31190. return (*x)(p, zSym);
  31191. }
  31192. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  31193. UNUSED_PARAMETER(NotUsed);
  31194. dlclose(pHandle);
  31195. }
  31196. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  31197. #define unixDlOpen 0
  31198. #define unixDlError 0
  31199. #define unixDlSym 0
  31200. #define unixDlClose 0
  31201. #endif
  31202. /*
  31203. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  31204. */
  31205. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  31206. UNUSED_PARAMETER(NotUsed);
  31207. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  31208. /* We have to initialize zBuf to prevent valgrind from reporting
  31209. ** errors. The reports issued by valgrind are incorrect - we would
  31210. ** prefer that the randomness be increased by making use of the
  31211. ** uninitialized space in zBuf - but valgrind errors tend to worry
  31212. ** some users. Rather than argue, it seems easier just to initialize
  31213. ** the whole array and silence valgrind, even if that means less randomness
  31214. ** in the random seed.
  31215. **
  31216. ** When testing, initializing zBuf[] to zero is all we do. That means
  31217. ** that we always use the same random number sequence. This makes the
  31218. ** tests repeatable.
  31219. */
  31220. memset(zBuf, 0, nBuf);
  31221. randomnessPid = osGetpid(0);
  31222. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  31223. {
  31224. int fd, got;
  31225. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  31226. if( fd<0 ){
  31227. time_t t;
  31228. time(&t);
  31229. memcpy(zBuf, &t, sizeof(t));
  31230. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  31231. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  31232. nBuf = sizeof(t) + sizeof(randomnessPid);
  31233. }else{
  31234. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  31235. robust_close(0, fd, __LINE__);
  31236. }
  31237. }
  31238. #endif
  31239. return nBuf;
  31240. }
  31241. /*
  31242. ** Sleep for a little while. Return the amount of time slept.
  31243. ** The argument is the number of microseconds we want to sleep.
  31244. ** The return value is the number of microseconds of sleep actually
  31245. ** requested from the underlying operating system, a number which
  31246. ** might be greater than or equal to the argument, but not less
  31247. ** than the argument.
  31248. */
  31249. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  31250. #if OS_VXWORKS
  31251. struct timespec sp;
  31252. sp.tv_sec = microseconds / 1000000;
  31253. sp.tv_nsec = (microseconds % 1000000) * 1000;
  31254. nanosleep(&sp, NULL);
  31255. UNUSED_PARAMETER(NotUsed);
  31256. return microseconds;
  31257. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  31258. usleep(microseconds);
  31259. UNUSED_PARAMETER(NotUsed);
  31260. return microseconds;
  31261. #else
  31262. int seconds = (microseconds+999999)/1000000;
  31263. sleep(seconds);
  31264. UNUSED_PARAMETER(NotUsed);
  31265. return seconds*1000000;
  31266. #endif
  31267. }
  31268. /*
  31269. ** The following variable, if set to a non-zero value, is interpreted as
  31270. ** the number of seconds since 1970 and is used to set the result of
  31271. ** sqlite3OsCurrentTime() during testing.
  31272. */
  31273. #ifdef SQLITE_TEST
  31274. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  31275. #endif
  31276. /*
  31277. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  31278. ** the current time and date as a Julian Day number times 86_400_000. In
  31279. ** other words, write into *piNow the number of milliseconds since the Julian
  31280. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  31281. ** proleptic Gregorian calendar.
  31282. **
  31283. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  31284. ** cannot be found.
  31285. */
  31286. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  31287. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  31288. int rc = SQLITE_OK;
  31289. #if defined(NO_GETTOD)
  31290. time_t t;
  31291. time(&t);
  31292. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  31293. #elif OS_VXWORKS
  31294. struct timespec sNow;
  31295. clock_gettime(CLOCK_REALTIME, &sNow);
  31296. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  31297. #else
  31298. struct timeval sNow;
  31299. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  31300. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  31301. #endif
  31302. #ifdef SQLITE_TEST
  31303. if( sqlite3_current_time ){
  31304. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  31305. }
  31306. #endif
  31307. UNUSED_PARAMETER(NotUsed);
  31308. return rc;
  31309. }
  31310. #if 0 /* Not used */
  31311. /*
  31312. ** Find the current time (in Universal Coordinated Time). Write the
  31313. ** current time and date as a Julian Day number into *prNow and
  31314. ** return 0. Return 1 if the time and date cannot be found.
  31315. */
  31316. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  31317. sqlite3_int64 i = 0;
  31318. int rc;
  31319. UNUSED_PARAMETER(NotUsed);
  31320. rc = unixCurrentTimeInt64(0, &i);
  31321. *prNow = i/86400000.0;
  31322. return rc;
  31323. }
  31324. #else
  31325. # define unixCurrentTime 0
  31326. #endif
  31327. #if 0 /* Not used */
  31328. /*
  31329. ** We added the xGetLastError() method with the intention of providing
  31330. ** better low-level error messages when operating-system problems come up
  31331. ** during SQLite operation. But so far, none of that has been implemented
  31332. ** in the core. So this routine is never called. For now, it is merely
  31333. ** a place-holder.
  31334. */
  31335. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  31336. UNUSED_PARAMETER(NotUsed);
  31337. UNUSED_PARAMETER(NotUsed2);
  31338. UNUSED_PARAMETER(NotUsed3);
  31339. return 0;
  31340. }
  31341. #else
  31342. # define unixGetLastError 0
  31343. #endif
  31344. /*
  31345. ************************ End of sqlite3_vfs methods ***************************
  31346. ******************************************************************************/
  31347. /******************************************************************************
  31348. ************************** Begin Proxy Locking ********************************
  31349. **
  31350. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  31351. ** other locking methods on secondary lock files. Proxy locking is a
  31352. ** meta-layer over top of the primitive locking implemented above. For
  31353. ** this reason, the division that implements of proxy locking is deferred
  31354. ** until late in the file (here) after all of the other I/O methods have
  31355. ** been defined - so that the primitive locking methods are available
  31356. ** as services to help with the implementation of proxy locking.
  31357. **
  31358. ****
  31359. **
  31360. ** The default locking schemes in SQLite use byte-range locks on the
  31361. ** database file to coordinate safe, concurrent access by multiple readers
  31362. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  31363. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  31364. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  31365. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  31366. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  31367. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  31368. ** address in the shared range is taken for a SHARED lock, the entire
  31369. ** shared range is taken for an EXCLUSIVE lock):
  31370. **
  31371. ** PENDING_BYTE 0x40000000
  31372. ** RESERVED_BYTE 0x40000001
  31373. ** SHARED_RANGE 0x40000002 -> 0x40000200
  31374. **
  31375. ** This works well on the local file system, but shows a nearly 100x
  31376. ** slowdown in read performance on AFP because the AFP client disables
  31377. ** the read cache when byte-range locks are present. Enabling the read
  31378. ** cache exposes a cache coherency problem that is present on all OS X
  31379. ** supported network file systems. NFS and AFP both observe the
  31380. ** close-to-open semantics for ensuring cache coherency
  31381. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  31382. ** address the requirements for concurrent database access by multiple
  31383. ** readers and writers
  31384. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  31385. **
  31386. ** To address the performance and cache coherency issues, proxy file locking
  31387. ** changes the way database access is controlled by limiting access to a
  31388. ** single host at a time and moving file locks off of the database file
  31389. ** and onto a proxy file on the local file system.
  31390. **
  31391. **
  31392. ** Using proxy locks
  31393. ** -----------------
  31394. **
  31395. ** C APIs
  31396. **
  31397. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  31398. ** <proxy_path> | ":auto:");
  31399. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  31400. ** &<proxy_path>);
  31401. **
  31402. **
  31403. ** SQL pragmas
  31404. **
  31405. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  31406. ** PRAGMA [database.]lock_proxy_file
  31407. **
  31408. ** Specifying ":auto:" means that if there is a conch file with a matching
  31409. ** host ID in it, the proxy path in the conch file will be used, otherwise
  31410. ** a proxy path based on the user's temp dir
  31411. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  31412. ** actual proxy file name is generated from the name and path of the
  31413. ** database file. For example:
  31414. **
  31415. ** For database path "/Users/me/foo.db"
  31416. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  31417. **
  31418. ** Once a lock proxy is configured for a database connection, it can not
  31419. ** be removed, however it may be switched to a different proxy path via
  31420. ** the above APIs (assuming the conch file is not being held by another
  31421. ** connection or process).
  31422. **
  31423. **
  31424. ** How proxy locking works
  31425. ** -----------------------
  31426. **
  31427. ** Proxy file locking relies primarily on two new supporting files:
  31428. **
  31429. ** * conch file to limit access to the database file to a single host
  31430. ** at a time
  31431. **
  31432. ** * proxy file to act as a proxy for the advisory locks normally
  31433. ** taken on the database
  31434. **
  31435. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  31436. ** by taking an sqlite-style shared lock on the conch file, reading the
  31437. ** contents and comparing the host's unique host ID (see below) and lock
  31438. ** proxy path against the values stored in the conch. The conch file is
  31439. ** stored in the same directory as the database file and the file name
  31440. ** is patterned after the database file name as ".<databasename>-conch".
  31441. ** If the conch file does not exist, or its contents do not match the
  31442. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  31443. ** lock and the conch file contents is updated with the host ID and proxy
  31444. ** path and the lock is downgraded to a shared lock again. If the conch
  31445. ** is held by another process (with a shared lock), the exclusive lock
  31446. ** will fail and SQLITE_BUSY is returned.
  31447. **
  31448. ** The proxy file - a single-byte file used for all advisory file locks
  31449. ** normally taken on the database file. This allows for safe sharing
  31450. ** of the database file for multiple readers and writers on the same
  31451. ** host (the conch ensures that they all use the same local lock file).
  31452. **
  31453. ** Requesting the lock proxy does not immediately take the conch, it is
  31454. ** only taken when the first request to lock database file is made.
  31455. ** This matches the semantics of the traditional locking behavior, where
  31456. ** opening a connection to a database file does not take a lock on it.
  31457. ** The shared lock and an open file descriptor are maintained until
  31458. ** the connection to the database is closed.
  31459. **
  31460. ** The proxy file and the lock file are never deleted so they only need
  31461. ** to be created the first time they are used.
  31462. **
  31463. ** Configuration options
  31464. ** ---------------------
  31465. **
  31466. ** SQLITE_PREFER_PROXY_LOCKING
  31467. **
  31468. ** Database files accessed on non-local file systems are
  31469. ** automatically configured for proxy locking, lock files are
  31470. ** named automatically using the same logic as
  31471. ** PRAGMA lock_proxy_file=":auto:"
  31472. **
  31473. ** SQLITE_PROXY_DEBUG
  31474. **
  31475. ** Enables the logging of error messages during host id file
  31476. ** retrieval and creation
  31477. **
  31478. ** LOCKPROXYDIR
  31479. **
  31480. ** Overrides the default directory used for lock proxy files that
  31481. ** are named automatically via the ":auto:" setting
  31482. **
  31483. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  31484. **
  31485. ** Permissions to use when creating a directory for storing the
  31486. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  31487. **
  31488. **
  31489. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  31490. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  31491. ** force proxy locking to be used for every database file opened, and 0
  31492. ** will force automatic proxy locking to be disabled for all database
  31493. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  31494. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  31495. */
  31496. /*
  31497. ** Proxy locking is only available on MacOSX
  31498. */
  31499. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31500. /*
  31501. ** The proxyLockingContext has the path and file structures for the remote
  31502. ** and local proxy files in it
  31503. */
  31504. typedef struct proxyLockingContext proxyLockingContext;
  31505. struct proxyLockingContext {
  31506. unixFile *conchFile; /* Open conch file */
  31507. char *conchFilePath; /* Name of the conch file */
  31508. unixFile *lockProxy; /* Open proxy lock file */
  31509. char *lockProxyPath; /* Name of the proxy lock file */
  31510. char *dbPath; /* Name of the open file */
  31511. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  31512. int nFails; /* Number of conch taking failures */
  31513. void *oldLockingContext; /* Original lockingcontext to restore on close */
  31514. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  31515. };
  31516. /*
  31517. ** The proxy lock file path for the database at dbPath is written into lPath,
  31518. ** which must point to valid, writable memory large enough for a maxLen length
  31519. ** file path.
  31520. */
  31521. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  31522. int len;
  31523. int dbLen;
  31524. int i;
  31525. #ifdef LOCKPROXYDIR
  31526. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  31527. #else
  31528. # ifdef _CS_DARWIN_USER_TEMP_DIR
  31529. {
  31530. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  31531. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  31532. lPath, errno, osGetpid(0)));
  31533. return SQLITE_IOERR_LOCK;
  31534. }
  31535. len = strlcat(lPath, "sqliteplocks", maxLen);
  31536. }
  31537. # else
  31538. len = strlcpy(lPath, "/tmp/", maxLen);
  31539. # endif
  31540. #endif
  31541. if( lPath[len-1]!='/' ){
  31542. len = strlcat(lPath, "/", maxLen);
  31543. }
  31544. /* transform the db path to a unique cache name */
  31545. dbLen = (int)strlen(dbPath);
  31546. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  31547. char c = dbPath[i];
  31548. lPath[i+len] = (c=='/')?'_':c;
  31549. }
  31550. lPath[i+len]='\0';
  31551. strlcat(lPath, ":auto:", maxLen);
  31552. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  31553. return SQLITE_OK;
  31554. }
  31555. /*
  31556. ** Creates the lock file and any missing directories in lockPath
  31557. */
  31558. static int proxyCreateLockPath(const char *lockPath){
  31559. int i, len;
  31560. char buf[MAXPATHLEN];
  31561. int start = 0;
  31562. assert(lockPath!=NULL);
  31563. /* try to create all the intermediate directories */
  31564. len = (int)strlen(lockPath);
  31565. buf[0] = lockPath[0];
  31566. for( i=1; i<len; i++ ){
  31567. if( lockPath[i] == '/' && (i - start > 0) ){
  31568. /* only mkdir if leaf dir != "." or "/" or ".." */
  31569. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  31570. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  31571. buf[i]='\0';
  31572. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  31573. int err=errno;
  31574. if( err!=EEXIST ) {
  31575. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  31576. "'%s' proxy lock path=%s pid=%d\n",
  31577. buf, strerror(err), lockPath, osGetpid(0)));
  31578. return err;
  31579. }
  31580. }
  31581. }
  31582. start=i+1;
  31583. }
  31584. buf[i] = lockPath[i];
  31585. }
  31586. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  31587. return 0;
  31588. }
  31589. /*
  31590. ** Create a new VFS file descriptor (stored in memory obtained from
  31591. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  31592. **
  31593. ** The caller is responsible not only for closing the file descriptor
  31594. ** but also for freeing the memory associated with the file descriptor.
  31595. */
  31596. static int proxyCreateUnixFile(
  31597. const char *path, /* path for the new unixFile */
  31598. unixFile **ppFile, /* unixFile created and returned by ref */
  31599. int islockfile /* if non zero missing dirs will be created */
  31600. ) {
  31601. int fd = -1;
  31602. unixFile *pNew;
  31603. int rc = SQLITE_OK;
  31604. int openFlags = O_RDWR | O_CREAT;
  31605. sqlite3_vfs dummyVfs;
  31606. int terrno = 0;
  31607. UnixUnusedFd *pUnused = NULL;
  31608. /* 1. first try to open/create the file
  31609. ** 2. if that fails, and this is a lock file (not-conch), try creating
  31610. ** the parent directories and then try again.
  31611. ** 3. if that fails, try to open the file read-only
  31612. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  31613. */
  31614. pUnused = findReusableFd(path, openFlags);
  31615. if( pUnused ){
  31616. fd = pUnused->fd;
  31617. }else{
  31618. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  31619. if( !pUnused ){
  31620. return SQLITE_NOMEM;
  31621. }
  31622. }
  31623. if( fd<0 ){
  31624. fd = robust_open(path, openFlags, 0);
  31625. terrno = errno;
  31626. if( fd<0 && errno==ENOENT && islockfile ){
  31627. if( proxyCreateLockPath(path) == SQLITE_OK ){
  31628. fd = robust_open(path, openFlags, 0);
  31629. }
  31630. }
  31631. }
  31632. if( fd<0 ){
  31633. openFlags = O_RDONLY;
  31634. fd = robust_open(path, openFlags, 0);
  31635. terrno = errno;
  31636. }
  31637. if( fd<0 ){
  31638. if( islockfile ){
  31639. return SQLITE_BUSY;
  31640. }
  31641. switch (terrno) {
  31642. case EACCES:
  31643. return SQLITE_PERM;
  31644. case EIO:
  31645. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  31646. default:
  31647. return SQLITE_CANTOPEN_BKPT;
  31648. }
  31649. }
  31650. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  31651. if( pNew==NULL ){
  31652. rc = SQLITE_NOMEM;
  31653. goto end_create_proxy;
  31654. }
  31655. memset(pNew, 0, sizeof(unixFile));
  31656. pNew->openFlags = openFlags;
  31657. memset(&dummyVfs, 0, sizeof(dummyVfs));
  31658. dummyVfs.pAppData = (void*)&autolockIoFinder;
  31659. dummyVfs.zName = "dummy";
  31660. pUnused->fd = fd;
  31661. pUnused->flags = openFlags;
  31662. pNew->pUnused = pUnused;
  31663. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  31664. if( rc==SQLITE_OK ){
  31665. *ppFile = pNew;
  31666. return SQLITE_OK;
  31667. }
  31668. end_create_proxy:
  31669. robust_close(pNew, fd, __LINE__);
  31670. sqlite3_free(pNew);
  31671. sqlite3_free(pUnused);
  31672. return rc;
  31673. }
  31674. #ifdef SQLITE_TEST
  31675. /* simulate multiple hosts by creating unique hostid file paths */
  31676. SQLITE_API int sqlite3_hostid_num = 0;
  31677. #endif
  31678. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  31679. #ifdef HAVE_GETHOSTUUID
  31680. /* Not always defined in the headers as it ought to be */
  31681. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  31682. #endif
  31683. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  31684. ** bytes of writable memory.
  31685. */
  31686. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  31687. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  31688. memset(pHostID, 0, PROXY_HOSTIDLEN);
  31689. #ifdef HAVE_GETHOSTUUID
  31690. {
  31691. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  31692. if( gethostuuid(pHostID, &timeout) ){
  31693. int err = errno;
  31694. if( pError ){
  31695. *pError = err;
  31696. }
  31697. return SQLITE_IOERR;
  31698. }
  31699. }
  31700. #else
  31701. UNUSED_PARAMETER(pError);
  31702. #endif
  31703. #ifdef SQLITE_TEST
  31704. /* simulate multiple hosts by creating unique hostid file paths */
  31705. if( sqlite3_hostid_num != 0){
  31706. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  31707. }
  31708. #endif
  31709. return SQLITE_OK;
  31710. }
  31711. /* The conch file contains the header, host id and lock file path
  31712. */
  31713. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  31714. #define PROXY_HEADERLEN 1 /* conch file header length */
  31715. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  31716. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  31717. /*
  31718. ** Takes an open conch file, copies the contents to a new path and then moves
  31719. ** it back. The newly created file's file descriptor is assigned to the
  31720. ** conch file structure and finally the original conch file descriptor is
  31721. ** closed. Returns zero if successful.
  31722. */
  31723. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  31724. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31725. unixFile *conchFile = pCtx->conchFile;
  31726. char tPath[MAXPATHLEN];
  31727. char buf[PROXY_MAXCONCHLEN];
  31728. char *cPath = pCtx->conchFilePath;
  31729. size_t readLen = 0;
  31730. size_t pathLen = 0;
  31731. char errmsg[64] = "";
  31732. int fd = -1;
  31733. int rc = -1;
  31734. UNUSED_PARAMETER(myHostID);
  31735. /* create a new path by replace the trailing '-conch' with '-break' */
  31736. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  31737. if( pathLen>MAXPATHLEN || pathLen<6 ||
  31738. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  31739. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  31740. goto end_breaklock;
  31741. }
  31742. /* read the conch content */
  31743. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  31744. if( readLen<PROXY_PATHINDEX ){
  31745. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  31746. goto end_breaklock;
  31747. }
  31748. /* write it out to the temporary break file */
  31749. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  31750. if( fd<0 ){
  31751. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  31752. goto end_breaklock;
  31753. }
  31754. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  31755. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  31756. goto end_breaklock;
  31757. }
  31758. if( rename(tPath, cPath) ){
  31759. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  31760. goto end_breaklock;
  31761. }
  31762. rc = 0;
  31763. fprintf(stderr, "broke stale lock on %s\n", cPath);
  31764. robust_close(pFile, conchFile->h, __LINE__);
  31765. conchFile->h = fd;
  31766. conchFile->openFlags = O_RDWR | O_CREAT;
  31767. end_breaklock:
  31768. if( rc ){
  31769. if( fd>=0 ){
  31770. osUnlink(tPath);
  31771. robust_close(pFile, fd, __LINE__);
  31772. }
  31773. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  31774. }
  31775. return rc;
  31776. }
  31777. /* Take the requested lock on the conch file and break a stale lock if the
  31778. ** host id matches.
  31779. */
  31780. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  31781. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31782. unixFile *conchFile = pCtx->conchFile;
  31783. int rc = SQLITE_OK;
  31784. int nTries = 0;
  31785. struct timespec conchModTime;
  31786. memset(&conchModTime, 0, sizeof(conchModTime));
  31787. do {
  31788. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  31789. nTries ++;
  31790. if( rc==SQLITE_BUSY ){
  31791. /* If the lock failed (busy):
  31792. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  31793. * 2nd try: fail if the mod time changed or host id is different, wait
  31794. * 10 sec and try again
  31795. * 3rd try: break the lock unless the mod time has changed.
  31796. */
  31797. struct stat buf;
  31798. if( osFstat(conchFile->h, &buf) ){
  31799. storeLastErrno(pFile, errno);
  31800. return SQLITE_IOERR_LOCK;
  31801. }
  31802. if( nTries==1 ){
  31803. conchModTime = buf.st_mtimespec;
  31804. usleep(500000); /* wait 0.5 sec and try the lock again*/
  31805. continue;
  31806. }
  31807. assert( nTries>1 );
  31808. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  31809. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  31810. return SQLITE_BUSY;
  31811. }
  31812. if( nTries==2 ){
  31813. char tBuf[PROXY_MAXCONCHLEN];
  31814. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  31815. if( len<0 ){
  31816. storeLastErrno(pFile, errno);
  31817. return SQLITE_IOERR_LOCK;
  31818. }
  31819. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  31820. /* don't break the lock if the host id doesn't match */
  31821. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  31822. return SQLITE_BUSY;
  31823. }
  31824. }else{
  31825. /* don't break the lock on short read or a version mismatch */
  31826. return SQLITE_BUSY;
  31827. }
  31828. usleep(10000000); /* wait 10 sec and try the lock again */
  31829. continue;
  31830. }
  31831. assert( nTries==3 );
  31832. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  31833. rc = SQLITE_OK;
  31834. if( lockType==EXCLUSIVE_LOCK ){
  31835. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  31836. }
  31837. if( !rc ){
  31838. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  31839. }
  31840. }
  31841. }
  31842. } while( rc==SQLITE_BUSY && nTries<3 );
  31843. return rc;
  31844. }
  31845. /* Takes the conch by taking a shared lock and read the contents conch, if
  31846. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  31847. ** lockPath means that the lockPath in the conch file will be used if the
  31848. ** host IDs match, or a new lock path will be generated automatically
  31849. ** and written to the conch file.
  31850. */
  31851. static int proxyTakeConch(unixFile *pFile){
  31852. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31853. if( pCtx->conchHeld!=0 ){
  31854. return SQLITE_OK;
  31855. }else{
  31856. unixFile *conchFile = pCtx->conchFile;
  31857. uuid_t myHostID;
  31858. int pError = 0;
  31859. char readBuf[PROXY_MAXCONCHLEN];
  31860. char lockPath[MAXPATHLEN];
  31861. char *tempLockPath = NULL;
  31862. int rc = SQLITE_OK;
  31863. int createConch = 0;
  31864. int hostIdMatch = 0;
  31865. int readLen = 0;
  31866. int tryOldLockPath = 0;
  31867. int forceNewLockPath = 0;
  31868. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  31869. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  31870. osGetpid(0)));
  31871. rc = proxyGetHostID(myHostID, &pError);
  31872. if( (rc&0xff)==SQLITE_IOERR ){
  31873. storeLastErrno(pFile, pError);
  31874. goto end_takeconch;
  31875. }
  31876. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  31877. if( rc!=SQLITE_OK ){
  31878. goto end_takeconch;
  31879. }
  31880. /* read the existing conch file */
  31881. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  31882. if( readLen<0 ){
  31883. /* I/O error: lastErrno set by seekAndRead */
  31884. storeLastErrno(pFile, conchFile->lastErrno);
  31885. rc = SQLITE_IOERR_READ;
  31886. goto end_takeconch;
  31887. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  31888. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  31889. /* a short read or version format mismatch means we need to create a new
  31890. ** conch file.
  31891. */
  31892. createConch = 1;
  31893. }
  31894. /* if the host id matches and the lock path already exists in the conch
  31895. ** we'll try to use the path there, if we can't open that path, we'll
  31896. ** retry with a new auto-generated path
  31897. */
  31898. do { /* in case we need to try again for an :auto: named lock file */
  31899. if( !createConch && !forceNewLockPath ){
  31900. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  31901. PROXY_HOSTIDLEN);
  31902. /* if the conch has data compare the contents */
  31903. if( !pCtx->lockProxyPath ){
  31904. /* for auto-named local lock file, just check the host ID and we'll
  31905. ** use the local lock file path that's already in there
  31906. */
  31907. if( hostIdMatch ){
  31908. size_t pathLen = (readLen - PROXY_PATHINDEX);
  31909. if( pathLen>=MAXPATHLEN ){
  31910. pathLen=MAXPATHLEN-1;
  31911. }
  31912. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  31913. lockPath[pathLen] = 0;
  31914. tempLockPath = lockPath;
  31915. tryOldLockPath = 1;
  31916. /* create a copy of the lock path if the conch is taken */
  31917. goto end_takeconch;
  31918. }
  31919. }else if( hostIdMatch
  31920. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  31921. readLen-PROXY_PATHINDEX)
  31922. ){
  31923. /* conch host and lock path match */
  31924. goto end_takeconch;
  31925. }
  31926. }
  31927. /* if the conch isn't writable and doesn't match, we can't take it */
  31928. if( (conchFile->openFlags&O_RDWR) == 0 ){
  31929. rc = SQLITE_BUSY;
  31930. goto end_takeconch;
  31931. }
  31932. /* either the conch didn't match or we need to create a new one */
  31933. if( !pCtx->lockProxyPath ){
  31934. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  31935. tempLockPath = lockPath;
  31936. /* create a copy of the lock path _only_ if the conch is taken */
  31937. }
  31938. /* update conch with host and path (this will fail if other process
  31939. ** has a shared lock already), if the host id matches, use the big
  31940. ** stick.
  31941. */
  31942. futimes(conchFile->h, NULL);
  31943. if( hostIdMatch && !createConch ){
  31944. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  31945. /* We are trying for an exclusive lock but another thread in this
  31946. ** same process is still holding a shared lock. */
  31947. rc = SQLITE_BUSY;
  31948. } else {
  31949. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  31950. }
  31951. }else{
  31952. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  31953. }
  31954. if( rc==SQLITE_OK ){
  31955. char writeBuffer[PROXY_MAXCONCHLEN];
  31956. int writeSize = 0;
  31957. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  31958. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  31959. if( pCtx->lockProxyPath!=NULL ){
  31960. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  31961. MAXPATHLEN);
  31962. }else{
  31963. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  31964. }
  31965. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  31966. robust_ftruncate(conchFile->h, writeSize);
  31967. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  31968. fsync(conchFile->h);
  31969. /* If we created a new conch file (not just updated the contents of a
  31970. ** valid conch file), try to match the permissions of the database
  31971. */
  31972. if( rc==SQLITE_OK && createConch ){
  31973. struct stat buf;
  31974. int err = osFstat(pFile->h, &buf);
  31975. if( err==0 ){
  31976. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  31977. S_IROTH|S_IWOTH);
  31978. /* try to match the database file R/W permissions, ignore failure */
  31979. #ifndef SQLITE_PROXY_DEBUG
  31980. osFchmod(conchFile->h, cmode);
  31981. #else
  31982. do{
  31983. rc = osFchmod(conchFile->h, cmode);
  31984. }while( rc==(-1) && errno==EINTR );
  31985. if( rc!=0 ){
  31986. int code = errno;
  31987. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  31988. cmode, code, strerror(code));
  31989. } else {
  31990. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  31991. }
  31992. }else{
  31993. int code = errno;
  31994. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  31995. err, code, strerror(code));
  31996. #endif
  31997. }
  31998. }
  31999. }
  32000. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  32001. end_takeconch:
  32002. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  32003. if( rc==SQLITE_OK && pFile->openFlags ){
  32004. int fd;
  32005. if( pFile->h>=0 ){
  32006. robust_close(pFile, pFile->h, __LINE__);
  32007. }
  32008. pFile->h = -1;
  32009. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  32010. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  32011. if( fd>=0 ){
  32012. pFile->h = fd;
  32013. }else{
  32014. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  32015. during locking */
  32016. }
  32017. }
  32018. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  32019. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  32020. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  32021. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  32022. /* we couldn't create the proxy lock file with the old lock file path
  32023. ** so try again via auto-naming
  32024. */
  32025. forceNewLockPath = 1;
  32026. tryOldLockPath = 0;
  32027. continue; /* go back to the do {} while start point, try again */
  32028. }
  32029. }
  32030. if( rc==SQLITE_OK ){
  32031. /* Need to make a copy of path if we extracted the value
  32032. ** from the conch file or the path was allocated on the stack
  32033. */
  32034. if( tempLockPath ){
  32035. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  32036. if( !pCtx->lockProxyPath ){
  32037. rc = SQLITE_NOMEM;
  32038. }
  32039. }
  32040. }
  32041. if( rc==SQLITE_OK ){
  32042. pCtx->conchHeld = 1;
  32043. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  32044. afpLockingContext *afpCtx;
  32045. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  32046. afpCtx->dbPath = pCtx->lockProxyPath;
  32047. }
  32048. } else {
  32049. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  32050. }
  32051. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  32052. rc==SQLITE_OK?"ok":"failed"));
  32053. return rc;
  32054. } while (1); /* in case we need to retry the :auto: lock file -
  32055. ** we should never get here except via the 'continue' call. */
  32056. }
  32057. }
  32058. /*
  32059. ** If pFile holds a lock on a conch file, then release that lock.
  32060. */
  32061. static int proxyReleaseConch(unixFile *pFile){
  32062. int rc = SQLITE_OK; /* Subroutine return code */
  32063. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  32064. unixFile *conchFile; /* Name of the conch file */
  32065. pCtx = (proxyLockingContext *)pFile->lockingContext;
  32066. conchFile = pCtx->conchFile;
  32067. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  32068. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  32069. osGetpid(0)));
  32070. if( pCtx->conchHeld>0 ){
  32071. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  32072. }
  32073. pCtx->conchHeld = 0;
  32074. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  32075. (rc==SQLITE_OK ? "ok" : "failed")));
  32076. return rc;
  32077. }
  32078. /*
  32079. ** Given the name of a database file, compute the name of its conch file.
  32080. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  32081. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  32082. ** or SQLITE_NOMEM if unable to obtain memory.
  32083. **
  32084. ** The caller is responsible for ensuring that the allocated memory
  32085. ** space is eventually freed.
  32086. **
  32087. ** *pConchPath is set to NULL if a memory allocation error occurs.
  32088. */
  32089. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  32090. int i; /* Loop counter */
  32091. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  32092. char *conchPath; /* buffer in which to construct conch name */
  32093. /* Allocate space for the conch filename and initialize the name to
  32094. ** the name of the original database file. */
  32095. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  32096. if( conchPath==0 ){
  32097. return SQLITE_NOMEM;
  32098. }
  32099. memcpy(conchPath, dbPath, len+1);
  32100. /* now insert a "." before the last / character */
  32101. for( i=(len-1); i>=0; i-- ){
  32102. if( conchPath[i]=='/' ){
  32103. i++;
  32104. break;
  32105. }
  32106. }
  32107. conchPath[i]='.';
  32108. while ( i<len ){
  32109. conchPath[i+1]=dbPath[i];
  32110. i++;
  32111. }
  32112. /* append the "-conch" suffix to the file */
  32113. memcpy(&conchPath[i+1], "-conch", 7);
  32114. assert( (int)strlen(conchPath) == len+7 );
  32115. return SQLITE_OK;
  32116. }
  32117. /* Takes a fully configured proxy locking-style unix file and switches
  32118. ** the local lock file path
  32119. */
  32120. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  32121. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  32122. char *oldPath = pCtx->lockProxyPath;
  32123. int rc = SQLITE_OK;
  32124. if( pFile->eFileLock!=NO_LOCK ){
  32125. return SQLITE_BUSY;
  32126. }
  32127. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  32128. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  32129. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  32130. return SQLITE_OK;
  32131. }else{
  32132. unixFile *lockProxy = pCtx->lockProxy;
  32133. pCtx->lockProxy=NULL;
  32134. pCtx->conchHeld = 0;
  32135. if( lockProxy!=NULL ){
  32136. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  32137. if( rc ) return rc;
  32138. sqlite3_free(lockProxy);
  32139. }
  32140. sqlite3_free(oldPath);
  32141. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  32142. }
  32143. return rc;
  32144. }
  32145. /*
  32146. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  32147. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  32148. **
  32149. ** This routine find the filename associated with pFile and writes it
  32150. ** int dbPath.
  32151. */
  32152. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  32153. #if defined(__APPLE__)
  32154. if( pFile->pMethod == &afpIoMethods ){
  32155. /* afp style keeps a reference to the db path in the filePath field
  32156. ** of the struct */
  32157. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  32158. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  32159. MAXPATHLEN);
  32160. } else
  32161. #endif
  32162. if( pFile->pMethod == &dotlockIoMethods ){
  32163. /* dot lock style uses the locking context to store the dot lock
  32164. ** file path */
  32165. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  32166. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  32167. }else{
  32168. /* all other styles use the locking context to store the db file path */
  32169. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  32170. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  32171. }
  32172. return SQLITE_OK;
  32173. }
  32174. /*
  32175. ** Takes an already filled in unix file and alters it so all file locking
  32176. ** will be performed on the local proxy lock file. The following fields
  32177. ** are preserved in the locking context so that they can be restored and
  32178. ** the unix structure properly cleaned up at close time:
  32179. ** ->lockingContext
  32180. ** ->pMethod
  32181. */
  32182. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  32183. proxyLockingContext *pCtx;
  32184. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  32185. char *lockPath=NULL;
  32186. int rc = SQLITE_OK;
  32187. if( pFile->eFileLock!=NO_LOCK ){
  32188. return SQLITE_BUSY;
  32189. }
  32190. proxyGetDbPathForUnixFile(pFile, dbPath);
  32191. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  32192. lockPath=NULL;
  32193. }else{
  32194. lockPath=(char *)path;
  32195. }
  32196. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  32197. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  32198. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  32199. if( pCtx==0 ){
  32200. return SQLITE_NOMEM;
  32201. }
  32202. memset(pCtx, 0, sizeof(*pCtx));
  32203. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  32204. if( rc==SQLITE_OK ){
  32205. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  32206. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  32207. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  32208. ** (c) the file system is read-only, then enable no-locking access.
  32209. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  32210. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  32211. */
  32212. struct statfs fsInfo;
  32213. struct stat conchInfo;
  32214. int goLockless = 0;
  32215. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  32216. int err = errno;
  32217. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  32218. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  32219. }
  32220. }
  32221. if( goLockless ){
  32222. pCtx->conchHeld = -1; /* read only FS/ lockless */
  32223. rc = SQLITE_OK;
  32224. }
  32225. }
  32226. }
  32227. if( rc==SQLITE_OK && lockPath ){
  32228. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  32229. }
  32230. if( rc==SQLITE_OK ){
  32231. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  32232. if( pCtx->dbPath==NULL ){
  32233. rc = SQLITE_NOMEM;
  32234. }
  32235. }
  32236. if( rc==SQLITE_OK ){
  32237. /* all memory is allocated, proxys are created and assigned,
  32238. ** switch the locking context and pMethod then return.
  32239. */
  32240. pCtx->oldLockingContext = pFile->lockingContext;
  32241. pFile->lockingContext = pCtx;
  32242. pCtx->pOldMethod = pFile->pMethod;
  32243. pFile->pMethod = &proxyIoMethods;
  32244. }else{
  32245. if( pCtx->conchFile ){
  32246. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  32247. sqlite3_free(pCtx->conchFile);
  32248. }
  32249. sqlite3DbFree(0, pCtx->lockProxyPath);
  32250. sqlite3_free(pCtx->conchFilePath);
  32251. sqlite3_free(pCtx);
  32252. }
  32253. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  32254. (rc==SQLITE_OK ? "ok" : "failed")));
  32255. return rc;
  32256. }
  32257. /*
  32258. ** This routine handles sqlite3_file_control() calls that are specific
  32259. ** to proxy locking.
  32260. */
  32261. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  32262. switch( op ){
  32263. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  32264. unixFile *pFile = (unixFile*)id;
  32265. if( pFile->pMethod == &proxyIoMethods ){
  32266. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  32267. proxyTakeConch(pFile);
  32268. if( pCtx->lockProxyPath ){
  32269. *(const char **)pArg = pCtx->lockProxyPath;
  32270. }else{
  32271. *(const char **)pArg = ":auto: (not held)";
  32272. }
  32273. } else {
  32274. *(const char **)pArg = NULL;
  32275. }
  32276. return SQLITE_OK;
  32277. }
  32278. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  32279. unixFile *pFile = (unixFile*)id;
  32280. int rc = SQLITE_OK;
  32281. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  32282. if( pArg==NULL || (const char *)pArg==0 ){
  32283. if( isProxyStyle ){
  32284. /* turn off proxy locking - not supported. If support is added for
  32285. ** switching proxy locking mode off then it will need to fail if
  32286. ** the journal mode is WAL mode.
  32287. */
  32288. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  32289. }else{
  32290. /* turn off proxy locking - already off - NOOP */
  32291. rc = SQLITE_OK;
  32292. }
  32293. }else{
  32294. const char *proxyPath = (const char *)pArg;
  32295. if( isProxyStyle ){
  32296. proxyLockingContext *pCtx =
  32297. (proxyLockingContext*)pFile->lockingContext;
  32298. if( !strcmp(pArg, ":auto:")
  32299. || (pCtx->lockProxyPath &&
  32300. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  32301. ){
  32302. rc = SQLITE_OK;
  32303. }else{
  32304. rc = switchLockProxyPath(pFile, proxyPath);
  32305. }
  32306. }else{
  32307. /* turn on proxy file locking */
  32308. rc = proxyTransformUnixFile(pFile, proxyPath);
  32309. }
  32310. }
  32311. return rc;
  32312. }
  32313. default: {
  32314. assert( 0 ); /* The call assures that only valid opcodes are sent */
  32315. }
  32316. }
  32317. /*NOTREACHED*/
  32318. return SQLITE_ERROR;
  32319. }
  32320. /*
  32321. ** Within this division (the proxying locking implementation) the procedures
  32322. ** above this point are all utilities. The lock-related methods of the
  32323. ** proxy-locking sqlite3_io_method object follow.
  32324. */
  32325. /*
  32326. ** This routine checks if there is a RESERVED lock held on the specified
  32327. ** file by this or any other process. If such a lock is held, set *pResOut
  32328. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32329. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32330. */
  32331. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  32332. unixFile *pFile = (unixFile*)id;
  32333. int rc = proxyTakeConch(pFile);
  32334. if( rc==SQLITE_OK ){
  32335. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32336. if( pCtx->conchHeld>0 ){
  32337. unixFile *proxy = pCtx->lockProxy;
  32338. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  32339. }else{ /* conchHeld < 0 is lockless */
  32340. pResOut=0;
  32341. }
  32342. }
  32343. return rc;
  32344. }
  32345. /*
  32346. ** Lock the file with the lock specified by parameter eFileLock - one
  32347. ** of the following:
  32348. **
  32349. ** (1) SHARED_LOCK
  32350. ** (2) RESERVED_LOCK
  32351. ** (3) PENDING_LOCK
  32352. ** (4) EXCLUSIVE_LOCK
  32353. **
  32354. ** Sometimes when requesting one lock state, additional lock states
  32355. ** are inserted in between. The locking might fail on one of the later
  32356. ** transitions leaving the lock state different from what it started but
  32357. ** still short of its goal. The following chart shows the allowed
  32358. ** transitions and the inserted intermediate states:
  32359. **
  32360. ** UNLOCKED -> SHARED
  32361. ** SHARED -> RESERVED
  32362. ** SHARED -> (PENDING) -> EXCLUSIVE
  32363. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32364. ** PENDING -> EXCLUSIVE
  32365. **
  32366. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32367. ** routine to lower a locking level.
  32368. */
  32369. static int proxyLock(sqlite3_file *id, int eFileLock) {
  32370. unixFile *pFile = (unixFile*)id;
  32371. int rc = proxyTakeConch(pFile);
  32372. if( rc==SQLITE_OK ){
  32373. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32374. if( pCtx->conchHeld>0 ){
  32375. unixFile *proxy = pCtx->lockProxy;
  32376. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  32377. pFile->eFileLock = proxy->eFileLock;
  32378. }else{
  32379. /* conchHeld < 0 is lockless */
  32380. }
  32381. }
  32382. return rc;
  32383. }
  32384. /*
  32385. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32386. ** must be either NO_LOCK or SHARED_LOCK.
  32387. **
  32388. ** If the locking level of the file descriptor is already at or below
  32389. ** the requested locking level, this routine is a no-op.
  32390. */
  32391. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  32392. unixFile *pFile = (unixFile*)id;
  32393. int rc = proxyTakeConch(pFile);
  32394. if( rc==SQLITE_OK ){
  32395. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32396. if( pCtx->conchHeld>0 ){
  32397. unixFile *proxy = pCtx->lockProxy;
  32398. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  32399. pFile->eFileLock = proxy->eFileLock;
  32400. }else{
  32401. /* conchHeld < 0 is lockless */
  32402. }
  32403. }
  32404. return rc;
  32405. }
  32406. /*
  32407. ** Close a file that uses proxy locks.
  32408. */
  32409. static int proxyClose(sqlite3_file *id) {
  32410. if( ALWAYS(id) ){
  32411. unixFile *pFile = (unixFile*)id;
  32412. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  32413. unixFile *lockProxy = pCtx->lockProxy;
  32414. unixFile *conchFile = pCtx->conchFile;
  32415. int rc = SQLITE_OK;
  32416. if( lockProxy ){
  32417. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  32418. if( rc ) return rc;
  32419. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  32420. if( rc ) return rc;
  32421. sqlite3_free(lockProxy);
  32422. pCtx->lockProxy = 0;
  32423. }
  32424. if( conchFile ){
  32425. if( pCtx->conchHeld ){
  32426. rc = proxyReleaseConch(pFile);
  32427. if( rc ) return rc;
  32428. }
  32429. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  32430. if( rc ) return rc;
  32431. sqlite3_free(conchFile);
  32432. }
  32433. sqlite3DbFree(0, pCtx->lockProxyPath);
  32434. sqlite3_free(pCtx->conchFilePath);
  32435. sqlite3DbFree(0, pCtx->dbPath);
  32436. /* restore the original locking context and pMethod then close it */
  32437. pFile->lockingContext = pCtx->oldLockingContext;
  32438. pFile->pMethod = pCtx->pOldMethod;
  32439. sqlite3_free(pCtx);
  32440. return pFile->pMethod->xClose(id);
  32441. }
  32442. return SQLITE_OK;
  32443. }
  32444. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32445. /*
  32446. ** The proxy locking style is intended for use with AFP filesystems.
  32447. ** And since AFP is only supported on MacOSX, the proxy locking is also
  32448. ** restricted to MacOSX.
  32449. **
  32450. **
  32451. ******************* End of the proxy lock implementation **********************
  32452. ******************************************************************************/
  32453. /*
  32454. ** Initialize the operating system interface.
  32455. **
  32456. ** This routine registers all VFS implementations for unix-like operating
  32457. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  32458. ** should be the only routines in this file that are visible from other
  32459. ** files.
  32460. **
  32461. ** This routine is called once during SQLite initialization and by a
  32462. ** single thread. The memory allocation and mutex subsystems have not
  32463. ** necessarily been initialized when this routine is called, and so they
  32464. ** should not be used.
  32465. */
  32466. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  32467. /*
  32468. ** The following macro defines an initializer for an sqlite3_vfs object.
  32469. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  32470. ** to the "finder" function. (pAppData is a pointer to a pointer because
  32471. ** silly C90 rules prohibit a void* from being cast to a function pointer
  32472. ** and so we have to go through the intermediate pointer to avoid problems
  32473. ** when compiling with -pedantic-errors on GCC.)
  32474. **
  32475. ** The FINDER parameter to this macro is the name of the pointer to the
  32476. ** finder-function. The finder-function returns a pointer to the
  32477. ** sqlite_io_methods object that implements the desired locking
  32478. ** behaviors. See the division above that contains the IOMETHODS
  32479. ** macro for addition information on finder-functions.
  32480. **
  32481. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  32482. ** object. But the "autolockIoFinder" available on MacOSX does a little
  32483. ** more than that; it looks at the filesystem type that hosts the
  32484. ** database file and tries to choose an locking method appropriate for
  32485. ** that filesystem time.
  32486. */
  32487. #define UNIXVFS(VFSNAME, FINDER) { \
  32488. 3, /* iVersion */ \
  32489. sizeof(unixFile), /* szOsFile */ \
  32490. MAX_PATHNAME, /* mxPathname */ \
  32491. 0, /* pNext */ \
  32492. VFSNAME, /* zName */ \
  32493. (void*)&FINDER, /* pAppData */ \
  32494. unixOpen, /* xOpen */ \
  32495. unixDelete, /* xDelete */ \
  32496. unixAccess, /* xAccess */ \
  32497. unixFullPathname, /* xFullPathname */ \
  32498. unixDlOpen, /* xDlOpen */ \
  32499. unixDlError, /* xDlError */ \
  32500. unixDlSym, /* xDlSym */ \
  32501. unixDlClose, /* xDlClose */ \
  32502. unixRandomness, /* xRandomness */ \
  32503. unixSleep, /* xSleep */ \
  32504. unixCurrentTime, /* xCurrentTime */ \
  32505. unixGetLastError, /* xGetLastError */ \
  32506. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  32507. unixSetSystemCall, /* xSetSystemCall */ \
  32508. unixGetSystemCall, /* xGetSystemCall */ \
  32509. unixNextSystemCall, /* xNextSystemCall */ \
  32510. }
  32511. /*
  32512. ** All default VFSes for unix are contained in the following array.
  32513. **
  32514. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  32515. ** by the SQLite core when the VFS is registered. So the following
  32516. ** array cannot be const.
  32517. */
  32518. static sqlite3_vfs aVfs[] = {
  32519. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  32520. UNIXVFS("unix", autolockIoFinder ),
  32521. #elif OS_VXWORKS
  32522. UNIXVFS("unix", vxworksIoFinder ),
  32523. #else
  32524. UNIXVFS("unix", posixIoFinder ),
  32525. #endif
  32526. UNIXVFS("unix-none", nolockIoFinder ),
  32527. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  32528. UNIXVFS("unix-excl", posixIoFinder ),
  32529. #if OS_VXWORKS
  32530. UNIXVFS("unix-namedsem", semIoFinder ),
  32531. #endif
  32532. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  32533. UNIXVFS("unix-posix", posixIoFinder ),
  32534. #endif
  32535. #if SQLITE_ENABLE_LOCKING_STYLE
  32536. UNIXVFS("unix-flock", flockIoFinder ),
  32537. #endif
  32538. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  32539. UNIXVFS("unix-afp", afpIoFinder ),
  32540. UNIXVFS("unix-nfs", nfsIoFinder ),
  32541. UNIXVFS("unix-proxy", proxyIoFinder ),
  32542. #endif
  32543. };
  32544. unsigned int i; /* Loop counter */
  32545. /* Double-check that the aSyscall[] array has been constructed
  32546. ** correctly. See ticket [bb3a86e890c8e96ab] */
  32547. assert( ArraySize(aSyscall)==27 );
  32548. /* Register all VFSes defined in the aVfs[] array */
  32549. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  32550. sqlite3_vfs_register(&aVfs[i], i==0);
  32551. }
  32552. return SQLITE_OK;
  32553. }
  32554. /*
  32555. ** Shutdown the operating system interface.
  32556. **
  32557. ** Some operating systems might need to do some cleanup in this routine,
  32558. ** to release dynamically allocated objects. But not on unix.
  32559. ** This routine is a no-op for unix.
  32560. */
  32561. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  32562. return SQLITE_OK;
  32563. }
  32564. #endif /* SQLITE_OS_UNIX */
  32565. /************** End of os_unix.c *********************************************/
  32566. /************** Begin file os_win.c ******************************************/
  32567. /*
  32568. ** 2004 May 22
  32569. **
  32570. ** The author disclaims copyright to this source code. In place of
  32571. ** a legal notice, here is a blessing:
  32572. **
  32573. ** May you do good and not evil.
  32574. ** May you find forgiveness for yourself and forgive others.
  32575. ** May you share freely, never taking more than you give.
  32576. **
  32577. ******************************************************************************
  32578. **
  32579. ** This file contains code that is specific to Windows.
  32580. */
  32581. /* #include "sqliteInt.h" */
  32582. #if SQLITE_OS_WIN /* This file is used for Windows only */
  32583. /*
  32584. ** Include code that is common to all os_*.c files
  32585. */
  32586. /************** Include os_common.h in the middle of os_win.c ****************/
  32587. /************** Begin file os_common.h ***************************************/
  32588. /*
  32589. ** 2004 May 22
  32590. **
  32591. ** The author disclaims copyright to this source code. In place of
  32592. ** a legal notice, here is a blessing:
  32593. **
  32594. ** May you do good and not evil.
  32595. ** May you find forgiveness for yourself and forgive others.
  32596. ** May you share freely, never taking more than you give.
  32597. **
  32598. ******************************************************************************
  32599. **
  32600. ** This file contains macros and a little bit of code that is common to
  32601. ** all of the platform-specific files (os_*.c) and is #included into those
  32602. ** files.
  32603. **
  32604. ** This file should be #included by the os_*.c files only. It is not a
  32605. ** general purpose header file.
  32606. */
  32607. #ifndef _OS_COMMON_H_
  32608. #define _OS_COMMON_H_
  32609. /*
  32610. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  32611. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  32612. ** switch. The following code should catch this problem at compile-time.
  32613. */
  32614. #ifdef MEMORY_DEBUG
  32615. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  32616. #endif
  32617. /*
  32618. ** Macros for performance tracing. Normally turned off. Only works
  32619. ** on i486 hardware.
  32620. */
  32621. #ifdef SQLITE_PERFORMANCE_TRACE
  32622. /*
  32623. ** hwtime.h contains inline assembler code for implementing
  32624. ** high-performance timing routines.
  32625. */
  32626. /************** Include hwtime.h in the middle of os_common.h ****************/
  32627. /************** Begin file hwtime.h ******************************************/
  32628. /*
  32629. ** 2008 May 27
  32630. **
  32631. ** The author disclaims copyright to this source code. In place of
  32632. ** a legal notice, here is a blessing:
  32633. **
  32634. ** May you do good and not evil.
  32635. ** May you find forgiveness for yourself and forgive others.
  32636. ** May you share freely, never taking more than you give.
  32637. **
  32638. ******************************************************************************
  32639. **
  32640. ** This file contains inline asm code for retrieving "high-performance"
  32641. ** counters for x86 class CPUs.
  32642. */
  32643. #ifndef _HWTIME_H_
  32644. #define _HWTIME_H_
  32645. /*
  32646. ** The following routine only works on pentium-class (or newer) processors.
  32647. ** It uses the RDTSC opcode to read the cycle count value out of the
  32648. ** processor and returns that value. This can be used for high-res
  32649. ** profiling.
  32650. */
  32651. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  32652. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  32653. #if defined(__GNUC__)
  32654. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32655. unsigned int lo, hi;
  32656. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  32657. return (sqlite_uint64)hi << 32 | lo;
  32658. }
  32659. #elif defined(_MSC_VER)
  32660. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  32661. __asm {
  32662. rdtsc
  32663. ret ; return value at EDX:EAX
  32664. }
  32665. }
  32666. #endif
  32667. #elif (defined(__GNUC__) && defined(__x86_64__))
  32668. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32669. unsigned long val;
  32670. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  32671. return val;
  32672. }
  32673. #elif (defined(__GNUC__) && defined(__ppc__))
  32674. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32675. unsigned long long retval;
  32676. unsigned long junk;
  32677. __asm__ __volatile__ ("\n\
  32678. 1: mftbu %1\n\
  32679. mftb %L0\n\
  32680. mftbu %0\n\
  32681. cmpw %0,%1\n\
  32682. bne 1b"
  32683. : "=r" (retval), "=r" (junk));
  32684. return retval;
  32685. }
  32686. #else
  32687. #error Need implementation of sqlite3Hwtime() for your platform.
  32688. /*
  32689. ** To compile without implementing sqlite3Hwtime() for your platform,
  32690. ** you can remove the above #error and use the following
  32691. ** stub function. You will lose timing support for many
  32692. ** of the debugging and testing utilities, but it should at
  32693. ** least compile and run.
  32694. */
  32695. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  32696. #endif
  32697. #endif /* !defined(_HWTIME_H_) */
  32698. /************** End of hwtime.h **********************************************/
  32699. /************** Continuing where we left off in os_common.h ******************/
  32700. static sqlite_uint64 g_start;
  32701. static sqlite_uint64 g_elapsed;
  32702. #define TIMER_START g_start=sqlite3Hwtime()
  32703. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  32704. #define TIMER_ELAPSED g_elapsed
  32705. #else
  32706. #define TIMER_START
  32707. #define TIMER_END
  32708. #define TIMER_ELAPSED ((sqlite_uint64)0)
  32709. #endif
  32710. /*
  32711. ** If we compile with the SQLITE_TEST macro set, then the following block
  32712. ** of code will give us the ability to simulate a disk I/O error. This
  32713. ** is used for testing the I/O recovery logic.
  32714. */
  32715. #ifdef SQLITE_TEST
  32716. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  32717. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  32718. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  32719. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  32720. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  32721. SQLITE_API int sqlite3_diskfull_pending = 0;
  32722. SQLITE_API int sqlite3_diskfull = 0;
  32723. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  32724. #define SimulateIOError(CODE) \
  32725. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  32726. || sqlite3_io_error_pending-- == 1 ) \
  32727. { local_ioerr(); CODE; }
  32728. static void local_ioerr(){
  32729. IOTRACE(("IOERR\n"));
  32730. sqlite3_io_error_hit++;
  32731. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  32732. }
  32733. #define SimulateDiskfullError(CODE) \
  32734. if( sqlite3_diskfull_pending ){ \
  32735. if( sqlite3_diskfull_pending == 1 ){ \
  32736. local_ioerr(); \
  32737. sqlite3_diskfull = 1; \
  32738. sqlite3_io_error_hit = 1; \
  32739. CODE; \
  32740. }else{ \
  32741. sqlite3_diskfull_pending--; \
  32742. } \
  32743. }
  32744. #else
  32745. #define SimulateIOErrorBenign(X)
  32746. #define SimulateIOError(A)
  32747. #define SimulateDiskfullError(A)
  32748. #endif
  32749. /*
  32750. ** When testing, keep a count of the number of open files.
  32751. */
  32752. #ifdef SQLITE_TEST
  32753. SQLITE_API int sqlite3_open_file_count = 0;
  32754. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  32755. #else
  32756. #define OpenCounter(X)
  32757. #endif
  32758. #endif /* !defined(_OS_COMMON_H_) */
  32759. /************** End of os_common.h *******************************************/
  32760. /************** Continuing where we left off in os_win.c *********************/
  32761. /*
  32762. ** Include the header file for the Windows VFS.
  32763. */
  32764. /* #include "os_win.h" */
  32765. /*
  32766. ** Compiling and using WAL mode requires several APIs that are only
  32767. ** available in Windows platforms based on the NT kernel.
  32768. */
  32769. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  32770. # error "WAL mode requires support from the Windows NT kernel, compile\
  32771. with SQLITE_OMIT_WAL."
  32772. #endif
  32773. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  32774. # error "Memory mapped files require support from the Windows NT kernel,\
  32775. compile with SQLITE_MAX_MMAP_SIZE=0."
  32776. #endif
  32777. /*
  32778. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  32779. ** based on the sub-platform)?
  32780. */
  32781. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  32782. # define SQLITE_WIN32_HAS_ANSI
  32783. #endif
  32784. /*
  32785. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  32786. ** based on the sub-platform)?
  32787. */
  32788. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  32789. !defined(SQLITE_WIN32_NO_WIDE)
  32790. # define SQLITE_WIN32_HAS_WIDE
  32791. #endif
  32792. /*
  32793. ** Make sure at least one set of Win32 APIs is available.
  32794. */
  32795. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  32796. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  32797. must be defined."
  32798. #endif
  32799. /*
  32800. ** Define the required Windows SDK version constants if they are not
  32801. ** already available.
  32802. */
  32803. #ifndef NTDDI_WIN8
  32804. # define NTDDI_WIN8 0x06020000
  32805. #endif
  32806. #ifndef NTDDI_WINBLUE
  32807. # define NTDDI_WINBLUE 0x06030000
  32808. #endif
  32809. /*
  32810. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  32811. ** target system. GetVersionEx was first deprecated in Win8.1.
  32812. */
  32813. #ifndef SQLITE_WIN32_GETVERSIONEX
  32814. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  32815. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  32816. # else
  32817. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  32818. # endif
  32819. #endif
  32820. /*
  32821. ** This constant should already be defined (in the "WinDef.h" SDK file).
  32822. */
  32823. #ifndef MAX_PATH
  32824. # define MAX_PATH (260)
  32825. #endif
  32826. /*
  32827. ** Maximum pathname length (in chars) for Win32. This should normally be
  32828. ** MAX_PATH.
  32829. */
  32830. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  32831. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  32832. #endif
  32833. /*
  32834. ** This constant should already be defined (in the "WinNT.h" SDK file).
  32835. */
  32836. #ifndef UNICODE_STRING_MAX_CHARS
  32837. # define UNICODE_STRING_MAX_CHARS (32767)
  32838. #endif
  32839. /*
  32840. ** Maximum pathname length (in chars) for WinNT. This should normally be
  32841. ** UNICODE_STRING_MAX_CHARS.
  32842. */
  32843. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  32844. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  32845. #endif
  32846. /*
  32847. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  32848. ** characters, so we allocate 4 bytes per character assuming worst-case of
  32849. ** 4-bytes-per-character for UTF8.
  32850. */
  32851. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  32852. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  32853. #endif
  32854. /*
  32855. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  32856. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  32857. */
  32858. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  32859. # define SQLITE_WINNT_MAX_PATH_BYTES \
  32860. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  32861. #endif
  32862. /*
  32863. ** Maximum error message length (in chars) for WinRT.
  32864. */
  32865. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  32866. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  32867. #endif
  32868. /*
  32869. ** Returns non-zero if the character should be treated as a directory
  32870. ** separator.
  32871. */
  32872. #ifndef winIsDirSep
  32873. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  32874. #endif
  32875. /*
  32876. ** This macro is used when a local variable is set to a value that is
  32877. ** [sometimes] not used by the code (e.g. via conditional compilation).
  32878. */
  32879. #ifndef UNUSED_VARIABLE_VALUE
  32880. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  32881. #endif
  32882. /*
  32883. ** Returns the character that should be used as the directory separator.
  32884. */
  32885. #ifndef winGetDirSep
  32886. # define winGetDirSep() '\\'
  32887. #endif
  32888. /*
  32889. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  32890. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  32891. ** CE SDK; however, they are not present in the header file)?
  32892. */
  32893. #if SQLITE_WIN32_FILEMAPPING_API && \
  32894. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  32895. /*
  32896. ** Two of the file mapping APIs are different under WinRT. Figure out which
  32897. ** set we need.
  32898. */
  32899. #if SQLITE_OS_WINRT
  32900. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  32901. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  32902. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  32903. #else
  32904. #if defined(SQLITE_WIN32_HAS_ANSI)
  32905. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  32906. DWORD, DWORD, DWORD, LPCSTR);
  32907. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  32908. #if defined(SQLITE_WIN32_HAS_WIDE)
  32909. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  32910. DWORD, DWORD, DWORD, LPCWSTR);
  32911. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  32912. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  32913. #endif /* SQLITE_OS_WINRT */
  32914. /*
  32915. ** These file mapping APIs are common to both Win32 and WinRT.
  32916. */
  32917. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  32918. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  32919. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  32920. /*
  32921. ** Some Microsoft compilers lack this definition.
  32922. */
  32923. #ifndef INVALID_FILE_ATTRIBUTES
  32924. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  32925. #endif
  32926. #ifndef FILE_FLAG_MASK
  32927. # define FILE_FLAG_MASK (0xFF3C0000)
  32928. #endif
  32929. #ifndef FILE_ATTRIBUTE_MASK
  32930. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  32931. #endif
  32932. #ifndef SQLITE_OMIT_WAL
  32933. /* Forward references to structures used for WAL */
  32934. typedef struct winShm winShm; /* A connection to shared-memory */
  32935. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  32936. #endif
  32937. /*
  32938. ** WinCE lacks native support for file locking so we have to fake it
  32939. ** with some code of our own.
  32940. */
  32941. #if SQLITE_OS_WINCE
  32942. typedef struct winceLock {
  32943. int nReaders; /* Number of reader locks obtained */
  32944. BOOL bPending; /* Indicates a pending lock has been obtained */
  32945. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  32946. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  32947. } winceLock;
  32948. #endif
  32949. /*
  32950. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  32951. ** portability layer.
  32952. */
  32953. typedef struct winFile winFile;
  32954. struct winFile {
  32955. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  32956. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  32957. HANDLE h; /* Handle for accessing the file */
  32958. u8 locktype; /* Type of lock currently held on this file */
  32959. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  32960. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  32961. DWORD lastErrno; /* The Windows errno from the last I/O error */
  32962. #ifndef SQLITE_OMIT_WAL
  32963. winShm *pShm; /* Instance of shared memory on this file */
  32964. #endif
  32965. const char *zPath; /* Full pathname of this file */
  32966. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  32967. #if SQLITE_OS_WINCE
  32968. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  32969. HANDLE hMutex; /* Mutex used to control access to shared lock */
  32970. HANDLE hShared; /* Shared memory segment used for locking */
  32971. winceLock local; /* Locks obtained by this instance of winFile */
  32972. winceLock *shared; /* Global shared lock memory for the file */
  32973. #endif
  32974. #if SQLITE_MAX_MMAP_SIZE>0
  32975. int nFetchOut; /* Number of outstanding xFetch references */
  32976. HANDLE hMap; /* Handle for accessing memory mapping */
  32977. void *pMapRegion; /* Area memory mapped */
  32978. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  32979. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  32980. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  32981. #endif
  32982. };
  32983. /*
  32984. ** Allowed values for winFile.ctrlFlags
  32985. */
  32986. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  32987. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  32988. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  32989. /*
  32990. * The size of the buffer used by sqlite3_win32_write_debug().
  32991. */
  32992. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  32993. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  32994. #endif
  32995. /*
  32996. * The value used with sqlite3_win32_set_directory() to specify that
  32997. * the data directory should be changed.
  32998. */
  32999. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  33000. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  33001. #endif
  33002. /*
  33003. * The value used with sqlite3_win32_set_directory() to specify that
  33004. * the temporary directory should be changed.
  33005. */
  33006. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  33007. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  33008. #endif
  33009. /*
  33010. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  33011. * various Win32 API heap functions instead of our own.
  33012. */
  33013. #ifdef SQLITE_WIN32_MALLOC
  33014. /*
  33015. * If this is non-zero, an isolated heap will be created by the native Win32
  33016. * allocator subsystem; otherwise, the default process heap will be used. This
  33017. * setting has no effect when compiling for WinRT. By default, this is enabled
  33018. * and an isolated heap will be created to store all allocated data.
  33019. *
  33020. ******************************************************************************
  33021. * WARNING: It is important to note that when this setting is non-zero and the
  33022. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  33023. * function), all data that was allocated using the isolated heap will
  33024. * be freed immediately and any attempt to access any of that freed
  33025. * data will almost certainly result in an immediate access violation.
  33026. ******************************************************************************
  33027. */
  33028. #ifndef SQLITE_WIN32_HEAP_CREATE
  33029. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  33030. #endif
  33031. /*
  33032. * The initial size of the Win32-specific heap. This value may be zero.
  33033. */
  33034. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  33035. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  33036. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  33037. #endif
  33038. /*
  33039. * The maximum size of the Win32-specific heap. This value may be zero.
  33040. */
  33041. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  33042. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  33043. #endif
  33044. /*
  33045. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  33046. * zero for the default behavior.
  33047. */
  33048. #ifndef SQLITE_WIN32_HEAP_FLAGS
  33049. # define SQLITE_WIN32_HEAP_FLAGS (0)
  33050. #endif
  33051. /*
  33052. ** The winMemData structure stores information required by the Win32-specific
  33053. ** sqlite3_mem_methods implementation.
  33054. */
  33055. typedef struct winMemData winMemData;
  33056. struct winMemData {
  33057. #ifndef NDEBUG
  33058. u32 magic1; /* Magic number to detect structure corruption. */
  33059. #endif
  33060. HANDLE hHeap; /* The handle to our heap. */
  33061. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  33062. #ifndef NDEBUG
  33063. u32 magic2; /* Magic number to detect structure corruption. */
  33064. #endif
  33065. };
  33066. #ifndef NDEBUG
  33067. #define WINMEM_MAGIC1 0x42b2830b
  33068. #define WINMEM_MAGIC2 0xbd4d7cf4
  33069. #endif
  33070. static struct winMemData win_mem_data = {
  33071. #ifndef NDEBUG
  33072. WINMEM_MAGIC1,
  33073. #endif
  33074. NULL, FALSE
  33075. #ifndef NDEBUG
  33076. ,WINMEM_MAGIC2
  33077. #endif
  33078. };
  33079. #ifndef NDEBUG
  33080. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  33081. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  33082. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  33083. #else
  33084. #define winMemAssertMagic()
  33085. #endif
  33086. #define winMemGetDataPtr() &win_mem_data
  33087. #define winMemGetHeap() win_mem_data.hHeap
  33088. #define winMemGetOwned() win_mem_data.bOwned
  33089. static void *winMemMalloc(int nBytes);
  33090. static void winMemFree(void *pPrior);
  33091. static void *winMemRealloc(void *pPrior, int nBytes);
  33092. static int winMemSize(void *p);
  33093. static int winMemRoundup(int n);
  33094. static int winMemInit(void *pAppData);
  33095. static void winMemShutdown(void *pAppData);
  33096. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  33097. #endif /* SQLITE_WIN32_MALLOC */
  33098. /*
  33099. ** The following variable is (normally) set once and never changes
  33100. ** thereafter. It records whether the operating system is Win9x
  33101. ** or WinNT.
  33102. **
  33103. ** 0: Operating system unknown.
  33104. ** 1: Operating system is Win9x.
  33105. ** 2: Operating system is WinNT.
  33106. **
  33107. ** In order to facilitate testing on a WinNT system, the test fixture
  33108. ** can manually set this value to 1 to emulate Win98 behavior.
  33109. */
  33110. #ifdef SQLITE_TEST
  33111. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  33112. #else
  33113. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  33114. #endif
  33115. #ifndef SYSCALL
  33116. # define SYSCALL sqlite3_syscall_ptr
  33117. #endif
  33118. /*
  33119. ** This function is not available on Windows CE or WinRT.
  33120. */
  33121. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  33122. # define osAreFileApisANSI() 1
  33123. #endif
  33124. /*
  33125. ** Many system calls are accessed through pointer-to-functions so that
  33126. ** they may be overridden at runtime to facilitate fault injection during
  33127. ** testing and sandboxing. The following array holds the names and pointers
  33128. ** to all overrideable system calls.
  33129. */
  33130. static struct win_syscall {
  33131. const char *zName; /* Name of the system call */
  33132. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  33133. sqlite3_syscall_ptr pDefault; /* Default value */
  33134. } aSyscall[] = {
  33135. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33136. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  33137. #else
  33138. { "AreFileApisANSI", (SYSCALL)0, 0 },
  33139. #endif
  33140. #ifndef osAreFileApisANSI
  33141. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  33142. #endif
  33143. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  33144. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  33145. #else
  33146. { "CharLowerW", (SYSCALL)0, 0 },
  33147. #endif
  33148. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  33149. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  33150. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  33151. #else
  33152. { "CharUpperW", (SYSCALL)0, 0 },
  33153. #endif
  33154. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  33155. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  33156. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  33157. #if defined(SQLITE_WIN32_HAS_ANSI)
  33158. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  33159. #else
  33160. { "CreateFileA", (SYSCALL)0, 0 },
  33161. #endif
  33162. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  33163. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  33164. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33165. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  33166. #else
  33167. { "CreateFileW", (SYSCALL)0, 0 },
  33168. #endif
  33169. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  33170. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  33171. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  33172. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  33173. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  33174. #else
  33175. { "CreateFileMappingA", (SYSCALL)0, 0 },
  33176. #endif
  33177. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  33178. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  33179. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  33180. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  33181. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  33182. #else
  33183. { "CreateFileMappingW", (SYSCALL)0, 0 },
  33184. #endif
  33185. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  33186. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  33187. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33188. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  33189. #else
  33190. { "CreateMutexW", (SYSCALL)0, 0 },
  33191. #endif
  33192. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  33193. LPCWSTR))aSyscall[8].pCurrent)
  33194. #if defined(SQLITE_WIN32_HAS_ANSI)
  33195. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  33196. #else
  33197. { "DeleteFileA", (SYSCALL)0, 0 },
  33198. #endif
  33199. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  33200. #if defined(SQLITE_WIN32_HAS_WIDE)
  33201. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  33202. #else
  33203. { "DeleteFileW", (SYSCALL)0, 0 },
  33204. #endif
  33205. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  33206. #if SQLITE_OS_WINCE
  33207. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  33208. #else
  33209. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  33210. #endif
  33211. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  33212. LPFILETIME))aSyscall[11].pCurrent)
  33213. #if SQLITE_OS_WINCE
  33214. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  33215. #else
  33216. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  33217. #endif
  33218. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  33219. LPSYSTEMTIME))aSyscall[12].pCurrent)
  33220. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  33221. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  33222. #if defined(SQLITE_WIN32_HAS_ANSI)
  33223. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  33224. #else
  33225. { "FormatMessageA", (SYSCALL)0, 0 },
  33226. #endif
  33227. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  33228. DWORD,va_list*))aSyscall[14].pCurrent)
  33229. #if defined(SQLITE_WIN32_HAS_WIDE)
  33230. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  33231. #else
  33232. { "FormatMessageW", (SYSCALL)0, 0 },
  33233. #endif
  33234. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  33235. DWORD,va_list*))aSyscall[15].pCurrent)
  33236. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33237. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  33238. #else
  33239. { "FreeLibrary", (SYSCALL)0, 0 },
  33240. #endif
  33241. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  33242. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  33243. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  33244. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  33245. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  33246. #else
  33247. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  33248. #endif
  33249. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  33250. LPDWORD))aSyscall[18].pCurrent)
  33251. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33252. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  33253. #else
  33254. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  33255. #endif
  33256. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  33257. LPDWORD))aSyscall[19].pCurrent)
  33258. #if defined(SQLITE_WIN32_HAS_ANSI)
  33259. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  33260. #else
  33261. { "GetFileAttributesA", (SYSCALL)0, 0 },
  33262. #endif
  33263. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  33264. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33265. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  33266. #else
  33267. { "GetFileAttributesW", (SYSCALL)0, 0 },
  33268. #endif
  33269. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  33270. #if defined(SQLITE_WIN32_HAS_WIDE)
  33271. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  33272. #else
  33273. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  33274. #endif
  33275. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  33276. LPVOID))aSyscall[22].pCurrent)
  33277. #if !SQLITE_OS_WINRT
  33278. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  33279. #else
  33280. { "GetFileSize", (SYSCALL)0, 0 },
  33281. #endif
  33282. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  33283. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  33284. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  33285. #else
  33286. { "GetFullPathNameA", (SYSCALL)0, 0 },
  33287. #endif
  33288. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  33289. LPSTR*))aSyscall[24].pCurrent)
  33290. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33291. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  33292. #else
  33293. { "GetFullPathNameW", (SYSCALL)0, 0 },
  33294. #endif
  33295. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  33296. LPWSTR*))aSyscall[25].pCurrent)
  33297. { "GetLastError", (SYSCALL)GetLastError, 0 },
  33298. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  33299. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33300. #if SQLITE_OS_WINCE
  33301. /* The GetProcAddressA() routine is only available on Windows CE. */
  33302. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  33303. #else
  33304. /* All other Windows platforms expect GetProcAddress() to take
  33305. ** an ANSI string regardless of the _UNICODE setting */
  33306. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  33307. #endif
  33308. #else
  33309. { "GetProcAddressA", (SYSCALL)0, 0 },
  33310. #endif
  33311. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  33312. LPCSTR))aSyscall[27].pCurrent)
  33313. #if !SQLITE_OS_WINRT
  33314. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  33315. #else
  33316. { "GetSystemInfo", (SYSCALL)0, 0 },
  33317. #endif
  33318. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  33319. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  33320. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  33321. #if !SQLITE_OS_WINCE
  33322. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  33323. #else
  33324. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  33325. #endif
  33326. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  33327. LPFILETIME))aSyscall[30].pCurrent)
  33328. #if defined(SQLITE_WIN32_HAS_ANSI)
  33329. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  33330. #else
  33331. { "GetTempPathA", (SYSCALL)0, 0 },
  33332. #endif
  33333. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  33334. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  33335. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  33336. #else
  33337. { "GetTempPathW", (SYSCALL)0, 0 },
  33338. #endif
  33339. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  33340. #if !SQLITE_OS_WINRT
  33341. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  33342. #else
  33343. { "GetTickCount", (SYSCALL)0, 0 },
  33344. #endif
  33345. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  33346. #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
  33347. SQLITE_WIN32_GETVERSIONEX
  33348. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  33349. #else
  33350. { "GetVersionExA", (SYSCALL)0, 0 },
  33351. #endif
  33352. #define osGetVersionExA ((BOOL(WINAPI*)( \
  33353. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  33354. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  33355. defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  33356. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  33357. #else
  33358. { "GetVersionExW", (SYSCALL)0, 0 },
  33359. #endif
  33360. #define osGetVersionExW ((BOOL(WINAPI*)( \
  33361. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  33362. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  33363. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  33364. SIZE_T))aSyscall[36].pCurrent)
  33365. #if !SQLITE_OS_WINRT
  33366. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  33367. #else
  33368. { "HeapCreate", (SYSCALL)0, 0 },
  33369. #endif
  33370. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  33371. SIZE_T))aSyscall[37].pCurrent)
  33372. #if !SQLITE_OS_WINRT
  33373. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  33374. #else
  33375. { "HeapDestroy", (SYSCALL)0, 0 },
  33376. #endif
  33377. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  33378. { "HeapFree", (SYSCALL)HeapFree, 0 },
  33379. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  33380. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  33381. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  33382. SIZE_T))aSyscall[40].pCurrent)
  33383. { "HeapSize", (SYSCALL)HeapSize, 0 },
  33384. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  33385. LPCVOID))aSyscall[41].pCurrent)
  33386. #if !SQLITE_OS_WINRT
  33387. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  33388. #else
  33389. { "HeapValidate", (SYSCALL)0, 0 },
  33390. #endif
  33391. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  33392. LPCVOID))aSyscall[42].pCurrent)
  33393. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33394. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  33395. #else
  33396. { "HeapCompact", (SYSCALL)0, 0 },
  33397. #endif
  33398. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  33399. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33400. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  33401. #else
  33402. { "LoadLibraryA", (SYSCALL)0, 0 },
  33403. #endif
  33404. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  33405. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  33406. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33407. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  33408. #else
  33409. { "LoadLibraryW", (SYSCALL)0, 0 },
  33410. #endif
  33411. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  33412. #if !SQLITE_OS_WINRT
  33413. { "LocalFree", (SYSCALL)LocalFree, 0 },
  33414. #else
  33415. { "LocalFree", (SYSCALL)0, 0 },
  33416. #endif
  33417. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  33418. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33419. { "LockFile", (SYSCALL)LockFile, 0 },
  33420. #else
  33421. { "LockFile", (SYSCALL)0, 0 },
  33422. #endif
  33423. #ifndef osLockFile
  33424. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33425. DWORD))aSyscall[47].pCurrent)
  33426. #endif
  33427. #if !SQLITE_OS_WINCE
  33428. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  33429. #else
  33430. { "LockFileEx", (SYSCALL)0, 0 },
  33431. #endif
  33432. #ifndef osLockFileEx
  33433. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  33434. LPOVERLAPPED))aSyscall[48].pCurrent)
  33435. #endif
  33436. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  33437. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  33438. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  33439. #else
  33440. { "MapViewOfFile", (SYSCALL)0, 0 },
  33441. #endif
  33442. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33443. SIZE_T))aSyscall[49].pCurrent)
  33444. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  33445. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  33446. int))aSyscall[50].pCurrent)
  33447. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  33448. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  33449. LARGE_INTEGER*))aSyscall[51].pCurrent)
  33450. { "ReadFile", (SYSCALL)ReadFile, 0 },
  33451. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  33452. LPOVERLAPPED))aSyscall[52].pCurrent)
  33453. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  33454. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  33455. #if !SQLITE_OS_WINRT
  33456. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  33457. #else
  33458. { "SetFilePointer", (SYSCALL)0, 0 },
  33459. #endif
  33460. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  33461. DWORD))aSyscall[54].pCurrent)
  33462. #if !SQLITE_OS_WINRT
  33463. { "Sleep", (SYSCALL)Sleep, 0 },
  33464. #else
  33465. { "Sleep", (SYSCALL)0, 0 },
  33466. #endif
  33467. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  33468. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  33469. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  33470. LPFILETIME))aSyscall[56].pCurrent)
  33471. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33472. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  33473. #else
  33474. { "UnlockFile", (SYSCALL)0, 0 },
  33475. #endif
  33476. #ifndef osUnlockFile
  33477. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33478. DWORD))aSyscall[57].pCurrent)
  33479. #endif
  33480. #if !SQLITE_OS_WINCE
  33481. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  33482. #else
  33483. { "UnlockFileEx", (SYSCALL)0, 0 },
  33484. #endif
  33485. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  33486. LPOVERLAPPED))aSyscall[58].pCurrent)
  33487. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  33488. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  33489. #else
  33490. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  33491. #endif
  33492. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  33493. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  33494. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  33495. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  33496. { "WriteFile", (SYSCALL)WriteFile, 0 },
  33497. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  33498. LPOVERLAPPED))aSyscall[61].pCurrent)
  33499. #if SQLITE_OS_WINRT
  33500. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  33501. #else
  33502. { "CreateEventExW", (SYSCALL)0, 0 },
  33503. #endif
  33504. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  33505. DWORD,DWORD))aSyscall[62].pCurrent)
  33506. #if !SQLITE_OS_WINRT
  33507. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  33508. #else
  33509. { "WaitForSingleObject", (SYSCALL)0, 0 },
  33510. #endif
  33511. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  33512. DWORD))aSyscall[63].pCurrent)
  33513. #if !SQLITE_OS_WINCE
  33514. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  33515. #else
  33516. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  33517. #endif
  33518. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  33519. BOOL))aSyscall[64].pCurrent)
  33520. #if SQLITE_OS_WINRT
  33521. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  33522. #else
  33523. { "SetFilePointerEx", (SYSCALL)0, 0 },
  33524. #endif
  33525. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  33526. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  33527. #if SQLITE_OS_WINRT
  33528. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  33529. #else
  33530. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  33531. #endif
  33532. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  33533. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  33534. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  33535. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  33536. #else
  33537. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  33538. #endif
  33539. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  33540. SIZE_T))aSyscall[67].pCurrent)
  33541. #if SQLITE_OS_WINRT
  33542. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  33543. #else
  33544. { "CreateFile2", (SYSCALL)0, 0 },
  33545. #endif
  33546. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  33547. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  33548. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  33549. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  33550. #else
  33551. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  33552. #endif
  33553. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  33554. DWORD))aSyscall[69].pCurrent)
  33555. #if SQLITE_OS_WINRT
  33556. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  33557. #else
  33558. { "GetTickCount64", (SYSCALL)0, 0 },
  33559. #endif
  33560. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  33561. #if SQLITE_OS_WINRT
  33562. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  33563. #else
  33564. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  33565. #endif
  33566. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  33567. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  33568. #if defined(SQLITE_WIN32_HAS_ANSI)
  33569. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  33570. #else
  33571. { "OutputDebugStringA", (SYSCALL)0, 0 },
  33572. #endif
  33573. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  33574. #if defined(SQLITE_WIN32_HAS_WIDE)
  33575. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  33576. #else
  33577. { "OutputDebugStringW", (SYSCALL)0, 0 },
  33578. #endif
  33579. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  33580. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  33581. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  33582. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  33583. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  33584. #else
  33585. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  33586. #endif
  33587. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  33588. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  33589. /*
  33590. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  33591. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  33592. ** So do not try to make this is into a redefinable interface.
  33593. */
  33594. #if defined(InterlockedCompareExchange)
  33595. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  33596. #define osInterlockedCompareExchange InterlockedCompareExchange
  33597. #else
  33598. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  33599. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  33600. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  33601. #endif /* defined(InterlockedCompareExchange) */
  33602. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  33603. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  33604. #else
  33605. { "UuidCreate", (SYSCALL)0, 0 },
  33606. #endif
  33607. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  33608. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  33609. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  33610. #else
  33611. { "UuidCreateSequential", (SYSCALL)0, 0 },
  33612. #endif
  33613. #define osUuidCreateSequential \
  33614. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  33615. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  33616. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  33617. #else
  33618. { "FlushViewOfFile", (SYSCALL)0, 0 },
  33619. #endif
  33620. #define osFlushViewOfFile \
  33621. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  33622. }; /* End of the overrideable system calls */
  33623. /*
  33624. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  33625. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  33626. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  33627. ** system call named zName.
  33628. */
  33629. static int winSetSystemCall(
  33630. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  33631. const char *zName, /* Name of system call to override */
  33632. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  33633. ){
  33634. unsigned int i;
  33635. int rc = SQLITE_NOTFOUND;
  33636. UNUSED_PARAMETER(pNotUsed);
  33637. if( zName==0 ){
  33638. /* If no zName is given, restore all system calls to their default
  33639. ** settings and return NULL
  33640. */
  33641. rc = SQLITE_OK;
  33642. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  33643. if( aSyscall[i].pDefault ){
  33644. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  33645. }
  33646. }
  33647. }else{
  33648. /* If zName is specified, operate on only the one system call
  33649. ** specified.
  33650. */
  33651. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  33652. if( strcmp(zName, aSyscall[i].zName)==0 ){
  33653. if( aSyscall[i].pDefault==0 ){
  33654. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  33655. }
  33656. rc = SQLITE_OK;
  33657. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  33658. aSyscall[i].pCurrent = pNewFunc;
  33659. break;
  33660. }
  33661. }
  33662. }
  33663. return rc;
  33664. }
  33665. /*
  33666. ** Return the value of a system call. Return NULL if zName is not a
  33667. ** recognized system call name. NULL is also returned if the system call
  33668. ** is currently undefined.
  33669. */
  33670. static sqlite3_syscall_ptr winGetSystemCall(
  33671. sqlite3_vfs *pNotUsed,
  33672. const char *zName
  33673. ){
  33674. unsigned int i;
  33675. UNUSED_PARAMETER(pNotUsed);
  33676. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  33677. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  33678. }
  33679. return 0;
  33680. }
  33681. /*
  33682. ** Return the name of the first system call after zName. If zName==NULL
  33683. ** then return the name of the first system call. Return NULL if zName
  33684. ** is the last system call or if zName is not the name of a valid
  33685. ** system call.
  33686. */
  33687. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  33688. int i = -1;
  33689. UNUSED_PARAMETER(p);
  33690. if( zName ){
  33691. for(i=0; i<ArraySize(aSyscall)-1; i++){
  33692. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  33693. }
  33694. }
  33695. for(i++; i<ArraySize(aSyscall); i++){
  33696. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  33697. }
  33698. return 0;
  33699. }
  33700. #ifdef SQLITE_WIN32_MALLOC
  33701. /*
  33702. ** If a Win32 native heap has been configured, this function will attempt to
  33703. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  33704. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  33705. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  33706. ** largest committed free block in the heap, in bytes.
  33707. */
  33708. SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
  33709. int rc = SQLITE_OK;
  33710. UINT nLargest = 0;
  33711. HANDLE hHeap;
  33712. winMemAssertMagic();
  33713. hHeap = winMemGetHeap();
  33714. assert( hHeap!=0 );
  33715. assert( hHeap!=INVALID_HANDLE_VALUE );
  33716. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33717. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  33718. #endif
  33719. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  33720. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  33721. DWORD lastErrno = osGetLastError();
  33722. if( lastErrno==NO_ERROR ){
  33723. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  33724. (void*)hHeap);
  33725. rc = SQLITE_NOMEM;
  33726. }else{
  33727. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  33728. osGetLastError(), (void*)hHeap);
  33729. rc = SQLITE_ERROR;
  33730. }
  33731. }
  33732. #else
  33733. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  33734. (void*)hHeap);
  33735. rc = SQLITE_NOTFOUND;
  33736. #endif
  33737. if( pnLargest ) *pnLargest = nLargest;
  33738. return rc;
  33739. }
  33740. /*
  33741. ** If a Win32 native heap has been configured, this function will attempt to
  33742. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  33743. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  33744. ** be returned and no changes will be made to the Win32 native heap.
  33745. */
  33746. SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
  33747. int rc;
  33748. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  33749. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  33750. MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
  33751. MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
  33752. sqlite3_mutex_enter(pMaster);
  33753. sqlite3_mutex_enter(pMem);
  33754. winMemAssertMagic();
  33755. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  33756. /*
  33757. ** At this point, there should be no outstanding memory allocations on
  33758. ** the heap. Also, since both the master and memsys locks are currently
  33759. ** being held by us, no other function (i.e. from another thread) should
  33760. ** be able to even access the heap. Attempt to destroy and recreate our
  33761. ** isolated Win32 native heap now.
  33762. */
  33763. assert( winMemGetHeap()!=NULL );
  33764. assert( winMemGetOwned() );
  33765. assert( sqlite3_memory_used()==0 );
  33766. winMemShutdown(winMemGetDataPtr());
  33767. assert( winMemGetHeap()==NULL );
  33768. assert( !winMemGetOwned() );
  33769. assert( sqlite3_memory_used()==0 );
  33770. rc = winMemInit(winMemGetDataPtr());
  33771. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  33772. assert( rc!=SQLITE_OK || winMemGetOwned() );
  33773. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  33774. }else{
  33775. /*
  33776. ** The Win32 native heap cannot be modified because it may be in use.
  33777. */
  33778. rc = SQLITE_BUSY;
  33779. }
  33780. sqlite3_mutex_leave(pMem);
  33781. sqlite3_mutex_leave(pMaster);
  33782. return rc;
  33783. }
  33784. #endif /* SQLITE_WIN32_MALLOC */
  33785. /*
  33786. ** This function outputs the specified (ANSI) string to the Win32 debugger
  33787. ** (if available).
  33788. */
  33789. SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  33790. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  33791. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  33792. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  33793. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  33794. #if defined(SQLITE_WIN32_HAS_ANSI)
  33795. if( nMin>0 ){
  33796. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  33797. memcpy(zDbgBuf, zBuf, nMin);
  33798. osOutputDebugStringA(zDbgBuf);
  33799. }else{
  33800. osOutputDebugStringA(zBuf);
  33801. }
  33802. #elif defined(SQLITE_WIN32_HAS_WIDE)
  33803. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  33804. if ( osMultiByteToWideChar(
  33805. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  33806. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  33807. return;
  33808. }
  33809. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  33810. #else
  33811. if( nMin>0 ){
  33812. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  33813. memcpy(zDbgBuf, zBuf, nMin);
  33814. fprintf(stderr, "%s", zDbgBuf);
  33815. }else{
  33816. fprintf(stderr, "%s", zBuf);
  33817. }
  33818. #endif
  33819. }
  33820. /*
  33821. ** The following routine suspends the current thread for at least ms
  33822. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  33823. */
  33824. #if SQLITE_OS_WINRT
  33825. static HANDLE sleepObj = NULL;
  33826. #endif
  33827. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
  33828. #if SQLITE_OS_WINRT
  33829. if ( sleepObj==NULL ){
  33830. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  33831. SYNCHRONIZE);
  33832. }
  33833. assert( sleepObj!=NULL );
  33834. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  33835. #else
  33836. osSleep(milliseconds);
  33837. #endif
  33838. }
  33839. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  33840. SQLITE_THREADSAFE>0
  33841. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  33842. DWORD rc;
  33843. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  33844. TRUE))==WAIT_IO_COMPLETION ){}
  33845. return rc;
  33846. }
  33847. #endif
  33848. /*
  33849. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  33850. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  33851. **
  33852. ** Here is an interesting observation: Win95, Win98, and WinME lack
  33853. ** the LockFileEx() API. But we can still statically link against that
  33854. ** API as long as we don't call it when running Win95/98/ME. A call to
  33855. ** this routine is used to determine if the host is Win95/98/ME or
  33856. ** WinNT/2K/XP so that we will know whether or not we can safely call
  33857. ** the LockFileEx() API.
  33858. */
  33859. #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
  33860. # define osIsNT() (1)
  33861. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  33862. # define osIsNT() (1)
  33863. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  33864. # define osIsNT() (0)
  33865. #else
  33866. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  33867. #endif
  33868. /*
  33869. ** This function determines if the machine is running a version of Windows
  33870. ** based on the NT kernel.
  33871. */
  33872. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
  33873. #if SQLITE_OS_WINRT
  33874. /*
  33875. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  33876. ** kernel.
  33877. */
  33878. return 1;
  33879. #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  33880. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  33881. #if defined(SQLITE_WIN32_HAS_ANSI)
  33882. OSVERSIONINFOA sInfo;
  33883. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  33884. osGetVersionExA(&sInfo);
  33885. osInterlockedCompareExchange(&sqlite3_os_type,
  33886. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  33887. #elif defined(SQLITE_WIN32_HAS_WIDE)
  33888. OSVERSIONINFOW sInfo;
  33889. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  33890. osGetVersionExW(&sInfo);
  33891. osInterlockedCompareExchange(&sqlite3_os_type,
  33892. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  33893. #endif
  33894. }
  33895. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  33896. #elif SQLITE_TEST
  33897. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  33898. #else
  33899. /*
  33900. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  33901. ** deprecated are always assumed to be based on the NT kernel.
  33902. */
  33903. return 1;
  33904. #endif
  33905. }
  33906. #ifdef SQLITE_WIN32_MALLOC
  33907. /*
  33908. ** Allocate nBytes of memory.
  33909. */
  33910. static void *winMemMalloc(int nBytes){
  33911. HANDLE hHeap;
  33912. void *p;
  33913. winMemAssertMagic();
  33914. hHeap = winMemGetHeap();
  33915. assert( hHeap!=0 );
  33916. assert( hHeap!=INVALID_HANDLE_VALUE );
  33917. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33918. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  33919. #endif
  33920. assert( nBytes>=0 );
  33921. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  33922. if( !p ){
  33923. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  33924. nBytes, osGetLastError(), (void*)hHeap);
  33925. }
  33926. return p;
  33927. }
  33928. /*
  33929. ** Free memory.
  33930. */
  33931. static void winMemFree(void *pPrior){
  33932. HANDLE hHeap;
  33933. winMemAssertMagic();
  33934. hHeap = winMemGetHeap();
  33935. assert( hHeap!=0 );
  33936. assert( hHeap!=INVALID_HANDLE_VALUE );
  33937. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33938. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  33939. #endif
  33940. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  33941. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  33942. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  33943. pPrior, osGetLastError(), (void*)hHeap);
  33944. }
  33945. }
  33946. /*
  33947. ** Change the size of an existing memory allocation
  33948. */
  33949. static void *winMemRealloc(void *pPrior, int nBytes){
  33950. HANDLE hHeap;
  33951. void *p;
  33952. winMemAssertMagic();
  33953. hHeap = winMemGetHeap();
  33954. assert( hHeap!=0 );
  33955. assert( hHeap!=INVALID_HANDLE_VALUE );
  33956. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33957. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  33958. #endif
  33959. assert( nBytes>=0 );
  33960. if( !pPrior ){
  33961. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  33962. }else{
  33963. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  33964. }
  33965. if( !p ){
  33966. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  33967. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  33968. (void*)hHeap);
  33969. }
  33970. return p;
  33971. }
  33972. /*
  33973. ** Return the size of an outstanding allocation, in bytes.
  33974. */
  33975. static int winMemSize(void *p){
  33976. HANDLE hHeap;
  33977. SIZE_T n;
  33978. winMemAssertMagic();
  33979. hHeap = winMemGetHeap();
  33980. assert( hHeap!=0 );
  33981. assert( hHeap!=INVALID_HANDLE_VALUE );
  33982. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33983. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  33984. #endif
  33985. if( !p ) return 0;
  33986. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  33987. if( n==(SIZE_T)-1 ){
  33988. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  33989. p, osGetLastError(), (void*)hHeap);
  33990. return 0;
  33991. }
  33992. return (int)n;
  33993. }
  33994. /*
  33995. ** Round up a request size to the next valid allocation size.
  33996. */
  33997. static int winMemRoundup(int n){
  33998. return n;
  33999. }
  34000. /*
  34001. ** Initialize this module.
  34002. */
  34003. static int winMemInit(void *pAppData){
  34004. winMemData *pWinMemData = (winMemData *)pAppData;
  34005. if( !pWinMemData ) return SQLITE_ERROR;
  34006. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  34007. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  34008. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  34009. if( !pWinMemData->hHeap ){
  34010. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  34011. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  34012. if( dwMaximumSize==0 ){
  34013. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  34014. }else if( dwInitialSize>dwMaximumSize ){
  34015. dwInitialSize = dwMaximumSize;
  34016. }
  34017. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  34018. dwInitialSize, dwMaximumSize);
  34019. if( !pWinMemData->hHeap ){
  34020. sqlite3_log(SQLITE_NOMEM,
  34021. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  34022. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  34023. dwMaximumSize);
  34024. return SQLITE_NOMEM;
  34025. }
  34026. pWinMemData->bOwned = TRUE;
  34027. assert( pWinMemData->bOwned );
  34028. }
  34029. #else
  34030. pWinMemData->hHeap = osGetProcessHeap();
  34031. if( !pWinMemData->hHeap ){
  34032. sqlite3_log(SQLITE_NOMEM,
  34033. "failed to GetProcessHeap (%lu)", osGetLastError());
  34034. return SQLITE_NOMEM;
  34035. }
  34036. pWinMemData->bOwned = FALSE;
  34037. assert( !pWinMemData->bOwned );
  34038. #endif
  34039. assert( pWinMemData->hHeap!=0 );
  34040. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  34041. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34042. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  34043. #endif
  34044. return SQLITE_OK;
  34045. }
  34046. /*
  34047. ** Deinitialize this module.
  34048. */
  34049. static void winMemShutdown(void *pAppData){
  34050. winMemData *pWinMemData = (winMemData *)pAppData;
  34051. if( !pWinMemData ) return;
  34052. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  34053. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  34054. if( pWinMemData->hHeap ){
  34055. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  34056. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  34057. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  34058. #endif
  34059. if( pWinMemData->bOwned ){
  34060. if( !osHeapDestroy(pWinMemData->hHeap) ){
  34061. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  34062. osGetLastError(), (void*)pWinMemData->hHeap);
  34063. }
  34064. pWinMemData->bOwned = FALSE;
  34065. }
  34066. pWinMemData->hHeap = NULL;
  34067. }
  34068. }
  34069. /*
  34070. ** Populate the low-level memory allocation function pointers in
  34071. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  34072. ** arguments specify the block of memory to manage.
  34073. **
  34074. ** This routine is only called by sqlite3_config(), and therefore
  34075. ** is not required to be threadsafe (it is not).
  34076. */
  34077. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  34078. static const sqlite3_mem_methods winMemMethods = {
  34079. winMemMalloc,
  34080. winMemFree,
  34081. winMemRealloc,
  34082. winMemSize,
  34083. winMemRoundup,
  34084. winMemInit,
  34085. winMemShutdown,
  34086. &win_mem_data
  34087. };
  34088. return &winMemMethods;
  34089. }
  34090. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  34091. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  34092. }
  34093. #endif /* SQLITE_WIN32_MALLOC */
  34094. /*
  34095. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  34096. **
  34097. ** Space to hold the returned string is obtained from malloc.
  34098. */
  34099. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  34100. int nChar;
  34101. LPWSTR zWideFilename;
  34102. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  34103. if( nChar==0 ){
  34104. return 0;
  34105. }
  34106. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  34107. if( zWideFilename==0 ){
  34108. return 0;
  34109. }
  34110. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  34111. nChar);
  34112. if( nChar==0 ){
  34113. sqlite3_free(zWideFilename);
  34114. zWideFilename = 0;
  34115. }
  34116. return zWideFilename;
  34117. }
  34118. /*
  34119. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  34120. ** obtained from sqlite3_malloc().
  34121. */
  34122. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  34123. int nByte;
  34124. char *zFilename;
  34125. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  34126. if( nByte == 0 ){
  34127. return 0;
  34128. }
  34129. zFilename = sqlite3MallocZero( nByte );
  34130. if( zFilename==0 ){
  34131. return 0;
  34132. }
  34133. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  34134. 0, 0);
  34135. if( nByte == 0 ){
  34136. sqlite3_free(zFilename);
  34137. zFilename = 0;
  34138. }
  34139. return zFilename;
  34140. }
  34141. /*
  34142. ** Convert an ANSI string to Microsoft Unicode, based on the
  34143. ** current codepage settings for file apis.
  34144. **
  34145. ** Space to hold the returned string is obtained
  34146. ** from sqlite3_malloc.
  34147. */
  34148. static LPWSTR winMbcsToUnicode(const char *zFilename){
  34149. int nByte;
  34150. LPWSTR zMbcsFilename;
  34151. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  34152. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  34153. 0)*sizeof(WCHAR);
  34154. if( nByte==0 ){
  34155. return 0;
  34156. }
  34157. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  34158. if( zMbcsFilename==0 ){
  34159. return 0;
  34160. }
  34161. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  34162. nByte);
  34163. if( nByte==0 ){
  34164. sqlite3_free(zMbcsFilename);
  34165. zMbcsFilename = 0;
  34166. }
  34167. return zMbcsFilename;
  34168. }
  34169. /*
  34170. ** Convert Microsoft Unicode to multi-byte character string, based on the
  34171. ** user's ANSI codepage.
  34172. **
  34173. ** Space to hold the returned string is obtained from
  34174. ** sqlite3_malloc().
  34175. */
  34176. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  34177. int nByte;
  34178. char *zFilename;
  34179. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  34180. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  34181. if( nByte == 0 ){
  34182. return 0;
  34183. }
  34184. zFilename = sqlite3MallocZero( nByte );
  34185. if( zFilename==0 ){
  34186. return 0;
  34187. }
  34188. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  34189. nByte, 0, 0);
  34190. if( nByte == 0 ){
  34191. sqlite3_free(zFilename);
  34192. zFilename = 0;
  34193. }
  34194. return zFilename;
  34195. }
  34196. /*
  34197. ** Convert multibyte character string to UTF-8. Space to hold the
  34198. ** returned string is obtained from sqlite3_malloc().
  34199. */
  34200. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  34201. char *zFilenameUtf8;
  34202. LPWSTR zTmpWide;
  34203. zTmpWide = winMbcsToUnicode(zFilename);
  34204. if( zTmpWide==0 ){
  34205. return 0;
  34206. }
  34207. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  34208. sqlite3_free(zTmpWide);
  34209. return zFilenameUtf8;
  34210. }
  34211. /*
  34212. ** Convert UTF-8 to multibyte character string. Space to hold the
  34213. ** returned string is obtained from sqlite3_malloc().
  34214. */
  34215. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  34216. char *zFilenameMbcs;
  34217. LPWSTR zTmpWide;
  34218. zTmpWide = winUtf8ToUnicode(zFilename);
  34219. if( zTmpWide==0 ){
  34220. return 0;
  34221. }
  34222. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  34223. sqlite3_free(zTmpWide);
  34224. return zFilenameMbcs;
  34225. }
  34226. /*
  34227. ** This function sets the data directory or the temporary directory based on
  34228. ** the provided arguments. The type argument must be 1 in order to set the
  34229. ** data directory or 2 in order to set the temporary directory. The zValue
  34230. ** argument is the name of the directory to use. The return value will be
  34231. ** SQLITE_OK if successful.
  34232. */
  34233. SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  34234. char **ppDirectory = 0;
  34235. #ifndef SQLITE_OMIT_AUTOINIT
  34236. int rc = sqlite3_initialize();
  34237. if( rc ) return rc;
  34238. #endif
  34239. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  34240. ppDirectory = &sqlite3_data_directory;
  34241. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  34242. ppDirectory = &sqlite3_temp_directory;
  34243. }
  34244. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  34245. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  34246. );
  34247. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  34248. if( ppDirectory ){
  34249. char *zValueUtf8 = 0;
  34250. if( zValue && zValue[0] ){
  34251. zValueUtf8 = winUnicodeToUtf8(zValue);
  34252. if ( zValueUtf8==0 ){
  34253. return SQLITE_NOMEM;
  34254. }
  34255. }
  34256. sqlite3_free(*ppDirectory);
  34257. *ppDirectory = zValueUtf8;
  34258. return SQLITE_OK;
  34259. }
  34260. return SQLITE_ERROR;
  34261. }
  34262. /*
  34263. ** The return value of winGetLastErrorMsg
  34264. ** is zero if the error message fits in the buffer, or non-zero
  34265. ** otherwise (if the message was truncated).
  34266. */
  34267. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  34268. /* FormatMessage returns 0 on failure. Otherwise it
  34269. ** returns the number of TCHARs written to the output
  34270. ** buffer, excluding the terminating null char.
  34271. */
  34272. DWORD dwLen = 0;
  34273. char *zOut = 0;
  34274. if( osIsNT() ){
  34275. #if SQLITE_OS_WINRT
  34276. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  34277. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  34278. FORMAT_MESSAGE_IGNORE_INSERTS,
  34279. NULL,
  34280. lastErrno,
  34281. 0,
  34282. zTempWide,
  34283. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  34284. 0);
  34285. #else
  34286. LPWSTR zTempWide = NULL;
  34287. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  34288. FORMAT_MESSAGE_FROM_SYSTEM |
  34289. FORMAT_MESSAGE_IGNORE_INSERTS,
  34290. NULL,
  34291. lastErrno,
  34292. 0,
  34293. (LPWSTR) &zTempWide,
  34294. 0,
  34295. 0);
  34296. #endif
  34297. if( dwLen > 0 ){
  34298. /* allocate a buffer and convert to UTF8 */
  34299. sqlite3BeginBenignMalloc();
  34300. zOut = winUnicodeToUtf8(zTempWide);
  34301. sqlite3EndBenignMalloc();
  34302. #if !SQLITE_OS_WINRT
  34303. /* free the system buffer allocated by FormatMessage */
  34304. osLocalFree(zTempWide);
  34305. #endif
  34306. }
  34307. }
  34308. #ifdef SQLITE_WIN32_HAS_ANSI
  34309. else{
  34310. char *zTemp = NULL;
  34311. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  34312. FORMAT_MESSAGE_FROM_SYSTEM |
  34313. FORMAT_MESSAGE_IGNORE_INSERTS,
  34314. NULL,
  34315. lastErrno,
  34316. 0,
  34317. (LPSTR) &zTemp,
  34318. 0,
  34319. 0);
  34320. if( dwLen > 0 ){
  34321. /* allocate a buffer and convert to UTF8 */
  34322. sqlite3BeginBenignMalloc();
  34323. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  34324. sqlite3EndBenignMalloc();
  34325. /* free the system buffer allocated by FormatMessage */
  34326. osLocalFree(zTemp);
  34327. }
  34328. }
  34329. #endif
  34330. if( 0 == dwLen ){
  34331. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  34332. }else{
  34333. /* copy a maximum of nBuf chars to output buffer */
  34334. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  34335. /* free the UTF8 buffer */
  34336. sqlite3_free(zOut);
  34337. }
  34338. return 0;
  34339. }
  34340. /*
  34341. **
  34342. ** This function - winLogErrorAtLine() - is only ever called via the macro
  34343. ** winLogError().
  34344. **
  34345. ** This routine is invoked after an error occurs in an OS function.
  34346. ** It logs a message using sqlite3_log() containing the current value of
  34347. ** error code and, if possible, the human-readable equivalent from
  34348. ** FormatMessage.
  34349. **
  34350. ** The first argument passed to the macro should be the error code that
  34351. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  34352. ** The two subsequent arguments should be the name of the OS function that
  34353. ** failed and the associated file-system path, if any.
  34354. */
  34355. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  34356. static int winLogErrorAtLine(
  34357. int errcode, /* SQLite error code */
  34358. DWORD lastErrno, /* Win32 last error */
  34359. const char *zFunc, /* Name of OS function that failed */
  34360. const char *zPath, /* File path associated with error */
  34361. int iLine /* Source line number where error occurred */
  34362. ){
  34363. char zMsg[500]; /* Human readable error text */
  34364. int i; /* Loop counter */
  34365. zMsg[0] = 0;
  34366. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  34367. assert( errcode!=SQLITE_OK );
  34368. if( zPath==0 ) zPath = "";
  34369. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  34370. zMsg[i] = 0;
  34371. sqlite3_log(errcode,
  34372. "os_win.c:%d: (%lu) %s(%s) - %s",
  34373. iLine, lastErrno, zFunc, zPath, zMsg
  34374. );
  34375. return errcode;
  34376. }
  34377. /*
  34378. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  34379. ** will be retried following a locking error - probably caused by
  34380. ** antivirus software. Also the initial delay before the first retry.
  34381. ** The delay increases linearly with each retry.
  34382. */
  34383. #ifndef SQLITE_WIN32_IOERR_RETRY
  34384. # define SQLITE_WIN32_IOERR_RETRY 10
  34385. #endif
  34386. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  34387. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  34388. #endif
  34389. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  34390. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  34391. /*
  34392. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  34393. ** error code obtained via GetLastError() is eligible to be retried. It
  34394. ** must accept the error code DWORD as its only argument and should return
  34395. ** non-zero if the error code is transient in nature and the operation
  34396. ** responsible for generating the original error might succeed upon being
  34397. ** retried. The argument to this macro should be a variable.
  34398. **
  34399. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  34400. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  34401. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  34402. ** may be used to include additional error codes in the set that should
  34403. ** result in the failing I/O operation being retried by the caller. If
  34404. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  34405. ** identical to those of the "winIoerrCanRetry1" macro.
  34406. */
  34407. #if !defined(winIoerrCanRetry1)
  34408. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  34409. ((a)==ERROR_SHARING_VIOLATION) || \
  34410. ((a)==ERROR_LOCK_VIOLATION) || \
  34411. ((a)==ERROR_DEV_NOT_EXIST) || \
  34412. ((a)==ERROR_NETNAME_DELETED) || \
  34413. ((a)==ERROR_SEM_TIMEOUT) || \
  34414. ((a)==ERROR_NETWORK_UNREACHABLE))
  34415. #endif
  34416. /*
  34417. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  34418. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  34419. ** to give up with an error.
  34420. */
  34421. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  34422. DWORD e = osGetLastError();
  34423. if( *pnRetry>=winIoerrRetry ){
  34424. if( pError ){
  34425. *pError = e;
  34426. }
  34427. return 0;
  34428. }
  34429. if( winIoerrCanRetry1(e) ){
  34430. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  34431. ++*pnRetry;
  34432. return 1;
  34433. }
  34434. #if defined(winIoerrCanRetry2)
  34435. else if( winIoerrCanRetry2(e) ){
  34436. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  34437. ++*pnRetry;
  34438. return 1;
  34439. }
  34440. #endif
  34441. if( pError ){
  34442. *pError = e;
  34443. }
  34444. return 0;
  34445. }
  34446. /*
  34447. ** Log a I/O error retry episode.
  34448. */
  34449. static void winLogIoerr(int nRetry, int lineno){
  34450. if( nRetry ){
  34451. sqlite3_log(SQLITE_NOTICE,
  34452. "delayed %dms for lock/sharing conflict at line %d",
  34453. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  34454. );
  34455. }
  34456. }
  34457. #if SQLITE_OS_WINCE
  34458. /*************************************************************************
  34459. ** This section contains code for WinCE only.
  34460. */
  34461. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  34462. /*
  34463. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  34464. ** create a substitute.
  34465. */
  34466. /* #include <time.h> */
  34467. struct tm *__cdecl localtime(const time_t *t)
  34468. {
  34469. static struct tm y;
  34470. FILETIME uTm, lTm;
  34471. SYSTEMTIME pTm;
  34472. sqlite3_int64 t64;
  34473. t64 = *t;
  34474. t64 = (t64 + 11644473600)*10000000;
  34475. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  34476. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  34477. osFileTimeToLocalFileTime(&uTm,&lTm);
  34478. osFileTimeToSystemTime(&lTm,&pTm);
  34479. y.tm_year = pTm.wYear - 1900;
  34480. y.tm_mon = pTm.wMonth - 1;
  34481. y.tm_wday = pTm.wDayOfWeek;
  34482. y.tm_mday = pTm.wDay;
  34483. y.tm_hour = pTm.wHour;
  34484. y.tm_min = pTm.wMinute;
  34485. y.tm_sec = pTm.wSecond;
  34486. return &y;
  34487. }
  34488. #endif
  34489. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  34490. /*
  34491. ** Acquire a lock on the handle h
  34492. */
  34493. static void winceMutexAcquire(HANDLE h){
  34494. DWORD dwErr;
  34495. do {
  34496. dwErr = osWaitForSingleObject(h, INFINITE);
  34497. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  34498. }
  34499. /*
  34500. ** Release a lock acquired by winceMutexAcquire()
  34501. */
  34502. #define winceMutexRelease(h) ReleaseMutex(h)
  34503. /*
  34504. ** Create the mutex and shared memory used for locking in the file
  34505. ** descriptor pFile
  34506. */
  34507. static int winceCreateLock(const char *zFilename, winFile *pFile){
  34508. LPWSTR zTok;
  34509. LPWSTR zName;
  34510. DWORD lastErrno;
  34511. BOOL bLogged = FALSE;
  34512. BOOL bInit = TRUE;
  34513. zName = winUtf8ToUnicode(zFilename);
  34514. if( zName==0 ){
  34515. /* out of memory */
  34516. return SQLITE_IOERR_NOMEM;
  34517. }
  34518. /* Initialize the local lockdata */
  34519. memset(&pFile->local, 0, sizeof(pFile->local));
  34520. /* Replace the backslashes from the filename and lowercase it
  34521. ** to derive a mutex name. */
  34522. zTok = osCharLowerW(zName);
  34523. for (;*zTok;zTok++){
  34524. if (*zTok == '\\') *zTok = '_';
  34525. }
  34526. /* Create/open the named mutex */
  34527. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  34528. if (!pFile->hMutex){
  34529. pFile->lastErrno = osGetLastError();
  34530. sqlite3_free(zName);
  34531. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  34532. "winceCreateLock1", zFilename);
  34533. }
  34534. /* Acquire the mutex before continuing */
  34535. winceMutexAcquire(pFile->hMutex);
  34536. /* Since the names of named mutexes, semaphores, file mappings etc are
  34537. ** case-sensitive, take advantage of that by uppercasing the mutex name
  34538. ** and using that as the shared filemapping name.
  34539. */
  34540. osCharUpperW(zName);
  34541. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  34542. PAGE_READWRITE, 0, sizeof(winceLock),
  34543. zName);
  34544. /* Set a flag that indicates we're the first to create the memory so it
  34545. ** must be zero-initialized */
  34546. lastErrno = osGetLastError();
  34547. if (lastErrno == ERROR_ALREADY_EXISTS){
  34548. bInit = FALSE;
  34549. }
  34550. sqlite3_free(zName);
  34551. /* If we succeeded in making the shared memory handle, map it. */
  34552. if( pFile->hShared ){
  34553. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  34554. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  34555. /* If mapping failed, close the shared memory handle and erase it */
  34556. if( !pFile->shared ){
  34557. pFile->lastErrno = osGetLastError();
  34558. winLogError(SQLITE_IOERR, pFile->lastErrno,
  34559. "winceCreateLock2", zFilename);
  34560. bLogged = TRUE;
  34561. osCloseHandle(pFile->hShared);
  34562. pFile->hShared = NULL;
  34563. }
  34564. }
  34565. /* If shared memory could not be created, then close the mutex and fail */
  34566. if( pFile->hShared==NULL ){
  34567. if( !bLogged ){
  34568. pFile->lastErrno = lastErrno;
  34569. winLogError(SQLITE_IOERR, pFile->lastErrno,
  34570. "winceCreateLock3", zFilename);
  34571. bLogged = TRUE;
  34572. }
  34573. winceMutexRelease(pFile->hMutex);
  34574. osCloseHandle(pFile->hMutex);
  34575. pFile->hMutex = NULL;
  34576. return SQLITE_IOERR;
  34577. }
  34578. /* Initialize the shared memory if we're supposed to */
  34579. if( bInit ){
  34580. memset(pFile->shared, 0, sizeof(winceLock));
  34581. }
  34582. winceMutexRelease(pFile->hMutex);
  34583. return SQLITE_OK;
  34584. }
  34585. /*
  34586. ** Destroy the part of winFile that deals with wince locks
  34587. */
  34588. static void winceDestroyLock(winFile *pFile){
  34589. if (pFile->hMutex){
  34590. /* Acquire the mutex */
  34591. winceMutexAcquire(pFile->hMutex);
  34592. /* The following blocks should probably assert in debug mode, but they
  34593. are to cleanup in case any locks remained open */
  34594. if (pFile->local.nReaders){
  34595. pFile->shared->nReaders --;
  34596. }
  34597. if (pFile->local.bReserved){
  34598. pFile->shared->bReserved = FALSE;
  34599. }
  34600. if (pFile->local.bPending){
  34601. pFile->shared->bPending = FALSE;
  34602. }
  34603. if (pFile->local.bExclusive){
  34604. pFile->shared->bExclusive = FALSE;
  34605. }
  34606. /* De-reference and close our copy of the shared memory handle */
  34607. osUnmapViewOfFile(pFile->shared);
  34608. osCloseHandle(pFile->hShared);
  34609. /* Done with the mutex */
  34610. winceMutexRelease(pFile->hMutex);
  34611. osCloseHandle(pFile->hMutex);
  34612. pFile->hMutex = NULL;
  34613. }
  34614. }
  34615. /*
  34616. ** An implementation of the LockFile() API of Windows for CE
  34617. */
  34618. static BOOL winceLockFile(
  34619. LPHANDLE phFile,
  34620. DWORD dwFileOffsetLow,
  34621. DWORD dwFileOffsetHigh,
  34622. DWORD nNumberOfBytesToLockLow,
  34623. DWORD nNumberOfBytesToLockHigh
  34624. ){
  34625. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  34626. BOOL bReturn = FALSE;
  34627. UNUSED_PARAMETER(dwFileOffsetHigh);
  34628. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  34629. if (!pFile->hMutex) return TRUE;
  34630. winceMutexAcquire(pFile->hMutex);
  34631. /* Wanting an exclusive lock? */
  34632. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  34633. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  34634. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  34635. pFile->shared->bExclusive = TRUE;
  34636. pFile->local.bExclusive = TRUE;
  34637. bReturn = TRUE;
  34638. }
  34639. }
  34640. /* Want a read-only lock? */
  34641. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  34642. nNumberOfBytesToLockLow == 1){
  34643. if (pFile->shared->bExclusive == 0){
  34644. pFile->local.nReaders ++;
  34645. if (pFile->local.nReaders == 1){
  34646. pFile->shared->nReaders ++;
  34647. }
  34648. bReturn = TRUE;
  34649. }
  34650. }
  34651. /* Want a pending lock? */
  34652. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  34653. && nNumberOfBytesToLockLow == 1){
  34654. /* If no pending lock has been acquired, then acquire it */
  34655. if (pFile->shared->bPending == 0) {
  34656. pFile->shared->bPending = TRUE;
  34657. pFile->local.bPending = TRUE;
  34658. bReturn = TRUE;
  34659. }
  34660. }
  34661. /* Want a reserved lock? */
  34662. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  34663. && nNumberOfBytesToLockLow == 1){
  34664. if (pFile->shared->bReserved == 0) {
  34665. pFile->shared->bReserved = TRUE;
  34666. pFile->local.bReserved = TRUE;
  34667. bReturn = TRUE;
  34668. }
  34669. }
  34670. winceMutexRelease(pFile->hMutex);
  34671. return bReturn;
  34672. }
  34673. /*
  34674. ** An implementation of the UnlockFile API of Windows for CE
  34675. */
  34676. static BOOL winceUnlockFile(
  34677. LPHANDLE phFile,
  34678. DWORD dwFileOffsetLow,
  34679. DWORD dwFileOffsetHigh,
  34680. DWORD nNumberOfBytesToUnlockLow,
  34681. DWORD nNumberOfBytesToUnlockHigh
  34682. ){
  34683. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  34684. BOOL bReturn = FALSE;
  34685. UNUSED_PARAMETER(dwFileOffsetHigh);
  34686. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  34687. if (!pFile->hMutex) return TRUE;
  34688. winceMutexAcquire(pFile->hMutex);
  34689. /* Releasing a reader lock or an exclusive lock */
  34690. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  34691. /* Did we have an exclusive lock? */
  34692. if (pFile->local.bExclusive){
  34693. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  34694. pFile->local.bExclusive = FALSE;
  34695. pFile->shared->bExclusive = FALSE;
  34696. bReturn = TRUE;
  34697. }
  34698. /* Did we just have a reader lock? */
  34699. else if (pFile->local.nReaders){
  34700. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  34701. || nNumberOfBytesToUnlockLow == 1);
  34702. pFile->local.nReaders --;
  34703. if (pFile->local.nReaders == 0)
  34704. {
  34705. pFile->shared->nReaders --;
  34706. }
  34707. bReturn = TRUE;
  34708. }
  34709. }
  34710. /* Releasing a pending lock */
  34711. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  34712. && nNumberOfBytesToUnlockLow == 1){
  34713. if (pFile->local.bPending){
  34714. pFile->local.bPending = FALSE;
  34715. pFile->shared->bPending = FALSE;
  34716. bReturn = TRUE;
  34717. }
  34718. }
  34719. /* Releasing a reserved lock */
  34720. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  34721. && nNumberOfBytesToUnlockLow == 1){
  34722. if (pFile->local.bReserved) {
  34723. pFile->local.bReserved = FALSE;
  34724. pFile->shared->bReserved = FALSE;
  34725. bReturn = TRUE;
  34726. }
  34727. }
  34728. winceMutexRelease(pFile->hMutex);
  34729. return bReturn;
  34730. }
  34731. /*
  34732. ** End of the special code for wince
  34733. *****************************************************************************/
  34734. #endif /* SQLITE_OS_WINCE */
  34735. /*
  34736. ** Lock a file region.
  34737. */
  34738. static BOOL winLockFile(
  34739. LPHANDLE phFile,
  34740. DWORD flags,
  34741. DWORD offsetLow,
  34742. DWORD offsetHigh,
  34743. DWORD numBytesLow,
  34744. DWORD numBytesHigh
  34745. ){
  34746. #if SQLITE_OS_WINCE
  34747. /*
  34748. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  34749. ** API LockFile.
  34750. */
  34751. return winceLockFile(phFile, offsetLow, offsetHigh,
  34752. numBytesLow, numBytesHigh);
  34753. #else
  34754. if( osIsNT() ){
  34755. OVERLAPPED ovlp;
  34756. memset(&ovlp, 0, sizeof(OVERLAPPED));
  34757. ovlp.Offset = offsetLow;
  34758. ovlp.OffsetHigh = offsetHigh;
  34759. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  34760. }else{
  34761. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  34762. numBytesHigh);
  34763. }
  34764. #endif
  34765. }
  34766. /*
  34767. ** Unlock a file region.
  34768. */
  34769. static BOOL winUnlockFile(
  34770. LPHANDLE phFile,
  34771. DWORD offsetLow,
  34772. DWORD offsetHigh,
  34773. DWORD numBytesLow,
  34774. DWORD numBytesHigh
  34775. ){
  34776. #if SQLITE_OS_WINCE
  34777. /*
  34778. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  34779. ** API UnlockFile.
  34780. */
  34781. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  34782. numBytesLow, numBytesHigh);
  34783. #else
  34784. if( osIsNT() ){
  34785. OVERLAPPED ovlp;
  34786. memset(&ovlp, 0, sizeof(OVERLAPPED));
  34787. ovlp.Offset = offsetLow;
  34788. ovlp.OffsetHigh = offsetHigh;
  34789. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  34790. }else{
  34791. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  34792. numBytesHigh);
  34793. }
  34794. #endif
  34795. }
  34796. /*****************************************************************************
  34797. ** The next group of routines implement the I/O methods specified
  34798. ** by the sqlite3_io_methods object.
  34799. ******************************************************************************/
  34800. /*
  34801. ** Some Microsoft compilers lack this definition.
  34802. */
  34803. #ifndef INVALID_SET_FILE_POINTER
  34804. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  34805. #endif
  34806. /*
  34807. ** Move the current position of the file handle passed as the first
  34808. ** argument to offset iOffset within the file. If successful, return 0.
  34809. ** Otherwise, set pFile->lastErrno and return non-zero.
  34810. */
  34811. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  34812. #if !SQLITE_OS_WINRT
  34813. LONG upperBits; /* Most sig. 32 bits of new offset */
  34814. LONG lowerBits; /* Least sig. 32 bits of new offset */
  34815. DWORD dwRet; /* Value returned by SetFilePointer() */
  34816. DWORD lastErrno; /* Value returned by GetLastError() */
  34817. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  34818. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  34819. lowerBits = (LONG)(iOffset & 0xffffffff);
  34820. /* API oddity: If successful, SetFilePointer() returns a dword
  34821. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  34822. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  34823. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  34824. ** whether an error has actually occurred, it is also necessary to call
  34825. ** GetLastError().
  34826. */
  34827. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  34828. if( (dwRet==INVALID_SET_FILE_POINTER
  34829. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  34830. pFile->lastErrno = lastErrno;
  34831. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  34832. "winSeekFile", pFile->zPath);
  34833. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  34834. return 1;
  34835. }
  34836. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  34837. return 0;
  34838. #else
  34839. /*
  34840. ** Same as above, except that this implementation works for WinRT.
  34841. */
  34842. LARGE_INTEGER x; /* The new offset */
  34843. BOOL bRet; /* Value returned by SetFilePointerEx() */
  34844. x.QuadPart = iOffset;
  34845. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  34846. if(!bRet){
  34847. pFile->lastErrno = osGetLastError();
  34848. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  34849. "winSeekFile", pFile->zPath);
  34850. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  34851. return 1;
  34852. }
  34853. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  34854. return 0;
  34855. #endif
  34856. }
  34857. #if SQLITE_MAX_MMAP_SIZE>0
  34858. /* Forward references to VFS helper methods used for memory mapped files */
  34859. static int winMapfile(winFile*, sqlite3_int64);
  34860. static int winUnmapfile(winFile*);
  34861. #endif
  34862. /*
  34863. ** Close a file.
  34864. **
  34865. ** It is reported that an attempt to close a handle might sometimes
  34866. ** fail. This is a very unreasonable result, but Windows is notorious
  34867. ** for being unreasonable so I do not doubt that it might happen. If
  34868. ** the close fails, we pause for 100 milliseconds and try again. As
  34869. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  34870. ** giving up and returning an error.
  34871. */
  34872. #define MX_CLOSE_ATTEMPT 3
  34873. static int winClose(sqlite3_file *id){
  34874. int rc, cnt = 0;
  34875. winFile *pFile = (winFile*)id;
  34876. assert( id!=0 );
  34877. #ifndef SQLITE_OMIT_WAL
  34878. assert( pFile->pShm==0 );
  34879. #endif
  34880. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  34881. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  34882. osGetCurrentProcessId(), pFile, pFile->h));
  34883. #if SQLITE_MAX_MMAP_SIZE>0
  34884. winUnmapfile(pFile);
  34885. #endif
  34886. do{
  34887. rc = osCloseHandle(pFile->h);
  34888. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  34889. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  34890. #if SQLITE_OS_WINCE
  34891. #define WINCE_DELETION_ATTEMPTS 3
  34892. winceDestroyLock(pFile);
  34893. if( pFile->zDeleteOnClose ){
  34894. int cnt = 0;
  34895. while(
  34896. osDeleteFileW(pFile->zDeleteOnClose)==0
  34897. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  34898. && cnt++ < WINCE_DELETION_ATTEMPTS
  34899. ){
  34900. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  34901. }
  34902. sqlite3_free(pFile->zDeleteOnClose);
  34903. }
  34904. #endif
  34905. if( rc ){
  34906. pFile->h = NULL;
  34907. }
  34908. OpenCounter(-1);
  34909. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  34910. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  34911. return rc ? SQLITE_OK
  34912. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  34913. "winClose", pFile->zPath);
  34914. }
  34915. /*
  34916. ** Read data from a file into a buffer. Return SQLITE_OK if all
  34917. ** bytes were read successfully and SQLITE_IOERR if anything goes
  34918. ** wrong.
  34919. */
  34920. static int winRead(
  34921. sqlite3_file *id, /* File to read from */
  34922. void *pBuf, /* Write content into this buffer */
  34923. int amt, /* Number of bytes to read */
  34924. sqlite3_int64 offset /* Begin reading at this offset */
  34925. ){
  34926. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  34927. OVERLAPPED overlapped; /* The offset for ReadFile. */
  34928. #endif
  34929. winFile *pFile = (winFile*)id; /* file handle */
  34930. DWORD nRead; /* Number of bytes actually read from file */
  34931. int nRetry = 0; /* Number of retrys */
  34932. assert( id!=0 );
  34933. assert( amt>0 );
  34934. assert( offset>=0 );
  34935. SimulateIOError(return SQLITE_IOERR_READ);
  34936. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  34937. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  34938. pFile->h, pBuf, amt, offset, pFile->locktype));
  34939. #if SQLITE_MAX_MMAP_SIZE>0
  34940. /* Deal with as much of this read request as possible by transfering
  34941. ** data from the memory mapping using memcpy(). */
  34942. if( offset<pFile->mmapSize ){
  34943. if( offset+amt <= pFile->mmapSize ){
  34944. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  34945. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34946. osGetCurrentProcessId(), pFile, pFile->h));
  34947. return SQLITE_OK;
  34948. }else{
  34949. int nCopy = (int)(pFile->mmapSize - offset);
  34950. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  34951. pBuf = &((u8 *)pBuf)[nCopy];
  34952. amt -= nCopy;
  34953. offset += nCopy;
  34954. }
  34955. }
  34956. #endif
  34957. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  34958. if( winSeekFile(pFile, offset) ){
  34959. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  34960. osGetCurrentProcessId(), pFile, pFile->h));
  34961. return SQLITE_FULL;
  34962. }
  34963. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  34964. #else
  34965. memset(&overlapped, 0, sizeof(OVERLAPPED));
  34966. overlapped.Offset = (LONG)(offset & 0xffffffff);
  34967. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  34968. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  34969. osGetLastError()!=ERROR_HANDLE_EOF ){
  34970. #endif
  34971. DWORD lastErrno;
  34972. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  34973. pFile->lastErrno = lastErrno;
  34974. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  34975. osGetCurrentProcessId(), pFile, pFile->h));
  34976. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  34977. "winRead", pFile->zPath);
  34978. }
  34979. winLogIoerr(nRetry, __LINE__);
  34980. if( nRead<(DWORD)amt ){
  34981. /* Unread parts of the buffer must be zero-filled */
  34982. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  34983. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  34984. osGetCurrentProcessId(), pFile, pFile->h));
  34985. return SQLITE_IOERR_SHORT_READ;
  34986. }
  34987. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34988. osGetCurrentProcessId(), pFile, pFile->h));
  34989. return SQLITE_OK;
  34990. }
  34991. /*
  34992. ** Write data from a buffer into a file. Return SQLITE_OK on success
  34993. ** or some other error code on failure.
  34994. */
  34995. static int winWrite(
  34996. sqlite3_file *id, /* File to write into */
  34997. const void *pBuf, /* The bytes to be written */
  34998. int amt, /* Number of bytes to write */
  34999. sqlite3_int64 offset /* Offset into the file to begin writing at */
  35000. ){
  35001. int rc = 0; /* True if error has occurred, else false */
  35002. winFile *pFile = (winFile*)id; /* File handle */
  35003. int nRetry = 0; /* Number of retries */
  35004. assert( amt>0 );
  35005. assert( pFile );
  35006. SimulateIOError(return SQLITE_IOERR_WRITE);
  35007. SimulateDiskfullError(return SQLITE_FULL);
  35008. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  35009. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  35010. pFile->h, pBuf, amt, offset, pFile->locktype));
  35011. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  35012. /* Deal with as much of this write request as possible by transfering
  35013. ** data from the memory mapping using memcpy(). */
  35014. if( offset<pFile->mmapSize ){
  35015. if( offset+amt <= pFile->mmapSize ){
  35016. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  35017. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35018. osGetCurrentProcessId(), pFile, pFile->h));
  35019. return SQLITE_OK;
  35020. }else{
  35021. int nCopy = (int)(pFile->mmapSize - offset);
  35022. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  35023. pBuf = &((u8 *)pBuf)[nCopy];
  35024. amt -= nCopy;
  35025. offset += nCopy;
  35026. }
  35027. }
  35028. #endif
  35029. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  35030. rc = winSeekFile(pFile, offset);
  35031. if( rc==0 ){
  35032. #else
  35033. {
  35034. #endif
  35035. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  35036. OVERLAPPED overlapped; /* The offset for WriteFile. */
  35037. #endif
  35038. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  35039. int nRem = amt; /* Number of bytes yet to be written */
  35040. DWORD nWrite; /* Bytes written by each WriteFile() call */
  35041. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  35042. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  35043. memset(&overlapped, 0, sizeof(OVERLAPPED));
  35044. overlapped.Offset = (LONG)(offset & 0xffffffff);
  35045. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  35046. #endif
  35047. while( nRem>0 ){
  35048. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  35049. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  35050. #else
  35051. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  35052. #endif
  35053. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  35054. break;
  35055. }
  35056. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  35057. if( nWrite==0 || nWrite>(DWORD)nRem ){
  35058. lastErrno = osGetLastError();
  35059. break;
  35060. }
  35061. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  35062. offset += nWrite;
  35063. overlapped.Offset = (LONG)(offset & 0xffffffff);
  35064. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  35065. #endif
  35066. aRem += nWrite;
  35067. nRem -= nWrite;
  35068. }
  35069. if( nRem>0 ){
  35070. pFile->lastErrno = lastErrno;
  35071. rc = 1;
  35072. }
  35073. }
  35074. if( rc ){
  35075. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  35076. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  35077. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  35078. osGetCurrentProcessId(), pFile, pFile->h));
  35079. return winLogError(SQLITE_FULL, pFile->lastErrno,
  35080. "winWrite1", pFile->zPath);
  35081. }
  35082. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  35083. osGetCurrentProcessId(), pFile, pFile->h));
  35084. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  35085. "winWrite2", pFile->zPath);
  35086. }else{
  35087. winLogIoerr(nRetry, __LINE__);
  35088. }
  35089. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35090. osGetCurrentProcessId(), pFile, pFile->h));
  35091. return SQLITE_OK;
  35092. }
  35093. /*
  35094. ** Truncate an open file to a specified size
  35095. */
  35096. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  35097. winFile *pFile = (winFile*)id; /* File handle object */
  35098. int rc = SQLITE_OK; /* Return code for this function */
  35099. DWORD lastErrno;
  35100. assert( pFile );
  35101. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  35102. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  35103. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  35104. /* If the user has configured a chunk-size for this file, truncate the
  35105. ** file so that it consists of an integer number of chunks (i.e. the
  35106. ** actual file size after the operation may be larger than the requested
  35107. ** size).
  35108. */
  35109. if( pFile->szChunk>0 ){
  35110. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  35111. }
  35112. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  35113. if( winSeekFile(pFile, nByte) ){
  35114. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  35115. "winTruncate1", pFile->zPath);
  35116. }else if( 0==osSetEndOfFile(pFile->h) &&
  35117. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  35118. pFile->lastErrno = lastErrno;
  35119. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  35120. "winTruncate2", pFile->zPath);
  35121. }
  35122. #if SQLITE_MAX_MMAP_SIZE>0
  35123. /* If the file was truncated to a size smaller than the currently
  35124. ** mapped region, reduce the effective mapping size as well. SQLite will
  35125. ** use read() and write() to access data beyond this point from now on.
  35126. */
  35127. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  35128. pFile->mmapSize = nByte;
  35129. }
  35130. #endif
  35131. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  35132. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  35133. return rc;
  35134. }
  35135. #ifdef SQLITE_TEST
  35136. /*
  35137. ** Count the number of fullsyncs and normal syncs. This is used to test
  35138. ** that syncs and fullsyncs are occuring at the right times.
  35139. */
  35140. SQLITE_API int sqlite3_sync_count = 0;
  35141. SQLITE_API int sqlite3_fullsync_count = 0;
  35142. #endif
  35143. /*
  35144. ** Make sure all writes to a particular file are committed to disk.
  35145. */
  35146. static int winSync(sqlite3_file *id, int flags){
  35147. #ifndef SQLITE_NO_SYNC
  35148. /*
  35149. ** Used only when SQLITE_NO_SYNC is not defined.
  35150. */
  35151. BOOL rc;
  35152. #endif
  35153. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  35154. defined(SQLITE_HAVE_OS_TRACE)
  35155. /*
  35156. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  35157. ** OSTRACE() macros.
  35158. */
  35159. winFile *pFile = (winFile*)id;
  35160. #else
  35161. UNUSED_PARAMETER(id);
  35162. #endif
  35163. assert( pFile );
  35164. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  35165. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  35166. || (flags&0x0F)==SQLITE_SYNC_FULL
  35167. );
  35168. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  35169. ** line is to test that doing so does not cause any problems.
  35170. */
  35171. SimulateDiskfullError( return SQLITE_FULL );
  35172. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  35173. osGetCurrentProcessId(), pFile, pFile->h, flags,
  35174. pFile->locktype));
  35175. #ifndef SQLITE_TEST
  35176. UNUSED_PARAMETER(flags);
  35177. #else
  35178. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  35179. sqlite3_fullsync_count++;
  35180. }
  35181. sqlite3_sync_count++;
  35182. #endif
  35183. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  35184. ** no-op
  35185. */
  35186. #ifdef SQLITE_NO_SYNC
  35187. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35188. osGetCurrentProcessId(), pFile, pFile->h));
  35189. return SQLITE_OK;
  35190. #else
  35191. #if SQLITE_MAX_MMAP_SIZE>0
  35192. if( pFile->pMapRegion ){
  35193. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  35194. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  35195. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  35196. pFile, pFile->pMapRegion));
  35197. }else{
  35198. pFile->lastErrno = osGetLastError();
  35199. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  35200. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  35201. pFile, pFile->pMapRegion));
  35202. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  35203. "winSync1", pFile->zPath);
  35204. }
  35205. }
  35206. #endif
  35207. rc = osFlushFileBuffers(pFile->h);
  35208. SimulateIOError( rc=FALSE );
  35209. if( rc ){
  35210. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  35211. osGetCurrentProcessId(), pFile, pFile->h));
  35212. return SQLITE_OK;
  35213. }else{
  35214. pFile->lastErrno = osGetLastError();
  35215. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  35216. osGetCurrentProcessId(), pFile, pFile->h));
  35217. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  35218. "winSync2", pFile->zPath);
  35219. }
  35220. #endif
  35221. }
  35222. /*
  35223. ** Determine the current size of a file in bytes
  35224. */
  35225. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  35226. winFile *pFile = (winFile*)id;
  35227. int rc = SQLITE_OK;
  35228. assert( id!=0 );
  35229. assert( pSize!=0 );
  35230. SimulateIOError(return SQLITE_IOERR_FSTAT);
  35231. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  35232. #if SQLITE_OS_WINRT
  35233. {
  35234. FILE_STANDARD_INFO info;
  35235. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  35236. &info, sizeof(info)) ){
  35237. *pSize = info.EndOfFile.QuadPart;
  35238. }else{
  35239. pFile->lastErrno = osGetLastError();
  35240. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  35241. "winFileSize", pFile->zPath);
  35242. }
  35243. }
  35244. #else
  35245. {
  35246. DWORD upperBits;
  35247. DWORD lowerBits;
  35248. DWORD lastErrno;
  35249. lowerBits = osGetFileSize(pFile->h, &upperBits);
  35250. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  35251. if( (lowerBits == INVALID_FILE_SIZE)
  35252. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  35253. pFile->lastErrno = lastErrno;
  35254. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  35255. "winFileSize", pFile->zPath);
  35256. }
  35257. }
  35258. #endif
  35259. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  35260. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  35261. return rc;
  35262. }
  35263. /*
  35264. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  35265. */
  35266. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  35267. # define LOCKFILE_FAIL_IMMEDIATELY 1
  35268. #endif
  35269. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  35270. # define LOCKFILE_EXCLUSIVE_LOCK 2
  35271. #endif
  35272. /*
  35273. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  35274. ** When the LockFile function was used, it was always expected to fail
  35275. ** immediately if the lock could not be obtained. Also, it always expected to
  35276. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  35277. ** and reflect those expectations; therefore, they should not be changed.
  35278. */
  35279. #ifndef SQLITE_LOCKFILE_FLAGS
  35280. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  35281. LOCKFILE_EXCLUSIVE_LOCK)
  35282. #endif
  35283. /*
  35284. ** Currently, SQLite never calls the LockFileEx function without wanting the
  35285. ** call to fail immediately if the lock cannot be obtained.
  35286. */
  35287. #ifndef SQLITE_LOCKFILEEX_FLAGS
  35288. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  35289. #endif
  35290. /*
  35291. ** Acquire a reader lock.
  35292. ** Different API routines are called depending on whether or not this
  35293. ** is Win9x or WinNT.
  35294. */
  35295. static int winGetReadLock(winFile *pFile){
  35296. int res;
  35297. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  35298. if( osIsNT() ){
  35299. #if SQLITE_OS_WINCE
  35300. /*
  35301. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  35302. ** API LockFileEx.
  35303. */
  35304. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  35305. #else
  35306. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  35307. SHARED_SIZE, 0);
  35308. #endif
  35309. }
  35310. #ifdef SQLITE_WIN32_HAS_ANSI
  35311. else{
  35312. int lk;
  35313. sqlite3_randomness(sizeof(lk), &lk);
  35314. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  35315. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  35316. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  35317. }
  35318. #endif
  35319. if( res == 0 ){
  35320. pFile->lastErrno = osGetLastError();
  35321. /* No need to log a failure to lock */
  35322. }
  35323. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  35324. return res;
  35325. }
  35326. /*
  35327. ** Undo a readlock
  35328. */
  35329. static int winUnlockReadLock(winFile *pFile){
  35330. int res;
  35331. DWORD lastErrno;
  35332. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  35333. if( osIsNT() ){
  35334. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  35335. }
  35336. #ifdef SQLITE_WIN32_HAS_ANSI
  35337. else{
  35338. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  35339. }
  35340. #endif
  35341. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  35342. pFile->lastErrno = lastErrno;
  35343. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  35344. "winUnlockReadLock", pFile->zPath);
  35345. }
  35346. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  35347. return res;
  35348. }
  35349. /*
  35350. ** Lock the file with the lock specified by parameter locktype - one
  35351. ** of the following:
  35352. **
  35353. ** (1) SHARED_LOCK
  35354. ** (2) RESERVED_LOCK
  35355. ** (3) PENDING_LOCK
  35356. ** (4) EXCLUSIVE_LOCK
  35357. **
  35358. ** Sometimes when requesting one lock state, additional lock states
  35359. ** are inserted in between. The locking might fail on one of the later
  35360. ** transitions leaving the lock state different from what it started but
  35361. ** still short of its goal. The following chart shows the allowed
  35362. ** transitions and the inserted intermediate states:
  35363. **
  35364. ** UNLOCKED -> SHARED
  35365. ** SHARED -> RESERVED
  35366. ** SHARED -> (PENDING) -> EXCLUSIVE
  35367. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35368. ** PENDING -> EXCLUSIVE
  35369. **
  35370. ** This routine will only increase a lock. The winUnlock() routine
  35371. ** erases all locks at once and returns us immediately to locking level 0.
  35372. ** It is not possible to lower the locking level one step at a time. You
  35373. ** must go straight to locking level 0.
  35374. */
  35375. static int winLock(sqlite3_file *id, int locktype){
  35376. int rc = SQLITE_OK; /* Return code from subroutines */
  35377. int res = 1; /* Result of a Windows lock call */
  35378. int newLocktype; /* Set pFile->locktype to this value before exiting */
  35379. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  35380. winFile *pFile = (winFile*)id;
  35381. DWORD lastErrno = NO_ERROR;
  35382. assert( id!=0 );
  35383. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  35384. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  35385. /* If there is already a lock of this type or more restrictive on the
  35386. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  35387. ** sqlite3OsEnterMutex() hasn't been called yet.
  35388. */
  35389. if( pFile->locktype>=locktype ){
  35390. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  35391. return SQLITE_OK;
  35392. }
  35393. /* Do not allow any kind of write-lock on a read-only database
  35394. */
  35395. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  35396. return SQLITE_IOERR_LOCK;
  35397. }
  35398. /* Make sure the locking sequence is correct
  35399. */
  35400. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  35401. assert( locktype!=PENDING_LOCK );
  35402. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  35403. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  35404. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  35405. ** the PENDING_LOCK byte is temporary.
  35406. */
  35407. newLocktype = pFile->locktype;
  35408. if( (pFile->locktype==NO_LOCK)
  35409. || ( (locktype==EXCLUSIVE_LOCK)
  35410. && (pFile->locktype==RESERVED_LOCK))
  35411. ){
  35412. int cnt = 3;
  35413. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  35414. PENDING_BYTE, 0, 1, 0))==0 ){
  35415. /* Try 3 times to get the pending lock. This is needed to work
  35416. ** around problems caused by indexing and/or anti-virus software on
  35417. ** Windows systems.
  35418. ** If you are using this code as a model for alternative VFSes, do not
  35419. ** copy this retry logic. It is a hack intended for Windows only.
  35420. */
  35421. lastErrno = osGetLastError();
  35422. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  35423. pFile->h, cnt, res));
  35424. if( lastErrno==ERROR_INVALID_HANDLE ){
  35425. pFile->lastErrno = lastErrno;
  35426. rc = SQLITE_IOERR_LOCK;
  35427. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  35428. pFile->h, cnt, sqlite3ErrName(rc)));
  35429. return rc;
  35430. }
  35431. if( cnt ) sqlite3_win32_sleep(1);
  35432. }
  35433. gotPendingLock = res;
  35434. if( !res ){
  35435. lastErrno = osGetLastError();
  35436. }
  35437. }
  35438. /* Acquire a shared lock
  35439. */
  35440. if( locktype==SHARED_LOCK && res ){
  35441. assert( pFile->locktype==NO_LOCK );
  35442. res = winGetReadLock(pFile);
  35443. if( res ){
  35444. newLocktype = SHARED_LOCK;
  35445. }else{
  35446. lastErrno = osGetLastError();
  35447. }
  35448. }
  35449. /* Acquire a RESERVED lock
  35450. */
  35451. if( locktype==RESERVED_LOCK && res ){
  35452. assert( pFile->locktype==SHARED_LOCK );
  35453. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  35454. if( res ){
  35455. newLocktype = RESERVED_LOCK;
  35456. }else{
  35457. lastErrno = osGetLastError();
  35458. }
  35459. }
  35460. /* Acquire a PENDING lock
  35461. */
  35462. if( locktype==EXCLUSIVE_LOCK && res ){
  35463. newLocktype = PENDING_LOCK;
  35464. gotPendingLock = 0;
  35465. }
  35466. /* Acquire an EXCLUSIVE lock
  35467. */
  35468. if( locktype==EXCLUSIVE_LOCK && res ){
  35469. assert( pFile->locktype>=SHARED_LOCK );
  35470. res = winUnlockReadLock(pFile);
  35471. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  35472. SHARED_SIZE, 0);
  35473. if( res ){
  35474. newLocktype = EXCLUSIVE_LOCK;
  35475. }else{
  35476. lastErrno = osGetLastError();
  35477. winGetReadLock(pFile);
  35478. }
  35479. }
  35480. /* If we are holding a PENDING lock that ought to be released, then
  35481. ** release it now.
  35482. */
  35483. if( gotPendingLock && locktype==SHARED_LOCK ){
  35484. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  35485. }
  35486. /* Update the state of the lock has held in the file descriptor then
  35487. ** return the appropriate result code.
  35488. */
  35489. if( res ){
  35490. rc = SQLITE_OK;
  35491. }else{
  35492. pFile->lastErrno = lastErrno;
  35493. rc = SQLITE_BUSY;
  35494. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  35495. pFile->h, locktype, newLocktype));
  35496. }
  35497. pFile->locktype = (u8)newLocktype;
  35498. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  35499. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  35500. return rc;
  35501. }
  35502. /*
  35503. ** This routine checks if there is a RESERVED lock held on the specified
  35504. ** file by this or any other process. If such a lock is held, return
  35505. ** non-zero, otherwise zero.
  35506. */
  35507. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  35508. int res;
  35509. winFile *pFile = (winFile*)id;
  35510. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  35511. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  35512. assert( id!=0 );
  35513. if( pFile->locktype>=RESERVED_LOCK ){
  35514. res = 1;
  35515. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  35516. }else{
  35517. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  35518. if( res ){
  35519. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  35520. }
  35521. res = !res;
  35522. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  35523. }
  35524. *pResOut = res;
  35525. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  35526. pFile->h, pResOut, *pResOut));
  35527. return SQLITE_OK;
  35528. }
  35529. /*
  35530. ** Lower the locking level on file descriptor id to locktype. locktype
  35531. ** must be either NO_LOCK or SHARED_LOCK.
  35532. **
  35533. ** If the locking level of the file descriptor is already at or below
  35534. ** the requested locking level, this routine is a no-op.
  35535. **
  35536. ** It is not possible for this routine to fail if the second argument
  35537. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  35538. ** might return SQLITE_IOERR;
  35539. */
  35540. static int winUnlock(sqlite3_file *id, int locktype){
  35541. int type;
  35542. winFile *pFile = (winFile*)id;
  35543. int rc = SQLITE_OK;
  35544. assert( pFile!=0 );
  35545. assert( locktype<=SHARED_LOCK );
  35546. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  35547. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  35548. type = pFile->locktype;
  35549. if( type>=EXCLUSIVE_LOCK ){
  35550. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  35551. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  35552. /* This should never happen. We should always be able to
  35553. ** reacquire the read lock */
  35554. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  35555. "winUnlock", pFile->zPath);
  35556. }
  35557. }
  35558. if( type>=RESERVED_LOCK ){
  35559. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  35560. }
  35561. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  35562. winUnlockReadLock(pFile);
  35563. }
  35564. if( type>=PENDING_LOCK ){
  35565. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  35566. }
  35567. pFile->locktype = (u8)locktype;
  35568. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  35569. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  35570. return rc;
  35571. }
  35572. /*
  35573. ** If *pArg is initially negative then this is a query. Set *pArg to
  35574. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  35575. **
  35576. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  35577. */
  35578. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  35579. if( *pArg<0 ){
  35580. *pArg = (pFile->ctrlFlags & mask)!=0;
  35581. }else if( (*pArg)==0 ){
  35582. pFile->ctrlFlags &= ~mask;
  35583. }else{
  35584. pFile->ctrlFlags |= mask;
  35585. }
  35586. }
  35587. /* Forward references to VFS helper methods used for temporary files */
  35588. static int winGetTempname(sqlite3_vfs *, char **);
  35589. static int winIsDir(const void *);
  35590. static BOOL winIsDriveLetterAndColon(const char *);
  35591. /*
  35592. ** Control and query of the open file handle.
  35593. */
  35594. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  35595. winFile *pFile = (winFile*)id;
  35596. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  35597. switch( op ){
  35598. case SQLITE_FCNTL_LOCKSTATE: {
  35599. *(int*)pArg = pFile->locktype;
  35600. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35601. return SQLITE_OK;
  35602. }
  35603. case SQLITE_LAST_ERRNO: {
  35604. *(int*)pArg = (int)pFile->lastErrno;
  35605. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35606. return SQLITE_OK;
  35607. }
  35608. case SQLITE_FCNTL_CHUNK_SIZE: {
  35609. pFile->szChunk = *(int *)pArg;
  35610. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35611. return SQLITE_OK;
  35612. }
  35613. case SQLITE_FCNTL_SIZE_HINT: {
  35614. if( pFile->szChunk>0 ){
  35615. sqlite3_int64 oldSz;
  35616. int rc = winFileSize(id, &oldSz);
  35617. if( rc==SQLITE_OK ){
  35618. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  35619. if( newSz>oldSz ){
  35620. SimulateIOErrorBenign(1);
  35621. rc = winTruncate(id, newSz);
  35622. SimulateIOErrorBenign(0);
  35623. }
  35624. }
  35625. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  35626. return rc;
  35627. }
  35628. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35629. return SQLITE_OK;
  35630. }
  35631. case SQLITE_FCNTL_PERSIST_WAL: {
  35632. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  35633. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35634. return SQLITE_OK;
  35635. }
  35636. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  35637. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  35638. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35639. return SQLITE_OK;
  35640. }
  35641. case SQLITE_FCNTL_VFSNAME: {
  35642. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  35643. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35644. return SQLITE_OK;
  35645. }
  35646. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  35647. int *a = (int*)pArg;
  35648. if( a[0]>0 ){
  35649. winIoerrRetry = a[0];
  35650. }else{
  35651. a[0] = winIoerrRetry;
  35652. }
  35653. if( a[1]>0 ){
  35654. winIoerrRetryDelay = a[1];
  35655. }else{
  35656. a[1] = winIoerrRetryDelay;
  35657. }
  35658. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  35659. return SQLITE_OK;
  35660. }
  35661. #ifdef SQLITE_TEST
  35662. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  35663. LPHANDLE phFile = (LPHANDLE)pArg;
  35664. HANDLE hOldFile = pFile->h;
  35665. pFile->h = *phFile;
  35666. *phFile = hOldFile;
  35667. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  35668. hOldFile, pFile->h));
  35669. return SQLITE_OK;
  35670. }
  35671. #endif
  35672. case SQLITE_FCNTL_TEMPFILENAME: {
  35673. char *zTFile = 0;
  35674. int rc = winGetTempname(pFile->pVfs, &zTFile);
  35675. if( rc==SQLITE_OK ){
  35676. *(char**)pArg = zTFile;
  35677. }
  35678. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  35679. return rc;
  35680. }
  35681. #if SQLITE_MAX_MMAP_SIZE>0
  35682. case SQLITE_FCNTL_MMAP_SIZE: {
  35683. i64 newLimit = *(i64*)pArg;
  35684. int rc = SQLITE_OK;
  35685. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  35686. newLimit = sqlite3GlobalConfig.mxMmap;
  35687. }
  35688. *(i64*)pArg = pFile->mmapSizeMax;
  35689. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  35690. pFile->mmapSizeMax = newLimit;
  35691. if( pFile->mmapSize>0 ){
  35692. winUnmapfile(pFile);
  35693. rc = winMapfile(pFile, -1);
  35694. }
  35695. }
  35696. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  35697. return rc;
  35698. }
  35699. #endif
  35700. }
  35701. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  35702. return SQLITE_NOTFOUND;
  35703. }
  35704. /*
  35705. ** Return the sector size in bytes of the underlying block device for
  35706. ** the specified file. This is almost always 512 bytes, but may be
  35707. ** larger for some devices.
  35708. **
  35709. ** SQLite code assumes this function cannot fail. It also assumes that
  35710. ** if two files are created in the same file-system directory (i.e.
  35711. ** a database and its journal file) that the sector size will be the
  35712. ** same for both.
  35713. */
  35714. static int winSectorSize(sqlite3_file *id){
  35715. (void)id;
  35716. return SQLITE_DEFAULT_SECTOR_SIZE;
  35717. }
  35718. /*
  35719. ** Return a vector of device characteristics.
  35720. */
  35721. static int winDeviceCharacteristics(sqlite3_file *id){
  35722. winFile *p = (winFile*)id;
  35723. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  35724. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  35725. }
  35726. /*
  35727. ** Windows will only let you create file view mappings
  35728. ** on allocation size granularity boundaries.
  35729. ** During sqlite3_os_init() we do a GetSystemInfo()
  35730. ** to get the granularity size.
  35731. */
  35732. static SYSTEM_INFO winSysInfo;
  35733. #ifndef SQLITE_OMIT_WAL
  35734. /*
  35735. ** Helper functions to obtain and relinquish the global mutex. The
  35736. ** global mutex is used to protect the winLockInfo objects used by
  35737. ** this file, all of which may be shared by multiple threads.
  35738. **
  35739. ** Function winShmMutexHeld() is used to assert() that the global mutex
  35740. ** is held when required. This function is only used as part of assert()
  35741. ** statements. e.g.
  35742. **
  35743. ** winShmEnterMutex()
  35744. ** assert( winShmMutexHeld() );
  35745. ** winShmLeaveMutex()
  35746. */
  35747. static void winShmEnterMutex(void){
  35748. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  35749. }
  35750. static void winShmLeaveMutex(void){
  35751. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  35752. }
  35753. #ifndef NDEBUG
  35754. static int winShmMutexHeld(void) {
  35755. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  35756. }
  35757. #endif
  35758. /*
  35759. ** Object used to represent a single file opened and mmapped to provide
  35760. ** shared memory. When multiple threads all reference the same
  35761. ** log-summary, each thread has its own winFile object, but they all
  35762. ** point to a single instance of this object. In other words, each
  35763. ** log-summary is opened only once per process.
  35764. **
  35765. ** winShmMutexHeld() must be true when creating or destroying
  35766. ** this object or while reading or writing the following fields:
  35767. **
  35768. ** nRef
  35769. ** pNext
  35770. **
  35771. ** The following fields are read-only after the object is created:
  35772. **
  35773. ** fid
  35774. ** zFilename
  35775. **
  35776. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  35777. ** winShmMutexHeld() is true when reading or writing any other field
  35778. ** in this structure.
  35779. **
  35780. */
  35781. struct winShmNode {
  35782. sqlite3_mutex *mutex; /* Mutex to access this object */
  35783. char *zFilename; /* Name of the file */
  35784. winFile hFile; /* File handle from winOpen */
  35785. int szRegion; /* Size of shared-memory regions */
  35786. int nRegion; /* Size of array apRegion */
  35787. struct ShmRegion {
  35788. HANDLE hMap; /* File handle from CreateFileMapping */
  35789. void *pMap;
  35790. } *aRegion;
  35791. DWORD lastErrno; /* The Windows errno from the last I/O error */
  35792. int nRef; /* Number of winShm objects pointing to this */
  35793. winShm *pFirst; /* All winShm objects pointing to this */
  35794. winShmNode *pNext; /* Next in list of all winShmNode objects */
  35795. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  35796. u8 nextShmId; /* Next available winShm.id value */
  35797. #endif
  35798. };
  35799. /*
  35800. ** A global array of all winShmNode objects.
  35801. **
  35802. ** The winShmMutexHeld() must be true while reading or writing this list.
  35803. */
  35804. static winShmNode *winShmNodeList = 0;
  35805. /*
  35806. ** Structure used internally by this VFS to record the state of an
  35807. ** open shared memory connection.
  35808. **
  35809. ** The following fields are initialized when this object is created and
  35810. ** are read-only thereafter:
  35811. **
  35812. ** winShm.pShmNode
  35813. ** winShm.id
  35814. **
  35815. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  35816. ** while accessing any read/write fields.
  35817. */
  35818. struct winShm {
  35819. winShmNode *pShmNode; /* The underlying winShmNode object */
  35820. winShm *pNext; /* Next winShm with the same winShmNode */
  35821. u8 hasMutex; /* True if holding the winShmNode mutex */
  35822. u16 sharedMask; /* Mask of shared locks held */
  35823. u16 exclMask; /* Mask of exclusive locks held */
  35824. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  35825. u8 id; /* Id of this connection with its winShmNode */
  35826. #endif
  35827. };
  35828. /*
  35829. ** Constants used for locking
  35830. */
  35831. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  35832. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  35833. /*
  35834. ** Apply advisory locks for all n bytes beginning at ofst.
  35835. */
  35836. #define _SHM_UNLCK 1
  35837. #define _SHM_RDLCK 2
  35838. #define _SHM_WRLCK 3
  35839. static int winShmSystemLock(
  35840. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  35841. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  35842. int ofst, /* Offset to first byte to be locked/unlocked */
  35843. int nByte /* Number of bytes to lock or unlock */
  35844. ){
  35845. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  35846. /* Access to the winShmNode object is serialized by the caller */
  35847. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  35848. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  35849. pFile->hFile.h, lockType, ofst, nByte));
  35850. /* Release/Acquire the system-level lock */
  35851. if( lockType==_SHM_UNLCK ){
  35852. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  35853. }else{
  35854. /* Initialize the locking parameters */
  35855. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  35856. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  35857. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  35858. }
  35859. if( rc!= 0 ){
  35860. rc = SQLITE_OK;
  35861. }else{
  35862. pFile->lastErrno = osGetLastError();
  35863. rc = SQLITE_BUSY;
  35864. }
  35865. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  35866. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  35867. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  35868. return rc;
  35869. }
  35870. /* Forward references to VFS methods */
  35871. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  35872. static int winDelete(sqlite3_vfs *,const char*,int);
  35873. /*
  35874. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  35875. **
  35876. ** This is not a VFS shared-memory method; it is a utility function called
  35877. ** by VFS shared-memory methods.
  35878. */
  35879. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  35880. winShmNode **pp;
  35881. winShmNode *p;
  35882. assert( winShmMutexHeld() );
  35883. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  35884. osGetCurrentProcessId(), deleteFlag));
  35885. pp = &winShmNodeList;
  35886. while( (p = *pp)!=0 ){
  35887. if( p->nRef==0 ){
  35888. int i;
  35889. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  35890. for(i=0; i<p->nRegion; i++){
  35891. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  35892. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  35893. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  35894. UNUSED_VARIABLE_VALUE(bRc);
  35895. bRc = osCloseHandle(p->aRegion[i].hMap);
  35896. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  35897. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  35898. UNUSED_VARIABLE_VALUE(bRc);
  35899. }
  35900. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  35901. SimulateIOErrorBenign(1);
  35902. winClose((sqlite3_file *)&p->hFile);
  35903. SimulateIOErrorBenign(0);
  35904. }
  35905. if( deleteFlag ){
  35906. SimulateIOErrorBenign(1);
  35907. sqlite3BeginBenignMalloc();
  35908. winDelete(pVfs, p->zFilename, 0);
  35909. sqlite3EndBenignMalloc();
  35910. SimulateIOErrorBenign(0);
  35911. }
  35912. *pp = p->pNext;
  35913. sqlite3_free(p->aRegion);
  35914. sqlite3_free(p);
  35915. }else{
  35916. pp = &p->pNext;
  35917. }
  35918. }
  35919. }
  35920. /*
  35921. ** Open the shared-memory area associated with database file pDbFd.
  35922. **
  35923. ** When opening a new shared-memory file, if no other instances of that
  35924. ** file are currently open, in this process or in other processes, then
  35925. ** the file must be truncated to zero length or have its header cleared.
  35926. */
  35927. static int winOpenSharedMemory(winFile *pDbFd){
  35928. struct winShm *p; /* The connection to be opened */
  35929. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  35930. int rc; /* Result code */
  35931. struct winShmNode *pNew; /* Newly allocated winShmNode */
  35932. int nName; /* Size of zName in bytes */
  35933. assert( pDbFd->pShm==0 ); /* Not previously opened */
  35934. /* Allocate space for the new sqlite3_shm object. Also speculatively
  35935. ** allocate space for a new winShmNode and filename.
  35936. */
  35937. p = sqlite3MallocZero( sizeof(*p) );
  35938. if( p==0 ) return SQLITE_IOERR_NOMEM;
  35939. nName = sqlite3Strlen30(pDbFd->zPath);
  35940. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  35941. if( pNew==0 ){
  35942. sqlite3_free(p);
  35943. return SQLITE_IOERR_NOMEM;
  35944. }
  35945. pNew->zFilename = (char*)&pNew[1];
  35946. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  35947. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  35948. /* Look to see if there is an existing winShmNode that can be used.
  35949. ** If no matching winShmNode currently exists, create a new one.
  35950. */
  35951. winShmEnterMutex();
  35952. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  35953. /* TBD need to come up with better match here. Perhaps
  35954. ** use FILE_ID_BOTH_DIR_INFO Structure.
  35955. */
  35956. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  35957. }
  35958. if( pShmNode ){
  35959. sqlite3_free(pNew);
  35960. }else{
  35961. pShmNode = pNew;
  35962. pNew = 0;
  35963. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  35964. pShmNode->pNext = winShmNodeList;
  35965. winShmNodeList = pShmNode;
  35966. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  35967. if( pShmNode->mutex==0 ){
  35968. rc = SQLITE_IOERR_NOMEM;
  35969. goto shm_open_err;
  35970. }
  35971. rc = winOpen(pDbFd->pVfs,
  35972. pShmNode->zFilename, /* Name of the file (UTF-8) */
  35973. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  35974. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  35975. 0);
  35976. if( SQLITE_OK!=rc ){
  35977. goto shm_open_err;
  35978. }
  35979. /* Check to see if another process is holding the dead-man switch.
  35980. ** If not, truncate the file to zero length.
  35981. */
  35982. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  35983. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  35984. if( rc!=SQLITE_OK ){
  35985. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  35986. "winOpenShm", pDbFd->zPath);
  35987. }
  35988. }
  35989. if( rc==SQLITE_OK ){
  35990. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  35991. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  35992. }
  35993. if( rc ) goto shm_open_err;
  35994. }
  35995. /* Make the new connection a child of the winShmNode */
  35996. p->pShmNode = pShmNode;
  35997. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  35998. p->id = pShmNode->nextShmId++;
  35999. #endif
  36000. pShmNode->nRef++;
  36001. pDbFd->pShm = p;
  36002. winShmLeaveMutex();
  36003. /* The reference count on pShmNode has already been incremented under
  36004. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  36005. ** new (struct winShm) object to the pShmNode has been set. All that is
  36006. ** left to do is to link the new object into the linked list starting
  36007. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  36008. ** mutex.
  36009. */
  36010. sqlite3_mutex_enter(pShmNode->mutex);
  36011. p->pNext = pShmNode->pFirst;
  36012. pShmNode->pFirst = p;
  36013. sqlite3_mutex_leave(pShmNode->mutex);
  36014. return SQLITE_OK;
  36015. /* Jump here on any error */
  36016. shm_open_err:
  36017. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  36018. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  36019. sqlite3_free(p);
  36020. sqlite3_free(pNew);
  36021. winShmLeaveMutex();
  36022. return rc;
  36023. }
  36024. /*
  36025. ** Close a connection to shared-memory. Delete the underlying
  36026. ** storage if deleteFlag is true.
  36027. */
  36028. static int winShmUnmap(
  36029. sqlite3_file *fd, /* Database holding shared memory */
  36030. int deleteFlag /* Delete after closing if true */
  36031. ){
  36032. winFile *pDbFd; /* Database holding shared-memory */
  36033. winShm *p; /* The connection to be closed */
  36034. winShmNode *pShmNode; /* The underlying shared-memory file */
  36035. winShm **pp; /* For looping over sibling connections */
  36036. pDbFd = (winFile*)fd;
  36037. p = pDbFd->pShm;
  36038. if( p==0 ) return SQLITE_OK;
  36039. pShmNode = p->pShmNode;
  36040. /* Remove connection p from the set of connections associated
  36041. ** with pShmNode */
  36042. sqlite3_mutex_enter(pShmNode->mutex);
  36043. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  36044. *pp = p->pNext;
  36045. /* Free the connection p */
  36046. sqlite3_free(p);
  36047. pDbFd->pShm = 0;
  36048. sqlite3_mutex_leave(pShmNode->mutex);
  36049. /* If pShmNode->nRef has reached 0, then close the underlying
  36050. ** shared-memory file, too */
  36051. winShmEnterMutex();
  36052. assert( pShmNode->nRef>0 );
  36053. pShmNode->nRef--;
  36054. if( pShmNode->nRef==0 ){
  36055. winShmPurge(pDbFd->pVfs, deleteFlag);
  36056. }
  36057. winShmLeaveMutex();
  36058. return SQLITE_OK;
  36059. }
  36060. /*
  36061. ** Change the lock state for a shared-memory segment.
  36062. */
  36063. static int winShmLock(
  36064. sqlite3_file *fd, /* Database file holding the shared memory */
  36065. int ofst, /* First lock to acquire or release */
  36066. int n, /* Number of locks to acquire or release */
  36067. int flags /* What to do with the lock */
  36068. ){
  36069. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  36070. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  36071. winShm *pX; /* For looping over all siblings */
  36072. winShmNode *pShmNode = p->pShmNode;
  36073. int rc = SQLITE_OK; /* Result code */
  36074. u16 mask; /* Mask of locks to take or release */
  36075. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  36076. assert( n>=1 );
  36077. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  36078. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  36079. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  36080. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  36081. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  36082. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  36083. assert( n>1 || mask==(1<<ofst) );
  36084. sqlite3_mutex_enter(pShmNode->mutex);
  36085. if( flags & SQLITE_SHM_UNLOCK ){
  36086. u16 allMask = 0; /* Mask of locks held by siblings */
  36087. /* See if any siblings hold this same lock */
  36088. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36089. if( pX==p ) continue;
  36090. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  36091. allMask |= pX->sharedMask;
  36092. }
  36093. /* Unlock the system-level locks */
  36094. if( (mask & allMask)==0 ){
  36095. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  36096. }else{
  36097. rc = SQLITE_OK;
  36098. }
  36099. /* Undo the local locks */
  36100. if( rc==SQLITE_OK ){
  36101. p->exclMask &= ~mask;
  36102. p->sharedMask &= ~mask;
  36103. }
  36104. }else if( flags & SQLITE_SHM_SHARED ){
  36105. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  36106. /* Find out which shared locks are already held by sibling connections.
  36107. ** If any sibling already holds an exclusive lock, go ahead and return
  36108. ** SQLITE_BUSY.
  36109. */
  36110. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36111. if( (pX->exclMask & mask)!=0 ){
  36112. rc = SQLITE_BUSY;
  36113. break;
  36114. }
  36115. allShared |= pX->sharedMask;
  36116. }
  36117. /* Get shared locks at the system level, if necessary */
  36118. if( rc==SQLITE_OK ){
  36119. if( (allShared & mask)==0 ){
  36120. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  36121. }else{
  36122. rc = SQLITE_OK;
  36123. }
  36124. }
  36125. /* Get the local shared locks */
  36126. if( rc==SQLITE_OK ){
  36127. p->sharedMask |= mask;
  36128. }
  36129. }else{
  36130. /* Make sure no sibling connections hold locks that will block this
  36131. ** lock. If any do, return SQLITE_BUSY right away.
  36132. */
  36133. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36134. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  36135. rc = SQLITE_BUSY;
  36136. break;
  36137. }
  36138. }
  36139. /* Get the exclusive locks at the system level. Then if successful
  36140. ** also mark the local connection as being locked.
  36141. */
  36142. if( rc==SQLITE_OK ){
  36143. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  36144. if( rc==SQLITE_OK ){
  36145. assert( (p->sharedMask & mask)==0 );
  36146. p->exclMask |= mask;
  36147. }
  36148. }
  36149. }
  36150. sqlite3_mutex_leave(pShmNode->mutex);
  36151. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  36152. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  36153. sqlite3ErrName(rc)));
  36154. return rc;
  36155. }
  36156. /*
  36157. ** Implement a memory barrier or memory fence on shared memory.
  36158. **
  36159. ** All loads and stores begun before the barrier must complete before
  36160. ** any load or store begun after the barrier.
  36161. */
  36162. static void winShmBarrier(
  36163. sqlite3_file *fd /* Database holding the shared memory */
  36164. ){
  36165. UNUSED_PARAMETER(fd);
  36166. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  36167. winShmEnterMutex(); /* Also mutex, for redundancy */
  36168. winShmLeaveMutex();
  36169. }
  36170. /*
  36171. ** This function is called to obtain a pointer to region iRegion of the
  36172. ** shared-memory associated with the database file fd. Shared-memory regions
  36173. ** are numbered starting from zero. Each shared-memory region is szRegion
  36174. ** bytes in size.
  36175. **
  36176. ** If an error occurs, an error code is returned and *pp is set to NULL.
  36177. **
  36178. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  36179. ** region has not been allocated (by any client, including one running in a
  36180. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  36181. ** isWrite is non-zero and the requested shared-memory region has not yet
  36182. ** been allocated, it is allocated by this function.
  36183. **
  36184. ** If the shared-memory region has already been allocated or is allocated by
  36185. ** this call as described above, then it is mapped into this processes
  36186. ** address space (if it is not already), *pp is set to point to the mapped
  36187. ** memory and SQLITE_OK returned.
  36188. */
  36189. static int winShmMap(
  36190. sqlite3_file *fd, /* Handle open on database file */
  36191. int iRegion, /* Region to retrieve */
  36192. int szRegion, /* Size of regions */
  36193. int isWrite, /* True to extend file if necessary */
  36194. void volatile **pp /* OUT: Mapped memory */
  36195. ){
  36196. winFile *pDbFd = (winFile*)fd;
  36197. winShm *pShm = pDbFd->pShm;
  36198. winShmNode *pShmNode;
  36199. int rc = SQLITE_OK;
  36200. if( !pShm ){
  36201. rc = winOpenSharedMemory(pDbFd);
  36202. if( rc!=SQLITE_OK ) return rc;
  36203. pShm = pDbFd->pShm;
  36204. }
  36205. pShmNode = pShm->pShmNode;
  36206. sqlite3_mutex_enter(pShmNode->mutex);
  36207. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  36208. if( pShmNode->nRegion<=iRegion ){
  36209. struct ShmRegion *apNew; /* New aRegion[] array */
  36210. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  36211. sqlite3_int64 sz; /* Current size of wal-index file */
  36212. pShmNode->szRegion = szRegion;
  36213. /* The requested region is not mapped into this processes address space.
  36214. ** Check to see if it has been allocated (i.e. if the wal-index file is
  36215. ** large enough to contain the requested region).
  36216. */
  36217. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  36218. if( rc!=SQLITE_OK ){
  36219. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  36220. "winShmMap1", pDbFd->zPath);
  36221. goto shmpage_out;
  36222. }
  36223. if( sz<nByte ){
  36224. /* The requested memory region does not exist. If isWrite is set to
  36225. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  36226. **
  36227. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  36228. ** the requested memory region.
  36229. */
  36230. if( !isWrite ) goto shmpage_out;
  36231. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  36232. if( rc!=SQLITE_OK ){
  36233. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  36234. "winShmMap2", pDbFd->zPath);
  36235. goto shmpage_out;
  36236. }
  36237. }
  36238. /* Map the requested memory region into this processes address space. */
  36239. apNew = (struct ShmRegion *)sqlite3_realloc64(
  36240. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  36241. );
  36242. if( !apNew ){
  36243. rc = SQLITE_IOERR_NOMEM;
  36244. goto shmpage_out;
  36245. }
  36246. pShmNode->aRegion = apNew;
  36247. while( pShmNode->nRegion<=iRegion ){
  36248. HANDLE hMap = NULL; /* file-mapping handle */
  36249. void *pMap = 0; /* Mapped memory region */
  36250. #if SQLITE_OS_WINRT
  36251. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  36252. NULL, PAGE_READWRITE, nByte, NULL
  36253. );
  36254. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36255. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  36256. NULL, PAGE_READWRITE, 0, nByte, NULL
  36257. );
  36258. #elif defined(SQLITE_WIN32_HAS_ANSI)
  36259. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  36260. NULL, PAGE_READWRITE, 0, nByte, NULL
  36261. );
  36262. #endif
  36263. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  36264. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  36265. hMap ? "ok" : "failed"));
  36266. if( hMap ){
  36267. int iOffset = pShmNode->nRegion*szRegion;
  36268. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  36269. #if SQLITE_OS_WINRT
  36270. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  36271. iOffset - iOffsetShift, szRegion + iOffsetShift
  36272. );
  36273. #else
  36274. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  36275. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  36276. );
  36277. #endif
  36278. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  36279. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  36280. szRegion, pMap ? "ok" : "failed"));
  36281. }
  36282. if( !pMap ){
  36283. pShmNode->lastErrno = osGetLastError();
  36284. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  36285. "winShmMap3", pDbFd->zPath);
  36286. if( hMap ) osCloseHandle(hMap);
  36287. goto shmpage_out;
  36288. }
  36289. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  36290. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  36291. pShmNode->nRegion++;
  36292. }
  36293. }
  36294. shmpage_out:
  36295. if( pShmNode->nRegion>iRegion ){
  36296. int iOffset = iRegion*szRegion;
  36297. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  36298. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  36299. *pp = (void *)&p[iOffsetShift];
  36300. }else{
  36301. *pp = 0;
  36302. }
  36303. sqlite3_mutex_leave(pShmNode->mutex);
  36304. return rc;
  36305. }
  36306. #else
  36307. # define winShmMap 0
  36308. # define winShmLock 0
  36309. # define winShmBarrier 0
  36310. # define winShmUnmap 0
  36311. #endif /* #ifndef SQLITE_OMIT_WAL */
  36312. /*
  36313. ** Cleans up the mapped region of the specified file, if any.
  36314. */
  36315. #if SQLITE_MAX_MMAP_SIZE>0
  36316. static int winUnmapfile(winFile *pFile){
  36317. assert( pFile!=0 );
  36318. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  36319. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  36320. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  36321. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  36322. if( pFile->pMapRegion ){
  36323. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  36324. pFile->lastErrno = osGetLastError();
  36325. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  36326. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  36327. pFile->pMapRegion));
  36328. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  36329. "winUnmapfile1", pFile->zPath);
  36330. }
  36331. pFile->pMapRegion = 0;
  36332. pFile->mmapSize = 0;
  36333. pFile->mmapSizeActual = 0;
  36334. }
  36335. if( pFile->hMap!=NULL ){
  36336. if( !osCloseHandle(pFile->hMap) ){
  36337. pFile->lastErrno = osGetLastError();
  36338. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  36339. osGetCurrentProcessId(), pFile, pFile->hMap));
  36340. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  36341. "winUnmapfile2", pFile->zPath);
  36342. }
  36343. pFile->hMap = NULL;
  36344. }
  36345. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  36346. osGetCurrentProcessId(), pFile));
  36347. return SQLITE_OK;
  36348. }
  36349. /*
  36350. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  36351. ** is already mapped, the existing mapping is replaced by the new). Or, if
  36352. ** there already exists a mapping for this file, and there are still
  36353. ** outstanding xFetch() references to it, this function is a no-op.
  36354. **
  36355. ** If parameter nByte is non-negative, then it is the requested size of
  36356. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  36357. ** requested size is the size of the file on disk. The actual size of the
  36358. ** created mapping is either the requested size or the value configured
  36359. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  36360. **
  36361. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  36362. ** recreated as a result of outstanding references) or an SQLite error
  36363. ** code otherwise.
  36364. */
  36365. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  36366. sqlite3_int64 nMap = nByte;
  36367. int rc;
  36368. assert( nMap>=0 || pFd->nFetchOut==0 );
  36369. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  36370. osGetCurrentProcessId(), pFd, nByte));
  36371. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  36372. if( nMap<0 ){
  36373. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  36374. if( rc ){
  36375. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  36376. osGetCurrentProcessId(), pFd));
  36377. return SQLITE_IOERR_FSTAT;
  36378. }
  36379. }
  36380. if( nMap>pFd->mmapSizeMax ){
  36381. nMap = pFd->mmapSizeMax;
  36382. }
  36383. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  36384. if( nMap==0 && pFd->mmapSize>0 ){
  36385. winUnmapfile(pFd);
  36386. }
  36387. if( nMap!=pFd->mmapSize ){
  36388. void *pNew = 0;
  36389. DWORD protect = PAGE_READONLY;
  36390. DWORD flags = FILE_MAP_READ;
  36391. winUnmapfile(pFd);
  36392. #ifdef SQLITE_MMAP_READWRITE
  36393. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  36394. protect = PAGE_READWRITE;
  36395. flags |= FILE_MAP_WRITE;
  36396. }
  36397. #endif
  36398. #if SQLITE_OS_WINRT
  36399. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  36400. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36401. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  36402. (DWORD)((nMap>>32) & 0xffffffff),
  36403. (DWORD)(nMap & 0xffffffff), NULL);
  36404. #elif defined(SQLITE_WIN32_HAS_ANSI)
  36405. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  36406. (DWORD)((nMap>>32) & 0xffffffff),
  36407. (DWORD)(nMap & 0xffffffff), NULL);
  36408. #endif
  36409. if( pFd->hMap==NULL ){
  36410. pFd->lastErrno = osGetLastError();
  36411. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  36412. "winMapfile1", pFd->zPath);
  36413. /* Log the error, but continue normal operation using xRead/xWrite */
  36414. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  36415. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36416. return SQLITE_OK;
  36417. }
  36418. assert( (nMap % winSysInfo.dwPageSize)==0 );
  36419. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  36420. #if SQLITE_OS_WINRT
  36421. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  36422. #else
  36423. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  36424. #endif
  36425. if( pNew==NULL ){
  36426. osCloseHandle(pFd->hMap);
  36427. pFd->hMap = NULL;
  36428. pFd->lastErrno = osGetLastError();
  36429. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  36430. "winMapfile2", pFd->zPath);
  36431. /* Log the error, but continue normal operation using xRead/xWrite */
  36432. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  36433. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36434. return SQLITE_OK;
  36435. }
  36436. pFd->pMapRegion = pNew;
  36437. pFd->mmapSize = nMap;
  36438. pFd->mmapSizeActual = nMap;
  36439. }
  36440. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  36441. osGetCurrentProcessId(), pFd));
  36442. return SQLITE_OK;
  36443. }
  36444. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  36445. /*
  36446. ** If possible, return a pointer to a mapping of file fd starting at offset
  36447. ** iOff. The mapping must be valid for at least nAmt bytes.
  36448. **
  36449. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  36450. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  36451. ** Finally, if an error does occur, return an SQLite error code. The final
  36452. ** value of *pp is undefined in this case.
  36453. **
  36454. ** If this function does return a pointer, the caller must eventually
  36455. ** release the reference by calling winUnfetch().
  36456. */
  36457. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  36458. #if SQLITE_MAX_MMAP_SIZE>0
  36459. winFile *pFd = (winFile*)fd; /* The underlying database file */
  36460. #endif
  36461. *pp = 0;
  36462. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  36463. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  36464. #if SQLITE_MAX_MMAP_SIZE>0
  36465. if( pFd->mmapSizeMax>0 ){
  36466. if( pFd->pMapRegion==0 ){
  36467. int rc = winMapfile(pFd, -1);
  36468. if( rc!=SQLITE_OK ){
  36469. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  36470. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  36471. return rc;
  36472. }
  36473. }
  36474. if( pFd->mmapSize >= iOff+nAmt ){
  36475. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  36476. pFd->nFetchOut++;
  36477. }
  36478. }
  36479. #endif
  36480. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  36481. osGetCurrentProcessId(), fd, pp, *pp));
  36482. return SQLITE_OK;
  36483. }
  36484. /*
  36485. ** If the third argument is non-NULL, then this function releases a
  36486. ** reference obtained by an earlier call to winFetch(). The second
  36487. ** argument passed to this function must be the same as the corresponding
  36488. ** argument that was passed to the winFetch() invocation.
  36489. **
  36490. ** Or, if the third argument is NULL, then this function is being called
  36491. ** to inform the VFS layer that, according to POSIX, any existing mapping
  36492. ** may now be invalid and should be unmapped.
  36493. */
  36494. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  36495. #if SQLITE_MAX_MMAP_SIZE>0
  36496. winFile *pFd = (winFile*)fd; /* The underlying database file */
  36497. /* If p==0 (unmap the entire file) then there must be no outstanding
  36498. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  36499. ** then there must be at least one outstanding. */
  36500. assert( (p==0)==(pFd->nFetchOut==0) );
  36501. /* If p!=0, it must match the iOff value. */
  36502. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  36503. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  36504. osGetCurrentProcessId(), pFd, iOff, p));
  36505. if( p ){
  36506. pFd->nFetchOut--;
  36507. }else{
  36508. /* FIXME: If Windows truly always prevents truncating or deleting a
  36509. ** file while a mapping is held, then the following winUnmapfile() call
  36510. ** is unnecessary can be omitted - potentially improving
  36511. ** performance. */
  36512. winUnmapfile(pFd);
  36513. }
  36514. assert( pFd->nFetchOut>=0 );
  36515. #endif
  36516. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  36517. osGetCurrentProcessId(), fd));
  36518. return SQLITE_OK;
  36519. }
  36520. /*
  36521. ** Here ends the implementation of all sqlite3_file methods.
  36522. **
  36523. ********************** End sqlite3_file Methods *******************************
  36524. ******************************************************************************/
  36525. /*
  36526. ** This vector defines all the methods that can operate on an
  36527. ** sqlite3_file for win32.
  36528. */
  36529. static const sqlite3_io_methods winIoMethod = {
  36530. 3, /* iVersion */
  36531. winClose, /* xClose */
  36532. winRead, /* xRead */
  36533. winWrite, /* xWrite */
  36534. winTruncate, /* xTruncate */
  36535. winSync, /* xSync */
  36536. winFileSize, /* xFileSize */
  36537. winLock, /* xLock */
  36538. winUnlock, /* xUnlock */
  36539. winCheckReservedLock, /* xCheckReservedLock */
  36540. winFileControl, /* xFileControl */
  36541. winSectorSize, /* xSectorSize */
  36542. winDeviceCharacteristics, /* xDeviceCharacteristics */
  36543. winShmMap, /* xShmMap */
  36544. winShmLock, /* xShmLock */
  36545. winShmBarrier, /* xShmBarrier */
  36546. winShmUnmap, /* xShmUnmap */
  36547. winFetch, /* xFetch */
  36548. winUnfetch /* xUnfetch */
  36549. };
  36550. /****************************************************************************
  36551. **************************** sqlite3_vfs methods ****************************
  36552. **
  36553. ** This division contains the implementation of methods on the
  36554. ** sqlite3_vfs object.
  36555. */
  36556. #if defined(__CYGWIN__)
  36557. /*
  36558. ** Convert a filename from whatever the underlying operating system
  36559. ** supports for filenames into UTF-8. Space to hold the result is
  36560. ** obtained from malloc and must be freed by the calling function.
  36561. */
  36562. static char *winConvertToUtf8Filename(const void *zFilename){
  36563. char *zConverted = 0;
  36564. if( osIsNT() ){
  36565. zConverted = winUnicodeToUtf8(zFilename);
  36566. }
  36567. #ifdef SQLITE_WIN32_HAS_ANSI
  36568. else{
  36569. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  36570. }
  36571. #endif
  36572. /* caller will handle out of memory */
  36573. return zConverted;
  36574. }
  36575. #endif
  36576. /*
  36577. ** Convert a UTF-8 filename into whatever form the underlying
  36578. ** operating system wants filenames in. Space to hold the result
  36579. ** is obtained from malloc and must be freed by the calling
  36580. ** function.
  36581. */
  36582. static void *winConvertFromUtf8Filename(const char *zFilename){
  36583. void *zConverted = 0;
  36584. if( osIsNT() ){
  36585. zConverted = winUtf8ToUnicode(zFilename);
  36586. }
  36587. #ifdef SQLITE_WIN32_HAS_ANSI
  36588. else{
  36589. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  36590. }
  36591. #endif
  36592. /* caller will handle out of memory */
  36593. return zConverted;
  36594. }
  36595. /*
  36596. ** This function returns non-zero if the specified UTF-8 string buffer
  36597. ** ends with a directory separator character or one was successfully
  36598. ** added to it.
  36599. */
  36600. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  36601. if( zBuf ){
  36602. int nLen = sqlite3Strlen30(zBuf);
  36603. if( nLen>0 ){
  36604. if( winIsDirSep(zBuf[nLen-1]) ){
  36605. return 1;
  36606. }else if( nLen+1<nBuf ){
  36607. zBuf[nLen] = winGetDirSep();
  36608. zBuf[nLen+1] = '\0';
  36609. return 1;
  36610. }
  36611. }
  36612. }
  36613. return 0;
  36614. }
  36615. /*
  36616. ** Create a temporary file name and store the resulting pointer into pzBuf.
  36617. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  36618. */
  36619. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  36620. static char zChars[] =
  36621. "abcdefghijklmnopqrstuvwxyz"
  36622. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  36623. "0123456789";
  36624. size_t i, j;
  36625. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  36626. int nMax, nBuf, nDir, nLen;
  36627. char *zBuf;
  36628. /* It's odd to simulate an io-error here, but really this is just
  36629. ** using the io-error infrastructure to test that SQLite handles this
  36630. ** function failing.
  36631. */
  36632. SimulateIOError( return SQLITE_IOERR );
  36633. /* Allocate a temporary buffer to store the fully qualified file
  36634. ** name for the temporary file. If this fails, we cannot continue.
  36635. */
  36636. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  36637. zBuf = sqlite3MallocZero( nBuf );
  36638. if( !zBuf ){
  36639. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36640. return SQLITE_IOERR_NOMEM;
  36641. }
  36642. /* Figure out the effective temporary directory. First, check if one
  36643. ** has been explicitly set by the application; otherwise, use the one
  36644. ** configured by the operating system.
  36645. */
  36646. nDir = nMax - (nPre + 15);
  36647. assert( nDir>0 );
  36648. if( sqlite3_temp_directory ){
  36649. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  36650. if( nDirLen>0 ){
  36651. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  36652. nDirLen++;
  36653. }
  36654. if( nDirLen>nDir ){
  36655. sqlite3_free(zBuf);
  36656. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  36657. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  36658. }
  36659. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  36660. }
  36661. }
  36662. #if defined(__CYGWIN__)
  36663. else{
  36664. static const char *azDirs[] = {
  36665. 0, /* getenv("SQLITE_TMPDIR") */
  36666. 0, /* getenv("TMPDIR") */
  36667. 0, /* getenv("TMP") */
  36668. 0, /* getenv("TEMP") */
  36669. 0, /* getenv("USERPROFILE") */
  36670. "/var/tmp",
  36671. "/usr/tmp",
  36672. "/tmp",
  36673. ".",
  36674. 0 /* List terminator */
  36675. };
  36676. unsigned int i;
  36677. const char *zDir = 0;
  36678. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  36679. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  36680. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  36681. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  36682. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  36683. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  36684. void *zConverted;
  36685. if( zDir==0 ) continue;
  36686. /* If the path starts with a drive letter followed by the colon
  36687. ** character, assume it is already a native Win32 path; otherwise,
  36688. ** it must be converted to a native Win32 path via the Cygwin API
  36689. ** prior to using it.
  36690. */
  36691. if( winIsDriveLetterAndColon(zDir) ){
  36692. zConverted = winConvertFromUtf8Filename(zDir);
  36693. if( !zConverted ){
  36694. sqlite3_free(zBuf);
  36695. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36696. return SQLITE_IOERR_NOMEM;
  36697. }
  36698. if( winIsDir(zConverted) ){
  36699. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  36700. sqlite3_free(zConverted);
  36701. break;
  36702. }
  36703. sqlite3_free(zConverted);
  36704. }else{
  36705. zConverted = sqlite3MallocZero( nMax+1 );
  36706. if( !zConverted ){
  36707. sqlite3_free(zBuf);
  36708. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36709. return SQLITE_IOERR_NOMEM;
  36710. }
  36711. if( cygwin_conv_path(
  36712. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  36713. zConverted, nMax+1)<0 ){
  36714. sqlite3_free(zConverted);
  36715. sqlite3_free(zBuf);
  36716. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  36717. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  36718. "winGetTempname2", zDir);
  36719. }
  36720. if( winIsDir(zConverted) ){
  36721. /* At this point, we know the candidate directory exists and should
  36722. ** be used. However, we may need to convert the string containing
  36723. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  36724. */
  36725. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  36726. if( !zUtf8 ){
  36727. sqlite3_free(zConverted);
  36728. sqlite3_free(zBuf);
  36729. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36730. return SQLITE_IOERR_NOMEM;
  36731. }
  36732. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  36733. sqlite3_free(zUtf8);
  36734. sqlite3_free(zConverted);
  36735. break;
  36736. }
  36737. sqlite3_free(zConverted);
  36738. }
  36739. }
  36740. }
  36741. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  36742. else if( osIsNT() ){
  36743. char *zMulti;
  36744. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  36745. if( !zWidePath ){
  36746. sqlite3_free(zBuf);
  36747. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36748. return SQLITE_IOERR_NOMEM;
  36749. }
  36750. if( osGetTempPathW(nMax, zWidePath)==0 ){
  36751. sqlite3_free(zWidePath);
  36752. sqlite3_free(zBuf);
  36753. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  36754. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  36755. "winGetTempname2", 0);
  36756. }
  36757. zMulti = winUnicodeToUtf8(zWidePath);
  36758. if( zMulti ){
  36759. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  36760. sqlite3_free(zMulti);
  36761. sqlite3_free(zWidePath);
  36762. }else{
  36763. sqlite3_free(zWidePath);
  36764. sqlite3_free(zBuf);
  36765. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36766. return SQLITE_IOERR_NOMEM;
  36767. }
  36768. }
  36769. #ifdef SQLITE_WIN32_HAS_ANSI
  36770. else{
  36771. char *zUtf8;
  36772. char *zMbcsPath = sqlite3MallocZero( nMax );
  36773. if( !zMbcsPath ){
  36774. sqlite3_free(zBuf);
  36775. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36776. return SQLITE_IOERR_NOMEM;
  36777. }
  36778. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  36779. sqlite3_free(zBuf);
  36780. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  36781. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  36782. "winGetTempname3", 0);
  36783. }
  36784. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  36785. if( zUtf8 ){
  36786. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  36787. sqlite3_free(zUtf8);
  36788. }else{
  36789. sqlite3_free(zBuf);
  36790. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  36791. return SQLITE_IOERR_NOMEM;
  36792. }
  36793. }
  36794. #endif /* SQLITE_WIN32_HAS_ANSI */
  36795. #endif /* !SQLITE_OS_WINRT */
  36796. /*
  36797. ** Check to make sure the temporary directory ends with an appropriate
  36798. ** separator. If it does not and there is not enough space left to add
  36799. ** one, fail.
  36800. */
  36801. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  36802. sqlite3_free(zBuf);
  36803. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  36804. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  36805. }
  36806. /*
  36807. ** Check that the output buffer is large enough for the temporary file
  36808. ** name in the following format:
  36809. **
  36810. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  36811. **
  36812. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  36813. ** account for the space used by the 15 character random suffix and the
  36814. ** two trailing NUL characters. The final directory separator character
  36815. ** has already added if it was not already present.
  36816. */
  36817. nLen = sqlite3Strlen30(zBuf);
  36818. if( (nLen + nPre + 17) > nBuf ){
  36819. sqlite3_free(zBuf);
  36820. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  36821. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  36822. }
  36823. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  36824. j = sqlite3Strlen30(zBuf);
  36825. sqlite3_randomness(15, &zBuf[j]);
  36826. for(i=0; i<15; i++, j++){
  36827. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  36828. }
  36829. zBuf[j] = 0;
  36830. zBuf[j+1] = 0;
  36831. *pzBuf = zBuf;
  36832. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  36833. return SQLITE_OK;
  36834. }
  36835. /*
  36836. ** Return TRUE if the named file is really a directory. Return false if
  36837. ** it is something other than a directory, or if there is any kind of memory
  36838. ** allocation failure.
  36839. */
  36840. static int winIsDir(const void *zConverted){
  36841. DWORD attr;
  36842. int rc = 0;
  36843. DWORD lastErrno;
  36844. if( osIsNT() ){
  36845. int cnt = 0;
  36846. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  36847. memset(&sAttrData, 0, sizeof(sAttrData));
  36848. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  36849. GetFileExInfoStandard,
  36850. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  36851. if( !rc ){
  36852. return 0; /* Invalid name? */
  36853. }
  36854. attr = sAttrData.dwFileAttributes;
  36855. #if SQLITE_OS_WINCE==0
  36856. }else{
  36857. attr = osGetFileAttributesA((char*)zConverted);
  36858. #endif
  36859. }
  36860. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  36861. }
  36862. /*
  36863. ** Open a file.
  36864. */
  36865. static int winOpen(
  36866. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  36867. const char *zName, /* Name of the file (UTF-8) */
  36868. sqlite3_file *id, /* Write the SQLite file handle here */
  36869. int flags, /* Open mode flags */
  36870. int *pOutFlags /* Status return flags */
  36871. ){
  36872. HANDLE h;
  36873. DWORD lastErrno = 0;
  36874. DWORD dwDesiredAccess;
  36875. DWORD dwShareMode;
  36876. DWORD dwCreationDisposition;
  36877. DWORD dwFlagsAndAttributes = 0;
  36878. #if SQLITE_OS_WINCE
  36879. int isTemp = 0;
  36880. #endif
  36881. winFile *pFile = (winFile*)id;
  36882. void *zConverted; /* Filename in OS encoding */
  36883. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  36884. int cnt = 0;
  36885. /* If argument zPath is a NULL pointer, this function is required to open
  36886. ** a temporary file. Use this buffer to store the file name in.
  36887. */
  36888. char *zTmpname = 0; /* For temporary filename, if necessary. */
  36889. int rc = SQLITE_OK; /* Function Return Code */
  36890. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  36891. int eType = flags&0xFFFFFF00; /* Type of file to open */
  36892. #endif
  36893. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  36894. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  36895. int isCreate = (flags & SQLITE_OPEN_CREATE);
  36896. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  36897. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  36898. #ifndef NDEBUG
  36899. int isOpenJournal = (isCreate && (
  36900. eType==SQLITE_OPEN_MASTER_JOURNAL
  36901. || eType==SQLITE_OPEN_MAIN_JOURNAL
  36902. || eType==SQLITE_OPEN_WAL
  36903. ));
  36904. #endif
  36905. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  36906. zUtf8Name, id, flags, pOutFlags));
  36907. /* Check the following statements are true:
  36908. **
  36909. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  36910. ** (b) if CREATE is set, then READWRITE must also be set, and
  36911. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  36912. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  36913. */
  36914. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  36915. assert(isCreate==0 || isReadWrite);
  36916. assert(isExclusive==0 || isCreate);
  36917. assert(isDelete==0 || isCreate);
  36918. /* The main DB, main journal, WAL file and master journal are never
  36919. ** automatically deleted. Nor are they ever temporary files. */
  36920. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  36921. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  36922. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  36923. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  36924. /* Assert that the upper layer has set one of the "file-type" flags. */
  36925. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  36926. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  36927. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  36928. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  36929. );
  36930. assert( pFile!=0 );
  36931. memset(pFile, 0, sizeof(winFile));
  36932. pFile->h = INVALID_HANDLE_VALUE;
  36933. #if SQLITE_OS_WINRT
  36934. if( !zUtf8Name && !sqlite3_temp_directory ){
  36935. sqlite3_log(SQLITE_ERROR,
  36936. "sqlite3_temp_directory variable should be set for WinRT");
  36937. }
  36938. #endif
  36939. /* If the second argument to this function is NULL, generate a
  36940. ** temporary file name to use
  36941. */
  36942. if( !zUtf8Name ){
  36943. assert( isDelete && !isOpenJournal );
  36944. rc = winGetTempname(pVfs, &zTmpname);
  36945. if( rc!=SQLITE_OK ){
  36946. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  36947. return rc;
  36948. }
  36949. zUtf8Name = zTmpname;
  36950. }
  36951. /* Database filenames are double-zero terminated if they are not
  36952. ** URIs with parameters. Hence, they can always be passed into
  36953. ** sqlite3_uri_parameter().
  36954. */
  36955. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  36956. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  36957. /* Convert the filename to the system encoding. */
  36958. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  36959. if( zConverted==0 ){
  36960. sqlite3_free(zTmpname);
  36961. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  36962. return SQLITE_IOERR_NOMEM;
  36963. }
  36964. if( winIsDir(zConverted) ){
  36965. sqlite3_free(zConverted);
  36966. sqlite3_free(zTmpname);
  36967. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  36968. return SQLITE_CANTOPEN_ISDIR;
  36969. }
  36970. if( isReadWrite ){
  36971. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  36972. }else{
  36973. dwDesiredAccess = GENERIC_READ;
  36974. }
  36975. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  36976. ** created. SQLite doesn't use it to indicate "exclusive access"
  36977. ** as it is usually understood.
  36978. */
  36979. if( isExclusive ){
  36980. /* Creates a new file, only if it does not already exist. */
  36981. /* If the file exists, it fails. */
  36982. dwCreationDisposition = CREATE_NEW;
  36983. }else if( isCreate ){
  36984. /* Open existing file, or create if it doesn't exist */
  36985. dwCreationDisposition = OPEN_ALWAYS;
  36986. }else{
  36987. /* Opens a file, only if it exists. */
  36988. dwCreationDisposition = OPEN_EXISTING;
  36989. }
  36990. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  36991. if( isDelete ){
  36992. #if SQLITE_OS_WINCE
  36993. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  36994. isTemp = 1;
  36995. #else
  36996. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  36997. | FILE_ATTRIBUTE_HIDDEN
  36998. | FILE_FLAG_DELETE_ON_CLOSE;
  36999. #endif
  37000. }else{
  37001. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  37002. }
  37003. /* Reports from the internet are that performance is always
  37004. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  37005. #if SQLITE_OS_WINCE
  37006. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  37007. #endif
  37008. if( osIsNT() ){
  37009. #if SQLITE_OS_WINRT
  37010. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  37011. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  37012. extendedParameters.dwFileAttributes =
  37013. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  37014. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  37015. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  37016. extendedParameters.lpSecurityAttributes = NULL;
  37017. extendedParameters.hTemplateFile = NULL;
  37018. while( (h = osCreateFile2((LPCWSTR)zConverted,
  37019. dwDesiredAccess,
  37020. dwShareMode,
  37021. dwCreationDisposition,
  37022. &extendedParameters))==INVALID_HANDLE_VALUE &&
  37023. winRetryIoerr(&cnt, &lastErrno) ){
  37024. /* Noop */
  37025. }
  37026. #else
  37027. while( (h = osCreateFileW((LPCWSTR)zConverted,
  37028. dwDesiredAccess,
  37029. dwShareMode, NULL,
  37030. dwCreationDisposition,
  37031. dwFlagsAndAttributes,
  37032. NULL))==INVALID_HANDLE_VALUE &&
  37033. winRetryIoerr(&cnt, &lastErrno) ){
  37034. /* Noop */
  37035. }
  37036. #endif
  37037. }
  37038. #ifdef SQLITE_WIN32_HAS_ANSI
  37039. else{
  37040. while( (h = osCreateFileA((LPCSTR)zConverted,
  37041. dwDesiredAccess,
  37042. dwShareMode, NULL,
  37043. dwCreationDisposition,
  37044. dwFlagsAndAttributes,
  37045. NULL))==INVALID_HANDLE_VALUE &&
  37046. winRetryIoerr(&cnt, &lastErrno) ){
  37047. /* Noop */
  37048. }
  37049. }
  37050. #endif
  37051. winLogIoerr(cnt, __LINE__);
  37052. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  37053. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  37054. if( h==INVALID_HANDLE_VALUE ){
  37055. pFile->lastErrno = lastErrno;
  37056. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  37057. sqlite3_free(zConverted);
  37058. sqlite3_free(zTmpname);
  37059. if( isReadWrite && !isExclusive ){
  37060. return winOpen(pVfs, zName, id,
  37061. ((flags|SQLITE_OPEN_READONLY) &
  37062. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  37063. pOutFlags);
  37064. }else{
  37065. return SQLITE_CANTOPEN_BKPT;
  37066. }
  37067. }
  37068. if( pOutFlags ){
  37069. if( isReadWrite ){
  37070. *pOutFlags = SQLITE_OPEN_READWRITE;
  37071. }else{
  37072. *pOutFlags = SQLITE_OPEN_READONLY;
  37073. }
  37074. }
  37075. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  37076. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  37077. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  37078. #if SQLITE_OS_WINCE
  37079. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  37080. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  37081. ){
  37082. osCloseHandle(h);
  37083. sqlite3_free(zConverted);
  37084. sqlite3_free(zTmpname);
  37085. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  37086. return rc;
  37087. }
  37088. if( isTemp ){
  37089. pFile->zDeleteOnClose = zConverted;
  37090. }else
  37091. #endif
  37092. {
  37093. sqlite3_free(zConverted);
  37094. }
  37095. sqlite3_free(zTmpname);
  37096. pFile->pMethod = &winIoMethod;
  37097. pFile->pVfs = pVfs;
  37098. pFile->h = h;
  37099. if( isReadonly ){
  37100. pFile->ctrlFlags |= WINFILE_RDONLY;
  37101. }
  37102. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  37103. pFile->ctrlFlags |= WINFILE_PSOW;
  37104. }
  37105. pFile->lastErrno = NO_ERROR;
  37106. pFile->zPath = zName;
  37107. #if SQLITE_MAX_MMAP_SIZE>0
  37108. pFile->hMap = NULL;
  37109. pFile->pMapRegion = 0;
  37110. pFile->mmapSize = 0;
  37111. pFile->mmapSizeActual = 0;
  37112. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  37113. #endif
  37114. OpenCounter(+1);
  37115. return rc;
  37116. }
  37117. /*
  37118. ** Delete the named file.
  37119. **
  37120. ** Note that Windows does not allow a file to be deleted if some other
  37121. ** process has it open. Sometimes a virus scanner or indexing program
  37122. ** will open a journal file shortly after it is created in order to do
  37123. ** whatever it does. While this other process is holding the
  37124. ** file open, we will be unable to delete it. To work around this
  37125. ** problem, we delay 100 milliseconds and try to delete again. Up
  37126. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  37127. ** up and returning an error.
  37128. */
  37129. static int winDelete(
  37130. sqlite3_vfs *pVfs, /* Not used on win32 */
  37131. const char *zFilename, /* Name of file to delete */
  37132. int syncDir /* Not used on win32 */
  37133. ){
  37134. int cnt = 0;
  37135. int rc;
  37136. DWORD attr;
  37137. DWORD lastErrno = 0;
  37138. void *zConverted;
  37139. UNUSED_PARAMETER(pVfs);
  37140. UNUSED_PARAMETER(syncDir);
  37141. SimulateIOError(return SQLITE_IOERR_DELETE);
  37142. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  37143. zConverted = winConvertFromUtf8Filename(zFilename);
  37144. if( zConverted==0 ){
  37145. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  37146. return SQLITE_IOERR_NOMEM;
  37147. }
  37148. if( osIsNT() ){
  37149. do {
  37150. #if SQLITE_OS_WINRT
  37151. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  37152. memset(&sAttrData, 0, sizeof(sAttrData));
  37153. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  37154. &sAttrData) ){
  37155. attr = sAttrData.dwFileAttributes;
  37156. }else{
  37157. lastErrno = osGetLastError();
  37158. if( lastErrno==ERROR_FILE_NOT_FOUND
  37159. || lastErrno==ERROR_PATH_NOT_FOUND ){
  37160. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  37161. }else{
  37162. rc = SQLITE_ERROR;
  37163. }
  37164. break;
  37165. }
  37166. #else
  37167. attr = osGetFileAttributesW(zConverted);
  37168. #endif
  37169. if ( attr==INVALID_FILE_ATTRIBUTES ){
  37170. lastErrno = osGetLastError();
  37171. if( lastErrno==ERROR_FILE_NOT_FOUND
  37172. || lastErrno==ERROR_PATH_NOT_FOUND ){
  37173. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  37174. }else{
  37175. rc = SQLITE_ERROR;
  37176. }
  37177. break;
  37178. }
  37179. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  37180. rc = SQLITE_ERROR; /* Files only. */
  37181. break;
  37182. }
  37183. if ( osDeleteFileW(zConverted) ){
  37184. rc = SQLITE_OK; /* Deleted OK. */
  37185. break;
  37186. }
  37187. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  37188. rc = SQLITE_ERROR; /* No more retries. */
  37189. break;
  37190. }
  37191. } while(1);
  37192. }
  37193. #ifdef SQLITE_WIN32_HAS_ANSI
  37194. else{
  37195. do {
  37196. attr = osGetFileAttributesA(zConverted);
  37197. if ( attr==INVALID_FILE_ATTRIBUTES ){
  37198. lastErrno = osGetLastError();
  37199. if( lastErrno==ERROR_FILE_NOT_FOUND
  37200. || lastErrno==ERROR_PATH_NOT_FOUND ){
  37201. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  37202. }else{
  37203. rc = SQLITE_ERROR;
  37204. }
  37205. break;
  37206. }
  37207. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  37208. rc = SQLITE_ERROR; /* Files only. */
  37209. break;
  37210. }
  37211. if ( osDeleteFileA(zConverted) ){
  37212. rc = SQLITE_OK; /* Deleted OK. */
  37213. break;
  37214. }
  37215. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  37216. rc = SQLITE_ERROR; /* No more retries. */
  37217. break;
  37218. }
  37219. } while(1);
  37220. }
  37221. #endif
  37222. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  37223. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  37224. }else{
  37225. winLogIoerr(cnt, __LINE__);
  37226. }
  37227. sqlite3_free(zConverted);
  37228. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  37229. return rc;
  37230. }
  37231. /*
  37232. ** Check the existence and status of a file.
  37233. */
  37234. static int winAccess(
  37235. sqlite3_vfs *pVfs, /* Not used on win32 */
  37236. const char *zFilename, /* Name of file to check */
  37237. int flags, /* Type of test to make on this file */
  37238. int *pResOut /* OUT: Result */
  37239. ){
  37240. DWORD attr;
  37241. int rc = 0;
  37242. DWORD lastErrno = 0;
  37243. void *zConverted;
  37244. UNUSED_PARAMETER(pVfs);
  37245. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  37246. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  37247. zFilename, flags, pResOut));
  37248. zConverted = winConvertFromUtf8Filename(zFilename);
  37249. if( zConverted==0 ){
  37250. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  37251. return SQLITE_IOERR_NOMEM;
  37252. }
  37253. if( osIsNT() ){
  37254. int cnt = 0;
  37255. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  37256. memset(&sAttrData, 0, sizeof(sAttrData));
  37257. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  37258. GetFileExInfoStandard,
  37259. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  37260. if( rc ){
  37261. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  37262. ** as if it does not exist.
  37263. */
  37264. if( flags==SQLITE_ACCESS_EXISTS
  37265. && sAttrData.nFileSizeHigh==0
  37266. && sAttrData.nFileSizeLow==0 ){
  37267. attr = INVALID_FILE_ATTRIBUTES;
  37268. }else{
  37269. attr = sAttrData.dwFileAttributes;
  37270. }
  37271. }else{
  37272. winLogIoerr(cnt, __LINE__);
  37273. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  37274. sqlite3_free(zConverted);
  37275. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  37276. zFilename);
  37277. }else{
  37278. attr = INVALID_FILE_ATTRIBUTES;
  37279. }
  37280. }
  37281. }
  37282. #ifdef SQLITE_WIN32_HAS_ANSI
  37283. else{
  37284. attr = osGetFileAttributesA((char*)zConverted);
  37285. }
  37286. #endif
  37287. sqlite3_free(zConverted);
  37288. switch( flags ){
  37289. case SQLITE_ACCESS_READ:
  37290. case SQLITE_ACCESS_EXISTS:
  37291. rc = attr!=INVALID_FILE_ATTRIBUTES;
  37292. break;
  37293. case SQLITE_ACCESS_READWRITE:
  37294. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  37295. (attr & FILE_ATTRIBUTE_READONLY)==0;
  37296. break;
  37297. default:
  37298. assert(!"Invalid flags argument");
  37299. }
  37300. *pResOut = rc;
  37301. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  37302. zFilename, pResOut, *pResOut));
  37303. return SQLITE_OK;
  37304. }
  37305. /*
  37306. ** Returns non-zero if the specified path name starts with a drive letter
  37307. ** followed by a colon character.
  37308. */
  37309. static BOOL winIsDriveLetterAndColon(
  37310. const char *zPathname
  37311. ){
  37312. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  37313. }
  37314. /*
  37315. ** Returns non-zero if the specified path name should be used verbatim. If
  37316. ** non-zero is returned from this function, the calling function must simply
  37317. ** use the provided path name verbatim -OR- resolve it into a full path name
  37318. ** using the GetFullPathName Win32 API function (if available).
  37319. */
  37320. static BOOL winIsVerbatimPathname(
  37321. const char *zPathname
  37322. ){
  37323. /*
  37324. ** If the path name starts with a forward slash or a backslash, it is either
  37325. ** a legal UNC name, a volume relative path, or an absolute path name in the
  37326. ** "Unix" format on Windows. There is no easy way to differentiate between
  37327. ** the final two cases; therefore, we return the safer return value of TRUE
  37328. ** so that callers of this function will simply use it verbatim.
  37329. */
  37330. if ( winIsDirSep(zPathname[0]) ){
  37331. return TRUE;
  37332. }
  37333. /*
  37334. ** If the path name starts with a letter and a colon it is either a volume
  37335. ** relative path or an absolute path. Callers of this function must not
  37336. ** attempt to treat it as a relative path name (i.e. they should simply use
  37337. ** it verbatim).
  37338. */
  37339. if ( winIsDriveLetterAndColon(zPathname) ){
  37340. return TRUE;
  37341. }
  37342. /*
  37343. ** If we get to this point, the path name should almost certainly be a purely
  37344. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  37345. */
  37346. return FALSE;
  37347. }
  37348. /*
  37349. ** Turn a relative pathname into a full pathname. Write the full
  37350. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  37351. ** bytes in size.
  37352. */
  37353. static int winFullPathname(
  37354. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  37355. const char *zRelative, /* Possibly relative input path */
  37356. int nFull, /* Size of output buffer in bytes */
  37357. char *zFull /* Output buffer */
  37358. ){
  37359. #if defined(__CYGWIN__)
  37360. SimulateIOError( return SQLITE_ERROR );
  37361. UNUSED_PARAMETER(nFull);
  37362. assert( nFull>=pVfs->mxPathname );
  37363. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37364. /*
  37365. ** NOTE: We are dealing with a relative path name and the data
  37366. ** directory has been set. Therefore, use it as the basis
  37367. ** for converting the relative path name to an absolute
  37368. ** one by prepending the data directory and a slash.
  37369. */
  37370. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  37371. if( !zOut ){
  37372. return SQLITE_IOERR_NOMEM;
  37373. }
  37374. if( cygwin_conv_path(
  37375. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  37376. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  37377. sqlite3_free(zOut);
  37378. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  37379. "winFullPathname1", zRelative);
  37380. }else{
  37381. char *zUtf8 = winConvertToUtf8Filename(zOut);
  37382. if( !zUtf8 ){
  37383. sqlite3_free(zOut);
  37384. return SQLITE_IOERR_NOMEM;
  37385. }
  37386. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37387. sqlite3_data_directory, winGetDirSep(), zUtf8);
  37388. sqlite3_free(zUtf8);
  37389. sqlite3_free(zOut);
  37390. }
  37391. }else{
  37392. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  37393. if( !zOut ){
  37394. return SQLITE_IOERR_NOMEM;
  37395. }
  37396. if( cygwin_conv_path(
  37397. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  37398. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  37399. sqlite3_free(zOut);
  37400. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  37401. "winFullPathname2", zRelative);
  37402. }else{
  37403. char *zUtf8 = winConvertToUtf8Filename(zOut);
  37404. if( !zUtf8 ){
  37405. sqlite3_free(zOut);
  37406. return SQLITE_IOERR_NOMEM;
  37407. }
  37408. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  37409. sqlite3_free(zUtf8);
  37410. sqlite3_free(zOut);
  37411. }
  37412. }
  37413. return SQLITE_OK;
  37414. #endif
  37415. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  37416. SimulateIOError( return SQLITE_ERROR );
  37417. /* WinCE has no concept of a relative pathname, or so I am told. */
  37418. /* WinRT has no way to convert a relative path to an absolute one. */
  37419. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37420. /*
  37421. ** NOTE: We are dealing with a relative path name and the data
  37422. ** directory has been set. Therefore, use it as the basis
  37423. ** for converting the relative path name to an absolute
  37424. ** one by prepending the data directory and a backslash.
  37425. */
  37426. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37427. sqlite3_data_directory, winGetDirSep(), zRelative);
  37428. }else{
  37429. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  37430. }
  37431. return SQLITE_OK;
  37432. #endif
  37433. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  37434. DWORD nByte;
  37435. void *zConverted;
  37436. char *zOut;
  37437. /* If this path name begins with "/X:", where "X" is any alphabetic
  37438. ** character, discard the initial "/" from the pathname.
  37439. */
  37440. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  37441. zRelative++;
  37442. }
  37443. /* It's odd to simulate an io-error here, but really this is just
  37444. ** using the io-error infrastructure to test that SQLite handles this
  37445. ** function failing. This function could fail if, for example, the
  37446. ** current working directory has been unlinked.
  37447. */
  37448. SimulateIOError( return SQLITE_ERROR );
  37449. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  37450. /*
  37451. ** NOTE: We are dealing with a relative path name and the data
  37452. ** directory has been set. Therefore, use it as the basis
  37453. ** for converting the relative path name to an absolute
  37454. ** one by prepending the data directory and a backslash.
  37455. */
  37456. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  37457. sqlite3_data_directory, winGetDirSep(), zRelative);
  37458. return SQLITE_OK;
  37459. }
  37460. zConverted = winConvertFromUtf8Filename(zRelative);
  37461. if( zConverted==0 ){
  37462. return SQLITE_IOERR_NOMEM;
  37463. }
  37464. if( osIsNT() ){
  37465. LPWSTR zTemp;
  37466. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  37467. if( nByte==0 ){
  37468. sqlite3_free(zConverted);
  37469. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37470. "winFullPathname1", zRelative);
  37471. }
  37472. nByte += 3;
  37473. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  37474. if( zTemp==0 ){
  37475. sqlite3_free(zConverted);
  37476. return SQLITE_IOERR_NOMEM;
  37477. }
  37478. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  37479. if( nByte==0 ){
  37480. sqlite3_free(zConverted);
  37481. sqlite3_free(zTemp);
  37482. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37483. "winFullPathname2", zRelative);
  37484. }
  37485. sqlite3_free(zConverted);
  37486. zOut = winUnicodeToUtf8(zTemp);
  37487. sqlite3_free(zTemp);
  37488. }
  37489. #ifdef SQLITE_WIN32_HAS_ANSI
  37490. else{
  37491. char *zTemp;
  37492. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  37493. if( nByte==0 ){
  37494. sqlite3_free(zConverted);
  37495. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37496. "winFullPathname3", zRelative);
  37497. }
  37498. nByte += 3;
  37499. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  37500. if( zTemp==0 ){
  37501. sqlite3_free(zConverted);
  37502. return SQLITE_IOERR_NOMEM;
  37503. }
  37504. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  37505. if( nByte==0 ){
  37506. sqlite3_free(zConverted);
  37507. sqlite3_free(zTemp);
  37508. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  37509. "winFullPathname4", zRelative);
  37510. }
  37511. sqlite3_free(zConverted);
  37512. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  37513. sqlite3_free(zTemp);
  37514. }
  37515. #endif
  37516. if( zOut ){
  37517. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  37518. sqlite3_free(zOut);
  37519. return SQLITE_OK;
  37520. }else{
  37521. return SQLITE_IOERR_NOMEM;
  37522. }
  37523. #endif
  37524. }
  37525. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  37526. /*
  37527. ** Interfaces for opening a shared library, finding entry points
  37528. ** within the shared library, and closing the shared library.
  37529. */
  37530. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  37531. HANDLE h;
  37532. #if defined(__CYGWIN__)
  37533. int nFull = pVfs->mxPathname+1;
  37534. char *zFull = sqlite3MallocZero( nFull );
  37535. void *zConverted = 0;
  37536. if( zFull==0 ){
  37537. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  37538. return 0;
  37539. }
  37540. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  37541. sqlite3_free(zFull);
  37542. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  37543. return 0;
  37544. }
  37545. zConverted = winConvertFromUtf8Filename(zFull);
  37546. sqlite3_free(zFull);
  37547. #else
  37548. void *zConverted = winConvertFromUtf8Filename(zFilename);
  37549. UNUSED_PARAMETER(pVfs);
  37550. #endif
  37551. if( zConverted==0 ){
  37552. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  37553. return 0;
  37554. }
  37555. if( osIsNT() ){
  37556. #if SQLITE_OS_WINRT
  37557. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  37558. #else
  37559. h = osLoadLibraryW((LPCWSTR)zConverted);
  37560. #endif
  37561. }
  37562. #ifdef SQLITE_WIN32_HAS_ANSI
  37563. else{
  37564. h = osLoadLibraryA((char*)zConverted);
  37565. }
  37566. #endif
  37567. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  37568. sqlite3_free(zConverted);
  37569. return (void*)h;
  37570. }
  37571. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  37572. UNUSED_PARAMETER(pVfs);
  37573. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  37574. }
  37575. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  37576. FARPROC proc;
  37577. UNUSED_PARAMETER(pVfs);
  37578. proc = osGetProcAddressA((HANDLE)pH, zSym);
  37579. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  37580. (void*)pH, zSym, (void*)proc));
  37581. return (void(*)(void))proc;
  37582. }
  37583. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  37584. UNUSED_PARAMETER(pVfs);
  37585. osFreeLibrary((HANDLE)pHandle);
  37586. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  37587. }
  37588. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  37589. #define winDlOpen 0
  37590. #define winDlError 0
  37591. #define winDlSym 0
  37592. #define winDlClose 0
  37593. #endif
  37594. /*
  37595. ** Write up to nBuf bytes of randomness into zBuf.
  37596. */
  37597. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  37598. int n = 0;
  37599. UNUSED_PARAMETER(pVfs);
  37600. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  37601. n = nBuf;
  37602. memset(zBuf, 0, nBuf);
  37603. #else
  37604. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  37605. SYSTEMTIME x;
  37606. osGetSystemTime(&x);
  37607. memcpy(&zBuf[n], &x, sizeof(x));
  37608. n += sizeof(x);
  37609. }
  37610. if( sizeof(DWORD)<=nBuf-n ){
  37611. DWORD pid = osGetCurrentProcessId();
  37612. memcpy(&zBuf[n], &pid, sizeof(pid));
  37613. n += sizeof(pid);
  37614. }
  37615. #if SQLITE_OS_WINRT
  37616. if( sizeof(ULONGLONG)<=nBuf-n ){
  37617. ULONGLONG cnt = osGetTickCount64();
  37618. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  37619. n += sizeof(cnt);
  37620. }
  37621. #else
  37622. if( sizeof(DWORD)<=nBuf-n ){
  37623. DWORD cnt = osGetTickCount();
  37624. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  37625. n += sizeof(cnt);
  37626. }
  37627. #endif
  37628. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  37629. LARGE_INTEGER i;
  37630. osQueryPerformanceCounter(&i);
  37631. memcpy(&zBuf[n], &i, sizeof(i));
  37632. n += sizeof(i);
  37633. }
  37634. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  37635. if( sizeof(UUID)<=nBuf-n ){
  37636. UUID id;
  37637. memset(&id, 0, sizeof(UUID));
  37638. osUuidCreate(&id);
  37639. memcpy(&zBuf[n], &id, sizeof(UUID));
  37640. n += sizeof(UUID);
  37641. }
  37642. if( sizeof(UUID)<=nBuf-n ){
  37643. UUID id;
  37644. memset(&id, 0, sizeof(UUID));
  37645. osUuidCreateSequential(&id);
  37646. memcpy(&zBuf[n], &id, sizeof(UUID));
  37647. n += sizeof(UUID);
  37648. }
  37649. #endif
  37650. #endif /* defined(SQLITE_TEST) || defined(SQLITE_ZERO_PRNG_SEED) */
  37651. return n;
  37652. }
  37653. /*
  37654. ** Sleep for a little while. Return the amount of time slept.
  37655. */
  37656. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  37657. sqlite3_win32_sleep((microsec+999)/1000);
  37658. UNUSED_PARAMETER(pVfs);
  37659. return ((microsec+999)/1000)*1000;
  37660. }
  37661. /*
  37662. ** The following variable, if set to a non-zero value, is interpreted as
  37663. ** the number of seconds since 1970 and is used to set the result of
  37664. ** sqlite3OsCurrentTime() during testing.
  37665. */
  37666. #ifdef SQLITE_TEST
  37667. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  37668. #endif
  37669. /*
  37670. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  37671. ** the current time and date as a Julian Day number times 86_400_000. In
  37672. ** other words, write into *piNow the number of milliseconds since the Julian
  37673. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  37674. ** proleptic Gregorian calendar.
  37675. **
  37676. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  37677. ** cannot be found.
  37678. */
  37679. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  37680. /* FILETIME structure is a 64-bit value representing the number of
  37681. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  37682. */
  37683. FILETIME ft;
  37684. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  37685. #ifdef SQLITE_TEST
  37686. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  37687. #endif
  37688. /* 2^32 - to avoid use of LL and warnings in gcc */
  37689. static const sqlite3_int64 max32BitValue =
  37690. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  37691. (sqlite3_int64)294967296;
  37692. #if SQLITE_OS_WINCE
  37693. SYSTEMTIME time;
  37694. osGetSystemTime(&time);
  37695. /* if SystemTimeToFileTime() fails, it returns zero. */
  37696. if (!osSystemTimeToFileTime(&time,&ft)){
  37697. return SQLITE_ERROR;
  37698. }
  37699. #else
  37700. osGetSystemTimeAsFileTime( &ft );
  37701. #endif
  37702. *piNow = winFiletimeEpoch +
  37703. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  37704. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  37705. #ifdef SQLITE_TEST
  37706. if( sqlite3_current_time ){
  37707. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  37708. }
  37709. #endif
  37710. UNUSED_PARAMETER(pVfs);
  37711. return SQLITE_OK;
  37712. }
  37713. /*
  37714. ** Find the current time (in Universal Coordinated Time). Write the
  37715. ** current time and date as a Julian Day number into *prNow and
  37716. ** return 0. Return 1 if the time and date cannot be found.
  37717. */
  37718. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  37719. int rc;
  37720. sqlite3_int64 i;
  37721. rc = winCurrentTimeInt64(pVfs, &i);
  37722. if( !rc ){
  37723. *prNow = i/86400000.0;
  37724. }
  37725. return rc;
  37726. }
  37727. /*
  37728. ** The idea is that this function works like a combination of
  37729. ** GetLastError() and FormatMessage() on Windows (or errno and
  37730. ** strerror_r() on Unix). After an error is returned by an OS
  37731. ** function, SQLite calls this function with zBuf pointing to
  37732. ** a buffer of nBuf bytes. The OS layer should populate the
  37733. ** buffer with a nul-terminated UTF-8 encoded error message
  37734. ** describing the last IO error to have occurred within the calling
  37735. ** thread.
  37736. **
  37737. ** If the error message is too large for the supplied buffer,
  37738. ** it should be truncated. The return value of xGetLastError
  37739. ** is zero if the error message fits in the buffer, or non-zero
  37740. ** otherwise (if the message was truncated). If non-zero is returned,
  37741. ** then it is not necessary to include the nul-terminator character
  37742. ** in the output buffer.
  37743. **
  37744. ** Not supplying an error message will have no adverse effect
  37745. ** on SQLite. It is fine to have an implementation that never
  37746. ** returns an error message:
  37747. **
  37748. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  37749. ** assert(zBuf[0]=='\0');
  37750. ** return 0;
  37751. ** }
  37752. **
  37753. ** However if an error message is supplied, it will be incorporated
  37754. ** by sqlite into the error message available to the user using
  37755. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  37756. */
  37757. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  37758. UNUSED_PARAMETER(pVfs);
  37759. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  37760. }
  37761. /*
  37762. ** Initialize and deinitialize the operating system interface.
  37763. */
  37764. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  37765. static sqlite3_vfs winVfs = {
  37766. 3, /* iVersion */
  37767. sizeof(winFile), /* szOsFile */
  37768. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  37769. 0, /* pNext */
  37770. "win32", /* zName */
  37771. 0, /* pAppData */
  37772. winOpen, /* xOpen */
  37773. winDelete, /* xDelete */
  37774. winAccess, /* xAccess */
  37775. winFullPathname, /* xFullPathname */
  37776. winDlOpen, /* xDlOpen */
  37777. winDlError, /* xDlError */
  37778. winDlSym, /* xDlSym */
  37779. winDlClose, /* xDlClose */
  37780. winRandomness, /* xRandomness */
  37781. winSleep, /* xSleep */
  37782. winCurrentTime, /* xCurrentTime */
  37783. winGetLastError, /* xGetLastError */
  37784. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  37785. winSetSystemCall, /* xSetSystemCall */
  37786. winGetSystemCall, /* xGetSystemCall */
  37787. winNextSystemCall, /* xNextSystemCall */
  37788. };
  37789. #if defined(SQLITE_WIN32_HAS_WIDE)
  37790. static sqlite3_vfs winLongPathVfs = {
  37791. 3, /* iVersion */
  37792. sizeof(winFile), /* szOsFile */
  37793. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  37794. 0, /* pNext */
  37795. "win32-longpath", /* zName */
  37796. 0, /* pAppData */
  37797. winOpen, /* xOpen */
  37798. winDelete, /* xDelete */
  37799. winAccess, /* xAccess */
  37800. winFullPathname, /* xFullPathname */
  37801. winDlOpen, /* xDlOpen */
  37802. winDlError, /* xDlError */
  37803. winDlSym, /* xDlSym */
  37804. winDlClose, /* xDlClose */
  37805. winRandomness, /* xRandomness */
  37806. winSleep, /* xSleep */
  37807. winCurrentTime, /* xCurrentTime */
  37808. winGetLastError, /* xGetLastError */
  37809. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  37810. winSetSystemCall, /* xSetSystemCall */
  37811. winGetSystemCall, /* xGetSystemCall */
  37812. winNextSystemCall, /* xNextSystemCall */
  37813. };
  37814. #endif
  37815. /* Double-check that the aSyscall[] array has been constructed
  37816. ** correctly. See ticket [bb3a86e890c8e96ab] */
  37817. assert( ArraySize(aSyscall)==80 );
  37818. /* get memory map allocation granularity */
  37819. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  37820. #if SQLITE_OS_WINRT
  37821. osGetNativeSystemInfo(&winSysInfo);
  37822. #else
  37823. osGetSystemInfo(&winSysInfo);
  37824. #endif
  37825. assert( winSysInfo.dwAllocationGranularity>0 );
  37826. assert( winSysInfo.dwPageSize>0 );
  37827. sqlite3_vfs_register(&winVfs, 1);
  37828. #if defined(SQLITE_WIN32_HAS_WIDE)
  37829. sqlite3_vfs_register(&winLongPathVfs, 0);
  37830. #endif
  37831. return SQLITE_OK;
  37832. }
  37833. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  37834. #if SQLITE_OS_WINRT
  37835. if( sleepObj!=NULL ){
  37836. osCloseHandle(sleepObj);
  37837. sleepObj = NULL;
  37838. }
  37839. #endif
  37840. return SQLITE_OK;
  37841. }
  37842. #endif /* SQLITE_OS_WIN */
  37843. /************** End of os_win.c **********************************************/
  37844. /************** Begin file bitvec.c ******************************************/
  37845. /*
  37846. ** 2008 February 16
  37847. **
  37848. ** The author disclaims copyright to this source code. In place of
  37849. ** a legal notice, here is a blessing:
  37850. **
  37851. ** May you do good and not evil.
  37852. ** May you find forgiveness for yourself and forgive others.
  37853. ** May you share freely, never taking more than you give.
  37854. **
  37855. *************************************************************************
  37856. ** This file implements an object that represents a fixed-length
  37857. ** bitmap. Bits are numbered starting with 1.
  37858. **
  37859. ** A bitmap is used to record which pages of a database file have been
  37860. ** journalled during a transaction, or which pages have the "dont-write"
  37861. ** property. Usually only a few pages are meet either condition.
  37862. ** So the bitmap is usually sparse and has low cardinality.
  37863. ** But sometimes (for example when during a DROP of a large table) most
  37864. ** or all of the pages in a database can get journalled. In those cases,
  37865. ** the bitmap becomes dense with high cardinality. The algorithm needs
  37866. ** to handle both cases well.
  37867. **
  37868. ** The size of the bitmap is fixed when the object is created.
  37869. **
  37870. ** All bits are clear when the bitmap is created. Individual bits
  37871. ** may be set or cleared one at a time.
  37872. **
  37873. ** Test operations are about 100 times more common that set operations.
  37874. ** Clear operations are exceedingly rare. There are usually between
  37875. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  37876. ** sometimes grow into tens of thousands or larger. The size of the
  37877. ** Bitvec object is the number of pages in the database file at the
  37878. ** start of a transaction, and is thus usually less than a few thousand,
  37879. ** but can be as large as 2 billion for a really big database.
  37880. */
  37881. /* #include "sqliteInt.h" */
  37882. /* Size of the Bitvec structure in bytes. */
  37883. #define BITVEC_SZ 512
  37884. /* Round the union size down to the nearest pointer boundary, since that's how
  37885. ** it will be aligned within the Bitvec struct. */
  37886. #define BITVEC_USIZE \
  37887. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  37888. /* Type of the array "element" for the bitmap representation.
  37889. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  37890. ** Setting this to the "natural word" size of your CPU may improve
  37891. ** performance. */
  37892. #define BITVEC_TELEM u8
  37893. /* Size, in bits, of the bitmap element. */
  37894. #define BITVEC_SZELEM 8
  37895. /* Number of elements in a bitmap array. */
  37896. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  37897. /* Number of bits in the bitmap array. */
  37898. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  37899. /* Number of u32 values in hash table. */
  37900. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  37901. /* Maximum number of entries in hash table before
  37902. ** sub-dividing and re-hashing. */
  37903. #define BITVEC_MXHASH (BITVEC_NINT/2)
  37904. /* Hashing function for the aHash representation.
  37905. ** Empirical testing showed that the *37 multiplier
  37906. ** (an arbitrary prime)in the hash function provided
  37907. ** no fewer collisions than the no-op *1. */
  37908. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  37909. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  37910. /*
  37911. ** A bitmap is an instance of the following structure.
  37912. **
  37913. ** This bitmap records the existence of zero or more bits
  37914. ** with values between 1 and iSize, inclusive.
  37915. **
  37916. ** There are three possible representations of the bitmap.
  37917. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  37918. ** bitmap. The least significant bit is bit 1.
  37919. **
  37920. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  37921. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  37922. **
  37923. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  37924. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  37925. ** handles up to iDivisor separate values of i. apSub[0] holds
  37926. ** values between 1 and iDivisor. apSub[1] holds values between
  37927. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  37928. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  37929. ** to hold deal with values between 1 and iDivisor.
  37930. */
  37931. struct Bitvec {
  37932. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  37933. u32 nSet; /* Number of bits that are set - only valid for aHash
  37934. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  37935. ** this would be 125. */
  37936. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  37937. /* Should >=0 for apSub element. */
  37938. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  37939. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  37940. union {
  37941. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  37942. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  37943. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  37944. } u;
  37945. };
  37946. /*
  37947. ** Create a new bitmap object able to handle bits between 0 and iSize,
  37948. ** inclusive. Return a pointer to the new object. Return NULL if
  37949. ** malloc fails.
  37950. */
  37951. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  37952. Bitvec *p;
  37953. assert( sizeof(*p)==BITVEC_SZ );
  37954. p = sqlite3MallocZero( sizeof(*p) );
  37955. if( p ){
  37956. p->iSize = iSize;
  37957. }
  37958. return p;
  37959. }
  37960. /*
  37961. ** Check to see if the i-th bit is set. Return true or false.
  37962. ** If p is NULL (if the bitmap has not been created) or if
  37963. ** i is out of range, then return false.
  37964. */
  37965. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  37966. assert( p!=0 );
  37967. i--;
  37968. if( i>=p->iSize ) return 0;
  37969. while( p->iDivisor ){
  37970. u32 bin = i/p->iDivisor;
  37971. i = i%p->iDivisor;
  37972. p = p->u.apSub[bin];
  37973. if (!p) {
  37974. return 0;
  37975. }
  37976. }
  37977. if( p->iSize<=BITVEC_NBIT ){
  37978. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  37979. } else{
  37980. u32 h = BITVEC_HASH(i++);
  37981. while( p->u.aHash[h] ){
  37982. if( p->u.aHash[h]==i ) return 1;
  37983. h = (h+1) % BITVEC_NINT;
  37984. }
  37985. return 0;
  37986. }
  37987. }
  37988. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  37989. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  37990. }
  37991. /*
  37992. ** Set the i-th bit. Return 0 on success and an error code if
  37993. ** anything goes wrong.
  37994. **
  37995. ** This routine might cause sub-bitmaps to be allocated. Failing
  37996. ** to get the memory needed to hold the sub-bitmap is the only
  37997. ** that can go wrong with an insert, assuming p and i are valid.
  37998. **
  37999. ** The calling function must ensure that p is a valid Bitvec object
  38000. ** and that the value for "i" is within range of the Bitvec object.
  38001. ** Otherwise the behavior is undefined.
  38002. */
  38003. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  38004. u32 h;
  38005. if( p==0 ) return SQLITE_OK;
  38006. assert( i>0 );
  38007. assert( i<=p->iSize );
  38008. i--;
  38009. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  38010. u32 bin = i/p->iDivisor;
  38011. i = i%p->iDivisor;
  38012. if( p->u.apSub[bin]==0 ){
  38013. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  38014. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  38015. }
  38016. p = p->u.apSub[bin];
  38017. }
  38018. if( p->iSize<=BITVEC_NBIT ){
  38019. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  38020. return SQLITE_OK;
  38021. }
  38022. h = BITVEC_HASH(i++);
  38023. /* if there wasn't a hash collision, and this doesn't */
  38024. /* completely fill the hash, then just add it without */
  38025. /* worring about sub-dividing and re-hashing. */
  38026. if( !p->u.aHash[h] ){
  38027. if (p->nSet<(BITVEC_NINT-1)) {
  38028. goto bitvec_set_end;
  38029. } else {
  38030. goto bitvec_set_rehash;
  38031. }
  38032. }
  38033. /* there was a collision, check to see if it's already */
  38034. /* in hash, if not, try to find a spot for it */
  38035. do {
  38036. if( p->u.aHash[h]==i ) return SQLITE_OK;
  38037. h++;
  38038. if( h>=BITVEC_NINT ) h = 0;
  38039. } while( p->u.aHash[h] );
  38040. /* we didn't find it in the hash. h points to the first */
  38041. /* available free spot. check to see if this is going to */
  38042. /* make our hash too "full". */
  38043. bitvec_set_rehash:
  38044. if( p->nSet>=BITVEC_MXHASH ){
  38045. unsigned int j;
  38046. int rc;
  38047. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  38048. if( aiValues==0 ){
  38049. return SQLITE_NOMEM;
  38050. }else{
  38051. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  38052. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  38053. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  38054. rc = sqlite3BitvecSet(p, i);
  38055. for(j=0; j<BITVEC_NINT; j++){
  38056. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  38057. }
  38058. sqlite3StackFree(0, aiValues);
  38059. return rc;
  38060. }
  38061. }
  38062. bitvec_set_end:
  38063. p->nSet++;
  38064. p->u.aHash[h] = i;
  38065. return SQLITE_OK;
  38066. }
  38067. /*
  38068. ** Clear the i-th bit.
  38069. **
  38070. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  38071. ** that BitvecClear can use to rebuilt its hash table.
  38072. */
  38073. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  38074. if( p==0 ) return;
  38075. assert( i>0 );
  38076. i--;
  38077. while( p->iDivisor ){
  38078. u32 bin = i/p->iDivisor;
  38079. i = i%p->iDivisor;
  38080. p = p->u.apSub[bin];
  38081. if (!p) {
  38082. return;
  38083. }
  38084. }
  38085. if( p->iSize<=BITVEC_NBIT ){
  38086. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  38087. }else{
  38088. unsigned int j;
  38089. u32 *aiValues = pBuf;
  38090. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  38091. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  38092. p->nSet = 0;
  38093. for(j=0; j<BITVEC_NINT; j++){
  38094. if( aiValues[j] && aiValues[j]!=(i+1) ){
  38095. u32 h = BITVEC_HASH(aiValues[j]-1);
  38096. p->nSet++;
  38097. while( p->u.aHash[h] ){
  38098. h++;
  38099. if( h>=BITVEC_NINT ) h = 0;
  38100. }
  38101. p->u.aHash[h] = aiValues[j];
  38102. }
  38103. }
  38104. }
  38105. }
  38106. /*
  38107. ** Destroy a bitmap object. Reclaim all memory used.
  38108. */
  38109. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  38110. if( p==0 ) return;
  38111. if( p->iDivisor ){
  38112. unsigned int i;
  38113. for(i=0; i<BITVEC_NPTR; i++){
  38114. sqlite3BitvecDestroy(p->u.apSub[i]);
  38115. }
  38116. }
  38117. sqlite3_free(p);
  38118. }
  38119. /*
  38120. ** Return the value of the iSize parameter specified when Bitvec *p
  38121. ** was created.
  38122. */
  38123. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  38124. return p->iSize;
  38125. }
  38126. #ifndef SQLITE_OMIT_BUILTIN_TEST
  38127. /*
  38128. ** Let V[] be an array of unsigned characters sufficient to hold
  38129. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  38130. ** Then the following macros can be used to set, clear, or test
  38131. ** individual bits within V.
  38132. */
  38133. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  38134. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  38135. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  38136. /*
  38137. ** This routine runs an extensive test of the Bitvec code.
  38138. **
  38139. ** The input is an array of integers that acts as a program
  38140. ** to test the Bitvec. The integers are opcodes followed
  38141. ** by 0, 1, or 3 operands, depending on the opcode. Another
  38142. ** opcode follows immediately after the last operand.
  38143. **
  38144. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  38145. ** "halt" opcode and causes the test to end.
  38146. **
  38147. ** 0 Halt and return the number of errors
  38148. ** 1 N S X Set N bits beginning with S and incrementing by X
  38149. ** 2 N S X Clear N bits beginning with S and incrementing by X
  38150. ** 3 N Set N randomly chosen bits
  38151. ** 4 N Clear N randomly chosen bits
  38152. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  38153. **
  38154. ** The opcodes 1 through 4 perform set and clear operations are performed
  38155. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  38156. ** Opcode 5 works on the linear array only, not on the Bitvec.
  38157. ** Opcode 5 is used to deliberately induce a fault in order to
  38158. ** confirm that error detection works.
  38159. **
  38160. ** At the conclusion of the test the linear array is compared
  38161. ** against the Bitvec object. If there are any differences,
  38162. ** an error is returned. If they are the same, zero is returned.
  38163. **
  38164. ** If a memory allocation error occurs, return -1.
  38165. */
  38166. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  38167. Bitvec *pBitvec = 0;
  38168. unsigned char *pV = 0;
  38169. int rc = -1;
  38170. int i, nx, pc, op;
  38171. void *pTmpSpace;
  38172. /* Allocate the Bitvec to be tested and a linear array of
  38173. ** bits to act as the reference */
  38174. pBitvec = sqlite3BitvecCreate( sz );
  38175. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  38176. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  38177. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  38178. /* NULL pBitvec tests */
  38179. sqlite3BitvecSet(0, 1);
  38180. sqlite3BitvecClear(0, 1, pTmpSpace);
  38181. /* Run the program */
  38182. pc = 0;
  38183. while( (op = aOp[pc])!=0 ){
  38184. switch( op ){
  38185. case 1:
  38186. case 2:
  38187. case 5: {
  38188. nx = 4;
  38189. i = aOp[pc+2] - 1;
  38190. aOp[pc+2] += aOp[pc+3];
  38191. break;
  38192. }
  38193. case 3:
  38194. case 4:
  38195. default: {
  38196. nx = 2;
  38197. sqlite3_randomness(sizeof(i), &i);
  38198. break;
  38199. }
  38200. }
  38201. if( (--aOp[pc+1]) > 0 ) nx = 0;
  38202. pc += nx;
  38203. i = (i & 0x7fffffff)%sz;
  38204. if( (op & 1)!=0 ){
  38205. SETBIT(pV, (i+1));
  38206. if( op!=5 ){
  38207. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  38208. }
  38209. }else{
  38210. CLEARBIT(pV, (i+1));
  38211. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  38212. }
  38213. }
  38214. /* Test to make sure the linear array exactly matches the
  38215. ** Bitvec object. Start with the assumption that they do
  38216. ** match (rc==0). Change rc to non-zero if a discrepancy
  38217. ** is found.
  38218. */
  38219. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  38220. + sqlite3BitvecTest(pBitvec, 0)
  38221. + (sqlite3BitvecSize(pBitvec) - sz);
  38222. for(i=1; i<=sz; i++){
  38223. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  38224. rc = i;
  38225. break;
  38226. }
  38227. }
  38228. /* Free allocated structure */
  38229. bitvec_end:
  38230. sqlite3_free(pTmpSpace);
  38231. sqlite3_free(pV);
  38232. sqlite3BitvecDestroy(pBitvec);
  38233. return rc;
  38234. }
  38235. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  38236. /************** End of bitvec.c **********************************************/
  38237. /************** Begin file pcache.c ******************************************/
  38238. /*
  38239. ** 2008 August 05
  38240. **
  38241. ** The author disclaims copyright to this source code. In place of
  38242. ** a legal notice, here is a blessing:
  38243. **
  38244. ** May you do good and not evil.
  38245. ** May you find forgiveness for yourself and forgive others.
  38246. ** May you share freely, never taking more than you give.
  38247. **
  38248. *************************************************************************
  38249. ** This file implements that page cache.
  38250. */
  38251. /* #include "sqliteInt.h" */
  38252. /*
  38253. ** A complete page cache is an instance of this structure.
  38254. */
  38255. struct PCache {
  38256. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  38257. PgHdr *pSynced; /* Last synced page in dirty page list */
  38258. int nRefSum; /* Sum of ref counts over all pages */
  38259. int szCache; /* Configured cache size */
  38260. int szSpill; /* Size before spilling occurs */
  38261. int szPage; /* Size of every page in this cache */
  38262. int szExtra; /* Size of extra space for each page */
  38263. u8 bPurgeable; /* True if pages are on backing store */
  38264. u8 eCreate; /* eCreate value for for xFetch() */
  38265. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  38266. void *pStress; /* Argument to xStress */
  38267. sqlite3_pcache *pCache; /* Pluggable cache module */
  38268. };
  38269. /********************************** Linked List Management ********************/
  38270. /* Allowed values for second argument to pcacheManageDirtyList() */
  38271. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  38272. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  38273. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  38274. /*
  38275. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  38276. ** argument determines what operation to do. The 0x01 bit means first
  38277. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  38278. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  38279. */
  38280. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  38281. PCache *p = pPage->pCache;
  38282. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  38283. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  38284. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  38285. /* Update the PCache1.pSynced variable if necessary. */
  38286. if( p->pSynced==pPage ){
  38287. PgHdr *pSynced = pPage->pDirtyPrev;
  38288. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  38289. pSynced = pSynced->pDirtyPrev;
  38290. }
  38291. p->pSynced = pSynced;
  38292. }
  38293. if( pPage->pDirtyNext ){
  38294. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  38295. }else{
  38296. assert( pPage==p->pDirtyTail );
  38297. p->pDirtyTail = pPage->pDirtyPrev;
  38298. }
  38299. if( pPage->pDirtyPrev ){
  38300. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  38301. }else{
  38302. assert( pPage==p->pDirty );
  38303. p->pDirty = pPage->pDirtyNext;
  38304. if( p->pDirty==0 && p->bPurgeable ){
  38305. assert( p->eCreate==1 );
  38306. p->eCreate = 2;
  38307. }
  38308. }
  38309. pPage->pDirtyNext = 0;
  38310. pPage->pDirtyPrev = 0;
  38311. }
  38312. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  38313. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  38314. pPage->pDirtyNext = p->pDirty;
  38315. if( pPage->pDirtyNext ){
  38316. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  38317. pPage->pDirtyNext->pDirtyPrev = pPage;
  38318. }else{
  38319. p->pDirtyTail = pPage;
  38320. if( p->bPurgeable ){
  38321. assert( p->eCreate==2 );
  38322. p->eCreate = 1;
  38323. }
  38324. }
  38325. p->pDirty = pPage;
  38326. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  38327. p->pSynced = pPage;
  38328. }
  38329. }
  38330. }
  38331. /*
  38332. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  38333. ** being used for an in-memory database, this function is a no-op.
  38334. */
  38335. static void pcacheUnpin(PgHdr *p){
  38336. if( p->pCache->bPurgeable ){
  38337. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  38338. }
  38339. }
  38340. /*
  38341. ** Compute the number of pages of cache requested. p->szCache is the
  38342. ** cache size requested by the "PRAGMA cache_size" statement.
  38343. */
  38344. static int numberOfCachePages(PCache *p){
  38345. if( p->szCache>=0 ){
  38346. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  38347. ** suggested cache size is set to N. */
  38348. return p->szCache;
  38349. }else{
  38350. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  38351. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  38352. ** bytes of memory. */
  38353. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  38354. }
  38355. }
  38356. /*************************************************** General Interfaces ******
  38357. **
  38358. ** Initialize and shutdown the page cache subsystem. Neither of these
  38359. ** functions are threadsafe.
  38360. */
  38361. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  38362. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  38363. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  38364. ** built-in default page cache is used instead of the application defined
  38365. ** page cache. */
  38366. sqlite3PCacheSetDefault();
  38367. }
  38368. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  38369. }
  38370. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  38371. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  38372. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  38373. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  38374. }
  38375. }
  38376. /*
  38377. ** Return the size in bytes of a PCache object.
  38378. */
  38379. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  38380. /*
  38381. ** Create a new PCache object. Storage space to hold the object
  38382. ** has already been allocated and is passed in as the p pointer.
  38383. ** The caller discovers how much space needs to be allocated by
  38384. ** calling sqlite3PcacheSize().
  38385. */
  38386. SQLITE_PRIVATE int sqlite3PcacheOpen(
  38387. int szPage, /* Size of every page */
  38388. int szExtra, /* Extra space associated with each page */
  38389. int bPurgeable, /* True if pages are on backing store */
  38390. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  38391. void *pStress, /* Argument to xStress */
  38392. PCache *p /* Preallocated space for the PCache */
  38393. ){
  38394. memset(p, 0, sizeof(PCache));
  38395. p->szPage = 1;
  38396. p->szExtra = szExtra;
  38397. p->bPurgeable = bPurgeable;
  38398. p->eCreate = 2;
  38399. p->xStress = xStress;
  38400. p->pStress = pStress;
  38401. p->szCache = 100;
  38402. p->szSpill = 1;
  38403. return sqlite3PcacheSetPageSize(p, szPage);
  38404. }
  38405. /*
  38406. ** Change the page size for PCache object. The caller must ensure that there
  38407. ** are no outstanding page references when this function is called.
  38408. */
  38409. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  38410. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  38411. if( pCache->szPage ){
  38412. sqlite3_pcache *pNew;
  38413. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  38414. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  38415. pCache->bPurgeable
  38416. );
  38417. if( pNew==0 ) return SQLITE_NOMEM;
  38418. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  38419. if( pCache->pCache ){
  38420. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  38421. }
  38422. pCache->pCache = pNew;
  38423. pCache->szPage = szPage;
  38424. }
  38425. return SQLITE_OK;
  38426. }
  38427. /*
  38428. ** Try to obtain a page from the cache.
  38429. **
  38430. ** This routine returns a pointer to an sqlite3_pcache_page object if
  38431. ** such an object is already in cache, or if a new one is created.
  38432. ** This routine returns a NULL pointer if the object was not in cache
  38433. ** and could not be created.
  38434. **
  38435. ** The createFlags should be 0 to check for existing pages and should
  38436. ** be 3 (not 1, but 3) to try to create a new page.
  38437. **
  38438. ** If the createFlag is 0, then NULL is always returned if the page
  38439. ** is not already in the cache. If createFlag is 1, then a new page
  38440. ** is created only if that can be done without spilling dirty pages
  38441. ** and without exceeding the cache size limit.
  38442. **
  38443. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  38444. ** initialize the sqlite3_pcache_page object and convert it into a
  38445. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  38446. ** routines are split this way for performance reasons. When separated
  38447. ** they can both (usually) operate without having to push values to
  38448. ** the stack on entry and pop them back off on exit, which saves a
  38449. ** lot of pushing and popping.
  38450. */
  38451. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  38452. PCache *pCache, /* Obtain the page from this cache */
  38453. Pgno pgno, /* Page number to obtain */
  38454. int createFlag /* If true, create page if it does not exist already */
  38455. ){
  38456. int eCreate;
  38457. assert( pCache!=0 );
  38458. assert( pCache->pCache!=0 );
  38459. assert( createFlag==3 || createFlag==0 );
  38460. assert( pgno>0 );
  38461. /* eCreate defines what to do if the page does not exist.
  38462. ** 0 Do not allocate a new page. (createFlag==0)
  38463. ** 1 Allocate a new page if doing so is inexpensive.
  38464. ** (createFlag==1 AND bPurgeable AND pDirty)
  38465. ** 2 Allocate a new page even it doing so is difficult.
  38466. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  38467. */
  38468. eCreate = createFlag & pCache->eCreate;
  38469. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  38470. assert( createFlag==0 || pCache->eCreate==eCreate );
  38471. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  38472. return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  38473. }
  38474. /*
  38475. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  38476. ** page because new clean pages are available for reuse and the cache
  38477. ** size limit has been reached, then this routine can be invoked to
  38478. ** try harder to allocate a page. This routine might invoke the stress
  38479. ** callback to spill dirty pages to the journal. It will then try to
  38480. ** allocate the new page and will only fail to allocate a new page on
  38481. ** an OOM error.
  38482. **
  38483. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  38484. */
  38485. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  38486. PCache *pCache, /* Obtain the page from this cache */
  38487. Pgno pgno, /* Page number to obtain */
  38488. sqlite3_pcache_page **ppPage /* Write result here */
  38489. ){
  38490. PgHdr *pPg;
  38491. if( pCache->eCreate==2 ) return 0;
  38492. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  38493. /* Find a dirty page to write-out and recycle. First try to find a
  38494. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  38495. ** cleared), but if that is not possible settle for any other
  38496. ** unreferenced dirty page.
  38497. */
  38498. for(pPg=pCache->pSynced;
  38499. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  38500. pPg=pPg->pDirtyPrev
  38501. );
  38502. pCache->pSynced = pPg;
  38503. if( !pPg ){
  38504. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  38505. }
  38506. if( pPg ){
  38507. int rc;
  38508. #ifdef SQLITE_LOG_CACHE_SPILL
  38509. sqlite3_log(SQLITE_FULL,
  38510. "spill page %d making room for %d - cache used: %d/%d",
  38511. pPg->pgno, pgno,
  38512. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  38513. numberOfCachePages(pCache));
  38514. #endif
  38515. rc = pCache->xStress(pCache->pStress, pPg);
  38516. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  38517. return rc;
  38518. }
  38519. }
  38520. }
  38521. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  38522. return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
  38523. }
  38524. /*
  38525. ** This is a helper routine for sqlite3PcacheFetchFinish()
  38526. **
  38527. ** In the uncommon case where the page being fetched has not been
  38528. ** initialized, this routine is invoked to do the initialization.
  38529. ** This routine is broken out into a separate function since it
  38530. ** requires extra stack manipulation that can be avoided in the common
  38531. ** case.
  38532. */
  38533. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  38534. PCache *pCache, /* Obtain the page from this cache */
  38535. Pgno pgno, /* Page number obtained */
  38536. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  38537. ){
  38538. PgHdr *pPgHdr;
  38539. assert( pPage!=0 );
  38540. pPgHdr = (PgHdr*)pPage->pExtra;
  38541. assert( pPgHdr->pPage==0 );
  38542. memset(pPgHdr, 0, sizeof(PgHdr));
  38543. pPgHdr->pPage = pPage;
  38544. pPgHdr->pData = pPage->pBuf;
  38545. pPgHdr->pExtra = (void *)&pPgHdr[1];
  38546. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  38547. pPgHdr->pCache = pCache;
  38548. pPgHdr->pgno = pgno;
  38549. pPgHdr->flags = PGHDR_CLEAN;
  38550. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  38551. }
  38552. /*
  38553. ** This routine converts the sqlite3_pcache_page object returned by
  38554. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  38555. ** must be called after sqlite3PcacheFetch() in order to get a usable
  38556. ** result.
  38557. */
  38558. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  38559. PCache *pCache, /* Obtain the page from this cache */
  38560. Pgno pgno, /* Page number obtained */
  38561. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  38562. ){
  38563. PgHdr *pPgHdr;
  38564. assert( pPage!=0 );
  38565. pPgHdr = (PgHdr *)pPage->pExtra;
  38566. if( !pPgHdr->pPage ){
  38567. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  38568. }
  38569. pCache->nRefSum++;
  38570. pPgHdr->nRef++;
  38571. return pPgHdr;
  38572. }
  38573. /*
  38574. ** Decrement the reference count on a page. If the page is clean and the
  38575. ** reference count drops to 0, then it is made eligible for recycling.
  38576. */
  38577. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  38578. assert( p->nRef>0 );
  38579. p->pCache->nRefSum--;
  38580. if( (--p->nRef)==0 ){
  38581. if( p->flags&PGHDR_CLEAN ){
  38582. pcacheUnpin(p);
  38583. }else if( p->pDirtyPrev!=0 ){
  38584. /* Move the page to the head of the dirty list. */
  38585. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  38586. }
  38587. }
  38588. }
  38589. /*
  38590. ** Increase the reference count of a supplied page by 1.
  38591. */
  38592. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  38593. assert(p->nRef>0);
  38594. p->nRef++;
  38595. p->pCache->nRefSum++;
  38596. }
  38597. /*
  38598. ** Drop a page from the cache. There must be exactly one reference to the
  38599. ** page. This function deletes that reference, so after it returns the
  38600. ** page pointed to by p is invalid.
  38601. */
  38602. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  38603. assert( p->nRef==1 );
  38604. if( p->flags&PGHDR_DIRTY ){
  38605. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  38606. }
  38607. p->pCache->nRefSum--;
  38608. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  38609. }
  38610. /*
  38611. ** Make sure the page is marked as dirty. If it isn't dirty already,
  38612. ** make it so.
  38613. */
  38614. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  38615. assert( p->nRef>0 );
  38616. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){
  38617. p->flags &= ~PGHDR_DONT_WRITE;
  38618. if( p->flags & PGHDR_CLEAN ){
  38619. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  38620. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  38621. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  38622. }
  38623. }
  38624. }
  38625. /*
  38626. ** Make sure the page is marked as clean. If it isn't clean already,
  38627. ** make it so.
  38628. */
  38629. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  38630. if( (p->flags & PGHDR_DIRTY) ){
  38631. assert( (p->flags & PGHDR_CLEAN)==0 );
  38632. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  38633. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  38634. p->flags |= PGHDR_CLEAN;
  38635. if( p->nRef==0 ){
  38636. pcacheUnpin(p);
  38637. }
  38638. }
  38639. }
  38640. /*
  38641. ** Make every page in the cache clean.
  38642. */
  38643. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  38644. PgHdr *p;
  38645. while( (p = pCache->pDirty)!=0 ){
  38646. sqlite3PcacheMakeClean(p);
  38647. }
  38648. }
  38649. /*
  38650. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  38651. */
  38652. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  38653. PgHdr *p;
  38654. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  38655. p->flags &= ~PGHDR_NEED_SYNC;
  38656. }
  38657. pCache->pSynced = pCache->pDirtyTail;
  38658. }
  38659. /*
  38660. ** Change the page number of page p to newPgno.
  38661. */
  38662. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  38663. PCache *pCache = p->pCache;
  38664. assert( p->nRef>0 );
  38665. assert( newPgno>0 );
  38666. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  38667. p->pgno = newPgno;
  38668. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  38669. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  38670. }
  38671. }
  38672. /*
  38673. ** Drop every cache entry whose page number is greater than "pgno". The
  38674. ** caller must ensure that there are no outstanding references to any pages
  38675. ** other than page 1 with a page number greater than pgno.
  38676. **
  38677. ** If there is a reference to page 1 and the pgno parameter passed to this
  38678. ** function is 0, then the data area associated with page 1 is zeroed, but
  38679. ** the page object is not dropped.
  38680. */
  38681. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  38682. if( pCache->pCache ){
  38683. PgHdr *p;
  38684. PgHdr *pNext;
  38685. for(p=pCache->pDirty; p; p=pNext){
  38686. pNext = p->pDirtyNext;
  38687. /* This routine never gets call with a positive pgno except right
  38688. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  38689. ** it must be that pgno==0.
  38690. */
  38691. assert( p->pgno>0 );
  38692. if( ALWAYS(p->pgno>pgno) ){
  38693. assert( p->flags&PGHDR_DIRTY );
  38694. sqlite3PcacheMakeClean(p);
  38695. }
  38696. }
  38697. if( pgno==0 && pCache->nRefSum ){
  38698. sqlite3_pcache_page *pPage1;
  38699. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  38700. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  38701. ** pCache->nRefSum>0 */
  38702. memset(pPage1->pBuf, 0, pCache->szPage);
  38703. pgno = 1;
  38704. }
  38705. }
  38706. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  38707. }
  38708. }
  38709. /*
  38710. ** Close a cache.
  38711. */
  38712. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  38713. assert( pCache->pCache!=0 );
  38714. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  38715. }
  38716. /*
  38717. ** Discard the contents of the cache.
  38718. */
  38719. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  38720. sqlite3PcacheTruncate(pCache, 0);
  38721. }
  38722. /*
  38723. ** Merge two lists of pages connected by pDirty and in pgno order.
  38724. ** Do not both fixing the pDirtyPrev pointers.
  38725. */
  38726. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  38727. PgHdr result, *pTail;
  38728. pTail = &result;
  38729. while( pA && pB ){
  38730. if( pA->pgno<pB->pgno ){
  38731. pTail->pDirty = pA;
  38732. pTail = pA;
  38733. pA = pA->pDirty;
  38734. }else{
  38735. pTail->pDirty = pB;
  38736. pTail = pB;
  38737. pB = pB->pDirty;
  38738. }
  38739. }
  38740. if( pA ){
  38741. pTail->pDirty = pA;
  38742. }else if( pB ){
  38743. pTail->pDirty = pB;
  38744. }else{
  38745. pTail->pDirty = 0;
  38746. }
  38747. return result.pDirty;
  38748. }
  38749. /*
  38750. ** Sort the list of pages in accending order by pgno. Pages are
  38751. ** connected by pDirty pointers. The pDirtyPrev pointers are
  38752. ** corrupted by this sort.
  38753. **
  38754. ** Since there cannot be more than 2^31 distinct pages in a database,
  38755. ** there cannot be more than 31 buckets required by the merge sorter.
  38756. ** One extra bucket is added to catch overflow in case something
  38757. ** ever changes to make the previous sentence incorrect.
  38758. */
  38759. #define N_SORT_BUCKET 32
  38760. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  38761. PgHdr *a[N_SORT_BUCKET], *p;
  38762. int i;
  38763. memset(a, 0, sizeof(a));
  38764. while( pIn ){
  38765. p = pIn;
  38766. pIn = p->pDirty;
  38767. p->pDirty = 0;
  38768. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  38769. if( a[i]==0 ){
  38770. a[i] = p;
  38771. break;
  38772. }else{
  38773. p = pcacheMergeDirtyList(a[i], p);
  38774. a[i] = 0;
  38775. }
  38776. }
  38777. if( NEVER(i==N_SORT_BUCKET-1) ){
  38778. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  38779. ** the input list. But that is impossible.
  38780. */
  38781. a[i] = pcacheMergeDirtyList(a[i], p);
  38782. }
  38783. }
  38784. p = a[0];
  38785. for(i=1; i<N_SORT_BUCKET; i++){
  38786. p = pcacheMergeDirtyList(p, a[i]);
  38787. }
  38788. return p;
  38789. }
  38790. /*
  38791. ** Return a list of all dirty pages in the cache, sorted by page number.
  38792. */
  38793. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  38794. PgHdr *p;
  38795. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  38796. p->pDirty = p->pDirtyNext;
  38797. }
  38798. return pcacheSortDirtyList(pCache->pDirty);
  38799. }
  38800. /*
  38801. ** Return the total number of references to all pages held by the cache.
  38802. **
  38803. ** This is not the total number of pages referenced, but the sum of the
  38804. ** reference count for all pages.
  38805. */
  38806. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  38807. return pCache->nRefSum;
  38808. }
  38809. /*
  38810. ** Return the number of references to the page supplied as an argument.
  38811. */
  38812. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  38813. return p->nRef;
  38814. }
  38815. /*
  38816. ** Return the total number of pages in the cache.
  38817. */
  38818. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  38819. assert( pCache->pCache!=0 );
  38820. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  38821. }
  38822. #ifdef SQLITE_TEST
  38823. /*
  38824. ** Get the suggested cache-size value.
  38825. */
  38826. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  38827. return numberOfCachePages(pCache);
  38828. }
  38829. #endif
  38830. /*
  38831. ** Set the suggested cache-size value.
  38832. */
  38833. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  38834. assert( pCache->pCache!=0 );
  38835. pCache->szCache = mxPage;
  38836. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  38837. numberOfCachePages(pCache));
  38838. }
  38839. /*
  38840. ** Set the suggested cache-spill value. Make no changes if if the
  38841. ** argument is zero. Return the effective cache-spill size, which will
  38842. ** be the larger of the szSpill and szCache.
  38843. */
  38844. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  38845. int res;
  38846. assert( p->pCache!=0 );
  38847. if( mxPage ){
  38848. if( mxPage<0 ){
  38849. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  38850. }
  38851. p->szSpill = mxPage;
  38852. }
  38853. res = numberOfCachePages(p);
  38854. if( res<p->szSpill ) res = p->szSpill;
  38855. return res;
  38856. }
  38857. /*
  38858. ** Free up as much memory as possible from the page cache.
  38859. */
  38860. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  38861. assert( pCache->pCache!=0 );
  38862. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  38863. }
  38864. /*
  38865. ** Return the size of the header added by this middleware layer
  38866. ** in the page-cache hierarchy.
  38867. */
  38868. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  38869. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  38870. /*
  38871. ** For all dirty pages currently in the cache, invoke the specified
  38872. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  38873. ** defined.
  38874. */
  38875. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  38876. PgHdr *pDirty;
  38877. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  38878. xIter(pDirty);
  38879. }
  38880. }
  38881. #endif
  38882. /************** End of pcache.c **********************************************/
  38883. /************** Begin file pcache1.c *****************************************/
  38884. /*
  38885. ** 2008 November 05
  38886. **
  38887. ** The author disclaims copyright to this source code. In place of
  38888. ** a legal notice, here is a blessing:
  38889. **
  38890. ** May you do good and not evil.
  38891. ** May you find forgiveness for yourself and forgive others.
  38892. ** May you share freely, never taking more than you give.
  38893. **
  38894. *************************************************************************
  38895. **
  38896. ** This file implements the default page cache implementation (the
  38897. ** sqlite3_pcache interface). It also contains part of the implementation
  38898. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  38899. ** If the default page cache implementation is overridden, then neither of
  38900. ** these two features are available.
  38901. **
  38902. ** A Page cache line looks like this:
  38903. **
  38904. ** -------------------------------------------------------------
  38905. ** | database page content | PgHdr1 | MemPage | PgHdr |
  38906. ** -------------------------------------------------------------
  38907. **
  38908. ** The database page content is up front (so that buffer overreads tend to
  38909. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  38910. ** is the extension added by the btree.c module containing information such
  38911. ** as the database page number and how that database page is used. PgHdr
  38912. ** is added by the pcache.c layer and contains information used to keep track
  38913. ** of which pages are "dirty". PgHdr1 is an extension added by this
  38914. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  38915. ** PgHdr1 contains information needed to look up a page by its page number.
  38916. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  38917. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  38918. **
  38919. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  38920. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  38921. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  38922. ** size can vary according to architecture, compile-time options, and
  38923. ** SQLite library version number.
  38924. **
  38925. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  38926. ** using a separate memory allocation from the database page content. This
  38927. ** seeks to overcome the "clownshoe" problem (also called "internal
  38928. ** fragmentation" in academic literature) of allocating a few bytes more
  38929. ** than a power of two with the memory allocator rounding up to the next
  38930. ** power of two, and leaving the rounded-up space unused.
  38931. **
  38932. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  38933. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  38934. **
  38935. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  38936. ** The btree.c module deals with pointers to MemPage objects.
  38937. **
  38938. ** SOURCE OF PAGE CACHE MEMORY:
  38939. **
  38940. ** Memory for a page might come from any of three sources:
  38941. **
  38942. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  38943. ** (2) Global page-cache memory provided using sqlite3_config() with
  38944. ** SQLITE_CONFIG_PAGECACHE.
  38945. ** (3) PCache-local bulk allocation.
  38946. **
  38947. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  38948. ** that is allocated when the page cache is created. The size of the local
  38949. ** bulk allocation can be adjusted using
  38950. **
  38951. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  38952. **
  38953. ** If N is positive, then N pages worth of memory are allocated using a single
  38954. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  38955. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  38956. ** for as many pages as can be accomodated.
  38957. **
  38958. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  38959. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  38960. ** memory allocator (1).
  38961. **
  38962. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  38963. ** show that method (3) with N==100 provides about a 5% performance boost for
  38964. ** common workloads.
  38965. */
  38966. /* #include "sqliteInt.h" */
  38967. typedef struct PCache1 PCache1;
  38968. typedef struct PgHdr1 PgHdr1;
  38969. typedef struct PgFreeslot PgFreeslot;
  38970. typedef struct PGroup PGroup;
  38971. /*
  38972. ** Each cache entry is represented by an instance of the following
  38973. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  38974. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  38975. ** in memory.
  38976. */
  38977. struct PgHdr1 {
  38978. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  38979. unsigned int iKey; /* Key value (page number) */
  38980. u8 isPinned; /* Page in use, not on the LRU list */
  38981. u8 isBulkLocal; /* This page from bulk local storage */
  38982. u8 isAnchor; /* This is the PGroup.lru element */
  38983. PgHdr1 *pNext; /* Next in hash table chain */
  38984. PCache1 *pCache; /* Cache that currently owns this page */
  38985. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  38986. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  38987. };
  38988. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  38989. ** of one or more PCaches that are able to recycle each other's unpinned
  38990. ** pages when they are under memory pressure. A PGroup is an instance of
  38991. ** the following object.
  38992. **
  38993. ** This page cache implementation works in one of two modes:
  38994. **
  38995. ** (1) Every PCache is the sole member of its own PGroup. There is
  38996. ** one PGroup per PCache.
  38997. **
  38998. ** (2) There is a single global PGroup that all PCaches are a member
  38999. ** of.
  39000. **
  39001. ** Mode 1 uses more memory (since PCache instances are not able to rob
  39002. ** unused pages from other PCaches) but it also operates without a mutex,
  39003. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  39004. ** threadsafe, but recycles pages more efficiently.
  39005. **
  39006. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  39007. ** PGroup which is the pcache1.grp global variable and its mutex is
  39008. ** SQLITE_MUTEX_STATIC_LRU.
  39009. */
  39010. struct PGroup {
  39011. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  39012. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  39013. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  39014. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  39015. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  39016. PgHdr1 lru; /* The beginning and end of the LRU list */
  39017. };
  39018. /* Each page cache is an instance of the following object. Every
  39019. ** open database file (including each in-memory database and each
  39020. ** temporary or transient database) has a single page cache which
  39021. ** is an instance of this object.
  39022. **
  39023. ** Pointers to structures of this type are cast and returned as
  39024. ** opaque sqlite3_pcache* handles.
  39025. */
  39026. struct PCache1 {
  39027. /* Cache configuration parameters. Page size (szPage) and the purgeable
  39028. ** flag (bPurgeable) are set when the cache is created. nMax may be
  39029. ** modified at any time by a call to the pcache1Cachesize() method.
  39030. ** The PGroup mutex must be held when accessing nMax.
  39031. */
  39032. PGroup *pGroup; /* PGroup this cache belongs to */
  39033. int szPage; /* Size of database content section */
  39034. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  39035. int szAlloc; /* Total size of one pcache line */
  39036. int bPurgeable; /* True if cache is purgeable */
  39037. unsigned int nMin; /* Minimum number of pages reserved */
  39038. unsigned int nMax; /* Configured "cache_size" value */
  39039. unsigned int n90pct; /* nMax*9/10 */
  39040. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  39041. /* Hash table of all pages. The following variables may only be accessed
  39042. ** when the accessor is holding the PGroup mutex.
  39043. */
  39044. unsigned int nRecyclable; /* Number of pages in the LRU list */
  39045. unsigned int nPage; /* Total number of pages in apHash */
  39046. unsigned int nHash; /* Number of slots in apHash[] */
  39047. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  39048. PgHdr1 *pFree; /* List of unused pcache-local pages */
  39049. void *pBulk; /* Bulk memory used by pcache-local */
  39050. };
  39051. /*
  39052. ** Free slots in the allocator used to divide up the global page cache
  39053. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  39054. */
  39055. struct PgFreeslot {
  39056. PgFreeslot *pNext; /* Next free slot */
  39057. };
  39058. /*
  39059. ** Global data used by this cache.
  39060. */
  39061. static SQLITE_WSD struct PCacheGlobal {
  39062. PGroup grp; /* The global PGroup for mode (2) */
  39063. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  39064. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  39065. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  39066. ** The nFreeSlot and pFree values do require mutex protection.
  39067. */
  39068. int isInit; /* True if initialized */
  39069. int separateCache; /* Use a new PGroup for each PCache */
  39070. int nInitPage; /* Initial bulk allocation size */
  39071. int szSlot; /* Size of each free slot */
  39072. int nSlot; /* The number of pcache slots */
  39073. int nReserve; /* Try to keep nFreeSlot above this */
  39074. void *pStart, *pEnd; /* Bounds of global page cache memory */
  39075. /* Above requires no mutex. Use mutex below for variable that follow. */
  39076. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  39077. PgFreeslot *pFree; /* Free page blocks */
  39078. int nFreeSlot; /* Number of unused pcache slots */
  39079. /* The following value requires a mutex to change. We skip the mutex on
  39080. ** reading because (1) most platforms read a 32-bit integer atomically and
  39081. ** (2) even if an incorrect value is read, no great harm is done since this
  39082. ** is really just an optimization. */
  39083. int bUnderPressure; /* True if low on PAGECACHE memory */
  39084. } pcache1_g;
  39085. /*
  39086. ** All code in this file should access the global structure above via the
  39087. ** alias "pcache1". This ensures that the WSD emulation is used when
  39088. ** compiling for systems that do not support real WSD.
  39089. */
  39090. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  39091. /*
  39092. ** Macros to enter and leave the PCache LRU mutex.
  39093. */
  39094. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  39095. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  39096. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  39097. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  39098. #else
  39099. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  39100. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  39101. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  39102. #endif
  39103. /******************************************************************************/
  39104. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  39105. /*
  39106. ** This function is called during initialization if a static buffer is
  39107. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  39108. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  39109. ** enough to contain 'n' buffers of 'sz' bytes each.
  39110. **
  39111. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  39112. ** to be serialized already. There is no need for further mutexing.
  39113. */
  39114. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  39115. if( pcache1.isInit ){
  39116. PgFreeslot *p;
  39117. if( pBuf==0 ) sz = n = 0;
  39118. sz = ROUNDDOWN8(sz);
  39119. pcache1.szSlot = sz;
  39120. pcache1.nSlot = pcache1.nFreeSlot = n;
  39121. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  39122. pcache1.pStart = pBuf;
  39123. pcache1.pFree = 0;
  39124. pcache1.bUnderPressure = 0;
  39125. while( n-- ){
  39126. p = (PgFreeslot*)pBuf;
  39127. p->pNext = pcache1.pFree;
  39128. pcache1.pFree = p;
  39129. pBuf = (void*)&((char*)pBuf)[sz];
  39130. }
  39131. pcache1.pEnd = pBuf;
  39132. }
  39133. }
  39134. /*
  39135. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  39136. ** true if pCache->pFree ends up containing one or more free pages.
  39137. */
  39138. static int pcache1InitBulk(PCache1 *pCache){
  39139. i64 szBulk;
  39140. char *zBulk;
  39141. if( pcache1.nInitPage==0 ) return 0;
  39142. /* Do not bother with a bulk allocation if the cache size very small */
  39143. if( pCache->nMax<3 ) return 0;
  39144. sqlite3BeginBenignMalloc();
  39145. if( pcache1.nInitPage>0 ){
  39146. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  39147. }else{
  39148. szBulk = -1024 * (i64)pcache1.nInitPage;
  39149. }
  39150. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  39151. szBulk = pCache->szAlloc*pCache->nMax;
  39152. }
  39153. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  39154. sqlite3EndBenignMalloc();
  39155. if( zBulk ){
  39156. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  39157. int i;
  39158. for(i=0; i<nBulk; i++){
  39159. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  39160. pX->page.pBuf = zBulk;
  39161. pX->page.pExtra = &pX[1];
  39162. pX->isBulkLocal = 1;
  39163. pX->isAnchor = 0;
  39164. pX->pNext = pCache->pFree;
  39165. pCache->pFree = pX;
  39166. zBulk += pCache->szAlloc;
  39167. }
  39168. }
  39169. return pCache->pFree!=0;
  39170. }
  39171. /*
  39172. ** Malloc function used within this file to allocate space from the buffer
  39173. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  39174. ** such buffer exists or there is no space left in it, this function falls
  39175. ** back to sqlite3Malloc().
  39176. **
  39177. ** Multiple threads can run this routine at the same time. Global variables
  39178. ** in pcache1 need to be protected via mutex.
  39179. */
  39180. static void *pcache1Alloc(int nByte){
  39181. void *p = 0;
  39182. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  39183. if( nByte<=pcache1.szSlot ){
  39184. sqlite3_mutex_enter(pcache1.mutex);
  39185. p = (PgHdr1 *)pcache1.pFree;
  39186. if( p ){
  39187. pcache1.pFree = pcache1.pFree->pNext;
  39188. pcache1.nFreeSlot--;
  39189. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  39190. assert( pcache1.nFreeSlot>=0 );
  39191. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  39192. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  39193. }
  39194. sqlite3_mutex_leave(pcache1.mutex);
  39195. }
  39196. if( p==0 ){
  39197. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  39198. ** it from sqlite3Malloc instead.
  39199. */
  39200. p = sqlite3Malloc(nByte);
  39201. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  39202. if( p ){
  39203. int sz = sqlite3MallocSize(p);
  39204. sqlite3_mutex_enter(pcache1.mutex);
  39205. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  39206. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  39207. sqlite3_mutex_leave(pcache1.mutex);
  39208. }
  39209. #endif
  39210. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  39211. }
  39212. return p;
  39213. }
  39214. /*
  39215. ** Free an allocated buffer obtained from pcache1Alloc().
  39216. */
  39217. static void pcache1Free(void *p){
  39218. int nFreed = 0;
  39219. if( p==0 ) return;
  39220. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  39221. PgFreeslot *pSlot;
  39222. sqlite3_mutex_enter(pcache1.mutex);
  39223. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  39224. pSlot = (PgFreeslot*)p;
  39225. pSlot->pNext = pcache1.pFree;
  39226. pcache1.pFree = pSlot;
  39227. pcache1.nFreeSlot++;
  39228. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  39229. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  39230. sqlite3_mutex_leave(pcache1.mutex);
  39231. }else{
  39232. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  39233. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  39234. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  39235. nFreed = sqlite3MallocSize(p);
  39236. sqlite3_mutex_enter(pcache1.mutex);
  39237. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  39238. sqlite3_mutex_leave(pcache1.mutex);
  39239. #endif
  39240. sqlite3_free(p);
  39241. }
  39242. }
  39243. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  39244. /*
  39245. ** Return the size of a pcache allocation
  39246. */
  39247. static int pcache1MemSize(void *p){
  39248. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  39249. return pcache1.szSlot;
  39250. }else{
  39251. int iSize;
  39252. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  39253. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  39254. iSize = sqlite3MallocSize(p);
  39255. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  39256. return iSize;
  39257. }
  39258. }
  39259. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  39260. /*
  39261. ** Allocate a new page object initially associated with cache pCache.
  39262. */
  39263. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  39264. PgHdr1 *p = 0;
  39265. void *pPg;
  39266. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39267. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  39268. p = pCache->pFree;
  39269. pCache->pFree = p->pNext;
  39270. p->pNext = 0;
  39271. }else{
  39272. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  39273. /* The group mutex must be released before pcache1Alloc() is called. This
  39274. ** is because it might call sqlite3_release_memory(), which assumes that
  39275. ** this mutex is not held. */
  39276. assert( pcache1.separateCache==0 );
  39277. assert( pCache->pGroup==&pcache1.grp );
  39278. pcache1LeaveMutex(pCache->pGroup);
  39279. #endif
  39280. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  39281. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  39282. pPg = pcache1Alloc(pCache->szPage);
  39283. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  39284. if( !pPg || !p ){
  39285. pcache1Free(pPg);
  39286. sqlite3_free(p);
  39287. pPg = 0;
  39288. }
  39289. #else
  39290. pPg = pcache1Alloc(pCache->szAlloc);
  39291. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  39292. #endif
  39293. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  39294. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  39295. pcache1EnterMutex(pCache->pGroup);
  39296. #endif
  39297. if( pPg==0 ) return 0;
  39298. p->page.pBuf = pPg;
  39299. p->page.pExtra = &p[1];
  39300. p->isBulkLocal = 0;
  39301. p->isAnchor = 0;
  39302. }
  39303. if( pCache->bPurgeable ){
  39304. pCache->pGroup->nCurrentPage++;
  39305. }
  39306. return p;
  39307. }
  39308. /*
  39309. ** Free a page object allocated by pcache1AllocPage().
  39310. */
  39311. static void pcache1FreePage(PgHdr1 *p){
  39312. PCache1 *pCache;
  39313. assert( p!=0 );
  39314. pCache = p->pCache;
  39315. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  39316. if( p->isBulkLocal ){
  39317. p->pNext = pCache->pFree;
  39318. pCache->pFree = p;
  39319. }else{
  39320. pcache1Free(p->page.pBuf);
  39321. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  39322. sqlite3_free(p);
  39323. #endif
  39324. }
  39325. if( pCache->bPurgeable ){
  39326. pCache->pGroup->nCurrentPage--;
  39327. }
  39328. }
  39329. /*
  39330. ** Malloc function used by SQLite to obtain space from the buffer configured
  39331. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  39332. ** exists, this function falls back to sqlite3Malloc().
  39333. */
  39334. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  39335. return pcache1Alloc(sz);
  39336. }
  39337. /*
  39338. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  39339. */
  39340. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  39341. pcache1Free(p);
  39342. }
  39343. /*
  39344. ** Return true if it desirable to avoid allocating a new page cache
  39345. ** entry.
  39346. **
  39347. ** If memory was allocated specifically to the page cache using
  39348. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  39349. ** it is desirable to avoid allocating a new page cache entry because
  39350. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  39351. ** for all page cache needs and we should not need to spill the
  39352. ** allocation onto the heap.
  39353. **
  39354. ** Or, the heap is used for all page cache memory but the heap is
  39355. ** under memory pressure, then again it is desirable to avoid
  39356. ** allocating a new page cache entry in order to avoid stressing
  39357. ** the heap even further.
  39358. */
  39359. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  39360. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  39361. return pcache1.bUnderPressure;
  39362. }else{
  39363. return sqlite3HeapNearlyFull();
  39364. }
  39365. }
  39366. /******************************************************************************/
  39367. /******** General Implementation Functions ************************************/
  39368. /*
  39369. ** This function is used to resize the hash table used by the cache passed
  39370. ** as the first argument.
  39371. **
  39372. ** The PCache mutex must be held when this function is called.
  39373. */
  39374. static void pcache1ResizeHash(PCache1 *p){
  39375. PgHdr1 **apNew;
  39376. unsigned int nNew;
  39377. unsigned int i;
  39378. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  39379. nNew = p->nHash*2;
  39380. if( nNew<256 ){
  39381. nNew = 256;
  39382. }
  39383. pcache1LeaveMutex(p->pGroup);
  39384. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  39385. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  39386. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  39387. pcache1EnterMutex(p->pGroup);
  39388. if( apNew ){
  39389. for(i=0; i<p->nHash; i++){
  39390. PgHdr1 *pPage;
  39391. PgHdr1 *pNext = p->apHash[i];
  39392. while( (pPage = pNext)!=0 ){
  39393. unsigned int h = pPage->iKey % nNew;
  39394. pNext = pPage->pNext;
  39395. pPage->pNext = apNew[h];
  39396. apNew[h] = pPage;
  39397. }
  39398. }
  39399. sqlite3_free(p->apHash);
  39400. p->apHash = apNew;
  39401. p->nHash = nNew;
  39402. }
  39403. }
  39404. /*
  39405. ** This function is used internally to remove the page pPage from the
  39406. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  39407. ** LRU list, then this function is a no-op.
  39408. **
  39409. ** The PGroup mutex must be held when this function is called.
  39410. */
  39411. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  39412. PCache1 *pCache;
  39413. assert( pPage!=0 );
  39414. assert( pPage->isPinned==0 );
  39415. pCache = pPage->pCache;
  39416. assert( pPage->pLruNext );
  39417. assert( pPage->pLruPrev );
  39418. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39419. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  39420. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  39421. pPage->pLruNext = 0;
  39422. pPage->pLruPrev = 0;
  39423. pPage->isPinned = 1;
  39424. assert( pPage->isAnchor==0 );
  39425. assert( pCache->pGroup->lru.isAnchor==1 );
  39426. pCache->nRecyclable--;
  39427. return pPage;
  39428. }
  39429. /*
  39430. ** Remove the page supplied as an argument from the hash table
  39431. ** (PCache1.apHash structure) that it is currently stored in.
  39432. ** Also free the page if freePage is true.
  39433. **
  39434. ** The PGroup mutex must be held when this function is called.
  39435. */
  39436. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  39437. unsigned int h;
  39438. PCache1 *pCache = pPage->pCache;
  39439. PgHdr1 **pp;
  39440. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39441. h = pPage->iKey % pCache->nHash;
  39442. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  39443. *pp = (*pp)->pNext;
  39444. pCache->nPage--;
  39445. if( freeFlag ) pcache1FreePage(pPage);
  39446. }
  39447. /*
  39448. ** If there are currently more than nMaxPage pages allocated, try
  39449. ** to recycle pages to reduce the number allocated to nMaxPage.
  39450. */
  39451. static void pcache1EnforceMaxPage(PCache1 *pCache){
  39452. PGroup *pGroup = pCache->pGroup;
  39453. PgHdr1 *p;
  39454. assert( sqlite3_mutex_held(pGroup->mutex) );
  39455. while( pGroup->nCurrentPage>pGroup->nMaxPage
  39456. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  39457. ){
  39458. assert( p->pCache->pGroup==pGroup );
  39459. assert( p->isPinned==0 );
  39460. pcache1PinPage(p);
  39461. pcache1RemoveFromHash(p, 1);
  39462. }
  39463. if( pCache->nPage==0 && pCache->pBulk ){
  39464. sqlite3_free(pCache->pBulk);
  39465. pCache->pBulk = pCache->pFree = 0;
  39466. }
  39467. }
  39468. /*
  39469. ** Discard all pages from cache pCache with a page number (key value)
  39470. ** greater than or equal to iLimit. Any pinned pages that meet this
  39471. ** criteria are unpinned before they are discarded.
  39472. **
  39473. ** The PCache mutex must be held when this function is called.
  39474. */
  39475. static void pcache1TruncateUnsafe(
  39476. PCache1 *pCache, /* The cache to truncate */
  39477. unsigned int iLimit /* Drop pages with this pgno or larger */
  39478. ){
  39479. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  39480. unsigned int h;
  39481. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  39482. for(h=0; h<pCache->nHash; h++){
  39483. PgHdr1 **pp = &pCache->apHash[h];
  39484. PgHdr1 *pPage;
  39485. while( (pPage = *pp)!=0 ){
  39486. if( pPage->iKey>=iLimit ){
  39487. pCache->nPage--;
  39488. *pp = pPage->pNext;
  39489. if( !pPage->isPinned ) pcache1PinPage(pPage);
  39490. pcache1FreePage(pPage);
  39491. }else{
  39492. pp = &pPage->pNext;
  39493. TESTONLY( nPage++; )
  39494. }
  39495. }
  39496. }
  39497. assert( pCache->nPage==nPage );
  39498. }
  39499. /******************************************************************************/
  39500. /******** sqlite3_pcache Methods **********************************************/
  39501. /*
  39502. ** Implementation of the sqlite3_pcache.xInit method.
  39503. */
  39504. static int pcache1Init(void *NotUsed){
  39505. UNUSED_PARAMETER(NotUsed);
  39506. assert( pcache1.isInit==0 );
  39507. memset(&pcache1, 0, sizeof(pcache1));
  39508. /*
  39509. ** The pcache1.separateCache variable is true if each PCache has its own
  39510. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  39511. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  39512. **
  39513. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  39514. **
  39515. ** * Use a unified cache in single-threaded applications that have
  39516. ** configured a start-time buffer for use as page-cache memory using
  39517. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  39518. ** pBuf argument.
  39519. **
  39520. ** * Otherwise use separate caches (mode-1)
  39521. */
  39522. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  39523. pcache1.separateCache = 0;
  39524. #elif SQLITE_THREADSAFE
  39525. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  39526. || sqlite3GlobalConfig.bCoreMutex>0;
  39527. #else
  39528. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  39529. #endif
  39530. #if SQLITE_THREADSAFE
  39531. if( sqlite3GlobalConfig.bCoreMutex ){
  39532. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  39533. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  39534. }
  39535. #endif
  39536. if( pcache1.separateCache
  39537. && sqlite3GlobalConfig.nPage!=0
  39538. && sqlite3GlobalConfig.pPage==0
  39539. ){
  39540. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  39541. }else{
  39542. pcache1.nInitPage = 0;
  39543. }
  39544. pcache1.grp.mxPinned = 10;
  39545. pcache1.isInit = 1;
  39546. return SQLITE_OK;
  39547. }
  39548. /*
  39549. ** Implementation of the sqlite3_pcache.xShutdown method.
  39550. ** Note that the static mutex allocated in xInit does
  39551. ** not need to be freed.
  39552. */
  39553. static void pcache1Shutdown(void *NotUsed){
  39554. UNUSED_PARAMETER(NotUsed);
  39555. assert( pcache1.isInit!=0 );
  39556. memset(&pcache1, 0, sizeof(pcache1));
  39557. }
  39558. /* forward declaration */
  39559. static void pcache1Destroy(sqlite3_pcache *p);
  39560. /*
  39561. ** Implementation of the sqlite3_pcache.xCreate method.
  39562. **
  39563. ** Allocate a new cache.
  39564. */
  39565. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  39566. PCache1 *pCache; /* The newly created page cache */
  39567. PGroup *pGroup; /* The group the new page cache will belong to */
  39568. int sz; /* Bytes of memory required to allocate the new cache */
  39569. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  39570. assert( szExtra < 300 );
  39571. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  39572. pCache = (PCache1 *)sqlite3MallocZero(sz);
  39573. if( pCache ){
  39574. if( pcache1.separateCache ){
  39575. pGroup = (PGroup*)&pCache[1];
  39576. pGroup->mxPinned = 10;
  39577. }else{
  39578. pGroup = &pcache1.grp;
  39579. }
  39580. if( pGroup->lru.isAnchor==0 ){
  39581. pGroup->lru.isAnchor = 1;
  39582. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  39583. }
  39584. pCache->pGroup = pGroup;
  39585. pCache->szPage = szPage;
  39586. pCache->szExtra = szExtra;
  39587. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  39588. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  39589. pcache1EnterMutex(pGroup);
  39590. pcache1ResizeHash(pCache);
  39591. if( bPurgeable ){
  39592. pCache->nMin = 10;
  39593. pGroup->nMinPage += pCache->nMin;
  39594. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  39595. }
  39596. pcache1LeaveMutex(pGroup);
  39597. if( pCache->nHash==0 ){
  39598. pcache1Destroy((sqlite3_pcache*)pCache);
  39599. pCache = 0;
  39600. }
  39601. }
  39602. return (sqlite3_pcache *)pCache;
  39603. }
  39604. /*
  39605. ** Implementation of the sqlite3_pcache.xCachesize method.
  39606. **
  39607. ** Configure the cache_size limit for a cache.
  39608. */
  39609. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  39610. PCache1 *pCache = (PCache1 *)p;
  39611. if( pCache->bPurgeable ){
  39612. PGroup *pGroup = pCache->pGroup;
  39613. pcache1EnterMutex(pGroup);
  39614. pGroup->nMaxPage += (nMax - pCache->nMax);
  39615. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  39616. pCache->nMax = nMax;
  39617. pCache->n90pct = pCache->nMax*9/10;
  39618. pcache1EnforceMaxPage(pCache);
  39619. pcache1LeaveMutex(pGroup);
  39620. }
  39621. }
  39622. /*
  39623. ** Implementation of the sqlite3_pcache.xShrink method.
  39624. **
  39625. ** Free up as much memory as possible.
  39626. */
  39627. static void pcache1Shrink(sqlite3_pcache *p){
  39628. PCache1 *pCache = (PCache1*)p;
  39629. if( pCache->bPurgeable ){
  39630. PGroup *pGroup = pCache->pGroup;
  39631. int savedMaxPage;
  39632. pcache1EnterMutex(pGroup);
  39633. savedMaxPage = pGroup->nMaxPage;
  39634. pGroup->nMaxPage = 0;
  39635. pcache1EnforceMaxPage(pCache);
  39636. pGroup->nMaxPage = savedMaxPage;
  39637. pcache1LeaveMutex(pGroup);
  39638. }
  39639. }
  39640. /*
  39641. ** Implementation of the sqlite3_pcache.xPagecount method.
  39642. */
  39643. static int pcache1Pagecount(sqlite3_pcache *p){
  39644. int n;
  39645. PCache1 *pCache = (PCache1*)p;
  39646. pcache1EnterMutex(pCache->pGroup);
  39647. n = pCache->nPage;
  39648. pcache1LeaveMutex(pCache->pGroup);
  39649. return n;
  39650. }
  39651. /*
  39652. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  39653. ** in the header of the pcache1Fetch() procedure.
  39654. **
  39655. ** This steps are broken out into a separate procedure because they are
  39656. ** usually not needed, and by avoiding the stack initialization required
  39657. ** for these steps, the main pcache1Fetch() procedure can run faster.
  39658. */
  39659. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  39660. PCache1 *pCache,
  39661. unsigned int iKey,
  39662. int createFlag
  39663. ){
  39664. unsigned int nPinned;
  39665. PGroup *pGroup = pCache->pGroup;
  39666. PgHdr1 *pPage = 0;
  39667. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  39668. assert( pCache->nPage >= pCache->nRecyclable );
  39669. nPinned = pCache->nPage - pCache->nRecyclable;
  39670. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  39671. assert( pCache->n90pct == pCache->nMax*9/10 );
  39672. if( createFlag==1 && (
  39673. nPinned>=pGroup->mxPinned
  39674. || nPinned>=pCache->n90pct
  39675. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  39676. )){
  39677. return 0;
  39678. }
  39679. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  39680. assert( pCache->nHash>0 && pCache->apHash );
  39681. /* Step 4. Try to recycle a page. */
  39682. if( pCache->bPurgeable
  39683. && !pGroup->lru.pLruPrev->isAnchor
  39684. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  39685. ){
  39686. PCache1 *pOther;
  39687. pPage = pGroup->lru.pLruPrev;
  39688. assert( pPage->isPinned==0 );
  39689. pcache1RemoveFromHash(pPage, 0);
  39690. pcache1PinPage(pPage);
  39691. pOther = pPage->pCache;
  39692. if( pOther->szAlloc != pCache->szAlloc ){
  39693. pcache1FreePage(pPage);
  39694. pPage = 0;
  39695. }else{
  39696. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  39697. }
  39698. }
  39699. /* Step 5. If a usable page buffer has still not been found,
  39700. ** attempt to allocate a new one.
  39701. */
  39702. if( !pPage ){
  39703. pPage = pcache1AllocPage(pCache, createFlag==1);
  39704. }
  39705. if( pPage ){
  39706. unsigned int h = iKey % pCache->nHash;
  39707. pCache->nPage++;
  39708. pPage->iKey = iKey;
  39709. pPage->pNext = pCache->apHash[h];
  39710. pPage->pCache = pCache;
  39711. pPage->pLruPrev = 0;
  39712. pPage->pLruNext = 0;
  39713. pPage->isPinned = 1;
  39714. *(void **)pPage->page.pExtra = 0;
  39715. pCache->apHash[h] = pPage;
  39716. if( iKey>pCache->iMaxKey ){
  39717. pCache->iMaxKey = iKey;
  39718. }
  39719. }
  39720. return pPage;
  39721. }
  39722. /*
  39723. ** Implementation of the sqlite3_pcache.xFetch method.
  39724. **
  39725. ** Fetch a page by key value.
  39726. **
  39727. ** Whether or not a new page may be allocated by this function depends on
  39728. ** the value of the createFlag argument. 0 means do not allocate a new
  39729. ** page. 1 means allocate a new page if space is easily available. 2
  39730. ** means to try really hard to allocate a new page.
  39731. **
  39732. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  39733. ** database) there is really no difference between createFlag 1 and 2. So
  39734. ** the calling function (pcache.c) will never have a createFlag of 1 on
  39735. ** a non-purgeable cache.
  39736. **
  39737. ** There are three different approaches to obtaining space for a page,
  39738. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  39739. **
  39740. ** 1. Regardless of the value of createFlag, the cache is searched for a
  39741. ** copy of the requested page. If one is found, it is returned.
  39742. **
  39743. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  39744. ** returned.
  39745. **
  39746. ** 3. If createFlag is 1, and the page is not already in the cache, then
  39747. ** return NULL (do not allocate a new page) if any of the following
  39748. ** conditions are true:
  39749. **
  39750. ** (a) the number of pages pinned by the cache is greater than
  39751. ** PCache1.nMax, or
  39752. **
  39753. ** (b) the number of pages pinned by the cache is greater than
  39754. ** the sum of nMax for all purgeable caches, less the sum of
  39755. ** nMin for all other purgeable caches, or
  39756. **
  39757. ** 4. If none of the first three conditions apply and the cache is marked
  39758. ** as purgeable, and if one of the following is true:
  39759. **
  39760. ** (a) The number of pages allocated for the cache is already
  39761. ** PCache1.nMax, or
  39762. **
  39763. ** (b) The number of pages allocated for all purgeable caches is
  39764. ** already equal to or greater than the sum of nMax for all
  39765. ** purgeable caches,
  39766. **
  39767. ** (c) The system is under memory pressure and wants to avoid
  39768. ** unnecessary pages cache entry allocations
  39769. **
  39770. ** then attempt to recycle a page from the LRU list. If it is the right
  39771. ** size, return the recycled buffer. Otherwise, free the buffer and
  39772. ** proceed to step 5.
  39773. **
  39774. ** 5. Otherwise, allocate and return a new page buffer.
  39775. **
  39776. ** There are two versions of this routine. pcache1FetchWithMutex() is
  39777. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  39778. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  39779. ** invokes the appropriate routine.
  39780. */
  39781. static PgHdr1 *pcache1FetchNoMutex(
  39782. sqlite3_pcache *p,
  39783. unsigned int iKey,
  39784. int createFlag
  39785. ){
  39786. PCache1 *pCache = (PCache1 *)p;
  39787. PgHdr1 *pPage = 0;
  39788. /* Step 1: Search the hash table for an existing entry. */
  39789. pPage = pCache->apHash[iKey % pCache->nHash];
  39790. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  39791. /* Step 2: If the page was found in the hash table, then return it.
  39792. ** If the page was not in the hash table and createFlag is 0, abort.
  39793. ** Otherwise (page not in hash and createFlag!=0) continue with
  39794. ** subsequent steps to try to create the page. */
  39795. if( pPage ){
  39796. if( !pPage->isPinned ){
  39797. return pcache1PinPage(pPage);
  39798. }else{
  39799. return pPage;
  39800. }
  39801. }else if( createFlag ){
  39802. /* Steps 3, 4, and 5 implemented by this subroutine */
  39803. return pcache1FetchStage2(pCache, iKey, createFlag);
  39804. }else{
  39805. return 0;
  39806. }
  39807. }
  39808. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  39809. static PgHdr1 *pcache1FetchWithMutex(
  39810. sqlite3_pcache *p,
  39811. unsigned int iKey,
  39812. int createFlag
  39813. ){
  39814. PCache1 *pCache = (PCache1 *)p;
  39815. PgHdr1 *pPage;
  39816. pcache1EnterMutex(pCache->pGroup);
  39817. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  39818. assert( pPage==0 || pCache->iMaxKey>=iKey );
  39819. pcache1LeaveMutex(pCache->pGroup);
  39820. return pPage;
  39821. }
  39822. #endif
  39823. static sqlite3_pcache_page *pcache1Fetch(
  39824. sqlite3_pcache *p,
  39825. unsigned int iKey,
  39826. int createFlag
  39827. ){
  39828. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  39829. PCache1 *pCache = (PCache1 *)p;
  39830. #endif
  39831. assert( offsetof(PgHdr1,page)==0 );
  39832. assert( pCache->bPurgeable || createFlag!=1 );
  39833. assert( pCache->bPurgeable || pCache->nMin==0 );
  39834. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  39835. assert( pCache->nMin==0 || pCache->bPurgeable );
  39836. assert( pCache->nHash>0 );
  39837. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  39838. if( pCache->pGroup->mutex ){
  39839. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  39840. }else
  39841. #endif
  39842. {
  39843. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  39844. }
  39845. }
  39846. /*
  39847. ** Implementation of the sqlite3_pcache.xUnpin method.
  39848. **
  39849. ** Mark a page as unpinned (eligible for asynchronous recycling).
  39850. */
  39851. static void pcache1Unpin(
  39852. sqlite3_pcache *p,
  39853. sqlite3_pcache_page *pPg,
  39854. int reuseUnlikely
  39855. ){
  39856. PCache1 *pCache = (PCache1 *)p;
  39857. PgHdr1 *pPage = (PgHdr1 *)pPg;
  39858. PGroup *pGroup = pCache->pGroup;
  39859. assert( pPage->pCache==pCache );
  39860. pcache1EnterMutex(pGroup);
  39861. /* It is an error to call this function if the page is already
  39862. ** part of the PGroup LRU list.
  39863. */
  39864. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  39865. assert( pPage->isPinned==1 );
  39866. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  39867. pcache1RemoveFromHash(pPage, 1);
  39868. }else{
  39869. /* Add the page to the PGroup LRU list. */
  39870. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  39871. pPage->pLruPrev = &pGroup->lru;
  39872. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  39873. *ppFirst = pPage;
  39874. pCache->nRecyclable++;
  39875. pPage->isPinned = 0;
  39876. }
  39877. pcache1LeaveMutex(pCache->pGroup);
  39878. }
  39879. /*
  39880. ** Implementation of the sqlite3_pcache.xRekey method.
  39881. */
  39882. static void pcache1Rekey(
  39883. sqlite3_pcache *p,
  39884. sqlite3_pcache_page *pPg,
  39885. unsigned int iOld,
  39886. unsigned int iNew
  39887. ){
  39888. PCache1 *pCache = (PCache1 *)p;
  39889. PgHdr1 *pPage = (PgHdr1 *)pPg;
  39890. PgHdr1 **pp;
  39891. unsigned int h;
  39892. assert( pPage->iKey==iOld );
  39893. assert( pPage->pCache==pCache );
  39894. pcache1EnterMutex(pCache->pGroup);
  39895. h = iOld%pCache->nHash;
  39896. pp = &pCache->apHash[h];
  39897. while( (*pp)!=pPage ){
  39898. pp = &(*pp)->pNext;
  39899. }
  39900. *pp = pPage->pNext;
  39901. h = iNew%pCache->nHash;
  39902. pPage->iKey = iNew;
  39903. pPage->pNext = pCache->apHash[h];
  39904. pCache->apHash[h] = pPage;
  39905. if( iNew>pCache->iMaxKey ){
  39906. pCache->iMaxKey = iNew;
  39907. }
  39908. pcache1LeaveMutex(pCache->pGroup);
  39909. }
  39910. /*
  39911. ** Implementation of the sqlite3_pcache.xTruncate method.
  39912. **
  39913. ** Discard all unpinned pages in the cache with a page number equal to
  39914. ** or greater than parameter iLimit. Any pinned pages with a page number
  39915. ** equal to or greater than iLimit are implicitly unpinned.
  39916. */
  39917. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  39918. PCache1 *pCache = (PCache1 *)p;
  39919. pcache1EnterMutex(pCache->pGroup);
  39920. if( iLimit<=pCache->iMaxKey ){
  39921. pcache1TruncateUnsafe(pCache, iLimit);
  39922. pCache->iMaxKey = iLimit-1;
  39923. }
  39924. pcache1LeaveMutex(pCache->pGroup);
  39925. }
  39926. /*
  39927. ** Implementation of the sqlite3_pcache.xDestroy method.
  39928. **
  39929. ** Destroy a cache allocated using pcache1Create().
  39930. */
  39931. static void pcache1Destroy(sqlite3_pcache *p){
  39932. PCache1 *pCache = (PCache1 *)p;
  39933. PGroup *pGroup = pCache->pGroup;
  39934. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  39935. pcache1EnterMutex(pGroup);
  39936. pcache1TruncateUnsafe(pCache, 0);
  39937. assert( pGroup->nMaxPage >= pCache->nMax );
  39938. pGroup->nMaxPage -= pCache->nMax;
  39939. assert( pGroup->nMinPage >= pCache->nMin );
  39940. pGroup->nMinPage -= pCache->nMin;
  39941. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  39942. pcache1EnforceMaxPage(pCache);
  39943. pcache1LeaveMutex(pGroup);
  39944. sqlite3_free(pCache->pBulk);
  39945. sqlite3_free(pCache->apHash);
  39946. sqlite3_free(pCache);
  39947. }
  39948. /*
  39949. ** This function is called during initialization (sqlite3_initialize()) to
  39950. ** install the default pluggable cache module, assuming the user has not
  39951. ** already provided an alternative.
  39952. */
  39953. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  39954. static const sqlite3_pcache_methods2 defaultMethods = {
  39955. 1, /* iVersion */
  39956. 0, /* pArg */
  39957. pcache1Init, /* xInit */
  39958. pcache1Shutdown, /* xShutdown */
  39959. pcache1Create, /* xCreate */
  39960. pcache1Cachesize, /* xCachesize */
  39961. pcache1Pagecount, /* xPagecount */
  39962. pcache1Fetch, /* xFetch */
  39963. pcache1Unpin, /* xUnpin */
  39964. pcache1Rekey, /* xRekey */
  39965. pcache1Truncate, /* xTruncate */
  39966. pcache1Destroy, /* xDestroy */
  39967. pcache1Shrink /* xShrink */
  39968. };
  39969. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  39970. }
  39971. /*
  39972. ** Return the size of the header on each page of this PCACHE implementation.
  39973. */
  39974. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  39975. /*
  39976. ** Return the global mutex used by this PCACHE implementation. The
  39977. ** sqlite3_status() routine needs access to this mutex.
  39978. */
  39979. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  39980. return pcache1.mutex;
  39981. }
  39982. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  39983. /*
  39984. ** This function is called to free superfluous dynamically allocated memory
  39985. ** held by the pager system. Memory in use by any SQLite pager allocated
  39986. ** by the current thread may be sqlite3_free()ed.
  39987. **
  39988. ** nReq is the number of bytes of memory required. Once this much has
  39989. ** been released, the function returns. The return value is the total number
  39990. ** of bytes of memory released.
  39991. */
  39992. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  39993. int nFree = 0;
  39994. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  39995. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  39996. if( sqlite3GlobalConfig.nPage==0 ){
  39997. PgHdr1 *p;
  39998. pcache1EnterMutex(&pcache1.grp);
  39999. while( (nReq<0 || nFree<nReq)
  40000. && (p=pcache1.grp.lru.pLruPrev)!=0
  40001. && p->isAnchor==0
  40002. ){
  40003. nFree += pcache1MemSize(p->page.pBuf);
  40004. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  40005. nFree += sqlite3MemSize(p);
  40006. #endif
  40007. assert( p->isPinned==0 );
  40008. pcache1PinPage(p);
  40009. pcache1RemoveFromHash(p, 1);
  40010. }
  40011. pcache1LeaveMutex(&pcache1.grp);
  40012. }
  40013. return nFree;
  40014. }
  40015. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  40016. #ifdef SQLITE_TEST
  40017. /*
  40018. ** This function is used by test procedures to inspect the internal state
  40019. ** of the global cache.
  40020. */
  40021. SQLITE_PRIVATE void sqlite3PcacheStats(
  40022. int *pnCurrent, /* OUT: Total number of pages cached */
  40023. int *pnMax, /* OUT: Global maximum cache size */
  40024. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  40025. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  40026. ){
  40027. PgHdr1 *p;
  40028. int nRecyclable = 0;
  40029. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  40030. assert( p->isPinned==0 );
  40031. nRecyclable++;
  40032. }
  40033. *pnCurrent = pcache1.grp.nCurrentPage;
  40034. *pnMax = (int)pcache1.grp.nMaxPage;
  40035. *pnMin = (int)pcache1.grp.nMinPage;
  40036. *pnRecyclable = nRecyclable;
  40037. }
  40038. #endif
  40039. /************** End of pcache1.c *********************************************/
  40040. /************** Begin file rowset.c ******************************************/
  40041. /*
  40042. ** 2008 December 3
  40043. **
  40044. ** The author disclaims copyright to this source code. In place of
  40045. ** a legal notice, here is a blessing:
  40046. **
  40047. ** May you do good and not evil.
  40048. ** May you find forgiveness for yourself and forgive others.
  40049. ** May you share freely, never taking more than you give.
  40050. **
  40051. *************************************************************************
  40052. **
  40053. ** This module implements an object we call a "RowSet".
  40054. **
  40055. ** The RowSet object is a collection of rowids. Rowids
  40056. ** are inserted into the RowSet in an arbitrary order. Inserts
  40057. ** can be intermixed with tests to see if a given rowid has been
  40058. ** previously inserted into the RowSet.
  40059. **
  40060. ** After all inserts are finished, it is possible to extract the
  40061. ** elements of the RowSet in sorted order. Once this extraction
  40062. ** process has started, no new elements may be inserted.
  40063. **
  40064. ** Hence, the primitive operations for a RowSet are:
  40065. **
  40066. ** CREATE
  40067. ** INSERT
  40068. ** TEST
  40069. ** SMALLEST
  40070. ** DESTROY
  40071. **
  40072. ** The CREATE and DESTROY primitives are the constructor and destructor,
  40073. ** obviously. The INSERT primitive adds a new element to the RowSet.
  40074. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  40075. ** extracts the least value from the RowSet.
  40076. **
  40077. ** The INSERT primitive might allocate additional memory. Memory is
  40078. ** allocated in chunks so most INSERTs do no allocation. There is an
  40079. ** upper bound on the size of allocated memory. No memory is freed
  40080. ** until DESTROY.
  40081. **
  40082. ** The TEST primitive includes a "batch" number. The TEST primitive
  40083. ** will only see elements that were inserted before the last change
  40084. ** in the batch number. In other words, if an INSERT occurs between
  40085. ** two TESTs where the TESTs have the same batch nubmer, then the
  40086. ** value added by the INSERT will not be visible to the second TEST.
  40087. ** The initial batch number is zero, so if the very first TEST contains
  40088. ** a non-zero batch number, it will see all prior INSERTs.
  40089. **
  40090. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  40091. ** that is attempted.
  40092. **
  40093. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  40094. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  40095. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  40096. ** The cost of a TEST using the same batch number is O(logN). The cost
  40097. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  40098. ** primitives are constant time. The cost of DESTROY is O(N).
  40099. **
  40100. ** There is an added cost of O(N) when switching between TEST and
  40101. ** SMALLEST primitives.
  40102. */
  40103. /* #include "sqliteInt.h" */
  40104. /*
  40105. ** Target size for allocation chunks.
  40106. */
  40107. #define ROWSET_ALLOCATION_SIZE 1024
  40108. /*
  40109. ** The number of rowset entries per allocation chunk.
  40110. */
  40111. #define ROWSET_ENTRY_PER_CHUNK \
  40112. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  40113. /*
  40114. ** Each entry in a RowSet is an instance of the following object.
  40115. **
  40116. ** This same object is reused to store a linked list of trees of RowSetEntry
  40117. ** objects. In that alternative use, pRight points to the next entry
  40118. ** in the list, pLeft points to the tree, and v is unused. The
  40119. ** RowSet.pForest value points to the head of this forest list.
  40120. */
  40121. struct RowSetEntry {
  40122. i64 v; /* ROWID value for this entry */
  40123. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  40124. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  40125. };
  40126. /*
  40127. ** RowSetEntry objects are allocated in large chunks (instances of the
  40128. ** following structure) to reduce memory allocation overhead. The
  40129. ** chunks are kept on a linked list so that they can be deallocated
  40130. ** when the RowSet is destroyed.
  40131. */
  40132. struct RowSetChunk {
  40133. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  40134. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  40135. };
  40136. /*
  40137. ** A RowSet in an instance of the following structure.
  40138. **
  40139. ** A typedef of this structure if found in sqliteInt.h.
  40140. */
  40141. struct RowSet {
  40142. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  40143. sqlite3 *db; /* The database connection */
  40144. struct RowSetEntry *pEntry; /* List of entries using pRight */
  40145. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  40146. struct RowSetEntry *pFresh; /* Source of new entry objects */
  40147. struct RowSetEntry *pForest; /* List of binary trees of entries */
  40148. u16 nFresh; /* Number of objects on pFresh */
  40149. u16 rsFlags; /* Various flags */
  40150. int iBatch; /* Current insert batch */
  40151. };
  40152. /*
  40153. ** Allowed values for RowSet.rsFlags
  40154. */
  40155. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  40156. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  40157. /*
  40158. ** Turn bulk memory into a RowSet object. N bytes of memory
  40159. ** are available at pSpace. The db pointer is used as a memory context
  40160. ** for any subsequent allocations that need to occur.
  40161. ** Return a pointer to the new RowSet object.
  40162. **
  40163. ** It must be the case that N is sufficient to make a Rowset. If not
  40164. ** an assertion fault occurs.
  40165. **
  40166. ** If N is larger than the minimum, use the surplus as an initial
  40167. ** allocation of entries available to be filled.
  40168. */
  40169. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  40170. RowSet *p;
  40171. assert( N >= ROUND8(sizeof(*p)) );
  40172. p = pSpace;
  40173. p->pChunk = 0;
  40174. p->db = db;
  40175. p->pEntry = 0;
  40176. p->pLast = 0;
  40177. p->pForest = 0;
  40178. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  40179. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  40180. p->rsFlags = ROWSET_SORTED;
  40181. p->iBatch = 0;
  40182. return p;
  40183. }
  40184. /*
  40185. ** Deallocate all chunks from a RowSet. This frees all memory that
  40186. ** the RowSet has allocated over its lifetime. This routine is
  40187. ** the destructor for the RowSet.
  40188. */
  40189. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  40190. struct RowSetChunk *pChunk, *pNextChunk;
  40191. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  40192. pNextChunk = pChunk->pNextChunk;
  40193. sqlite3DbFree(p->db, pChunk);
  40194. }
  40195. p->pChunk = 0;
  40196. p->nFresh = 0;
  40197. p->pEntry = 0;
  40198. p->pLast = 0;
  40199. p->pForest = 0;
  40200. p->rsFlags = ROWSET_SORTED;
  40201. }
  40202. /*
  40203. ** Allocate a new RowSetEntry object that is associated with the
  40204. ** given RowSet. Return a pointer to the new and completely uninitialized
  40205. ** objected.
  40206. **
  40207. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  40208. ** routine returns NULL.
  40209. */
  40210. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  40211. assert( p!=0 );
  40212. if( p->nFresh==0 ){
  40213. struct RowSetChunk *pNew;
  40214. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  40215. if( pNew==0 ){
  40216. return 0;
  40217. }
  40218. pNew->pNextChunk = p->pChunk;
  40219. p->pChunk = pNew;
  40220. p->pFresh = pNew->aEntry;
  40221. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  40222. }
  40223. p->nFresh--;
  40224. return p->pFresh++;
  40225. }
  40226. /*
  40227. ** Insert a new value into a RowSet.
  40228. **
  40229. ** The mallocFailed flag of the database connection is set if a
  40230. ** memory allocation fails.
  40231. */
  40232. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  40233. struct RowSetEntry *pEntry; /* The new entry */
  40234. struct RowSetEntry *pLast; /* The last prior entry */
  40235. /* This routine is never called after sqlite3RowSetNext() */
  40236. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  40237. pEntry = rowSetEntryAlloc(p);
  40238. if( pEntry==0 ) return;
  40239. pEntry->v = rowid;
  40240. pEntry->pRight = 0;
  40241. pLast = p->pLast;
  40242. if( pLast ){
  40243. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  40244. p->rsFlags &= ~ROWSET_SORTED;
  40245. }
  40246. pLast->pRight = pEntry;
  40247. }else{
  40248. p->pEntry = pEntry;
  40249. }
  40250. p->pLast = pEntry;
  40251. }
  40252. /*
  40253. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  40254. **
  40255. ** The input lists are connected via pRight pointers and are
  40256. ** assumed to each already be in sorted order.
  40257. */
  40258. static struct RowSetEntry *rowSetEntryMerge(
  40259. struct RowSetEntry *pA, /* First sorted list to be merged */
  40260. struct RowSetEntry *pB /* Second sorted list to be merged */
  40261. ){
  40262. struct RowSetEntry head;
  40263. struct RowSetEntry *pTail;
  40264. pTail = &head;
  40265. while( pA && pB ){
  40266. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  40267. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  40268. if( pA->v<pB->v ){
  40269. pTail->pRight = pA;
  40270. pA = pA->pRight;
  40271. pTail = pTail->pRight;
  40272. }else if( pB->v<pA->v ){
  40273. pTail->pRight = pB;
  40274. pB = pB->pRight;
  40275. pTail = pTail->pRight;
  40276. }else{
  40277. pA = pA->pRight;
  40278. }
  40279. }
  40280. if( pA ){
  40281. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  40282. pTail->pRight = pA;
  40283. }else{
  40284. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  40285. pTail->pRight = pB;
  40286. }
  40287. return head.pRight;
  40288. }
  40289. /*
  40290. ** Sort all elements on the list of RowSetEntry objects into order of
  40291. ** increasing v.
  40292. */
  40293. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  40294. unsigned int i;
  40295. struct RowSetEntry *pNext, *aBucket[40];
  40296. memset(aBucket, 0, sizeof(aBucket));
  40297. while( pIn ){
  40298. pNext = pIn->pRight;
  40299. pIn->pRight = 0;
  40300. for(i=0; aBucket[i]; i++){
  40301. pIn = rowSetEntryMerge(aBucket[i], pIn);
  40302. aBucket[i] = 0;
  40303. }
  40304. aBucket[i] = pIn;
  40305. pIn = pNext;
  40306. }
  40307. pIn = 0;
  40308. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  40309. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  40310. }
  40311. return pIn;
  40312. }
  40313. /*
  40314. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  40315. ** Convert this tree into a linked list connected by the pRight pointers
  40316. ** and return pointers to the first and last elements of the new list.
  40317. */
  40318. static void rowSetTreeToList(
  40319. struct RowSetEntry *pIn, /* Root of the input tree */
  40320. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  40321. struct RowSetEntry **ppLast /* Write tail of the output list here */
  40322. ){
  40323. assert( pIn!=0 );
  40324. if( pIn->pLeft ){
  40325. struct RowSetEntry *p;
  40326. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  40327. p->pRight = pIn;
  40328. }else{
  40329. *ppFirst = pIn;
  40330. }
  40331. if( pIn->pRight ){
  40332. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  40333. }else{
  40334. *ppLast = pIn;
  40335. }
  40336. assert( (*ppLast)->pRight==0 );
  40337. }
  40338. /*
  40339. ** Convert a sorted list of elements (connected by pRight) into a binary
  40340. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  40341. ** node taken from the head of *ppList. A depth of 2 means a tree with
  40342. ** three nodes. And so forth.
  40343. **
  40344. ** Use as many entries from the input list as required and update the
  40345. ** *ppList to point to the unused elements of the list. If the input
  40346. ** list contains too few elements, then construct an incomplete tree
  40347. ** and leave *ppList set to NULL.
  40348. **
  40349. ** Return a pointer to the root of the constructed binary tree.
  40350. */
  40351. static struct RowSetEntry *rowSetNDeepTree(
  40352. struct RowSetEntry **ppList,
  40353. int iDepth
  40354. ){
  40355. struct RowSetEntry *p; /* Root of the new tree */
  40356. struct RowSetEntry *pLeft; /* Left subtree */
  40357. if( *ppList==0 ){
  40358. return 0;
  40359. }
  40360. if( iDepth==1 ){
  40361. p = *ppList;
  40362. *ppList = p->pRight;
  40363. p->pLeft = p->pRight = 0;
  40364. return p;
  40365. }
  40366. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  40367. p = *ppList;
  40368. if( p==0 ){
  40369. return pLeft;
  40370. }
  40371. p->pLeft = pLeft;
  40372. *ppList = p->pRight;
  40373. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  40374. return p;
  40375. }
  40376. /*
  40377. ** Convert a sorted list of elements into a binary tree. Make the tree
  40378. ** as deep as it needs to be in order to contain the entire list.
  40379. */
  40380. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  40381. int iDepth; /* Depth of the tree so far */
  40382. struct RowSetEntry *p; /* Current tree root */
  40383. struct RowSetEntry *pLeft; /* Left subtree */
  40384. assert( pList!=0 );
  40385. p = pList;
  40386. pList = p->pRight;
  40387. p->pLeft = p->pRight = 0;
  40388. for(iDepth=1; pList; iDepth++){
  40389. pLeft = p;
  40390. p = pList;
  40391. pList = p->pRight;
  40392. p->pLeft = pLeft;
  40393. p->pRight = rowSetNDeepTree(&pList, iDepth);
  40394. }
  40395. return p;
  40396. }
  40397. /*
  40398. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  40399. ** sort them all together into one big ordered list on p->pEntry.
  40400. **
  40401. ** This routine should only be called once in the life of a RowSet.
  40402. */
  40403. static void rowSetToList(RowSet *p){
  40404. /* This routine is called only once */
  40405. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  40406. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  40407. p->pEntry = rowSetEntrySort(p->pEntry);
  40408. }
  40409. /* While this module could theoretically support it, sqlite3RowSetNext()
  40410. ** is never called after sqlite3RowSetText() for the same RowSet. So
  40411. ** there is never a forest to deal with. Should this change, simply
  40412. ** remove the assert() and the #if 0. */
  40413. assert( p->pForest==0 );
  40414. #if 0
  40415. while( p->pForest ){
  40416. struct RowSetEntry *pTree = p->pForest->pLeft;
  40417. if( pTree ){
  40418. struct RowSetEntry *pHead, *pTail;
  40419. rowSetTreeToList(pTree, &pHead, &pTail);
  40420. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  40421. }
  40422. p->pForest = p->pForest->pRight;
  40423. }
  40424. #endif
  40425. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  40426. }
  40427. /*
  40428. ** Extract the smallest element from the RowSet.
  40429. ** Write the element into *pRowid. Return 1 on success. Return
  40430. ** 0 if the RowSet is already empty.
  40431. **
  40432. ** After this routine has been called, the sqlite3RowSetInsert()
  40433. ** routine may not be called again.
  40434. */
  40435. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  40436. assert( p!=0 );
  40437. /* Merge the forest into a single sorted list on first call */
  40438. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  40439. /* Return the next entry on the list */
  40440. if( p->pEntry ){
  40441. *pRowid = p->pEntry->v;
  40442. p->pEntry = p->pEntry->pRight;
  40443. if( p->pEntry==0 ){
  40444. sqlite3RowSetClear(p);
  40445. }
  40446. return 1;
  40447. }else{
  40448. return 0;
  40449. }
  40450. }
  40451. /*
  40452. ** Check to see if element iRowid was inserted into the rowset as
  40453. ** part of any insert batch prior to iBatch. Return 1 or 0.
  40454. **
  40455. ** If this is the first test of a new batch and if there exist entries
  40456. ** on pRowSet->pEntry, then sort those entries into the forest at
  40457. ** pRowSet->pForest so that they can be tested.
  40458. */
  40459. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  40460. struct RowSetEntry *p, *pTree;
  40461. /* This routine is never called after sqlite3RowSetNext() */
  40462. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  40463. /* Sort entries into the forest on the first test of a new batch
  40464. */
  40465. if( iBatch!=pRowSet->iBatch ){
  40466. p = pRowSet->pEntry;
  40467. if( p ){
  40468. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  40469. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  40470. p = rowSetEntrySort(p);
  40471. }
  40472. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  40473. ppPrevTree = &pTree->pRight;
  40474. if( pTree->pLeft==0 ){
  40475. pTree->pLeft = rowSetListToTree(p);
  40476. break;
  40477. }else{
  40478. struct RowSetEntry *pAux, *pTail;
  40479. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  40480. pTree->pLeft = 0;
  40481. p = rowSetEntryMerge(pAux, p);
  40482. }
  40483. }
  40484. if( pTree==0 ){
  40485. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  40486. if( pTree ){
  40487. pTree->v = 0;
  40488. pTree->pRight = 0;
  40489. pTree->pLeft = rowSetListToTree(p);
  40490. }
  40491. }
  40492. pRowSet->pEntry = 0;
  40493. pRowSet->pLast = 0;
  40494. pRowSet->rsFlags |= ROWSET_SORTED;
  40495. }
  40496. pRowSet->iBatch = iBatch;
  40497. }
  40498. /* Test to see if the iRowid value appears anywhere in the forest.
  40499. ** Return 1 if it does and 0 if not.
  40500. */
  40501. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  40502. p = pTree->pLeft;
  40503. while( p ){
  40504. if( p->v<iRowid ){
  40505. p = p->pRight;
  40506. }else if( p->v>iRowid ){
  40507. p = p->pLeft;
  40508. }else{
  40509. return 1;
  40510. }
  40511. }
  40512. }
  40513. return 0;
  40514. }
  40515. /************** End of rowset.c **********************************************/
  40516. /************** Begin file pager.c *******************************************/
  40517. /*
  40518. ** 2001 September 15
  40519. **
  40520. ** The author disclaims copyright to this source code. In place of
  40521. ** a legal notice, here is a blessing:
  40522. **
  40523. ** May you do good and not evil.
  40524. ** May you find forgiveness for yourself and forgive others.
  40525. ** May you share freely, never taking more than you give.
  40526. **
  40527. *************************************************************************
  40528. ** This is the implementation of the page cache subsystem or "pager".
  40529. **
  40530. ** The pager is used to access a database disk file. It implements
  40531. ** atomic commit and rollback through the use of a journal file that
  40532. ** is separate from the database file. The pager also implements file
  40533. ** locking to prevent two processes from writing the same database
  40534. ** file simultaneously, or one process from reading the database while
  40535. ** another is writing.
  40536. */
  40537. #ifndef SQLITE_OMIT_DISKIO
  40538. /* #include "sqliteInt.h" */
  40539. /************** Include wal.h in the middle of pager.c ***********************/
  40540. /************** Begin file wal.h *********************************************/
  40541. /*
  40542. ** 2010 February 1
  40543. **
  40544. ** The author disclaims copyright to this source code. In place of
  40545. ** a legal notice, here is a blessing:
  40546. **
  40547. ** May you do good and not evil.
  40548. ** May you find forgiveness for yourself and forgive others.
  40549. ** May you share freely, never taking more than you give.
  40550. **
  40551. *************************************************************************
  40552. ** This header file defines the interface to the write-ahead logging
  40553. ** system. Refer to the comments below and the header comment attached to
  40554. ** the implementation of each function in log.c for further details.
  40555. */
  40556. #ifndef _WAL_H_
  40557. #define _WAL_H_
  40558. /* #include "sqliteInt.h" */
  40559. /* Additional values that can be added to the sync_flags argument of
  40560. ** sqlite3WalFrames():
  40561. */
  40562. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  40563. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  40564. #ifdef SQLITE_OMIT_WAL
  40565. # define sqlite3WalOpen(x,y,z) 0
  40566. # define sqlite3WalLimit(x,y)
  40567. # define sqlite3WalClose(w,x,y,z) 0
  40568. # define sqlite3WalBeginReadTransaction(y,z) 0
  40569. # define sqlite3WalEndReadTransaction(z)
  40570. # define sqlite3WalDbsize(y) 0
  40571. # define sqlite3WalBeginWriteTransaction(y) 0
  40572. # define sqlite3WalEndWriteTransaction(x) 0
  40573. # define sqlite3WalUndo(x,y,z) 0
  40574. # define sqlite3WalSavepoint(y,z)
  40575. # define sqlite3WalSavepointUndo(y,z) 0
  40576. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  40577. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  40578. # define sqlite3WalCallback(z) 0
  40579. # define sqlite3WalExclusiveMode(y,z) 0
  40580. # define sqlite3WalHeapMemory(z) 0
  40581. # define sqlite3WalFramesize(z) 0
  40582. # define sqlite3WalFindFrame(x,y,z) 0
  40583. # define sqlite3WalFile(x) 0
  40584. #else
  40585. #define WAL_SAVEPOINT_NDATA 4
  40586. /* Connection to a write-ahead log (WAL) file.
  40587. ** There is one object of this type for each pager.
  40588. */
  40589. typedef struct Wal Wal;
  40590. /* Open and close a connection to a write-ahead log. */
  40591. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  40592. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  40593. /* Set the limiting size of a WAL file. */
  40594. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  40595. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  40596. ** snapshot is like a read-transaction. It is the state of the database
  40597. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  40598. ** preserves the current state even if the other threads or processes
  40599. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  40600. ** transaction and releases the lock.
  40601. */
  40602. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  40603. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  40604. /* Read a page from the write-ahead log, if it is present. */
  40605. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  40606. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  40607. /* If the WAL is not empty, return the size of the database. */
  40608. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  40609. /* Obtain or release the WRITER lock. */
  40610. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  40611. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  40612. /* Undo any frames written (but not committed) to the log */
  40613. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  40614. /* Return an integer that records the current (uncommitted) write
  40615. ** position in the WAL */
  40616. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  40617. /* Move the write position of the WAL back to iFrame. Called in
  40618. ** response to a ROLLBACK TO command. */
  40619. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  40620. /* Write a frame or frames to the log. */
  40621. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  40622. /* Copy pages from the log to the database file */
  40623. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  40624. Wal *pWal, /* Write-ahead log connection */
  40625. int eMode, /* One of PASSIVE, FULL and RESTART */
  40626. int (*xBusy)(void*), /* Function to call when busy */
  40627. void *pBusyArg, /* Context argument for xBusyHandler */
  40628. int sync_flags, /* Flags to sync db file with (or 0) */
  40629. int nBuf, /* Size of buffer nBuf */
  40630. u8 *zBuf, /* Temporary buffer to use */
  40631. int *pnLog, /* OUT: Number of frames in WAL */
  40632. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  40633. );
  40634. /* Return the value to pass to a sqlite3_wal_hook callback, the
  40635. ** number of frames in the WAL at the point of the last commit since
  40636. ** sqlite3WalCallback() was called. If no commits have occurred since
  40637. ** the last call, then return 0.
  40638. */
  40639. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  40640. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  40641. ** by the pager layer on the database file.
  40642. */
  40643. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  40644. /* Return true if the argument is non-NULL and the WAL module is using
  40645. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  40646. ** WAL module is using shared-memory, return false.
  40647. */
  40648. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  40649. #ifdef SQLITE_ENABLE_SNAPSHOT
  40650. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  40651. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  40652. #endif
  40653. #ifdef SQLITE_ENABLE_ZIPVFS
  40654. /* If the WAL file is not empty, return the number of bytes of content
  40655. ** stored in each frame (i.e. the db page-size when the WAL was created).
  40656. */
  40657. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  40658. #endif
  40659. /* Return the sqlite3_file object for the WAL file */
  40660. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  40661. #endif /* ifndef SQLITE_OMIT_WAL */
  40662. #endif /* _WAL_H_ */
  40663. /************** End of wal.h *************************************************/
  40664. /************** Continuing where we left off in pager.c **********************/
  40665. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  40666. **
  40667. ** This comment block describes invariants that hold when using a rollback
  40668. ** journal. These invariants do not apply for journal_mode=WAL,
  40669. ** journal_mode=MEMORY, or journal_mode=OFF.
  40670. **
  40671. ** Within this comment block, a page is deemed to have been synced
  40672. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  40673. ** Otherwise, the page is not synced until the xSync method of the VFS
  40674. ** is called successfully on the file containing the page.
  40675. **
  40676. ** Definition: A page of the database file is said to be "overwriteable" if
  40677. ** one or more of the following are true about the page:
  40678. **
  40679. ** (a) The original content of the page as it was at the beginning of
  40680. ** the transaction has been written into the rollback journal and
  40681. ** synced.
  40682. **
  40683. ** (b) The page was a freelist leaf page at the start of the transaction.
  40684. **
  40685. ** (c) The page number is greater than the largest page that existed in
  40686. ** the database file at the start of the transaction.
  40687. **
  40688. ** (1) A page of the database file is never overwritten unless one of the
  40689. ** following are true:
  40690. **
  40691. ** (a) The page and all other pages on the same sector are overwriteable.
  40692. **
  40693. ** (b) The atomic page write optimization is enabled, and the entire
  40694. ** transaction other than the update of the transaction sequence
  40695. ** number consists of a single page change.
  40696. **
  40697. ** (2) The content of a page written into the rollback journal exactly matches
  40698. ** both the content in the database when the rollback journal was written
  40699. ** and the content in the database at the beginning of the current
  40700. ** transaction.
  40701. **
  40702. ** (3) Writes to the database file are an integer multiple of the page size
  40703. ** in length and are aligned on a page boundary.
  40704. **
  40705. ** (4) Reads from the database file are either aligned on a page boundary and
  40706. ** an integer multiple of the page size in length or are taken from the
  40707. ** first 100 bytes of the database file.
  40708. **
  40709. ** (5) All writes to the database file are synced prior to the rollback journal
  40710. ** being deleted, truncated, or zeroed.
  40711. **
  40712. ** (6) If a master journal file is used, then all writes to the database file
  40713. ** are synced prior to the master journal being deleted.
  40714. **
  40715. ** Definition: Two databases (or the same database at two points it time)
  40716. ** are said to be "logically equivalent" if they give the same answer to
  40717. ** all queries. Note in particular the content of freelist leaf
  40718. ** pages can be changed arbitrarily without affecting the logical equivalence
  40719. ** of the database.
  40720. **
  40721. ** (7) At any time, if any subset, including the empty set and the total set,
  40722. ** of the unsynced changes to a rollback journal are removed and the
  40723. ** journal is rolled back, the resulting database file will be logically
  40724. ** equivalent to the database file at the beginning of the transaction.
  40725. **
  40726. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  40727. ** is called to restore the database file to the same size it was at
  40728. ** the beginning of the transaction. (In some VFSes, the xTruncate
  40729. ** method is a no-op, but that does not change the fact the SQLite will
  40730. ** invoke it.)
  40731. **
  40732. ** (9) Whenever the database file is modified, at least one bit in the range
  40733. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  40734. ** the EXCLUSIVE lock, thus signaling other connections on the same
  40735. ** database to flush their caches.
  40736. **
  40737. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  40738. ** than one billion transactions.
  40739. **
  40740. ** (11) A database file is well-formed at the beginning and at the conclusion
  40741. ** of every transaction.
  40742. **
  40743. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  40744. ** the database file.
  40745. **
  40746. ** (13) A SHARED lock is held on the database file while reading any
  40747. ** content out of the database file.
  40748. **
  40749. ******************************************************************************/
  40750. /*
  40751. ** Macros for troubleshooting. Normally turned off
  40752. */
  40753. #if 0
  40754. int sqlite3PagerTrace=1; /* True to enable tracing */
  40755. #define sqlite3DebugPrintf printf
  40756. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  40757. #else
  40758. #define PAGERTRACE(X)
  40759. #endif
  40760. /*
  40761. ** The following two macros are used within the PAGERTRACE() macros above
  40762. ** to print out file-descriptors.
  40763. **
  40764. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  40765. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  40766. ** struct as its argument.
  40767. */
  40768. #define PAGERID(p) ((int)(p->fd))
  40769. #define FILEHANDLEID(fd) ((int)fd)
  40770. /*
  40771. ** The Pager.eState variable stores the current 'state' of a pager. A
  40772. ** pager may be in any one of the seven states shown in the following
  40773. ** state diagram.
  40774. **
  40775. ** OPEN <------+------+
  40776. ** | | |
  40777. ** V | |
  40778. ** +---------> READER-------+ |
  40779. ** | | |
  40780. ** | V |
  40781. ** |<-------WRITER_LOCKED------> ERROR
  40782. ** | | ^
  40783. ** | V |
  40784. ** |<------WRITER_CACHEMOD-------->|
  40785. ** | | |
  40786. ** | V |
  40787. ** |<-------WRITER_DBMOD---------->|
  40788. ** | | |
  40789. ** | V |
  40790. ** +<------WRITER_FINISHED-------->+
  40791. **
  40792. **
  40793. ** List of state transitions and the C [function] that performs each:
  40794. **
  40795. ** OPEN -> READER [sqlite3PagerSharedLock]
  40796. ** READER -> OPEN [pager_unlock]
  40797. **
  40798. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  40799. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  40800. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  40801. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  40802. ** WRITER_*** -> READER [pager_end_transaction]
  40803. **
  40804. ** WRITER_*** -> ERROR [pager_error]
  40805. ** ERROR -> OPEN [pager_unlock]
  40806. **
  40807. **
  40808. ** OPEN:
  40809. **
  40810. ** The pager starts up in this state. Nothing is guaranteed in this
  40811. ** state - the file may or may not be locked and the database size is
  40812. ** unknown. The database may not be read or written.
  40813. **
  40814. ** * No read or write transaction is active.
  40815. ** * Any lock, or no lock at all, may be held on the database file.
  40816. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  40817. **
  40818. ** READER:
  40819. **
  40820. ** In this state all the requirements for reading the database in
  40821. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  40822. ** was) in exclusive-locking mode, a user-level read transaction is
  40823. ** open. The database size is known in this state.
  40824. **
  40825. ** A connection running with locking_mode=normal enters this state when
  40826. ** it opens a read-transaction on the database and returns to state
  40827. ** OPEN after the read-transaction is completed. However a connection
  40828. ** running in locking_mode=exclusive (including temp databases) remains in
  40829. ** this state even after the read-transaction is closed. The only way
  40830. ** a locking_mode=exclusive connection can transition from READER to OPEN
  40831. ** is via the ERROR state (see below).
  40832. **
  40833. ** * A read transaction may be active (but a write-transaction cannot).
  40834. ** * A SHARED or greater lock is held on the database file.
  40835. ** * The dbSize variable may be trusted (even if a user-level read
  40836. ** transaction is not active). The dbOrigSize and dbFileSize variables
  40837. ** may not be trusted at this point.
  40838. ** * If the database is a WAL database, then the WAL connection is open.
  40839. ** * Even if a read-transaction is not open, it is guaranteed that
  40840. ** there is no hot-journal in the file-system.
  40841. **
  40842. ** WRITER_LOCKED:
  40843. **
  40844. ** The pager moves to this state from READER when a write-transaction
  40845. ** is first opened on the database. In WRITER_LOCKED state, all locks
  40846. ** required to start a write-transaction are held, but no actual
  40847. ** modifications to the cache or database have taken place.
  40848. **
  40849. ** In rollback mode, a RESERVED or (if the transaction was opened with
  40850. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  40851. ** moving to this state, but the journal file is not written to or opened
  40852. ** to in this state. If the transaction is committed or rolled back while
  40853. ** in WRITER_LOCKED state, all that is required is to unlock the database
  40854. ** file.
  40855. **
  40856. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  40857. ** If the connection is running with locking_mode=exclusive, an attempt
  40858. ** is made to obtain an EXCLUSIVE lock on the database file.
  40859. **
  40860. ** * A write transaction is active.
  40861. ** * If the connection is open in rollback-mode, a RESERVED or greater
  40862. ** lock is held on the database file.
  40863. ** * If the connection is open in WAL-mode, a WAL write transaction
  40864. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  40865. ** called).
  40866. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  40867. ** * The contents of the pager cache have not been modified.
  40868. ** * The journal file may or may not be open.
  40869. ** * Nothing (not even the first header) has been written to the journal.
  40870. **
  40871. ** WRITER_CACHEMOD:
  40872. **
  40873. ** A pager moves from WRITER_LOCKED state to this state when a page is
  40874. ** first modified by the upper layer. In rollback mode the journal file
  40875. ** is opened (if it is not already open) and a header written to the
  40876. ** start of it. The database file on disk has not been modified.
  40877. **
  40878. ** * A write transaction is active.
  40879. ** * A RESERVED or greater lock is held on the database file.
  40880. ** * The journal file is open and the first header has been written
  40881. ** to it, but the header has not been synced to disk.
  40882. ** * The contents of the page cache have been modified.
  40883. **
  40884. ** WRITER_DBMOD:
  40885. **
  40886. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  40887. ** when it modifies the contents of the database file. WAL connections
  40888. ** never enter this state (since they do not modify the database file,
  40889. ** just the log file).
  40890. **
  40891. ** * A write transaction is active.
  40892. ** * An EXCLUSIVE or greater lock is held on the database file.
  40893. ** * The journal file is open and the first header has been written
  40894. ** and synced to disk.
  40895. ** * The contents of the page cache have been modified (and possibly
  40896. ** written to disk).
  40897. **
  40898. ** WRITER_FINISHED:
  40899. **
  40900. ** It is not possible for a WAL connection to enter this state.
  40901. **
  40902. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  40903. ** state after the entire transaction has been successfully written into the
  40904. ** database file. In this state the transaction may be committed simply
  40905. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  40906. ** not possible to modify the database further. At this point, the upper
  40907. ** layer must either commit or rollback the transaction.
  40908. **
  40909. ** * A write transaction is active.
  40910. ** * An EXCLUSIVE or greater lock is held on the database file.
  40911. ** * All writing and syncing of journal and database data has finished.
  40912. ** If no error occurred, all that remains is to finalize the journal to
  40913. ** commit the transaction. If an error did occur, the caller will need
  40914. ** to rollback the transaction.
  40915. **
  40916. ** ERROR:
  40917. **
  40918. ** The ERROR state is entered when an IO or disk-full error (including
  40919. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  40920. ** difficult to be sure that the in-memory pager state (cache contents,
  40921. ** db size etc.) are consistent with the contents of the file-system.
  40922. **
  40923. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  40924. ** cannot.
  40925. **
  40926. ** For example, if an IO error occurs while performing a rollback,
  40927. ** the contents of the page-cache may be left in an inconsistent state.
  40928. ** At this point it would be dangerous to change back to READER state
  40929. ** (as usually happens after a rollback). Any subsequent readers might
  40930. ** report database corruption (due to the inconsistent cache), and if
  40931. ** they upgrade to writers, they may inadvertently corrupt the database
  40932. ** file. To avoid this hazard, the pager switches into the ERROR state
  40933. ** instead of READER following such an error.
  40934. **
  40935. ** Once it has entered the ERROR state, any attempt to use the pager
  40936. ** to read or write data returns an error. Eventually, once all
  40937. ** outstanding transactions have been abandoned, the pager is able to
  40938. ** transition back to OPEN state, discarding the contents of the
  40939. ** page-cache and any other in-memory state at the same time. Everything
  40940. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  40941. ** when a read-transaction is next opened on the pager (transitioning
  40942. ** the pager into READER state). At that point the system has recovered
  40943. ** from the error.
  40944. **
  40945. ** Specifically, the pager jumps into the ERROR state if:
  40946. **
  40947. ** 1. An error occurs while attempting a rollback. This happens in
  40948. ** function sqlite3PagerRollback().
  40949. **
  40950. ** 2. An error occurs while attempting to finalize a journal file
  40951. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  40952. **
  40953. ** 3. An error occurs while attempting to write to the journal or
  40954. ** database file in function pagerStress() in order to free up
  40955. ** memory.
  40956. **
  40957. ** In other cases, the error is returned to the b-tree layer. The b-tree
  40958. ** layer then attempts a rollback operation. If the error condition
  40959. ** persists, the pager enters the ERROR state via condition (1) above.
  40960. **
  40961. ** Condition (3) is necessary because it can be triggered by a read-only
  40962. ** statement executed within a transaction. In this case, if the error
  40963. ** code were simply returned to the user, the b-tree layer would not
  40964. ** automatically attempt a rollback, as it assumes that an error in a
  40965. ** read-only statement cannot leave the pager in an internally inconsistent
  40966. ** state.
  40967. **
  40968. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  40969. ** * There are one or more outstanding references to pages (after the
  40970. ** last reference is dropped the pager should move back to OPEN state).
  40971. ** * The pager is not an in-memory pager.
  40972. **
  40973. **
  40974. ** Notes:
  40975. **
  40976. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  40977. ** connection is open in WAL mode. A WAL connection is always in one
  40978. ** of the first four states.
  40979. **
  40980. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  40981. ** state. There are two exceptions: immediately after exclusive-mode has
  40982. ** been turned on (and before any read or write transactions are
  40983. ** executed), and when the pager is leaving the "error state".
  40984. **
  40985. ** * See also: assert_pager_state().
  40986. */
  40987. #define PAGER_OPEN 0
  40988. #define PAGER_READER 1
  40989. #define PAGER_WRITER_LOCKED 2
  40990. #define PAGER_WRITER_CACHEMOD 3
  40991. #define PAGER_WRITER_DBMOD 4
  40992. #define PAGER_WRITER_FINISHED 5
  40993. #define PAGER_ERROR 6
  40994. /*
  40995. ** The Pager.eLock variable is almost always set to one of the
  40996. ** following locking-states, according to the lock currently held on
  40997. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  40998. ** This variable is kept up to date as locks are taken and released by
  40999. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  41000. **
  41001. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  41002. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  41003. ** the operation was successful. In these circumstances pagerLockDb() and
  41004. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  41005. ** when unlocking the file, and only updated when locking the file if the
  41006. ** VFS call is successful. This way, the Pager.eLock variable may be set
  41007. ** to a less exclusive (lower) value than the lock that is actually held
  41008. ** at the system level, but it is never set to a more exclusive value.
  41009. **
  41010. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  41011. ** be a few redundant xLock() calls or a lock may be held for longer than
  41012. ** required, but nothing really goes wrong.
  41013. **
  41014. ** The exception is when the database file is unlocked as the pager moves
  41015. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  41016. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  41017. ** transition, by the same pager or any other). If the call to xUnlock()
  41018. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  41019. ** can confuse the call to xCheckReservedLock() call made later as part
  41020. ** of hot-journal detection.
  41021. **
  41022. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  41023. ** lock held by this process or any others". So xCheckReservedLock may
  41024. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  41025. ** doesn't know it because of a previous error in xUnlock). If this happens
  41026. ** a hot-journal may be mistaken for a journal being created by an active
  41027. ** transaction in another process, causing SQLite to read from the database
  41028. ** without rolling it back.
  41029. **
  41030. ** To work around this, if a call to xUnlock() fails when unlocking the
  41031. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  41032. ** is only changed back to a real locking state after a successful call
  41033. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  41034. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  41035. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  41036. ** lock on the database file before attempting to roll it back. See function
  41037. ** PagerSharedLock() for more detail.
  41038. **
  41039. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  41040. ** PAGER_OPEN state.
  41041. */
  41042. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  41043. /*
  41044. ** A macro used for invoking the codec if there is one
  41045. */
  41046. #ifdef SQLITE_HAS_CODEC
  41047. # define CODEC1(P,D,N,X,E) \
  41048. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  41049. # define CODEC2(P,D,N,X,E,O) \
  41050. if( P->xCodec==0 ){ O=(char*)D; }else \
  41051. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  41052. #else
  41053. # define CODEC1(P,D,N,X,E) /* NO-OP */
  41054. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  41055. #endif
  41056. /*
  41057. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  41058. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  41059. ** This could conceivably cause corruption following a power failure on
  41060. ** such a system. This is currently an undocumented limit.
  41061. */
  41062. #define MAX_SECTOR_SIZE 0x10000
  41063. /*
  41064. ** An instance of the following structure is allocated for each active
  41065. ** savepoint and statement transaction in the system. All such structures
  41066. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  41067. ** resized using sqlite3Realloc().
  41068. **
  41069. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  41070. ** set to 0. If a journal-header is written into the main journal while
  41071. ** the savepoint is active, then iHdrOffset is set to the byte offset
  41072. ** immediately following the last journal record written into the main
  41073. ** journal before the journal-header. This is required during savepoint
  41074. ** rollback (see pagerPlaybackSavepoint()).
  41075. */
  41076. typedef struct PagerSavepoint PagerSavepoint;
  41077. struct PagerSavepoint {
  41078. i64 iOffset; /* Starting offset in main journal */
  41079. i64 iHdrOffset; /* See above */
  41080. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  41081. Pgno nOrig; /* Original number of pages in file */
  41082. Pgno iSubRec; /* Index of first record in sub-journal */
  41083. #ifndef SQLITE_OMIT_WAL
  41084. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  41085. #endif
  41086. };
  41087. /*
  41088. ** Bits of the Pager.doNotSpill flag. See further description below.
  41089. */
  41090. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  41091. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  41092. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  41093. /*
  41094. ** An open page cache is an instance of struct Pager. A description of
  41095. ** some of the more important member variables follows:
  41096. **
  41097. ** eState
  41098. **
  41099. ** The current 'state' of the pager object. See the comment and state
  41100. ** diagram above for a description of the pager state.
  41101. **
  41102. ** eLock
  41103. **
  41104. ** For a real on-disk database, the current lock held on the database file -
  41105. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  41106. **
  41107. ** For a temporary or in-memory database (neither of which require any
  41108. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  41109. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  41110. ** logic into thinking that it already has all the locks it will ever
  41111. ** need (and no reason to release them).
  41112. **
  41113. ** In some (obscure) circumstances, this variable may also be set to
  41114. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  41115. ** details.
  41116. **
  41117. ** changeCountDone
  41118. **
  41119. ** This boolean variable is used to make sure that the change-counter
  41120. ** (the 4-byte header field at byte offset 24 of the database file) is
  41121. ** not updated more often than necessary.
  41122. **
  41123. ** It is set to true when the change-counter field is updated, which
  41124. ** can only happen if an exclusive lock is held on the database file.
  41125. ** It is cleared (set to false) whenever an exclusive lock is
  41126. ** relinquished on the database file. Each time a transaction is committed,
  41127. ** The changeCountDone flag is inspected. If it is true, the work of
  41128. ** updating the change-counter is omitted for the current transaction.
  41129. **
  41130. ** This mechanism means that when running in exclusive mode, a connection
  41131. ** need only update the change-counter once, for the first transaction
  41132. ** committed.
  41133. **
  41134. ** setMaster
  41135. **
  41136. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  41137. ** (or may not) specify a master-journal name to be written into the
  41138. ** journal file before it is synced to disk.
  41139. **
  41140. ** Whether or not a journal file contains a master-journal pointer affects
  41141. ** the way in which the journal file is finalized after the transaction is
  41142. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  41143. ** If a journal file does not contain a master-journal pointer, it is
  41144. ** finalized by overwriting the first journal header with zeroes. If
  41145. ** it does contain a master-journal pointer the journal file is finalized
  41146. ** by truncating it to zero bytes, just as if the connection were
  41147. ** running in "journal_mode=truncate" mode.
  41148. **
  41149. ** Journal files that contain master journal pointers cannot be finalized
  41150. ** simply by overwriting the first journal-header with zeroes, as the
  41151. ** master journal pointer could interfere with hot-journal rollback of any
  41152. ** subsequently interrupted transaction that reuses the journal file.
  41153. **
  41154. ** The flag is cleared as soon as the journal file is finalized (either
  41155. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  41156. ** journal file from being successfully finalized, the setMaster flag
  41157. ** is cleared anyway (and the pager will move to ERROR state).
  41158. **
  41159. ** doNotSpill
  41160. **
  41161. ** This variables control the behavior of cache-spills (calls made by
  41162. ** the pcache module to the pagerStress() routine to write cached data
  41163. ** to the file-system in order to free up memory).
  41164. **
  41165. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  41166. ** writing to the database from pagerStress() is disabled altogether.
  41167. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  41168. ** comes up during savepoint rollback that requires the pcache module
  41169. ** to allocate a new page to prevent the journal file from being written
  41170. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  41171. ** case is a user preference.
  41172. **
  41173. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  41174. ** pagerStress() is permitted, but syncing the journal file is not.
  41175. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  41176. ** is larger than the database page-size in order to prevent a journal sync
  41177. ** from happening in between the journalling of two pages on the same sector.
  41178. **
  41179. ** subjInMemory
  41180. **
  41181. ** This is a boolean variable. If true, then any required sub-journal
  41182. ** is opened as an in-memory journal file. If false, then in-memory
  41183. ** sub-journals are only used for in-memory pager files.
  41184. **
  41185. ** This variable is updated by the upper layer each time a new
  41186. ** write-transaction is opened.
  41187. **
  41188. ** dbSize, dbOrigSize, dbFileSize
  41189. **
  41190. ** Variable dbSize is set to the number of pages in the database file.
  41191. ** It is valid in PAGER_READER and higher states (all states except for
  41192. ** OPEN and ERROR).
  41193. **
  41194. ** dbSize is set based on the size of the database file, which may be
  41195. ** larger than the size of the database (the value stored at offset
  41196. ** 28 of the database header by the btree). If the size of the file
  41197. ** is not an integer multiple of the page-size, the value stored in
  41198. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  41199. ** Except, any file that is greater than 0 bytes in size is considered
  41200. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  41201. ** to dbSize==1).
  41202. **
  41203. ** During a write-transaction, if pages with page-numbers greater than
  41204. ** dbSize are modified in the cache, dbSize is updated accordingly.
  41205. ** Similarly, if the database is truncated using PagerTruncateImage(),
  41206. ** dbSize is updated.
  41207. **
  41208. ** Variables dbOrigSize and dbFileSize are valid in states
  41209. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  41210. ** variable at the start of the transaction. It is used during rollback,
  41211. ** and to determine whether or not pages need to be journalled before
  41212. ** being modified.
  41213. **
  41214. ** Throughout a write-transaction, dbFileSize contains the size of
  41215. ** the file on disk in pages. It is set to a copy of dbSize when the
  41216. ** write-transaction is first opened, and updated when VFS calls are made
  41217. ** to write or truncate the database file on disk.
  41218. **
  41219. ** The only reason the dbFileSize variable is required is to suppress
  41220. ** unnecessary calls to xTruncate() after committing a transaction. If,
  41221. ** when a transaction is committed, the dbFileSize variable indicates
  41222. ** that the database file is larger than the database image (Pager.dbSize),
  41223. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  41224. ** to measure the database file on disk, and then truncates it if required.
  41225. ** dbFileSize is not used when rolling back a transaction. In this case
  41226. ** pager_truncate() is called unconditionally (which means there may be
  41227. ** a call to xFilesize() that is not strictly required). In either case,
  41228. ** pager_truncate() may cause the file to become smaller or larger.
  41229. **
  41230. ** dbHintSize
  41231. **
  41232. ** The dbHintSize variable is used to limit the number of calls made to
  41233. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  41234. **
  41235. ** dbHintSize is set to a copy of the dbSize variable when a
  41236. ** write-transaction is opened (at the same time as dbFileSize and
  41237. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  41238. ** dbHintSize is increased to the number of pages that correspond to the
  41239. ** size-hint passed to the method call. See pager_write_pagelist() for
  41240. ** details.
  41241. **
  41242. ** errCode
  41243. **
  41244. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  41245. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  41246. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  41247. ** sub-codes.
  41248. */
  41249. struct Pager {
  41250. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  41251. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  41252. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  41253. u8 useJournal; /* Use a rollback journal on this file */
  41254. u8 noSync; /* Do not sync the journal if true */
  41255. u8 fullSync; /* Do extra syncs of the journal for robustness */
  41256. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  41257. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  41258. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  41259. u8 tempFile; /* zFilename is a temporary or immutable file */
  41260. u8 noLock; /* Do not lock (except in WAL mode) */
  41261. u8 readOnly; /* True for a read-only database */
  41262. u8 memDb; /* True to inhibit all file I/O */
  41263. /**************************************************************************
  41264. ** The following block contains those class members that change during
  41265. ** routine operation. Class members not in this block are either fixed
  41266. ** when the pager is first created or else only change when there is a
  41267. ** significant mode change (such as changing the page_size, locking_mode,
  41268. ** or the journal_mode). From another view, these class members describe
  41269. ** the "state" of the pager, while other class members describe the
  41270. ** "configuration" of the pager.
  41271. */
  41272. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  41273. u8 eLock; /* Current lock held on database file */
  41274. u8 changeCountDone; /* Set after incrementing the change-counter */
  41275. u8 setMaster; /* True if a m-j name has been written to jrnl */
  41276. u8 doNotSpill; /* Do not spill the cache when non-zero */
  41277. u8 subjInMemory; /* True to use in-memory sub-journals */
  41278. u8 bUseFetch; /* True to use xFetch() */
  41279. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  41280. Pgno dbSize; /* Number of pages in the database */
  41281. Pgno dbOrigSize; /* dbSize before the current transaction */
  41282. Pgno dbFileSize; /* Number of pages in the database file */
  41283. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  41284. int errCode; /* One of several kinds of errors */
  41285. int nRec; /* Pages journalled since last j-header written */
  41286. u32 cksumInit; /* Quasi-random value added to every checksum */
  41287. u32 nSubRec; /* Number of records written to sub-journal */
  41288. Bitvec *pInJournal; /* One bit for each page in the database file */
  41289. sqlite3_file *fd; /* File descriptor for database */
  41290. sqlite3_file *jfd; /* File descriptor for main journal */
  41291. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  41292. i64 journalOff; /* Current write offset in the journal file */
  41293. i64 journalHdr; /* Byte offset to previous journal header */
  41294. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  41295. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  41296. int nSavepoint; /* Number of elements in aSavepoint[] */
  41297. u32 iDataVersion; /* Changes whenever database content changes */
  41298. char dbFileVers[16]; /* Changes whenever database file changes */
  41299. int nMmapOut; /* Number of mmap pages currently outstanding */
  41300. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  41301. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  41302. /*
  41303. ** End of the routinely-changing class members
  41304. ***************************************************************************/
  41305. u16 nExtra; /* Add this many bytes to each in-memory page */
  41306. i16 nReserve; /* Number of unused bytes at end of each page */
  41307. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  41308. u32 sectorSize; /* Assumed sector size during rollback */
  41309. int pageSize; /* Number of bytes in a page */
  41310. Pgno mxPgno; /* Maximum allowed size of the database */
  41311. i64 journalSizeLimit; /* Size limit for persistent journal files */
  41312. char *zFilename; /* Name of the database file */
  41313. char *zJournal; /* Name of the journal file */
  41314. int (*xBusyHandler)(void*); /* Function to call when busy */
  41315. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  41316. int aStat[3]; /* Total cache hits, misses and writes */
  41317. #ifdef SQLITE_TEST
  41318. int nRead; /* Database pages read */
  41319. #endif
  41320. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  41321. #ifdef SQLITE_HAS_CODEC
  41322. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  41323. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  41324. void (*xCodecFree)(void*); /* Destructor for the codec */
  41325. void *pCodec; /* First argument to xCodec... methods */
  41326. #endif
  41327. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  41328. PCache *pPCache; /* Pointer to page cache object */
  41329. #ifndef SQLITE_OMIT_WAL
  41330. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  41331. char *zWal; /* File name for write-ahead log */
  41332. #endif
  41333. };
  41334. /*
  41335. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  41336. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  41337. ** or CACHE_WRITE to sqlite3_db_status().
  41338. */
  41339. #define PAGER_STAT_HIT 0
  41340. #define PAGER_STAT_MISS 1
  41341. #define PAGER_STAT_WRITE 2
  41342. /*
  41343. ** The following global variables hold counters used for
  41344. ** testing purposes only. These variables do not exist in
  41345. ** a non-testing build. These variables are not thread-safe.
  41346. */
  41347. #ifdef SQLITE_TEST
  41348. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  41349. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  41350. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  41351. # define PAGER_INCR(v) v++
  41352. #else
  41353. # define PAGER_INCR(v)
  41354. #endif
  41355. /*
  41356. ** Journal files begin with the following magic string. The data
  41357. ** was obtained from /dev/random. It is used only as a sanity check.
  41358. **
  41359. ** Since version 2.8.0, the journal format contains additional sanity
  41360. ** checking information. If the power fails while the journal is being
  41361. ** written, semi-random garbage data might appear in the journal
  41362. ** file after power is restored. If an attempt is then made
  41363. ** to roll the journal back, the database could be corrupted. The additional
  41364. ** sanity checking data is an attempt to discover the garbage in the
  41365. ** journal and ignore it.
  41366. **
  41367. ** The sanity checking information for the new journal format consists
  41368. ** of a 32-bit checksum on each page of data. The checksum covers both
  41369. ** the page number and the pPager->pageSize bytes of data for the page.
  41370. ** This cksum is initialized to a 32-bit random value that appears in the
  41371. ** journal file right after the header. The random initializer is important,
  41372. ** because garbage data that appears at the end of a journal is likely
  41373. ** data that was once in other files that have now been deleted. If the
  41374. ** garbage data came from an obsolete journal file, the checksums might
  41375. ** be correct. But by initializing the checksum to random value which
  41376. ** is different for every journal, we minimize that risk.
  41377. */
  41378. static const unsigned char aJournalMagic[] = {
  41379. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  41380. };
  41381. /*
  41382. ** The size of the of each page record in the journal is given by
  41383. ** the following macro.
  41384. */
  41385. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  41386. /*
  41387. ** The journal header size for this pager. This is usually the same
  41388. ** size as a single disk sector. See also setSectorSize().
  41389. */
  41390. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  41391. /*
  41392. ** The macro MEMDB is true if we are dealing with an in-memory database.
  41393. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  41394. ** the value of MEMDB will be a constant and the compiler will optimize
  41395. ** out code that would never execute.
  41396. */
  41397. #ifdef SQLITE_OMIT_MEMORYDB
  41398. # define MEMDB 0
  41399. #else
  41400. # define MEMDB pPager->memDb
  41401. #endif
  41402. /*
  41403. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  41404. ** interfaces to access the database using memory-mapped I/O.
  41405. */
  41406. #if SQLITE_MAX_MMAP_SIZE>0
  41407. # define USEFETCH(x) ((x)->bUseFetch)
  41408. #else
  41409. # define USEFETCH(x) 0
  41410. #endif
  41411. /*
  41412. ** The maximum legal page number is (2^31 - 1).
  41413. */
  41414. #define PAGER_MAX_PGNO 2147483647
  41415. /*
  41416. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  41417. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  41418. **
  41419. ** This is so that expressions can be written as:
  41420. **
  41421. ** if( isOpen(pPager->jfd) ){ ...
  41422. **
  41423. ** instead of
  41424. **
  41425. ** if( pPager->jfd->pMethods ){ ...
  41426. */
  41427. #define isOpen(pFd) ((pFd)->pMethods!=0)
  41428. /*
  41429. ** Return true if this pager uses a write-ahead log instead of the usual
  41430. ** rollback journal. Otherwise false.
  41431. */
  41432. #ifndef SQLITE_OMIT_WAL
  41433. static int pagerUseWal(Pager *pPager){
  41434. return (pPager->pWal!=0);
  41435. }
  41436. #else
  41437. # define pagerUseWal(x) 0
  41438. # define pagerRollbackWal(x) 0
  41439. # define pagerWalFrames(v,w,x,y) 0
  41440. # define pagerOpenWalIfPresent(z) SQLITE_OK
  41441. # define pagerBeginReadTransaction(z) SQLITE_OK
  41442. #endif
  41443. #ifndef NDEBUG
  41444. /*
  41445. ** Usage:
  41446. **
  41447. ** assert( assert_pager_state(pPager) );
  41448. **
  41449. ** This function runs many asserts to try to find inconsistencies in
  41450. ** the internal state of the Pager object.
  41451. */
  41452. static int assert_pager_state(Pager *p){
  41453. Pager *pPager = p;
  41454. /* State must be valid. */
  41455. assert( p->eState==PAGER_OPEN
  41456. || p->eState==PAGER_READER
  41457. || p->eState==PAGER_WRITER_LOCKED
  41458. || p->eState==PAGER_WRITER_CACHEMOD
  41459. || p->eState==PAGER_WRITER_DBMOD
  41460. || p->eState==PAGER_WRITER_FINISHED
  41461. || p->eState==PAGER_ERROR
  41462. );
  41463. /* Regardless of the current state, a temp-file connection always behaves
  41464. ** as if it has an exclusive lock on the database file. It never updates
  41465. ** the change-counter field, so the changeCountDone flag is always set.
  41466. */
  41467. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  41468. assert( p->tempFile==0 || pPager->changeCountDone );
  41469. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  41470. ** And if the journal-mode is "OFF", the journal file must not be open.
  41471. */
  41472. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  41473. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  41474. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  41475. ** this means an in-memory pager performs no IO at all, it cannot encounter
  41476. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  41477. ** a journal file. (although the in-memory journal implementation may
  41478. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  41479. ** is therefore not possible for an in-memory pager to enter the ERROR
  41480. ** state.
  41481. */
  41482. if( MEMDB ){
  41483. assert( p->noSync );
  41484. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  41485. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  41486. );
  41487. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  41488. assert( pagerUseWal(p)==0 );
  41489. }
  41490. /* If changeCountDone is set, a RESERVED lock or greater must be held
  41491. ** on the file.
  41492. */
  41493. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  41494. assert( p->eLock!=PENDING_LOCK );
  41495. switch( p->eState ){
  41496. case PAGER_OPEN:
  41497. assert( !MEMDB );
  41498. assert( pPager->errCode==SQLITE_OK );
  41499. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  41500. break;
  41501. case PAGER_READER:
  41502. assert( pPager->errCode==SQLITE_OK );
  41503. assert( p->eLock!=UNKNOWN_LOCK );
  41504. assert( p->eLock>=SHARED_LOCK );
  41505. break;
  41506. case PAGER_WRITER_LOCKED:
  41507. assert( p->eLock!=UNKNOWN_LOCK );
  41508. assert( pPager->errCode==SQLITE_OK );
  41509. if( !pagerUseWal(pPager) ){
  41510. assert( p->eLock>=RESERVED_LOCK );
  41511. }
  41512. assert( pPager->dbSize==pPager->dbOrigSize );
  41513. assert( pPager->dbOrigSize==pPager->dbFileSize );
  41514. assert( pPager->dbOrigSize==pPager->dbHintSize );
  41515. assert( pPager->setMaster==0 );
  41516. break;
  41517. case PAGER_WRITER_CACHEMOD:
  41518. assert( p->eLock!=UNKNOWN_LOCK );
  41519. assert( pPager->errCode==SQLITE_OK );
  41520. if( !pagerUseWal(pPager) ){
  41521. /* It is possible that if journal_mode=wal here that neither the
  41522. ** journal file nor the WAL file are open. This happens during
  41523. ** a rollback transaction that switches from journal_mode=off
  41524. ** to journal_mode=wal.
  41525. */
  41526. assert( p->eLock>=RESERVED_LOCK );
  41527. assert( isOpen(p->jfd)
  41528. || p->journalMode==PAGER_JOURNALMODE_OFF
  41529. || p->journalMode==PAGER_JOURNALMODE_WAL
  41530. );
  41531. }
  41532. assert( pPager->dbOrigSize==pPager->dbFileSize );
  41533. assert( pPager->dbOrigSize==pPager->dbHintSize );
  41534. break;
  41535. case PAGER_WRITER_DBMOD:
  41536. assert( p->eLock==EXCLUSIVE_LOCK );
  41537. assert( pPager->errCode==SQLITE_OK );
  41538. assert( !pagerUseWal(pPager) );
  41539. assert( p->eLock>=EXCLUSIVE_LOCK );
  41540. assert( isOpen(p->jfd)
  41541. || p->journalMode==PAGER_JOURNALMODE_OFF
  41542. || p->journalMode==PAGER_JOURNALMODE_WAL
  41543. );
  41544. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  41545. break;
  41546. case PAGER_WRITER_FINISHED:
  41547. assert( p->eLock==EXCLUSIVE_LOCK );
  41548. assert( pPager->errCode==SQLITE_OK );
  41549. assert( !pagerUseWal(pPager) );
  41550. assert( isOpen(p->jfd)
  41551. || p->journalMode==PAGER_JOURNALMODE_OFF
  41552. || p->journalMode==PAGER_JOURNALMODE_WAL
  41553. );
  41554. break;
  41555. case PAGER_ERROR:
  41556. /* There must be at least one outstanding reference to the pager if
  41557. ** in ERROR state. Otherwise the pager should have already dropped
  41558. ** back to OPEN state.
  41559. */
  41560. assert( pPager->errCode!=SQLITE_OK );
  41561. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  41562. break;
  41563. }
  41564. return 1;
  41565. }
  41566. #endif /* ifndef NDEBUG */
  41567. #ifdef SQLITE_DEBUG
  41568. /*
  41569. ** Return a pointer to a human readable string in a static buffer
  41570. ** containing the state of the Pager object passed as an argument. This
  41571. ** is intended to be used within debuggers. For example, as an alternative
  41572. ** to "print *pPager" in gdb:
  41573. **
  41574. ** (gdb) printf "%s", print_pager_state(pPager)
  41575. */
  41576. static char *print_pager_state(Pager *p){
  41577. static char zRet[1024];
  41578. sqlite3_snprintf(1024, zRet,
  41579. "Filename: %s\n"
  41580. "State: %s errCode=%d\n"
  41581. "Lock: %s\n"
  41582. "Locking mode: locking_mode=%s\n"
  41583. "Journal mode: journal_mode=%s\n"
  41584. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  41585. "Journal: journalOff=%lld journalHdr=%lld\n"
  41586. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  41587. , p->zFilename
  41588. , p->eState==PAGER_OPEN ? "OPEN" :
  41589. p->eState==PAGER_READER ? "READER" :
  41590. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  41591. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  41592. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  41593. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  41594. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  41595. , (int)p->errCode
  41596. , p->eLock==NO_LOCK ? "NO_LOCK" :
  41597. p->eLock==RESERVED_LOCK ? "RESERVED" :
  41598. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  41599. p->eLock==SHARED_LOCK ? "SHARED" :
  41600. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  41601. , p->exclusiveMode ? "exclusive" : "normal"
  41602. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  41603. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  41604. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  41605. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  41606. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  41607. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  41608. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  41609. , p->journalOff, p->journalHdr
  41610. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  41611. );
  41612. return zRet;
  41613. }
  41614. #endif
  41615. /*
  41616. ** Return true if it is necessary to write page *pPg into the sub-journal.
  41617. ** A page needs to be written into the sub-journal if there exists one
  41618. ** or more open savepoints for which:
  41619. **
  41620. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  41621. ** * The bit corresponding to the page-number is not set in
  41622. ** PagerSavepoint.pInSavepoint.
  41623. */
  41624. static int subjRequiresPage(PgHdr *pPg){
  41625. Pager *pPager = pPg->pPager;
  41626. PagerSavepoint *p;
  41627. Pgno pgno = pPg->pgno;
  41628. int i;
  41629. for(i=0; i<pPager->nSavepoint; i++){
  41630. p = &pPager->aSavepoint[i];
  41631. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  41632. return 1;
  41633. }
  41634. }
  41635. return 0;
  41636. }
  41637. #ifdef SQLITE_DEBUG
  41638. /*
  41639. ** Return true if the page is already in the journal file.
  41640. */
  41641. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  41642. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  41643. }
  41644. #endif
  41645. /*
  41646. ** Read a 32-bit integer from the given file descriptor. Store the integer
  41647. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  41648. ** error code is something goes wrong.
  41649. **
  41650. ** All values are stored on disk as big-endian.
  41651. */
  41652. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  41653. unsigned char ac[4];
  41654. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  41655. if( rc==SQLITE_OK ){
  41656. *pRes = sqlite3Get4byte(ac);
  41657. }
  41658. return rc;
  41659. }
  41660. /*
  41661. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  41662. */
  41663. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  41664. /*
  41665. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  41666. ** on success or an error code is something goes wrong.
  41667. */
  41668. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  41669. char ac[4];
  41670. put32bits(ac, val);
  41671. return sqlite3OsWrite(fd, ac, 4, offset);
  41672. }
  41673. /*
  41674. ** Unlock the database file to level eLock, which must be either NO_LOCK
  41675. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  41676. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  41677. **
  41678. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  41679. ** called, do not modify it. See the comment above the #define of
  41680. ** UNKNOWN_LOCK for an explanation of this.
  41681. */
  41682. static int pagerUnlockDb(Pager *pPager, int eLock){
  41683. int rc = SQLITE_OK;
  41684. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  41685. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  41686. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  41687. if( isOpen(pPager->fd) ){
  41688. assert( pPager->eLock>=eLock );
  41689. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  41690. if( pPager->eLock!=UNKNOWN_LOCK ){
  41691. pPager->eLock = (u8)eLock;
  41692. }
  41693. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  41694. }
  41695. return rc;
  41696. }
  41697. /*
  41698. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  41699. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  41700. ** Pager.eLock variable to the new locking state.
  41701. **
  41702. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  41703. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  41704. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  41705. ** of this.
  41706. */
  41707. static int pagerLockDb(Pager *pPager, int eLock){
  41708. int rc = SQLITE_OK;
  41709. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  41710. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  41711. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  41712. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  41713. pPager->eLock = (u8)eLock;
  41714. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  41715. }
  41716. }
  41717. return rc;
  41718. }
  41719. /*
  41720. ** This function determines whether or not the atomic-write optimization
  41721. ** can be used with this pager. The optimization can be used if:
  41722. **
  41723. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  41724. ** a database page may be written atomically, and
  41725. ** (b) the value returned by OsSectorSize() is less than or equal
  41726. ** to the page size.
  41727. **
  41728. ** The optimization is also always enabled for temporary files. It is
  41729. ** an error to call this function if pPager is opened on an in-memory
  41730. ** database.
  41731. **
  41732. ** If the optimization cannot be used, 0 is returned. If it can be used,
  41733. ** then the value returned is the size of the journal file when it
  41734. ** contains rollback data for exactly one page.
  41735. */
  41736. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  41737. static int jrnlBufferSize(Pager *pPager){
  41738. assert( !MEMDB );
  41739. if( !pPager->tempFile ){
  41740. int dc; /* Device characteristics */
  41741. int nSector; /* Sector size */
  41742. int szPage; /* Page size */
  41743. assert( isOpen(pPager->fd) );
  41744. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  41745. nSector = pPager->sectorSize;
  41746. szPage = pPager->pageSize;
  41747. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  41748. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  41749. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  41750. return 0;
  41751. }
  41752. }
  41753. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  41754. }
  41755. #endif
  41756. /*
  41757. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  41758. ** on the cache using a hash function. This is used for testing
  41759. ** and debugging only.
  41760. */
  41761. #ifdef SQLITE_CHECK_PAGES
  41762. /*
  41763. ** Return a 32-bit hash of the page data for pPage.
  41764. */
  41765. static u32 pager_datahash(int nByte, unsigned char *pData){
  41766. u32 hash = 0;
  41767. int i;
  41768. for(i=0; i<nByte; i++){
  41769. hash = (hash*1039) + pData[i];
  41770. }
  41771. return hash;
  41772. }
  41773. static u32 pager_pagehash(PgHdr *pPage){
  41774. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  41775. }
  41776. static void pager_set_pagehash(PgHdr *pPage){
  41777. pPage->pageHash = pager_pagehash(pPage);
  41778. }
  41779. /*
  41780. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  41781. ** is defined, and NDEBUG is not defined, an assert() statement checks
  41782. ** that the page is either dirty or still matches the calculated page-hash.
  41783. */
  41784. #define CHECK_PAGE(x) checkPage(x)
  41785. static void checkPage(PgHdr *pPg){
  41786. Pager *pPager = pPg->pPager;
  41787. assert( pPager->eState!=PAGER_ERROR );
  41788. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  41789. }
  41790. #else
  41791. #define pager_datahash(X,Y) 0
  41792. #define pager_pagehash(X) 0
  41793. #define pager_set_pagehash(X)
  41794. #define CHECK_PAGE(x)
  41795. #endif /* SQLITE_CHECK_PAGES */
  41796. /*
  41797. ** When this is called the journal file for pager pPager must be open.
  41798. ** This function attempts to read a master journal file name from the
  41799. ** end of the file and, if successful, copies it into memory supplied
  41800. ** by the caller. See comments above writeMasterJournal() for the format
  41801. ** used to store a master journal file name at the end of a journal file.
  41802. **
  41803. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  41804. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  41805. ** enough space to write the master journal name). If the master journal
  41806. ** name in the journal is longer than nMaster bytes (including a
  41807. ** nul-terminator), then this is handled as if no master journal name
  41808. ** were present in the journal.
  41809. **
  41810. ** If a master journal file name is present at the end of the journal
  41811. ** file, then it is copied into the buffer pointed to by zMaster. A
  41812. ** nul-terminator byte is appended to the buffer following the master
  41813. ** journal file name.
  41814. **
  41815. ** If it is determined that no master journal file name is present
  41816. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  41817. **
  41818. ** If an error occurs while reading from the journal file, an SQLite
  41819. ** error code is returned.
  41820. */
  41821. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  41822. int rc; /* Return code */
  41823. u32 len; /* Length in bytes of master journal name */
  41824. i64 szJ; /* Total size in bytes of journal file pJrnl */
  41825. u32 cksum; /* MJ checksum value read from journal */
  41826. u32 u; /* Unsigned loop counter */
  41827. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  41828. zMaster[0] = '\0';
  41829. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  41830. || szJ<16
  41831. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  41832. || len>=nMaster
  41833. || len==0
  41834. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  41835. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  41836. || memcmp(aMagic, aJournalMagic, 8)
  41837. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  41838. ){
  41839. return rc;
  41840. }
  41841. /* See if the checksum matches the master journal name */
  41842. for(u=0; u<len; u++){
  41843. cksum -= zMaster[u];
  41844. }
  41845. if( cksum ){
  41846. /* If the checksum doesn't add up, then one or more of the disk sectors
  41847. ** containing the master journal filename is corrupted. This means
  41848. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  41849. ** master-journal filename.
  41850. */
  41851. len = 0;
  41852. }
  41853. zMaster[len] = '\0';
  41854. return SQLITE_OK;
  41855. }
  41856. /*
  41857. ** Return the offset of the sector boundary at or immediately
  41858. ** following the value in pPager->journalOff, assuming a sector
  41859. ** size of pPager->sectorSize bytes.
  41860. **
  41861. ** i.e for a sector size of 512:
  41862. **
  41863. ** Pager.journalOff Return value
  41864. ** ---------------------------------------
  41865. ** 0 0
  41866. ** 512 512
  41867. ** 100 512
  41868. ** 2000 2048
  41869. **
  41870. */
  41871. static i64 journalHdrOffset(Pager *pPager){
  41872. i64 offset = 0;
  41873. i64 c = pPager->journalOff;
  41874. if( c ){
  41875. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  41876. }
  41877. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  41878. assert( offset>=c );
  41879. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  41880. return offset;
  41881. }
  41882. /*
  41883. ** The journal file must be open when this function is called.
  41884. **
  41885. ** This function is a no-op if the journal file has not been written to
  41886. ** within the current transaction (i.e. if Pager.journalOff==0).
  41887. **
  41888. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  41889. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  41890. ** zero the 28-byte header at the start of the journal file. In either case,
  41891. ** if the pager is not in no-sync mode, sync the journal file immediately
  41892. ** after writing or truncating it.
  41893. **
  41894. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  41895. ** following the truncation or zeroing described above the size of the
  41896. ** journal file in bytes is larger than this value, then truncate the
  41897. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  41898. ** not need to be synced following this operation.
  41899. **
  41900. ** If an IO error occurs, abandon processing and return the IO error code.
  41901. ** Otherwise, return SQLITE_OK.
  41902. */
  41903. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  41904. int rc = SQLITE_OK; /* Return code */
  41905. assert( isOpen(pPager->jfd) );
  41906. if( pPager->journalOff ){
  41907. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  41908. IOTRACE(("JZEROHDR %p\n", pPager))
  41909. if( doTruncate || iLimit==0 ){
  41910. rc = sqlite3OsTruncate(pPager->jfd, 0);
  41911. }else{
  41912. static const char zeroHdr[28] = {0};
  41913. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  41914. }
  41915. if( rc==SQLITE_OK && !pPager->noSync ){
  41916. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  41917. }
  41918. /* At this point the transaction is committed but the write lock
  41919. ** is still held on the file. If there is a size limit configured for
  41920. ** the persistent journal and the journal file currently consumes more
  41921. ** space than that limit allows for, truncate it now. There is no need
  41922. ** to sync the file following this operation.
  41923. */
  41924. if( rc==SQLITE_OK && iLimit>0 ){
  41925. i64 sz;
  41926. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  41927. if( rc==SQLITE_OK && sz>iLimit ){
  41928. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  41929. }
  41930. }
  41931. }
  41932. return rc;
  41933. }
  41934. /*
  41935. ** The journal file must be open when this routine is called. A journal
  41936. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  41937. ** current location.
  41938. **
  41939. ** The format for the journal header is as follows:
  41940. ** - 8 bytes: Magic identifying journal format.
  41941. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  41942. ** - 4 bytes: Random number used for page hash.
  41943. ** - 4 bytes: Initial database page count.
  41944. ** - 4 bytes: Sector size used by the process that wrote this journal.
  41945. ** - 4 bytes: Database page size.
  41946. **
  41947. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  41948. */
  41949. static int writeJournalHdr(Pager *pPager){
  41950. int rc = SQLITE_OK; /* Return code */
  41951. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  41952. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  41953. u32 nWrite; /* Bytes of header sector written */
  41954. int ii; /* Loop counter */
  41955. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  41956. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  41957. nHeader = JOURNAL_HDR_SZ(pPager);
  41958. }
  41959. /* If there are active savepoints and any of them were created
  41960. ** since the most recent journal header was written, update the
  41961. ** PagerSavepoint.iHdrOffset fields now.
  41962. */
  41963. for(ii=0; ii<pPager->nSavepoint; ii++){
  41964. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  41965. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  41966. }
  41967. }
  41968. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  41969. /*
  41970. ** Write the nRec Field - the number of page records that follow this
  41971. ** journal header. Normally, zero is written to this value at this time.
  41972. ** After the records are added to the journal (and the journal synced,
  41973. ** if in full-sync mode), the zero is overwritten with the true number
  41974. ** of records (see syncJournal()).
  41975. **
  41976. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  41977. ** reading the journal this value tells SQLite to assume that the
  41978. ** rest of the journal file contains valid page records. This assumption
  41979. ** is dangerous, as if a failure occurred whilst writing to the journal
  41980. ** file it may contain some garbage data. There are two scenarios
  41981. ** where this risk can be ignored:
  41982. **
  41983. ** * When the pager is in no-sync mode. Corruption can follow a
  41984. ** power failure in this case anyway.
  41985. **
  41986. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  41987. ** that garbage data is never appended to the journal file.
  41988. */
  41989. assert( isOpen(pPager->fd) || pPager->noSync );
  41990. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  41991. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  41992. ){
  41993. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  41994. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  41995. }else{
  41996. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  41997. }
  41998. /* The random check-hash initializer */
  41999. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  42000. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  42001. /* The initial database size */
  42002. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  42003. /* The assumed sector size for this process */
  42004. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  42005. /* The page size */
  42006. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  42007. /* Initializing the tail of the buffer is not necessary. Everything
  42008. ** works find if the following memset() is omitted. But initializing
  42009. ** the memory prevents valgrind from complaining, so we are willing to
  42010. ** take the performance hit.
  42011. */
  42012. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  42013. nHeader-(sizeof(aJournalMagic)+20));
  42014. /* In theory, it is only necessary to write the 28 bytes that the
  42015. ** journal header consumes to the journal file here. Then increment the
  42016. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  42017. ** record is written to the following sector (leaving a gap in the file
  42018. ** that will be implicitly filled in by the OS).
  42019. **
  42020. ** However it has been discovered that on some systems this pattern can
  42021. ** be significantly slower than contiguously writing data to the file,
  42022. ** even if that means explicitly writing data to the block of
  42023. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  42024. ** is done.
  42025. **
  42026. ** The loop is required here in case the sector-size is larger than the
  42027. ** database page size. Since the zHeader buffer is only Pager.pageSize
  42028. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  42029. ** to populate the entire journal header sector.
  42030. */
  42031. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  42032. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  42033. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  42034. assert( pPager->journalHdr <= pPager->journalOff );
  42035. pPager->journalOff += nHeader;
  42036. }
  42037. return rc;
  42038. }
  42039. /*
  42040. ** The journal file must be open when this is called. A journal header file
  42041. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  42042. ** file. The current location in the journal file is given by
  42043. ** pPager->journalOff. See comments above function writeJournalHdr() for
  42044. ** a description of the journal header format.
  42045. **
  42046. ** If the header is read successfully, *pNRec is set to the number of
  42047. ** page records following this header and *pDbSize is set to the size of the
  42048. ** database before the transaction began, in pages. Also, pPager->cksumInit
  42049. ** is set to the value read from the journal header. SQLITE_OK is returned
  42050. ** in this case.
  42051. **
  42052. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  42053. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  42054. ** cannot be read from the journal file an error code is returned.
  42055. */
  42056. static int readJournalHdr(
  42057. Pager *pPager, /* Pager object */
  42058. int isHot,
  42059. i64 journalSize, /* Size of the open journal file in bytes */
  42060. u32 *pNRec, /* OUT: Value read from the nRec field */
  42061. u32 *pDbSize /* OUT: Value of original database size field */
  42062. ){
  42063. int rc; /* Return code */
  42064. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  42065. i64 iHdrOff; /* Offset of journal header being read */
  42066. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  42067. /* Advance Pager.journalOff to the start of the next sector. If the
  42068. ** journal file is too small for there to be a header stored at this
  42069. ** point, return SQLITE_DONE.
  42070. */
  42071. pPager->journalOff = journalHdrOffset(pPager);
  42072. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  42073. return SQLITE_DONE;
  42074. }
  42075. iHdrOff = pPager->journalOff;
  42076. /* Read in the first 8 bytes of the journal header. If they do not match
  42077. ** the magic string found at the start of each journal header, return
  42078. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  42079. ** proceed.
  42080. */
  42081. if( isHot || iHdrOff!=pPager->journalHdr ){
  42082. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  42083. if( rc ){
  42084. return rc;
  42085. }
  42086. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  42087. return SQLITE_DONE;
  42088. }
  42089. }
  42090. /* Read the first three 32-bit fields of the journal header: The nRec
  42091. ** field, the checksum-initializer and the database size at the start
  42092. ** of the transaction. Return an error code if anything goes wrong.
  42093. */
  42094. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  42095. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  42096. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  42097. ){
  42098. return rc;
  42099. }
  42100. if( pPager->journalOff==0 ){
  42101. u32 iPageSize; /* Page-size field of journal header */
  42102. u32 iSectorSize; /* Sector-size field of journal header */
  42103. /* Read the page-size and sector-size journal header fields. */
  42104. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  42105. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  42106. ){
  42107. return rc;
  42108. }
  42109. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  42110. ** journal header to zero. In this case, assume that the Pager.pageSize
  42111. ** variable is already set to the correct page size.
  42112. */
  42113. if( iPageSize==0 ){
  42114. iPageSize = pPager->pageSize;
  42115. }
  42116. /* Check that the values read from the page-size and sector-size fields
  42117. ** are within range. To be 'in range', both values need to be a power
  42118. ** of two greater than or equal to 512 or 32, and not greater than their
  42119. ** respective compile time maximum limits.
  42120. */
  42121. if( iPageSize<512 || iSectorSize<32
  42122. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  42123. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  42124. ){
  42125. /* If the either the page-size or sector-size in the journal-header is
  42126. ** invalid, then the process that wrote the journal-header must have
  42127. ** crashed before the header was synced. In this case stop reading
  42128. ** the journal file here.
  42129. */
  42130. return SQLITE_DONE;
  42131. }
  42132. /* Update the page-size to match the value read from the journal.
  42133. ** Use a testcase() macro to make sure that malloc failure within
  42134. ** PagerSetPagesize() is tested.
  42135. */
  42136. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  42137. testcase( rc!=SQLITE_OK );
  42138. /* Update the assumed sector-size to match the value used by
  42139. ** the process that created this journal. If this journal was
  42140. ** created by a process other than this one, then this routine
  42141. ** is being called from within pager_playback(). The local value
  42142. ** of Pager.sectorSize is restored at the end of that routine.
  42143. */
  42144. pPager->sectorSize = iSectorSize;
  42145. }
  42146. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  42147. return rc;
  42148. }
  42149. /*
  42150. ** Write the supplied master journal name into the journal file for pager
  42151. ** pPager at the current location. The master journal name must be the last
  42152. ** thing written to a journal file. If the pager is in full-sync mode, the
  42153. ** journal file descriptor is advanced to the next sector boundary before
  42154. ** anything is written. The format is:
  42155. **
  42156. ** + 4 bytes: PAGER_MJ_PGNO.
  42157. ** + N bytes: Master journal filename in utf-8.
  42158. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  42159. ** + 4 bytes: Master journal name checksum.
  42160. ** + 8 bytes: aJournalMagic[].
  42161. **
  42162. ** The master journal page checksum is the sum of the bytes in the master
  42163. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  42164. **
  42165. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  42166. ** this call is a no-op.
  42167. */
  42168. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  42169. int rc; /* Return code */
  42170. int nMaster; /* Length of string zMaster */
  42171. i64 iHdrOff; /* Offset of header in journal file */
  42172. i64 jrnlSize; /* Size of journal file on disk */
  42173. u32 cksum = 0; /* Checksum of string zMaster */
  42174. assert( pPager->setMaster==0 );
  42175. assert( !pagerUseWal(pPager) );
  42176. if( !zMaster
  42177. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  42178. || !isOpen(pPager->jfd)
  42179. ){
  42180. return SQLITE_OK;
  42181. }
  42182. pPager->setMaster = 1;
  42183. assert( pPager->journalHdr <= pPager->journalOff );
  42184. /* Calculate the length in bytes and the checksum of zMaster */
  42185. for(nMaster=0; zMaster[nMaster]; nMaster++){
  42186. cksum += zMaster[nMaster];
  42187. }
  42188. /* If in full-sync mode, advance to the next disk sector before writing
  42189. ** the master journal name. This is in case the previous page written to
  42190. ** the journal has already been synced.
  42191. */
  42192. if( pPager->fullSync ){
  42193. pPager->journalOff = journalHdrOffset(pPager);
  42194. }
  42195. iHdrOff = pPager->journalOff;
  42196. /* Write the master journal data to the end of the journal file. If
  42197. ** an error occurs, return the error code to the caller.
  42198. */
  42199. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  42200. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  42201. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  42202. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  42203. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  42204. iHdrOff+4+nMaster+8)))
  42205. ){
  42206. return rc;
  42207. }
  42208. pPager->journalOff += (nMaster+20);
  42209. /* If the pager is in peristent-journal mode, then the physical
  42210. ** journal-file may extend past the end of the master-journal name
  42211. ** and 8 bytes of magic data just written to the file. This is
  42212. ** dangerous because the code to rollback a hot-journal file
  42213. ** will not be able to find the master-journal name to determine
  42214. ** whether or not the journal is hot.
  42215. **
  42216. ** Easiest thing to do in this scenario is to truncate the journal
  42217. ** file to the required size.
  42218. */
  42219. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  42220. && jrnlSize>pPager->journalOff
  42221. ){
  42222. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  42223. }
  42224. return rc;
  42225. }
  42226. /*
  42227. ** Discard the entire contents of the in-memory page-cache.
  42228. */
  42229. static void pager_reset(Pager *pPager){
  42230. pPager->iDataVersion++;
  42231. sqlite3BackupRestart(pPager->pBackup);
  42232. sqlite3PcacheClear(pPager->pPCache);
  42233. }
  42234. /*
  42235. ** Return the pPager->iDataVersion value
  42236. */
  42237. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  42238. assert( pPager->eState>PAGER_OPEN );
  42239. return pPager->iDataVersion;
  42240. }
  42241. /*
  42242. ** Free all structures in the Pager.aSavepoint[] array and set both
  42243. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  42244. ** if it is open and the pager is not in exclusive mode.
  42245. */
  42246. static void releaseAllSavepoints(Pager *pPager){
  42247. int ii; /* Iterator for looping through Pager.aSavepoint */
  42248. for(ii=0; ii<pPager->nSavepoint; ii++){
  42249. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  42250. }
  42251. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  42252. sqlite3OsClose(pPager->sjfd);
  42253. }
  42254. sqlite3_free(pPager->aSavepoint);
  42255. pPager->aSavepoint = 0;
  42256. pPager->nSavepoint = 0;
  42257. pPager->nSubRec = 0;
  42258. }
  42259. /*
  42260. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  42261. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  42262. ** or SQLITE_NOMEM if a malloc failure occurs.
  42263. */
  42264. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  42265. int ii; /* Loop counter */
  42266. int rc = SQLITE_OK; /* Result code */
  42267. for(ii=0; ii<pPager->nSavepoint; ii++){
  42268. PagerSavepoint *p = &pPager->aSavepoint[ii];
  42269. if( pgno<=p->nOrig ){
  42270. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  42271. testcase( rc==SQLITE_NOMEM );
  42272. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  42273. }
  42274. }
  42275. return rc;
  42276. }
  42277. /*
  42278. ** This function is a no-op if the pager is in exclusive mode and not
  42279. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  42280. ** state.
  42281. **
  42282. ** If the pager is not in exclusive-access mode, the database file is
  42283. ** completely unlocked. If the file is unlocked and the file-system does
  42284. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  42285. ** closed (if it is open).
  42286. **
  42287. ** If the pager is in ERROR state when this function is called, the
  42288. ** contents of the pager cache are discarded before switching back to
  42289. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  42290. ** or not, any journal file left in the file-system will be treated
  42291. ** as a hot-journal and rolled back the next time a read-transaction
  42292. ** is opened (by this or by any other connection).
  42293. */
  42294. static void pager_unlock(Pager *pPager){
  42295. assert( pPager->eState==PAGER_READER
  42296. || pPager->eState==PAGER_OPEN
  42297. || pPager->eState==PAGER_ERROR
  42298. );
  42299. sqlite3BitvecDestroy(pPager->pInJournal);
  42300. pPager->pInJournal = 0;
  42301. releaseAllSavepoints(pPager);
  42302. if( pagerUseWal(pPager) ){
  42303. assert( !isOpen(pPager->jfd) );
  42304. sqlite3WalEndReadTransaction(pPager->pWal);
  42305. pPager->eState = PAGER_OPEN;
  42306. }else if( !pPager->exclusiveMode ){
  42307. int rc; /* Error code returned by pagerUnlockDb() */
  42308. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  42309. /* If the operating system support deletion of open files, then
  42310. ** close the journal file when dropping the database lock. Otherwise
  42311. ** another connection with journal_mode=delete might delete the file
  42312. ** out from under us.
  42313. */
  42314. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  42315. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  42316. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  42317. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  42318. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  42319. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  42320. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  42321. || 1!=(pPager->journalMode & 5)
  42322. ){
  42323. sqlite3OsClose(pPager->jfd);
  42324. }
  42325. /* If the pager is in the ERROR state and the call to unlock the database
  42326. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  42327. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  42328. ** is necessary.
  42329. */
  42330. rc = pagerUnlockDb(pPager, NO_LOCK);
  42331. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  42332. pPager->eLock = UNKNOWN_LOCK;
  42333. }
  42334. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  42335. ** without clearing the error code. This is intentional - the error
  42336. ** code is cleared and the cache reset in the block below.
  42337. */
  42338. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  42339. pPager->changeCountDone = 0;
  42340. pPager->eState = PAGER_OPEN;
  42341. }
  42342. /* If Pager.errCode is set, the contents of the pager cache cannot be
  42343. ** trusted. Now that there are no outstanding references to the pager,
  42344. ** it can safely move back to PAGER_OPEN state. This happens in both
  42345. ** normal and exclusive-locking mode.
  42346. */
  42347. if( pPager->errCode ){
  42348. assert( !MEMDB );
  42349. pager_reset(pPager);
  42350. pPager->changeCountDone = pPager->tempFile;
  42351. pPager->eState = PAGER_OPEN;
  42352. pPager->errCode = SQLITE_OK;
  42353. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  42354. }
  42355. pPager->journalOff = 0;
  42356. pPager->journalHdr = 0;
  42357. pPager->setMaster = 0;
  42358. }
  42359. /*
  42360. ** This function is called whenever an IOERR or FULL error that requires
  42361. ** the pager to transition into the ERROR state may ahve occurred.
  42362. ** The first argument is a pointer to the pager structure, the second
  42363. ** the error-code about to be returned by a pager API function. The
  42364. ** value returned is a copy of the second argument to this function.
  42365. **
  42366. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  42367. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  42368. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  42369. ** all major API calls on the Pager will immediately return Pager.errCode.
  42370. **
  42371. ** The ERROR state indicates that the contents of the pager-cache
  42372. ** cannot be trusted. This state can be cleared by completely discarding
  42373. ** the contents of the pager-cache. If a transaction was active when
  42374. ** the persistent error occurred, then the rollback journal may need
  42375. ** to be replayed to restore the contents of the database file (as if
  42376. ** it were a hot-journal).
  42377. */
  42378. static int pager_error(Pager *pPager, int rc){
  42379. int rc2 = rc & 0xff;
  42380. assert( rc==SQLITE_OK || !MEMDB );
  42381. assert(
  42382. pPager->errCode==SQLITE_FULL ||
  42383. pPager->errCode==SQLITE_OK ||
  42384. (pPager->errCode & 0xff)==SQLITE_IOERR
  42385. );
  42386. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  42387. pPager->errCode = rc;
  42388. pPager->eState = PAGER_ERROR;
  42389. }
  42390. return rc;
  42391. }
  42392. static int pager_truncate(Pager *pPager, Pgno nPage);
  42393. /*
  42394. ** This routine ends a transaction. A transaction is usually ended by
  42395. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  42396. ** after rollback of a hot-journal, or if an error occurs while opening
  42397. ** the journal file or writing the very first journal-header of a
  42398. ** database transaction.
  42399. **
  42400. ** This routine is never called in PAGER_ERROR state. If it is called
  42401. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  42402. ** exclusive than a RESERVED lock, it is a no-op.
  42403. **
  42404. ** Otherwise, any active savepoints are released.
  42405. **
  42406. ** If the journal file is open, then it is "finalized". Once a journal
  42407. ** file has been finalized it is not possible to use it to roll back a
  42408. ** transaction. Nor will it be considered to be a hot-journal by this
  42409. ** or any other database connection. Exactly how a journal is finalized
  42410. ** depends on whether or not the pager is running in exclusive mode and
  42411. ** the current journal-mode (Pager.journalMode value), as follows:
  42412. **
  42413. ** journalMode==MEMORY
  42414. ** Journal file descriptor is simply closed. This destroys an
  42415. ** in-memory journal.
  42416. **
  42417. ** journalMode==TRUNCATE
  42418. ** Journal file is truncated to zero bytes in size.
  42419. **
  42420. ** journalMode==PERSIST
  42421. ** The first 28 bytes of the journal file are zeroed. This invalidates
  42422. ** the first journal header in the file, and hence the entire journal
  42423. ** file. An invalid journal file cannot be rolled back.
  42424. **
  42425. ** journalMode==DELETE
  42426. ** The journal file is closed and deleted using sqlite3OsDelete().
  42427. **
  42428. ** If the pager is running in exclusive mode, this method of finalizing
  42429. ** the journal file is never used. Instead, if the journalMode is
  42430. ** DELETE and the pager is in exclusive mode, the method described under
  42431. ** journalMode==PERSIST is used instead.
  42432. **
  42433. ** After the journal is finalized, the pager moves to PAGER_READER state.
  42434. ** If running in non-exclusive rollback mode, the lock on the file is
  42435. ** downgraded to a SHARED_LOCK.
  42436. **
  42437. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  42438. ** any of the IO operations to finalize the journal file or unlock the
  42439. ** database then the IO error code is returned to the user. If the
  42440. ** operation to finalize the journal file fails, then the code still
  42441. ** tries to unlock the database file if not in exclusive mode. If the
  42442. ** unlock operation fails as well, then the first error code related
  42443. ** to the first error encountered (the journal finalization one) is
  42444. ** returned.
  42445. */
  42446. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  42447. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  42448. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  42449. /* Do nothing if the pager does not have an open write transaction
  42450. ** or at least a RESERVED lock. This function may be called when there
  42451. ** is no write-transaction active but a RESERVED or greater lock is
  42452. ** held under two circumstances:
  42453. **
  42454. ** 1. After a successful hot-journal rollback, it is called with
  42455. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  42456. **
  42457. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  42458. ** lock switches back to locking_mode=normal and then executes a
  42459. ** read-transaction, this function is called with eState==PAGER_READER
  42460. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  42461. */
  42462. assert( assert_pager_state(pPager) );
  42463. assert( pPager->eState!=PAGER_ERROR );
  42464. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  42465. return SQLITE_OK;
  42466. }
  42467. releaseAllSavepoints(pPager);
  42468. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  42469. if( isOpen(pPager->jfd) ){
  42470. assert( !pagerUseWal(pPager) );
  42471. /* Finalize the journal file. */
  42472. if( sqlite3IsMemJournal(pPager->jfd) ){
  42473. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  42474. sqlite3OsClose(pPager->jfd);
  42475. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  42476. if( pPager->journalOff==0 ){
  42477. rc = SQLITE_OK;
  42478. }else{
  42479. rc = sqlite3OsTruncate(pPager->jfd, 0);
  42480. if( rc==SQLITE_OK && pPager->fullSync ){
  42481. /* Make sure the new file size is written into the inode right away.
  42482. ** Otherwise the journal might resurrect following a power loss and
  42483. ** cause the last transaction to roll back. See
  42484. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  42485. */
  42486. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  42487. }
  42488. }
  42489. pPager->journalOff = 0;
  42490. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  42491. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  42492. ){
  42493. rc = zeroJournalHdr(pPager, hasMaster);
  42494. pPager->journalOff = 0;
  42495. }else{
  42496. /* This branch may be executed with Pager.journalMode==MEMORY if
  42497. ** a hot-journal was just rolled back. In this case the journal
  42498. ** file should be closed and deleted. If this connection writes to
  42499. ** the database file, it will do so using an in-memory journal.
  42500. */
  42501. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  42502. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  42503. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  42504. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  42505. );
  42506. sqlite3OsClose(pPager->jfd);
  42507. if( bDelete ){
  42508. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  42509. }
  42510. }
  42511. }
  42512. #ifdef SQLITE_CHECK_PAGES
  42513. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  42514. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  42515. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  42516. if( p ){
  42517. p->pageHash = 0;
  42518. sqlite3PagerUnrefNotNull(p);
  42519. }
  42520. }
  42521. #endif
  42522. sqlite3BitvecDestroy(pPager->pInJournal);
  42523. pPager->pInJournal = 0;
  42524. pPager->nRec = 0;
  42525. sqlite3PcacheCleanAll(pPager->pPCache);
  42526. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  42527. if( pagerUseWal(pPager) ){
  42528. /* Drop the WAL write-lock, if any. Also, if the connection was in
  42529. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  42530. ** lock held on the database file.
  42531. */
  42532. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  42533. assert( rc2==SQLITE_OK );
  42534. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  42535. /* This branch is taken when committing a transaction in rollback-journal
  42536. ** mode if the database file on disk is larger than the database image.
  42537. ** At this point the journal has been finalized and the transaction
  42538. ** successfully committed, but the EXCLUSIVE lock is still held on the
  42539. ** file. So it is safe to truncate the database file to its minimum
  42540. ** required size. */
  42541. assert( pPager->eLock==EXCLUSIVE_LOCK );
  42542. rc = pager_truncate(pPager, pPager->dbSize);
  42543. }
  42544. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  42545. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  42546. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  42547. }
  42548. if( !pPager->exclusiveMode
  42549. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  42550. ){
  42551. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  42552. pPager->changeCountDone = 0;
  42553. }
  42554. pPager->eState = PAGER_READER;
  42555. pPager->setMaster = 0;
  42556. return (rc==SQLITE_OK?rc2:rc);
  42557. }
  42558. /*
  42559. ** Execute a rollback if a transaction is active and unlock the
  42560. ** database file.
  42561. **
  42562. ** If the pager has already entered the ERROR state, do not attempt
  42563. ** the rollback at this time. Instead, pager_unlock() is called. The
  42564. ** call to pager_unlock() will discard all in-memory pages, unlock
  42565. ** the database file and move the pager back to OPEN state. If this
  42566. ** means that there is a hot-journal left in the file-system, the next
  42567. ** connection to obtain a shared lock on the pager (which may be this one)
  42568. ** will roll it back.
  42569. **
  42570. ** If the pager has not already entered the ERROR state, but an IO or
  42571. ** malloc error occurs during a rollback, then this will itself cause
  42572. ** the pager to enter the ERROR state. Which will be cleared by the
  42573. ** call to pager_unlock(), as described above.
  42574. */
  42575. static void pagerUnlockAndRollback(Pager *pPager){
  42576. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  42577. assert( assert_pager_state(pPager) );
  42578. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  42579. sqlite3BeginBenignMalloc();
  42580. sqlite3PagerRollback(pPager);
  42581. sqlite3EndBenignMalloc();
  42582. }else if( !pPager->exclusiveMode ){
  42583. assert( pPager->eState==PAGER_READER );
  42584. pager_end_transaction(pPager, 0, 0);
  42585. }
  42586. }
  42587. pager_unlock(pPager);
  42588. }
  42589. /*
  42590. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  42591. ** of data. Compute and return a checksum based ont the contents of the
  42592. ** page of data and the current value of pPager->cksumInit.
  42593. **
  42594. ** This is not a real checksum. It is really just the sum of the
  42595. ** random initial value (pPager->cksumInit) and every 200th byte
  42596. ** of the page data, starting with byte offset (pPager->pageSize%200).
  42597. ** Each byte is interpreted as an 8-bit unsigned integer.
  42598. **
  42599. ** Changing the formula used to compute this checksum results in an
  42600. ** incompatible journal file format.
  42601. **
  42602. ** If journal corruption occurs due to a power failure, the most likely
  42603. ** scenario is that one end or the other of the record will be changed.
  42604. ** It is much less likely that the two ends of the journal record will be
  42605. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  42606. ** though fast and simple, catches the mostly likely kind of corruption.
  42607. */
  42608. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  42609. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  42610. int i = pPager->pageSize-200; /* Loop counter */
  42611. while( i>0 ){
  42612. cksum += aData[i];
  42613. i -= 200;
  42614. }
  42615. return cksum;
  42616. }
  42617. /*
  42618. ** Report the current page size and number of reserved bytes back
  42619. ** to the codec.
  42620. */
  42621. #ifdef SQLITE_HAS_CODEC
  42622. static void pagerReportSize(Pager *pPager){
  42623. if( pPager->xCodecSizeChng ){
  42624. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  42625. (int)pPager->nReserve);
  42626. }
  42627. }
  42628. #else
  42629. # define pagerReportSize(X) /* No-op if we do not support a codec */
  42630. #endif
  42631. #ifdef SQLITE_HAS_CODEC
  42632. /*
  42633. ** Make sure the number of reserved bits is the same in the destination
  42634. ** pager as it is in the source. This comes up when a VACUUM changes the
  42635. ** number of reserved bits to the "optimal" amount.
  42636. */
  42637. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  42638. if( pDest->nReserve!=pSrc->nReserve ){
  42639. pDest->nReserve = pSrc->nReserve;
  42640. pagerReportSize(pDest);
  42641. }
  42642. }
  42643. #endif
  42644. /*
  42645. ** Read a single page from either the journal file (if isMainJrnl==1) or
  42646. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  42647. ** The page begins at offset *pOffset into the file. The *pOffset
  42648. ** value is increased to the start of the next page in the journal.
  42649. **
  42650. ** The main rollback journal uses checksums - the statement journal does
  42651. ** not.
  42652. **
  42653. ** If the page number of the page record read from the (sub-)journal file
  42654. ** is greater than the current value of Pager.dbSize, then playback is
  42655. ** skipped and SQLITE_OK is returned.
  42656. **
  42657. ** If pDone is not NULL, then it is a record of pages that have already
  42658. ** been played back. If the page at *pOffset has already been played back
  42659. ** (if the corresponding pDone bit is set) then skip the playback.
  42660. ** Make sure the pDone bit corresponding to the *pOffset page is set
  42661. ** prior to returning.
  42662. **
  42663. ** If the page record is successfully read from the (sub-)journal file
  42664. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  42665. ** while reading the record from the (sub-)journal file or while writing
  42666. ** to the database file, then the IO error code is returned. If data
  42667. ** is successfully read from the (sub-)journal file but appears to be
  42668. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  42669. ** two circumstances:
  42670. **
  42671. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  42672. ** * If the record is being rolled back from the main journal file
  42673. ** and the checksum field does not match the record content.
  42674. **
  42675. ** Neither of these two scenarios are possible during a savepoint rollback.
  42676. **
  42677. ** If this is a savepoint rollback, then memory may have to be dynamically
  42678. ** allocated by this function. If this is the case and an allocation fails,
  42679. ** SQLITE_NOMEM is returned.
  42680. */
  42681. static int pager_playback_one_page(
  42682. Pager *pPager, /* The pager being played back */
  42683. i64 *pOffset, /* Offset of record to playback */
  42684. Bitvec *pDone, /* Bitvec of pages already played back */
  42685. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  42686. int isSavepnt /* True for a savepoint rollback */
  42687. ){
  42688. int rc;
  42689. PgHdr *pPg; /* An existing page in the cache */
  42690. Pgno pgno; /* The page number of a page in journal */
  42691. u32 cksum; /* Checksum used for sanity checking */
  42692. char *aData; /* Temporary storage for the page */
  42693. sqlite3_file *jfd; /* The file descriptor for the journal file */
  42694. int isSynced; /* True if journal page is synced */
  42695. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  42696. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  42697. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  42698. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  42699. aData = pPager->pTmpSpace;
  42700. assert( aData ); /* Temp storage must have already been allocated */
  42701. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  42702. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  42703. ** or savepoint rollback done at the request of the caller) or this is
  42704. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  42705. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  42706. ** only reads from the main journal, not the sub-journal.
  42707. */
  42708. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  42709. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  42710. );
  42711. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  42712. /* Read the page number and page data from the journal or sub-journal
  42713. ** file. Return an error code to the caller if an IO error occurs.
  42714. */
  42715. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  42716. rc = read32bits(jfd, *pOffset, &pgno);
  42717. if( rc!=SQLITE_OK ) return rc;
  42718. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  42719. if( rc!=SQLITE_OK ) return rc;
  42720. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  42721. /* Sanity checking on the page. This is more important that I originally
  42722. ** thought. If a power failure occurs while the journal is being written,
  42723. ** it could cause invalid data to be written into the journal. We need to
  42724. ** detect this invalid data (with high probability) and ignore it.
  42725. */
  42726. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  42727. assert( !isSavepnt );
  42728. return SQLITE_DONE;
  42729. }
  42730. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  42731. return SQLITE_OK;
  42732. }
  42733. if( isMainJrnl ){
  42734. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  42735. if( rc ) return rc;
  42736. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  42737. return SQLITE_DONE;
  42738. }
  42739. }
  42740. /* If this page has already been played back before during the current
  42741. ** rollback, then don't bother to play it back again.
  42742. */
  42743. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  42744. return rc;
  42745. }
  42746. /* When playing back page 1, restore the nReserve setting
  42747. */
  42748. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  42749. pPager->nReserve = ((u8*)aData)[20];
  42750. pagerReportSize(pPager);
  42751. }
  42752. /* If the pager is in CACHEMOD state, then there must be a copy of this
  42753. ** page in the pager cache. In this case just update the pager cache,
  42754. ** not the database file. The page is left marked dirty in this case.
  42755. **
  42756. ** An exception to the above rule: If the database is in no-sync mode
  42757. ** and a page is moved during an incremental vacuum then the page may
  42758. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  42759. ** during a Movepage() call, then the page may not be in the cache
  42760. ** either. So the condition described in the above paragraph is not
  42761. ** assert()able.
  42762. **
  42763. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  42764. ** pager cache if it exists and the main file. The page is then marked
  42765. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  42766. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  42767. ** if the pager is in OPEN state.
  42768. **
  42769. ** Ticket #1171: The statement journal might contain page content that is
  42770. ** different from the page content at the start of the transaction.
  42771. ** This occurs when a page is changed prior to the start of a statement
  42772. ** then changed again within the statement. When rolling back such a
  42773. ** statement we must not write to the original database unless we know
  42774. ** for certain that original page contents are synced into the main rollback
  42775. ** journal. Otherwise, a power loss might leave modified data in the
  42776. ** database file without an entry in the rollback journal that can
  42777. ** restore the database to its original form. Two conditions must be
  42778. ** met before writing to the database files. (1) the database must be
  42779. ** locked. (2) we know that the original page content is fully synced
  42780. ** in the main journal either because the page is not in cache or else
  42781. ** the page is marked as needSync==0.
  42782. **
  42783. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  42784. ** is possible to fail a statement on a database that does not yet exist.
  42785. ** Do not attempt to write if database file has never been opened.
  42786. */
  42787. if( pagerUseWal(pPager) ){
  42788. pPg = 0;
  42789. }else{
  42790. pPg = sqlite3PagerLookup(pPager, pgno);
  42791. }
  42792. assert( pPg || !MEMDB );
  42793. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  42794. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  42795. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  42796. (isMainJrnl?"main-journal":"sub-journal")
  42797. ));
  42798. if( isMainJrnl ){
  42799. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  42800. }else{
  42801. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  42802. }
  42803. if( isOpen(pPager->fd)
  42804. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  42805. && isSynced
  42806. ){
  42807. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  42808. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  42809. assert( !pagerUseWal(pPager) );
  42810. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  42811. if( pgno>pPager->dbFileSize ){
  42812. pPager->dbFileSize = pgno;
  42813. }
  42814. if( pPager->pBackup ){
  42815. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  42816. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  42817. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  42818. }
  42819. }else if( !isMainJrnl && pPg==0 ){
  42820. /* If this is a rollback of a savepoint and data was not written to
  42821. ** the database and the page is not in-memory, there is a potential
  42822. ** problem. When the page is next fetched by the b-tree layer, it
  42823. ** will be read from the database file, which may or may not be
  42824. ** current.
  42825. **
  42826. ** There are a couple of different ways this can happen. All are quite
  42827. ** obscure. When running in synchronous mode, this can only happen
  42828. ** if the page is on the free-list at the start of the transaction, then
  42829. ** populated, then moved using sqlite3PagerMovepage().
  42830. **
  42831. ** The solution is to add an in-memory page to the cache containing
  42832. ** the data just read from the sub-journal. Mark the page as dirty
  42833. ** and if the pager requires a journal-sync, then mark the page as
  42834. ** requiring a journal-sync before it is written.
  42835. */
  42836. assert( isSavepnt );
  42837. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  42838. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  42839. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  42840. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  42841. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  42842. if( rc!=SQLITE_OK ) return rc;
  42843. pPg->flags &= ~PGHDR_NEED_READ;
  42844. sqlite3PcacheMakeDirty(pPg);
  42845. }
  42846. if( pPg ){
  42847. /* No page should ever be explicitly rolled back that is in use, except
  42848. ** for page 1 which is held in use in order to keep the lock on the
  42849. ** database active. However such a page may be rolled back as a result
  42850. ** of an internal error resulting in an automatic call to
  42851. ** sqlite3PagerRollback().
  42852. */
  42853. void *pData;
  42854. pData = pPg->pData;
  42855. memcpy(pData, (u8*)aData, pPager->pageSize);
  42856. pPager->xReiniter(pPg);
  42857. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  42858. /* If the contents of this page were just restored from the main
  42859. ** journal file, then its content must be as they were when the
  42860. ** transaction was first opened. In this case we can mark the page
  42861. ** as clean, since there will be no need to write it out to the
  42862. ** database.
  42863. **
  42864. ** There is one exception to this rule. If the page is being rolled
  42865. ** back as part of a savepoint (or statement) rollback from an
  42866. ** unsynced portion of the main journal file, then it is not safe
  42867. ** to mark the page as clean. This is because marking the page as
  42868. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  42869. ** already in the journal file (recorded in Pager.pInJournal) and
  42870. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  42871. ** again within this transaction, it will be marked as dirty but
  42872. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  42873. ** be written out into the database file before its journal file
  42874. ** segment is synced. If a crash occurs during or following this,
  42875. ** database corruption may ensue.
  42876. */
  42877. assert( !pagerUseWal(pPager) );
  42878. sqlite3PcacheMakeClean(pPg);
  42879. }
  42880. pager_set_pagehash(pPg);
  42881. /* If this was page 1, then restore the value of Pager.dbFileVers.
  42882. ** Do this before any decoding. */
  42883. if( pgno==1 ){
  42884. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  42885. }
  42886. /* Decode the page just read from disk */
  42887. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  42888. sqlite3PcacheRelease(pPg);
  42889. }
  42890. return rc;
  42891. }
  42892. /*
  42893. ** Parameter zMaster is the name of a master journal file. A single journal
  42894. ** file that referred to the master journal file has just been rolled back.
  42895. ** This routine checks if it is possible to delete the master journal file,
  42896. ** and does so if it is.
  42897. **
  42898. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  42899. ** available for use within this function.
  42900. **
  42901. ** When a master journal file is created, it is populated with the names
  42902. ** of all of its child journals, one after another, formatted as utf-8
  42903. ** encoded text. The end of each child journal file is marked with a
  42904. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  42905. ** file for a transaction involving two databases might be:
  42906. **
  42907. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  42908. **
  42909. ** A master journal file may only be deleted once all of its child
  42910. ** journals have been rolled back.
  42911. **
  42912. ** This function reads the contents of the master-journal file into
  42913. ** memory and loops through each of the child journal names. For
  42914. ** each child journal, it checks if:
  42915. **
  42916. ** * if the child journal exists, and if so
  42917. ** * if the child journal contains a reference to master journal
  42918. ** file zMaster
  42919. **
  42920. ** If a child journal can be found that matches both of the criteria
  42921. ** above, this function returns without doing anything. Otherwise, if
  42922. ** no such child journal can be found, file zMaster is deleted from
  42923. ** the file-system using sqlite3OsDelete().
  42924. **
  42925. ** If an IO error within this function, an error code is returned. This
  42926. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  42927. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  42928. ** occur, SQLITE_OK is returned.
  42929. **
  42930. ** TODO: This function allocates a single block of memory to load
  42931. ** the entire contents of the master journal file. This could be
  42932. ** a couple of kilobytes or so - potentially larger than the page
  42933. ** size.
  42934. */
  42935. static int pager_delmaster(Pager *pPager, const char *zMaster){
  42936. sqlite3_vfs *pVfs = pPager->pVfs;
  42937. int rc; /* Return code */
  42938. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  42939. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  42940. char *zMasterJournal = 0; /* Contents of master journal file */
  42941. i64 nMasterJournal; /* Size of master journal file */
  42942. char *zJournal; /* Pointer to one journal within MJ file */
  42943. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  42944. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  42945. /* Allocate space for both the pJournal and pMaster file descriptors.
  42946. ** If successful, open the master journal file for reading.
  42947. */
  42948. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  42949. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  42950. if( !pMaster ){
  42951. rc = SQLITE_NOMEM;
  42952. }else{
  42953. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  42954. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  42955. }
  42956. if( rc!=SQLITE_OK ) goto delmaster_out;
  42957. /* Load the entire master journal file into space obtained from
  42958. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  42959. ** sufficient space (in zMasterPtr) to hold the names of master
  42960. ** journal files extracted from regular rollback-journals.
  42961. */
  42962. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  42963. if( rc!=SQLITE_OK ) goto delmaster_out;
  42964. nMasterPtr = pVfs->mxPathname+1;
  42965. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  42966. if( !zMasterJournal ){
  42967. rc = SQLITE_NOMEM;
  42968. goto delmaster_out;
  42969. }
  42970. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  42971. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  42972. if( rc!=SQLITE_OK ) goto delmaster_out;
  42973. zMasterJournal[nMasterJournal] = 0;
  42974. zJournal = zMasterJournal;
  42975. while( (zJournal-zMasterJournal)<nMasterJournal ){
  42976. int exists;
  42977. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  42978. if( rc!=SQLITE_OK ){
  42979. goto delmaster_out;
  42980. }
  42981. if( exists ){
  42982. /* One of the journals pointed to by the master journal exists.
  42983. ** Open it and check if it points at the master journal. If
  42984. ** so, return without deleting the master journal file.
  42985. */
  42986. int c;
  42987. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  42988. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  42989. if( rc!=SQLITE_OK ){
  42990. goto delmaster_out;
  42991. }
  42992. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  42993. sqlite3OsClose(pJournal);
  42994. if( rc!=SQLITE_OK ){
  42995. goto delmaster_out;
  42996. }
  42997. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  42998. if( c ){
  42999. /* We have a match. Do not delete the master journal file. */
  43000. goto delmaster_out;
  43001. }
  43002. }
  43003. zJournal += (sqlite3Strlen30(zJournal)+1);
  43004. }
  43005. sqlite3OsClose(pMaster);
  43006. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  43007. delmaster_out:
  43008. sqlite3_free(zMasterJournal);
  43009. if( pMaster ){
  43010. sqlite3OsClose(pMaster);
  43011. assert( !isOpen(pJournal) );
  43012. sqlite3_free(pMaster);
  43013. }
  43014. return rc;
  43015. }
  43016. /*
  43017. ** This function is used to change the actual size of the database
  43018. ** file in the file-system. This only happens when committing a transaction,
  43019. ** or rolling back a transaction (including rolling back a hot-journal).
  43020. **
  43021. ** If the main database file is not open, or the pager is not in either
  43022. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  43023. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  43024. ** If the file on disk is currently larger than nPage pages, then use the VFS
  43025. ** xTruncate() method to truncate it.
  43026. **
  43027. ** Or, it might be the case that the file on disk is smaller than
  43028. ** nPage pages. Some operating system implementations can get confused if
  43029. ** you try to truncate a file to some size that is larger than it
  43030. ** currently is, so detect this case and write a single zero byte to
  43031. ** the end of the new file instead.
  43032. **
  43033. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  43034. ** the database file, return the error code to the caller.
  43035. */
  43036. static int pager_truncate(Pager *pPager, Pgno nPage){
  43037. int rc = SQLITE_OK;
  43038. assert( pPager->eState!=PAGER_ERROR );
  43039. assert( pPager->eState!=PAGER_READER );
  43040. if( isOpen(pPager->fd)
  43041. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  43042. ){
  43043. i64 currentSize, newSize;
  43044. int szPage = pPager->pageSize;
  43045. assert( pPager->eLock==EXCLUSIVE_LOCK );
  43046. /* TODO: Is it safe to use Pager.dbFileSize here? */
  43047. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  43048. newSize = szPage*(i64)nPage;
  43049. if( rc==SQLITE_OK && currentSize!=newSize ){
  43050. if( currentSize>newSize ){
  43051. rc = sqlite3OsTruncate(pPager->fd, newSize);
  43052. }else if( (currentSize+szPage)<=newSize ){
  43053. char *pTmp = pPager->pTmpSpace;
  43054. memset(pTmp, 0, szPage);
  43055. testcase( (newSize-szPage) == currentSize );
  43056. testcase( (newSize-szPage) > currentSize );
  43057. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  43058. }
  43059. if( rc==SQLITE_OK ){
  43060. pPager->dbFileSize = nPage;
  43061. }
  43062. }
  43063. }
  43064. return rc;
  43065. }
  43066. /*
  43067. ** Return a sanitized version of the sector-size of OS file pFile. The
  43068. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  43069. */
  43070. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  43071. int iRet = sqlite3OsSectorSize(pFile);
  43072. if( iRet<32 ){
  43073. iRet = 512;
  43074. }else if( iRet>MAX_SECTOR_SIZE ){
  43075. assert( MAX_SECTOR_SIZE>=512 );
  43076. iRet = MAX_SECTOR_SIZE;
  43077. }
  43078. return iRet;
  43079. }
  43080. /*
  43081. ** Set the value of the Pager.sectorSize variable for the given
  43082. ** pager based on the value returned by the xSectorSize method
  43083. ** of the open database file. The sector size will be used
  43084. ** to determine the size and alignment of journal header and
  43085. ** master journal pointers within created journal files.
  43086. **
  43087. ** For temporary files the effective sector size is always 512 bytes.
  43088. **
  43089. ** Otherwise, for non-temporary files, the effective sector size is
  43090. ** the value returned by the xSectorSize() method rounded up to 32 if
  43091. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  43092. ** is greater than MAX_SECTOR_SIZE.
  43093. **
  43094. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  43095. ** the effective sector size to its minimum value (512). The purpose of
  43096. ** pPager->sectorSize is to define the "blast radius" of bytes that
  43097. ** might change if a crash occurs while writing to a single byte in
  43098. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  43099. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  43100. ** size. For backwards compatibility of the rollback journal file format,
  43101. ** we cannot reduce the effective sector size below 512.
  43102. */
  43103. static void setSectorSize(Pager *pPager){
  43104. assert( isOpen(pPager->fd) || pPager->tempFile );
  43105. if( pPager->tempFile
  43106. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  43107. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  43108. ){
  43109. /* Sector size doesn't matter for temporary files. Also, the file
  43110. ** may not have been opened yet, in which case the OsSectorSize()
  43111. ** call will segfault. */
  43112. pPager->sectorSize = 512;
  43113. }else{
  43114. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  43115. }
  43116. }
  43117. /*
  43118. ** Playback the journal and thus restore the database file to
  43119. ** the state it was in before we started making changes.
  43120. **
  43121. ** The journal file format is as follows:
  43122. **
  43123. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  43124. ** (2) 4 byte big-endian integer which is the number of valid page records
  43125. ** in the journal. If this value is 0xffffffff, then compute the
  43126. ** number of page records from the journal size.
  43127. ** (3) 4 byte big-endian integer which is the initial value for the
  43128. ** sanity checksum.
  43129. ** (4) 4 byte integer which is the number of pages to truncate the
  43130. ** database to during a rollback.
  43131. ** (5) 4 byte big-endian integer which is the sector size. The header
  43132. ** is this many bytes in size.
  43133. ** (6) 4 byte big-endian integer which is the page size.
  43134. ** (7) zero padding out to the next sector size.
  43135. ** (8) Zero or more pages instances, each as follows:
  43136. ** + 4 byte page number.
  43137. ** + pPager->pageSize bytes of data.
  43138. ** + 4 byte checksum
  43139. **
  43140. ** When we speak of the journal header, we mean the first 7 items above.
  43141. ** Each entry in the journal is an instance of the 8th item.
  43142. **
  43143. ** Call the value from the second bullet "nRec". nRec is the number of
  43144. ** valid page entries in the journal. In most cases, you can compute the
  43145. ** value of nRec from the size of the journal file. But if a power
  43146. ** failure occurred while the journal was being written, it could be the
  43147. ** case that the size of the journal file had already been increased but
  43148. ** the extra entries had not yet made it safely to disk. In such a case,
  43149. ** the value of nRec computed from the file size would be too large. For
  43150. ** that reason, we always use the nRec value in the header.
  43151. **
  43152. ** If the nRec value is 0xffffffff it means that nRec should be computed
  43153. ** from the file size. This value is used when the user selects the
  43154. ** no-sync option for the journal. A power failure could lead to corruption
  43155. ** in this case. But for things like temporary table (which will be
  43156. ** deleted when the power is restored) we don't care.
  43157. **
  43158. ** If the file opened as the journal file is not a well-formed
  43159. ** journal file then all pages up to the first corrupted page are rolled
  43160. ** back (or no pages if the journal header is corrupted). The journal file
  43161. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  43162. ** been encountered.
  43163. **
  43164. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  43165. ** and an error code is returned.
  43166. **
  43167. ** The isHot parameter indicates that we are trying to rollback a journal
  43168. ** that might be a hot journal. Or, it could be that the journal is
  43169. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  43170. ** If the journal really is hot, reset the pager cache prior rolling
  43171. ** back any content. If the journal is merely persistent, no reset is
  43172. ** needed.
  43173. */
  43174. static int pager_playback(Pager *pPager, int isHot){
  43175. sqlite3_vfs *pVfs = pPager->pVfs;
  43176. i64 szJ; /* Size of the journal file in bytes */
  43177. u32 nRec; /* Number of Records in the journal */
  43178. u32 u; /* Unsigned loop counter */
  43179. Pgno mxPg = 0; /* Size of the original file in pages */
  43180. int rc; /* Result code of a subroutine */
  43181. int res = 1; /* Value returned by sqlite3OsAccess() */
  43182. char *zMaster = 0; /* Name of master journal file if any */
  43183. int needPagerReset; /* True to reset page prior to first page rollback */
  43184. int nPlayback = 0; /* Total number of pages restored from journal */
  43185. /* Figure out how many records are in the journal. Abort early if
  43186. ** the journal is empty.
  43187. */
  43188. assert( isOpen(pPager->jfd) );
  43189. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  43190. if( rc!=SQLITE_OK ){
  43191. goto end_playback;
  43192. }
  43193. /* Read the master journal name from the journal, if it is present.
  43194. ** If a master journal file name is specified, but the file is not
  43195. ** present on disk, then the journal is not hot and does not need to be
  43196. ** played back.
  43197. **
  43198. ** TODO: Technically the following is an error because it assumes that
  43199. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  43200. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  43201. ** mxPathname is 512, which is the same as the minimum allowable value
  43202. ** for pageSize.
  43203. */
  43204. zMaster = pPager->pTmpSpace;
  43205. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  43206. if( rc==SQLITE_OK && zMaster[0] ){
  43207. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  43208. }
  43209. zMaster = 0;
  43210. if( rc!=SQLITE_OK || !res ){
  43211. goto end_playback;
  43212. }
  43213. pPager->journalOff = 0;
  43214. needPagerReset = isHot;
  43215. /* This loop terminates either when a readJournalHdr() or
  43216. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  43217. ** occurs.
  43218. */
  43219. while( 1 ){
  43220. /* Read the next journal header from the journal file. If there are
  43221. ** not enough bytes left in the journal file for a complete header, or
  43222. ** it is corrupted, then a process must have failed while writing it.
  43223. ** This indicates nothing more needs to be rolled back.
  43224. */
  43225. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  43226. if( rc!=SQLITE_OK ){
  43227. if( rc==SQLITE_DONE ){
  43228. rc = SQLITE_OK;
  43229. }
  43230. goto end_playback;
  43231. }
  43232. /* If nRec is 0xffffffff, then this journal was created by a process
  43233. ** working in no-sync mode. This means that the rest of the journal
  43234. ** file consists of pages, there are no more journal headers. Compute
  43235. ** the value of nRec based on this assumption.
  43236. */
  43237. if( nRec==0xffffffff ){
  43238. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  43239. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  43240. }
  43241. /* If nRec is 0 and this rollback is of a transaction created by this
  43242. ** process and if this is the final header in the journal, then it means
  43243. ** that this part of the journal was being filled but has not yet been
  43244. ** synced to disk. Compute the number of pages based on the remaining
  43245. ** size of the file.
  43246. **
  43247. ** The third term of the test was added to fix ticket #2565.
  43248. ** When rolling back a hot journal, nRec==0 always means that the next
  43249. ** chunk of the journal contains zero pages to be rolled back. But
  43250. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  43251. ** the journal, it means that the journal might contain additional
  43252. ** pages that need to be rolled back and that the number of pages
  43253. ** should be computed based on the journal file size.
  43254. */
  43255. if( nRec==0 && !isHot &&
  43256. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  43257. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  43258. }
  43259. /* If this is the first header read from the journal, truncate the
  43260. ** database file back to its original size.
  43261. */
  43262. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  43263. rc = pager_truncate(pPager, mxPg);
  43264. if( rc!=SQLITE_OK ){
  43265. goto end_playback;
  43266. }
  43267. pPager->dbSize = mxPg;
  43268. }
  43269. /* Copy original pages out of the journal and back into the
  43270. ** database file and/or page cache.
  43271. */
  43272. for(u=0; u<nRec; u++){
  43273. if( needPagerReset ){
  43274. pager_reset(pPager);
  43275. needPagerReset = 0;
  43276. }
  43277. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  43278. if( rc==SQLITE_OK ){
  43279. nPlayback++;
  43280. }else{
  43281. if( rc==SQLITE_DONE ){
  43282. pPager->journalOff = szJ;
  43283. break;
  43284. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  43285. /* If the journal has been truncated, simply stop reading and
  43286. ** processing the journal. This might happen if the journal was
  43287. ** not completely written and synced prior to a crash. In that
  43288. ** case, the database should have never been written in the
  43289. ** first place so it is OK to simply abandon the rollback. */
  43290. rc = SQLITE_OK;
  43291. goto end_playback;
  43292. }else{
  43293. /* If we are unable to rollback, quit and return the error
  43294. ** code. This will cause the pager to enter the error state
  43295. ** so that no further harm will be done. Perhaps the next
  43296. ** process to come along will be able to rollback the database.
  43297. */
  43298. goto end_playback;
  43299. }
  43300. }
  43301. }
  43302. }
  43303. /*NOTREACHED*/
  43304. assert( 0 );
  43305. end_playback:
  43306. /* Following a rollback, the database file should be back in its original
  43307. ** state prior to the start of the transaction, so invoke the
  43308. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  43309. ** assertion that the transaction counter was modified.
  43310. */
  43311. #ifdef SQLITE_DEBUG
  43312. if( pPager->fd->pMethods ){
  43313. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  43314. }
  43315. #endif
  43316. /* If this playback is happening automatically as a result of an IO or
  43317. ** malloc error that occurred after the change-counter was updated but
  43318. ** before the transaction was committed, then the change-counter
  43319. ** modification may just have been reverted. If this happens in exclusive
  43320. ** mode, then subsequent transactions performed by the connection will not
  43321. ** update the change-counter at all. This may lead to cache inconsistency
  43322. ** problems for other processes at some point in the future. So, just
  43323. ** in case this has happened, clear the changeCountDone flag now.
  43324. */
  43325. pPager->changeCountDone = pPager->tempFile;
  43326. if( rc==SQLITE_OK ){
  43327. zMaster = pPager->pTmpSpace;
  43328. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  43329. testcase( rc!=SQLITE_OK );
  43330. }
  43331. if( rc==SQLITE_OK
  43332. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  43333. ){
  43334. rc = sqlite3PagerSync(pPager, 0);
  43335. }
  43336. if( rc==SQLITE_OK ){
  43337. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  43338. testcase( rc!=SQLITE_OK );
  43339. }
  43340. if( rc==SQLITE_OK && zMaster[0] && res ){
  43341. /* If there was a master journal and this routine will return success,
  43342. ** see if it is possible to delete the master journal.
  43343. */
  43344. rc = pager_delmaster(pPager, zMaster);
  43345. testcase( rc!=SQLITE_OK );
  43346. }
  43347. if( isHot && nPlayback ){
  43348. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  43349. nPlayback, pPager->zJournal);
  43350. }
  43351. /* The Pager.sectorSize variable may have been updated while rolling
  43352. ** back a journal created by a process with a different sector size
  43353. ** value. Reset it to the correct value for this process.
  43354. */
  43355. setSectorSize(pPager);
  43356. return rc;
  43357. }
  43358. /*
  43359. ** Read the content for page pPg out of the database file and into
  43360. ** pPg->pData. A shared lock or greater must be held on the database
  43361. ** file before this function is called.
  43362. **
  43363. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  43364. ** the value read from the database file.
  43365. **
  43366. ** If an IO error occurs, then the IO error is returned to the caller.
  43367. ** Otherwise, SQLITE_OK is returned.
  43368. */
  43369. static int readDbPage(PgHdr *pPg, u32 iFrame){
  43370. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  43371. Pgno pgno = pPg->pgno; /* Page number to read */
  43372. int rc = SQLITE_OK; /* Return code */
  43373. int pgsz = pPager->pageSize; /* Number of bytes to read */
  43374. assert( pPager->eState>=PAGER_READER && !MEMDB );
  43375. assert( isOpen(pPager->fd) );
  43376. #ifndef SQLITE_OMIT_WAL
  43377. if( iFrame ){
  43378. /* Try to pull the page from the write-ahead log. */
  43379. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  43380. }else
  43381. #endif
  43382. {
  43383. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  43384. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  43385. if( rc==SQLITE_IOERR_SHORT_READ ){
  43386. rc = SQLITE_OK;
  43387. }
  43388. }
  43389. if( pgno==1 ){
  43390. if( rc ){
  43391. /* If the read is unsuccessful, set the dbFileVers[] to something
  43392. ** that will never be a valid file version. dbFileVers[] is a copy
  43393. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  43394. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  43395. ** should be page numbers which are never 0xffffffff. So filling
  43396. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  43397. **
  43398. ** For an encrypted database, the situation is more complex: bytes
  43399. ** 24..39 of the database are white noise. But the probability of
  43400. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  43401. ** we should still be ok.
  43402. */
  43403. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  43404. }else{
  43405. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  43406. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  43407. }
  43408. }
  43409. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  43410. PAGER_INCR(sqlite3_pager_readdb_count);
  43411. PAGER_INCR(pPager->nRead);
  43412. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  43413. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  43414. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  43415. return rc;
  43416. }
  43417. /*
  43418. ** Update the value of the change-counter at offsets 24 and 92 in
  43419. ** the header and the sqlite version number at offset 96.
  43420. **
  43421. ** This is an unconditional update. See also the pager_incr_changecounter()
  43422. ** routine which only updates the change-counter if the update is actually
  43423. ** needed, as determined by the pPager->changeCountDone state variable.
  43424. */
  43425. static void pager_write_changecounter(PgHdr *pPg){
  43426. u32 change_counter;
  43427. /* Increment the value just read and write it back to byte 24. */
  43428. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  43429. put32bits(((char*)pPg->pData)+24, change_counter);
  43430. /* Also store the SQLite version number in bytes 96..99 and in
  43431. ** bytes 92..95 store the change counter for which the version number
  43432. ** is valid. */
  43433. put32bits(((char*)pPg->pData)+92, change_counter);
  43434. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  43435. }
  43436. #ifndef SQLITE_OMIT_WAL
  43437. /*
  43438. ** This function is invoked once for each page that has already been
  43439. ** written into the log file when a WAL transaction is rolled back.
  43440. ** Parameter iPg is the page number of said page. The pCtx argument
  43441. ** is actually a pointer to the Pager structure.
  43442. **
  43443. ** If page iPg is present in the cache, and has no outstanding references,
  43444. ** it is discarded. Otherwise, if there are one or more outstanding
  43445. ** references, the page content is reloaded from the database. If the
  43446. ** attempt to reload content from the database is required and fails,
  43447. ** return an SQLite error code. Otherwise, SQLITE_OK.
  43448. */
  43449. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  43450. int rc = SQLITE_OK;
  43451. Pager *pPager = (Pager *)pCtx;
  43452. PgHdr *pPg;
  43453. assert( pagerUseWal(pPager) );
  43454. pPg = sqlite3PagerLookup(pPager, iPg);
  43455. if( pPg ){
  43456. if( sqlite3PcachePageRefcount(pPg)==1 ){
  43457. sqlite3PcacheDrop(pPg);
  43458. }else{
  43459. u32 iFrame = 0;
  43460. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  43461. if( rc==SQLITE_OK ){
  43462. rc = readDbPage(pPg, iFrame);
  43463. }
  43464. if( rc==SQLITE_OK ){
  43465. pPager->xReiniter(pPg);
  43466. }
  43467. sqlite3PagerUnrefNotNull(pPg);
  43468. }
  43469. }
  43470. /* Normally, if a transaction is rolled back, any backup processes are
  43471. ** updated as data is copied out of the rollback journal and into the
  43472. ** database. This is not generally possible with a WAL database, as
  43473. ** rollback involves simply truncating the log file. Therefore, if one
  43474. ** or more frames have already been written to the log (and therefore
  43475. ** also copied into the backup databases) as part of this transaction,
  43476. ** the backups must be restarted.
  43477. */
  43478. sqlite3BackupRestart(pPager->pBackup);
  43479. return rc;
  43480. }
  43481. /*
  43482. ** This function is called to rollback a transaction on a WAL database.
  43483. */
  43484. static int pagerRollbackWal(Pager *pPager){
  43485. int rc; /* Return Code */
  43486. PgHdr *pList; /* List of dirty pages to revert */
  43487. /* For all pages in the cache that are currently dirty or have already
  43488. ** been written (but not committed) to the log file, do one of the
  43489. ** following:
  43490. **
  43491. ** + Discard the cached page (if refcount==0), or
  43492. ** + Reload page content from the database (if refcount>0).
  43493. */
  43494. pPager->dbSize = pPager->dbOrigSize;
  43495. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  43496. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  43497. while( pList && rc==SQLITE_OK ){
  43498. PgHdr *pNext = pList->pDirty;
  43499. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  43500. pList = pNext;
  43501. }
  43502. return rc;
  43503. }
  43504. /*
  43505. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  43506. ** the contents of the list of pages headed by pList (connected by pDirty),
  43507. ** this function notifies any active backup processes that the pages have
  43508. ** changed.
  43509. **
  43510. ** The list of pages passed into this routine is always sorted by page number.
  43511. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  43512. */
  43513. static int pagerWalFrames(
  43514. Pager *pPager, /* Pager object */
  43515. PgHdr *pList, /* List of frames to log */
  43516. Pgno nTruncate, /* Database size after this commit */
  43517. int isCommit /* True if this is a commit */
  43518. ){
  43519. int rc; /* Return code */
  43520. int nList; /* Number of pages in pList */
  43521. PgHdr *p; /* For looping over pages */
  43522. assert( pPager->pWal );
  43523. assert( pList );
  43524. #ifdef SQLITE_DEBUG
  43525. /* Verify that the page list is in accending order */
  43526. for(p=pList; p && p->pDirty; p=p->pDirty){
  43527. assert( p->pgno < p->pDirty->pgno );
  43528. }
  43529. #endif
  43530. assert( pList->pDirty==0 || isCommit );
  43531. if( isCommit ){
  43532. /* If a WAL transaction is being committed, there is no point in writing
  43533. ** any pages with page numbers greater than nTruncate into the WAL file.
  43534. ** They will never be read by any client. So remove them from the pDirty
  43535. ** list here. */
  43536. PgHdr **ppNext = &pList;
  43537. nList = 0;
  43538. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  43539. if( p->pgno<=nTruncate ){
  43540. ppNext = &p->pDirty;
  43541. nList++;
  43542. }
  43543. }
  43544. assert( pList );
  43545. }else{
  43546. nList = 1;
  43547. }
  43548. pPager->aStat[PAGER_STAT_WRITE] += nList;
  43549. if( pList->pgno==1 ) pager_write_changecounter(pList);
  43550. rc = sqlite3WalFrames(pPager->pWal,
  43551. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  43552. );
  43553. if( rc==SQLITE_OK && pPager->pBackup ){
  43554. for(p=pList; p; p=p->pDirty){
  43555. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  43556. }
  43557. }
  43558. #ifdef SQLITE_CHECK_PAGES
  43559. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  43560. for(p=pList; p; p=p->pDirty){
  43561. pager_set_pagehash(p);
  43562. }
  43563. #endif
  43564. return rc;
  43565. }
  43566. /*
  43567. ** Begin a read transaction on the WAL.
  43568. **
  43569. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  43570. ** makes a snapshot of the database at the current point in time and preserves
  43571. ** that snapshot for use by the reader in spite of concurrently changes by
  43572. ** other writers or checkpointers.
  43573. */
  43574. static int pagerBeginReadTransaction(Pager *pPager){
  43575. int rc; /* Return code */
  43576. int changed = 0; /* True if cache must be reset */
  43577. assert( pagerUseWal(pPager) );
  43578. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  43579. /* sqlite3WalEndReadTransaction() was not called for the previous
  43580. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  43581. ** are in locking_mode=NORMAL and EndRead() was previously called,
  43582. ** the duplicate call is harmless.
  43583. */
  43584. sqlite3WalEndReadTransaction(pPager->pWal);
  43585. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  43586. if( rc!=SQLITE_OK || changed ){
  43587. pager_reset(pPager);
  43588. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  43589. }
  43590. return rc;
  43591. }
  43592. #endif
  43593. /*
  43594. ** This function is called as part of the transition from PAGER_OPEN
  43595. ** to PAGER_READER state to determine the size of the database file
  43596. ** in pages (assuming the page size currently stored in Pager.pageSize).
  43597. **
  43598. ** If no error occurs, SQLITE_OK is returned and the size of the database
  43599. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  43600. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  43601. */
  43602. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  43603. Pgno nPage; /* Value to return via *pnPage */
  43604. /* Query the WAL sub-system for the database size. The WalDbsize()
  43605. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  43606. ** if the database size is not available. The database size is not
  43607. ** available from the WAL sub-system if the log file is empty or
  43608. ** contains no valid committed transactions.
  43609. */
  43610. assert( pPager->eState==PAGER_OPEN );
  43611. assert( pPager->eLock>=SHARED_LOCK );
  43612. nPage = sqlite3WalDbsize(pPager->pWal);
  43613. /* If the number of pages in the database is not available from the
  43614. ** WAL sub-system, determine the page counte based on the size of
  43615. ** the database file. If the size of the database file is not an
  43616. ** integer multiple of the page-size, round up the result.
  43617. */
  43618. if( nPage==0 ){
  43619. i64 n = 0; /* Size of db file in bytes */
  43620. assert( isOpen(pPager->fd) || pPager->tempFile );
  43621. if( isOpen(pPager->fd) ){
  43622. int rc = sqlite3OsFileSize(pPager->fd, &n);
  43623. if( rc!=SQLITE_OK ){
  43624. return rc;
  43625. }
  43626. }
  43627. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  43628. }
  43629. /* If the current number of pages in the file is greater than the
  43630. ** configured maximum pager number, increase the allowed limit so
  43631. ** that the file can be read.
  43632. */
  43633. if( nPage>pPager->mxPgno ){
  43634. pPager->mxPgno = (Pgno)nPage;
  43635. }
  43636. *pnPage = nPage;
  43637. return SQLITE_OK;
  43638. }
  43639. #ifndef SQLITE_OMIT_WAL
  43640. /*
  43641. ** Check if the *-wal file that corresponds to the database opened by pPager
  43642. ** exists if the database is not empy, or verify that the *-wal file does
  43643. ** not exist (by deleting it) if the database file is empty.
  43644. **
  43645. ** If the database is not empty and the *-wal file exists, open the pager
  43646. ** in WAL mode. If the database is empty or if no *-wal file exists and
  43647. ** if no error occurs, make sure Pager.journalMode is not set to
  43648. ** PAGER_JOURNALMODE_WAL.
  43649. **
  43650. ** Return SQLITE_OK or an error code.
  43651. **
  43652. ** The caller must hold a SHARED lock on the database file to call this
  43653. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  43654. ** a WAL on a none-empty database, this ensures there is no race condition
  43655. ** between the xAccess() below and an xDelete() being executed by some
  43656. ** other connection.
  43657. */
  43658. static int pagerOpenWalIfPresent(Pager *pPager){
  43659. int rc = SQLITE_OK;
  43660. assert( pPager->eState==PAGER_OPEN );
  43661. assert( pPager->eLock>=SHARED_LOCK );
  43662. if( !pPager->tempFile ){
  43663. int isWal; /* True if WAL file exists */
  43664. Pgno nPage; /* Size of the database file */
  43665. rc = pagerPagecount(pPager, &nPage);
  43666. if( rc ) return rc;
  43667. if( nPage==0 ){
  43668. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  43669. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  43670. isWal = 0;
  43671. }else{
  43672. rc = sqlite3OsAccess(
  43673. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  43674. );
  43675. }
  43676. if( rc==SQLITE_OK ){
  43677. if( isWal ){
  43678. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  43679. rc = sqlite3PagerOpenWal(pPager, 0);
  43680. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  43681. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  43682. }
  43683. }
  43684. }
  43685. return rc;
  43686. }
  43687. #endif
  43688. /*
  43689. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  43690. ** the entire master journal file. The case pSavepoint==NULL occurs when
  43691. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  43692. ** savepoint.
  43693. **
  43694. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  43695. ** being rolled back), then the rollback consists of up to three stages,
  43696. ** performed in the order specified:
  43697. **
  43698. ** * Pages are played back from the main journal starting at byte
  43699. ** offset PagerSavepoint.iOffset and continuing to
  43700. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  43701. ** file if PagerSavepoint.iHdrOffset is zero.
  43702. **
  43703. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  43704. ** back starting from the journal header immediately following
  43705. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  43706. **
  43707. ** * Pages are then played back from the sub-journal file, starting
  43708. ** with the PagerSavepoint.iSubRec and continuing to the end of
  43709. ** the journal file.
  43710. **
  43711. ** Throughout the rollback process, each time a page is rolled back, the
  43712. ** corresponding bit is set in a bitvec structure (variable pDone in the
  43713. ** implementation below). This is used to ensure that a page is only
  43714. ** rolled back the first time it is encountered in either journal.
  43715. **
  43716. ** If pSavepoint is NULL, then pages are only played back from the main
  43717. ** journal file. There is no need for a bitvec in this case.
  43718. **
  43719. ** In either case, before playback commences the Pager.dbSize variable
  43720. ** is reset to the value that it held at the start of the savepoint
  43721. ** (or transaction). No page with a page-number greater than this value
  43722. ** is played back. If one is encountered it is simply skipped.
  43723. */
  43724. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  43725. i64 szJ; /* Effective size of the main journal */
  43726. i64 iHdrOff; /* End of first segment of main-journal records */
  43727. int rc = SQLITE_OK; /* Return code */
  43728. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  43729. assert( pPager->eState!=PAGER_ERROR );
  43730. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  43731. /* Allocate a bitvec to use to store the set of pages rolled back */
  43732. if( pSavepoint ){
  43733. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  43734. if( !pDone ){
  43735. return SQLITE_NOMEM;
  43736. }
  43737. }
  43738. /* Set the database size back to the value it was before the savepoint
  43739. ** being reverted was opened.
  43740. */
  43741. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  43742. pPager->changeCountDone = pPager->tempFile;
  43743. if( !pSavepoint && pagerUseWal(pPager) ){
  43744. return pagerRollbackWal(pPager);
  43745. }
  43746. /* Use pPager->journalOff as the effective size of the main rollback
  43747. ** journal. The actual file might be larger than this in
  43748. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  43749. ** past pPager->journalOff is off-limits to us.
  43750. */
  43751. szJ = pPager->journalOff;
  43752. assert( pagerUseWal(pPager)==0 || szJ==0 );
  43753. /* Begin by rolling back records from the main journal starting at
  43754. ** PagerSavepoint.iOffset and continuing to the next journal header.
  43755. ** There might be records in the main journal that have a page number
  43756. ** greater than the current database size (pPager->dbSize) but those
  43757. ** will be skipped automatically. Pages are added to pDone as they
  43758. ** are played back.
  43759. */
  43760. if( pSavepoint && !pagerUseWal(pPager) ){
  43761. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  43762. pPager->journalOff = pSavepoint->iOffset;
  43763. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  43764. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  43765. }
  43766. assert( rc!=SQLITE_DONE );
  43767. }else{
  43768. pPager->journalOff = 0;
  43769. }
  43770. /* Continue rolling back records out of the main journal starting at
  43771. ** the first journal header seen and continuing until the effective end
  43772. ** of the main journal file. Continue to skip out-of-range pages and
  43773. ** continue adding pages rolled back to pDone.
  43774. */
  43775. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  43776. u32 ii; /* Loop counter */
  43777. u32 nJRec = 0; /* Number of Journal Records */
  43778. u32 dummy;
  43779. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  43780. assert( rc!=SQLITE_DONE );
  43781. /*
  43782. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  43783. ** test is related to ticket #2565. See the discussion in the
  43784. ** pager_playback() function for additional information.
  43785. */
  43786. if( nJRec==0
  43787. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  43788. ){
  43789. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  43790. }
  43791. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  43792. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  43793. }
  43794. assert( rc!=SQLITE_DONE );
  43795. }
  43796. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  43797. /* Finally, rollback pages from the sub-journal. Page that were
  43798. ** previously rolled back out of the main journal (and are hence in pDone)
  43799. ** will be skipped. Out-of-range pages are also skipped.
  43800. */
  43801. if( pSavepoint ){
  43802. u32 ii; /* Loop counter */
  43803. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  43804. if( pagerUseWal(pPager) ){
  43805. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  43806. }
  43807. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  43808. assert( offset==(i64)ii*(4+pPager->pageSize) );
  43809. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  43810. }
  43811. assert( rc!=SQLITE_DONE );
  43812. }
  43813. sqlite3BitvecDestroy(pDone);
  43814. if( rc==SQLITE_OK ){
  43815. pPager->journalOff = szJ;
  43816. }
  43817. return rc;
  43818. }
  43819. /*
  43820. ** Change the maximum number of in-memory pages that are allowed
  43821. ** before attempting to recycle clean and unused pages.
  43822. */
  43823. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  43824. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  43825. }
  43826. /*
  43827. ** Change the maximum number of in-memory pages that are allowed
  43828. ** before attempting to spill pages to journal.
  43829. */
  43830. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  43831. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  43832. }
  43833. /*
  43834. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  43835. */
  43836. static void pagerFixMaplimit(Pager *pPager){
  43837. #if SQLITE_MAX_MMAP_SIZE>0
  43838. sqlite3_file *fd = pPager->fd;
  43839. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  43840. sqlite3_int64 sz;
  43841. sz = pPager->szMmap;
  43842. pPager->bUseFetch = (sz>0);
  43843. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  43844. }
  43845. #endif
  43846. }
  43847. /*
  43848. ** Change the maximum size of any memory mapping made of the database file.
  43849. */
  43850. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  43851. pPager->szMmap = szMmap;
  43852. pagerFixMaplimit(pPager);
  43853. }
  43854. /*
  43855. ** Free as much memory as possible from the pager.
  43856. */
  43857. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  43858. sqlite3PcacheShrink(pPager->pPCache);
  43859. }
  43860. /*
  43861. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  43862. **
  43863. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  43864. ** of the database to damage due to OS crashes or power failures by
  43865. ** changing the number of syncs()s when writing the journals.
  43866. ** There are three levels:
  43867. **
  43868. ** OFF sqlite3OsSync() is never called. This is the default
  43869. ** for temporary and transient files.
  43870. **
  43871. ** NORMAL The journal is synced once before writes begin on the
  43872. ** database. This is normally adequate protection, but
  43873. ** it is theoretically possible, though very unlikely,
  43874. ** that an inopertune power failure could leave the journal
  43875. ** in a state which would cause damage to the database
  43876. ** when it is rolled back.
  43877. **
  43878. ** FULL The journal is synced twice before writes begin on the
  43879. ** database (with some additional information - the nRec field
  43880. ** of the journal header - being written in between the two
  43881. ** syncs). If we assume that writing a
  43882. ** single disk sector is atomic, then this mode provides
  43883. ** assurance that the journal will not be corrupted to the
  43884. ** point of causing damage to the database during rollback.
  43885. **
  43886. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  43887. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  43888. ** prior to the start of checkpoint and that the database file is synced
  43889. ** at the conclusion of the checkpoint if the entire content of the WAL
  43890. ** was written back into the database. But no sync operations occur for
  43891. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  43892. ** file is synced following each commit operation, in addition to the
  43893. ** syncs associated with NORMAL.
  43894. **
  43895. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  43896. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  43897. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  43898. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  43899. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  43900. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  43901. ** the xSync primitive is called and is relevant to all platforms.
  43902. **
  43903. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  43904. ** and FULL=3.
  43905. */
  43906. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  43907. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  43908. Pager *pPager, /* The pager to set safety level for */
  43909. unsigned pgFlags /* Various flags */
  43910. ){
  43911. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  43912. assert( level>=1 && level<=3 );
  43913. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  43914. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  43915. if( pPager->noSync ){
  43916. pPager->syncFlags = 0;
  43917. pPager->ckptSyncFlags = 0;
  43918. }else if( pgFlags & PAGER_FULLFSYNC ){
  43919. pPager->syncFlags = SQLITE_SYNC_FULL;
  43920. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  43921. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  43922. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  43923. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  43924. }else{
  43925. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  43926. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  43927. }
  43928. pPager->walSyncFlags = pPager->syncFlags;
  43929. if( pPager->fullSync ){
  43930. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  43931. }
  43932. if( pgFlags & PAGER_CACHESPILL ){
  43933. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  43934. }else{
  43935. pPager->doNotSpill |= SPILLFLAG_OFF;
  43936. }
  43937. }
  43938. #endif
  43939. /*
  43940. ** The following global variable is incremented whenever the library
  43941. ** attempts to open a temporary file. This information is used for
  43942. ** testing and analysis only.
  43943. */
  43944. #ifdef SQLITE_TEST
  43945. SQLITE_API int sqlite3_opentemp_count = 0;
  43946. #endif
  43947. /*
  43948. ** Open a temporary file.
  43949. **
  43950. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  43951. ** or some other error code if we fail. The OS will automatically
  43952. ** delete the temporary file when it is closed.
  43953. **
  43954. ** The flags passed to the VFS layer xOpen() call are those specified
  43955. ** by parameter vfsFlags ORed with the following:
  43956. **
  43957. ** SQLITE_OPEN_READWRITE
  43958. ** SQLITE_OPEN_CREATE
  43959. ** SQLITE_OPEN_EXCLUSIVE
  43960. ** SQLITE_OPEN_DELETEONCLOSE
  43961. */
  43962. static int pagerOpentemp(
  43963. Pager *pPager, /* The pager object */
  43964. sqlite3_file *pFile, /* Write the file descriptor here */
  43965. int vfsFlags /* Flags passed through to the VFS */
  43966. ){
  43967. int rc; /* Return code */
  43968. #ifdef SQLITE_TEST
  43969. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  43970. #endif
  43971. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  43972. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  43973. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  43974. assert( rc!=SQLITE_OK || isOpen(pFile) );
  43975. return rc;
  43976. }
  43977. /*
  43978. ** Set the busy handler function.
  43979. **
  43980. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  43981. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  43982. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  43983. ** lock. It does *not* invoke the busy handler when upgrading from
  43984. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  43985. ** (which occurs during hot-journal rollback). Summary:
  43986. **
  43987. ** Transition | Invokes xBusyHandler
  43988. ** --------------------------------------------------------
  43989. ** NO_LOCK -> SHARED_LOCK | Yes
  43990. ** SHARED_LOCK -> RESERVED_LOCK | No
  43991. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  43992. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  43993. **
  43994. ** If the busy-handler callback returns non-zero, the lock is
  43995. ** retried. If it returns zero, then the SQLITE_BUSY error is
  43996. ** returned to the caller of the pager API function.
  43997. */
  43998. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  43999. Pager *pPager, /* Pager object */
  44000. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  44001. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  44002. ){
  44003. pPager->xBusyHandler = xBusyHandler;
  44004. pPager->pBusyHandlerArg = pBusyHandlerArg;
  44005. if( isOpen(pPager->fd) ){
  44006. void **ap = (void **)&pPager->xBusyHandler;
  44007. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  44008. assert( ap[1]==pBusyHandlerArg );
  44009. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  44010. }
  44011. }
  44012. /*
  44013. ** Change the page size used by the Pager object. The new page size
  44014. ** is passed in *pPageSize.
  44015. **
  44016. ** If the pager is in the error state when this function is called, it
  44017. ** is a no-op. The value returned is the error state error code (i.e.
  44018. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  44019. **
  44020. ** Otherwise, if all of the following are true:
  44021. **
  44022. ** * the new page size (value of *pPageSize) is valid (a power
  44023. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  44024. **
  44025. ** * there are no outstanding page references, and
  44026. **
  44027. ** * the database is either not an in-memory database or it is
  44028. ** an in-memory database that currently consists of zero pages.
  44029. **
  44030. ** then the pager object page size is set to *pPageSize.
  44031. **
  44032. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  44033. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  44034. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  44035. ** In all other cases, SQLITE_OK is returned.
  44036. **
  44037. ** If the page size is not changed, either because one of the enumerated
  44038. ** conditions above is not true, the pager was in error state when this
  44039. ** function was called, or because the memory allocation attempt failed,
  44040. ** then *pPageSize is set to the old, retained page size before returning.
  44041. */
  44042. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  44043. int rc = SQLITE_OK;
  44044. /* It is not possible to do a full assert_pager_state() here, as this
  44045. ** function may be called from within PagerOpen(), before the state
  44046. ** of the Pager object is internally consistent.
  44047. **
  44048. ** At one point this function returned an error if the pager was in
  44049. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  44050. ** there is at least one outstanding page reference, this function
  44051. ** is a no-op for that case anyhow.
  44052. */
  44053. u32 pageSize = *pPageSize;
  44054. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  44055. if( (pPager->memDb==0 || pPager->dbSize==0)
  44056. && sqlite3PcacheRefCount(pPager->pPCache)==0
  44057. && pageSize && pageSize!=(u32)pPager->pageSize
  44058. ){
  44059. char *pNew = NULL; /* New temp space */
  44060. i64 nByte = 0;
  44061. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  44062. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  44063. }
  44064. if( rc==SQLITE_OK ){
  44065. pNew = (char *)sqlite3PageMalloc(pageSize);
  44066. if( !pNew ) rc = SQLITE_NOMEM;
  44067. }
  44068. if( rc==SQLITE_OK ){
  44069. pager_reset(pPager);
  44070. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  44071. }
  44072. if( rc==SQLITE_OK ){
  44073. sqlite3PageFree(pPager->pTmpSpace);
  44074. pPager->pTmpSpace = pNew;
  44075. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  44076. pPager->pageSize = pageSize;
  44077. }else{
  44078. sqlite3PageFree(pNew);
  44079. }
  44080. }
  44081. *pPageSize = pPager->pageSize;
  44082. if( rc==SQLITE_OK ){
  44083. if( nReserve<0 ) nReserve = pPager->nReserve;
  44084. assert( nReserve>=0 && nReserve<1000 );
  44085. pPager->nReserve = (i16)nReserve;
  44086. pagerReportSize(pPager);
  44087. pagerFixMaplimit(pPager);
  44088. }
  44089. return rc;
  44090. }
  44091. /*
  44092. ** Return a pointer to the "temporary page" buffer held internally
  44093. ** by the pager. This is a buffer that is big enough to hold the
  44094. ** entire content of a database page. This buffer is used internally
  44095. ** during rollback and will be overwritten whenever a rollback
  44096. ** occurs. But other modules are free to use it too, as long as
  44097. ** no rollbacks are happening.
  44098. */
  44099. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  44100. return pPager->pTmpSpace;
  44101. }
  44102. /*
  44103. ** Attempt to set the maximum database page count if mxPage is positive.
  44104. ** Make no changes if mxPage is zero or negative. And never reduce the
  44105. ** maximum page count below the current size of the database.
  44106. **
  44107. ** Regardless of mxPage, return the current maximum page count.
  44108. */
  44109. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  44110. if( mxPage>0 ){
  44111. pPager->mxPgno = mxPage;
  44112. }
  44113. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  44114. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  44115. return pPager->mxPgno;
  44116. }
  44117. /*
  44118. ** The following set of routines are used to disable the simulated
  44119. ** I/O error mechanism. These routines are used to avoid simulated
  44120. ** errors in places where we do not care about errors.
  44121. **
  44122. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  44123. ** and generate no code.
  44124. */
  44125. #ifdef SQLITE_TEST
  44126. SQLITE_API extern int sqlite3_io_error_pending;
  44127. SQLITE_API extern int sqlite3_io_error_hit;
  44128. static int saved_cnt;
  44129. void disable_simulated_io_errors(void){
  44130. saved_cnt = sqlite3_io_error_pending;
  44131. sqlite3_io_error_pending = -1;
  44132. }
  44133. void enable_simulated_io_errors(void){
  44134. sqlite3_io_error_pending = saved_cnt;
  44135. }
  44136. #else
  44137. # define disable_simulated_io_errors()
  44138. # define enable_simulated_io_errors()
  44139. #endif
  44140. /*
  44141. ** Read the first N bytes from the beginning of the file into memory
  44142. ** that pDest points to.
  44143. **
  44144. ** If the pager was opened on a transient file (zFilename==""), or
  44145. ** opened on a file less than N bytes in size, the output buffer is
  44146. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  44147. ** function is used to read database headers, and a new transient or
  44148. ** zero sized database has a header than consists entirely of zeroes.
  44149. **
  44150. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  44151. ** the error code is returned to the caller and the contents of the
  44152. ** output buffer undefined.
  44153. */
  44154. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  44155. int rc = SQLITE_OK;
  44156. memset(pDest, 0, N);
  44157. assert( isOpen(pPager->fd) || pPager->tempFile );
  44158. /* This routine is only called by btree immediately after creating
  44159. ** the Pager object. There has not been an opportunity to transition
  44160. ** to WAL mode yet.
  44161. */
  44162. assert( !pagerUseWal(pPager) );
  44163. if( isOpen(pPager->fd) ){
  44164. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  44165. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  44166. if( rc==SQLITE_IOERR_SHORT_READ ){
  44167. rc = SQLITE_OK;
  44168. }
  44169. }
  44170. return rc;
  44171. }
  44172. /*
  44173. ** This function may only be called when a read-transaction is open on
  44174. ** the pager. It returns the total number of pages in the database.
  44175. **
  44176. ** However, if the file is between 1 and <page-size> bytes in size, then
  44177. ** this is considered a 1 page file.
  44178. */
  44179. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  44180. assert( pPager->eState>=PAGER_READER );
  44181. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  44182. *pnPage = (int)pPager->dbSize;
  44183. }
  44184. /*
  44185. ** Try to obtain a lock of type locktype on the database file. If
  44186. ** a similar or greater lock is already held, this function is a no-op
  44187. ** (returning SQLITE_OK immediately).
  44188. **
  44189. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  44190. ** the busy callback if the lock is currently not available. Repeat
  44191. ** until the busy callback returns false or until the attempt to
  44192. ** obtain the lock succeeds.
  44193. **
  44194. ** Return SQLITE_OK on success and an error code if we cannot obtain
  44195. ** the lock. If the lock is obtained successfully, set the Pager.state
  44196. ** variable to locktype before returning.
  44197. */
  44198. static int pager_wait_on_lock(Pager *pPager, int locktype){
  44199. int rc; /* Return code */
  44200. /* Check that this is either a no-op (because the requested lock is
  44201. ** already held), or one of the transitions that the busy-handler
  44202. ** may be invoked during, according to the comment above
  44203. ** sqlite3PagerSetBusyhandler().
  44204. */
  44205. assert( (pPager->eLock>=locktype)
  44206. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  44207. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  44208. );
  44209. do {
  44210. rc = pagerLockDb(pPager, locktype);
  44211. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  44212. return rc;
  44213. }
  44214. /*
  44215. ** Function assertTruncateConstraint(pPager) checks that one of the
  44216. ** following is true for all dirty pages currently in the page-cache:
  44217. **
  44218. ** a) The page number is less than or equal to the size of the
  44219. ** current database image, in pages, OR
  44220. **
  44221. ** b) if the page content were written at this time, it would not
  44222. ** be necessary to write the current content out to the sub-journal
  44223. ** (as determined by function subjRequiresPage()).
  44224. **
  44225. ** If the condition asserted by this function were not true, and the
  44226. ** dirty page were to be discarded from the cache via the pagerStress()
  44227. ** routine, pagerStress() would not write the current page content to
  44228. ** the database file. If a savepoint transaction were rolled back after
  44229. ** this happened, the correct behavior would be to restore the current
  44230. ** content of the page. However, since this content is not present in either
  44231. ** the database file or the portion of the rollback journal and
  44232. ** sub-journal rolled back the content could not be restored and the
  44233. ** database image would become corrupt. It is therefore fortunate that
  44234. ** this circumstance cannot arise.
  44235. */
  44236. #if defined(SQLITE_DEBUG)
  44237. static void assertTruncateConstraintCb(PgHdr *pPg){
  44238. assert( pPg->flags&PGHDR_DIRTY );
  44239. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  44240. }
  44241. static void assertTruncateConstraint(Pager *pPager){
  44242. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  44243. }
  44244. #else
  44245. # define assertTruncateConstraint(pPager)
  44246. #endif
  44247. /*
  44248. ** Truncate the in-memory database file image to nPage pages. This
  44249. ** function does not actually modify the database file on disk. It
  44250. ** just sets the internal state of the pager object so that the
  44251. ** truncation will be done when the current transaction is committed.
  44252. **
  44253. ** This function is only called right before committing a transaction.
  44254. ** Once this function has been called, the transaction must either be
  44255. ** rolled back or committed. It is not safe to call this function and
  44256. ** then continue writing to the database.
  44257. */
  44258. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  44259. assert( pPager->dbSize>=nPage );
  44260. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  44261. pPager->dbSize = nPage;
  44262. /* At one point the code here called assertTruncateConstraint() to
  44263. ** ensure that all pages being truncated away by this operation are,
  44264. ** if one or more savepoints are open, present in the savepoint
  44265. ** journal so that they can be restored if the savepoint is rolled
  44266. ** back. This is no longer necessary as this function is now only
  44267. ** called right before committing a transaction. So although the
  44268. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  44269. ** they cannot be rolled back. So the assertTruncateConstraint() call
  44270. ** is no longer correct. */
  44271. }
  44272. /*
  44273. ** This function is called before attempting a hot-journal rollback. It
  44274. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  44275. ** size of the journal file so that the pager_playback() routine knows
  44276. ** that the entire journal file has been synced.
  44277. **
  44278. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  44279. ** that if a power-failure occurs during the rollback, the process that
  44280. ** attempts rollback following system recovery sees the same journal
  44281. ** content as this process.
  44282. **
  44283. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  44284. ** an SQLite error code.
  44285. */
  44286. static int pagerSyncHotJournal(Pager *pPager){
  44287. int rc = SQLITE_OK;
  44288. if( !pPager->noSync ){
  44289. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  44290. }
  44291. if( rc==SQLITE_OK ){
  44292. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  44293. }
  44294. return rc;
  44295. }
  44296. /*
  44297. ** Obtain a reference to a memory mapped page object for page number pgno.
  44298. ** The new object will use the pointer pData, obtained from xFetch().
  44299. ** If successful, set *ppPage to point to the new page reference
  44300. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  44301. ** *ppPage to zero.
  44302. **
  44303. ** Page references obtained by calling this function should be released
  44304. ** by calling pagerReleaseMapPage().
  44305. */
  44306. static int pagerAcquireMapPage(
  44307. Pager *pPager, /* Pager object */
  44308. Pgno pgno, /* Page number */
  44309. void *pData, /* xFetch()'d data for this page */
  44310. PgHdr **ppPage /* OUT: Acquired page object */
  44311. ){
  44312. PgHdr *p; /* Memory mapped page to return */
  44313. if( pPager->pMmapFreelist ){
  44314. *ppPage = p = pPager->pMmapFreelist;
  44315. pPager->pMmapFreelist = p->pDirty;
  44316. p->pDirty = 0;
  44317. memset(p->pExtra, 0, pPager->nExtra);
  44318. }else{
  44319. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  44320. if( p==0 ){
  44321. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  44322. return SQLITE_NOMEM;
  44323. }
  44324. p->pExtra = (void *)&p[1];
  44325. p->flags = PGHDR_MMAP;
  44326. p->nRef = 1;
  44327. p->pPager = pPager;
  44328. }
  44329. assert( p->pExtra==(void *)&p[1] );
  44330. assert( p->pPage==0 );
  44331. assert( p->flags==PGHDR_MMAP );
  44332. assert( p->pPager==pPager );
  44333. assert( p->nRef==1 );
  44334. p->pgno = pgno;
  44335. p->pData = pData;
  44336. pPager->nMmapOut++;
  44337. return SQLITE_OK;
  44338. }
  44339. /*
  44340. ** Release a reference to page pPg. pPg must have been returned by an
  44341. ** earlier call to pagerAcquireMapPage().
  44342. */
  44343. static void pagerReleaseMapPage(PgHdr *pPg){
  44344. Pager *pPager = pPg->pPager;
  44345. pPager->nMmapOut--;
  44346. pPg->pDirty = pPager->pMmapFreelist;
  44347. pPager->pMmapFreelist = pPg;
  44348. assert( pPager->fd->pMethods->iVersion>=3 );
  44349. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  44350. }
  44351. /*
  44352. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  44353. */
  44354. static void pagerFreeMapHdrs(Pager *pPager){
  44355. PgHdr *p;
  44356. PgHdr *pNext;
  44357. for(p=pPager->pMmapFreelist; p; p=pNext){
  44358. pNext = p->pDirty;
  44359. sqlite3_free(p);
  44360. }
  44361. }
  44362. /*
  44363. ** Shutdown the page cache. Free all memory and close all files.
  44364. **
  44365. ** If a transaction was in progress when this routine is called, that
  44366. ** transaction is rolled back. All outstanding pages are invalidated
  44367. ** and their memory is freed. Any attempt to use a page associated
  44368. ** with this page cache after this function returns will likely
  44369. ** result in a coredump.
  44370. **
  44371. ** This function always succeeds. If a transaction is active an attempt
  44372. ** is made to roll it back. If an error occurs during the rollback
  44373. ** a hot journal may be left in the filesystem but no error is returned
  44374. ** to the caller.
  44375. */
  44376. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  44377. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  44378. assert( assert_pager_state(pPager) );
  44379. disable_simulated_io_errors();
  44380. sqlite3BeginBenignMalloc();
  44381. pagerFreeMapHdrs(pPager);
  44382. /* pPager->errCode = 0; */
  44383. pPager->exclusiveMode = 0;
  44384. #ifndef SQLITE_OMIT_WAL
  44385. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  44386. pPager->pWal = 0;
  44387. #endif
  44388. pager_reset(pPager);
  44389. if( MEMDB ){
  44390. pager_unlock(pPager);
  44391. }else{
  44392. /* If it is open, sync the journal file before calling UnlockAndRollback.
  44393. ** If this is not done, then an unsynced portion of the open journal
  44394. ** file may be played back into the database. If a power failure occurs
  44395. ** while this is happening, the database could become corrupt.
  44396. **
  44397. ** If an error occurs while trying to sync the journal, shift the pager
  44398. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  44399. ** database and close the journal file without attempting to roll it
  44400. ** back or finalize it. The next database user will have to do hot-journal
  44401. ** rollback before accessing the database file.
  44402. */
  44403. if( isOpen(pPager->jfd) ){
  44404. pager_error(pPager, pagerSyncHotJournal(pPager));
  44405. }
  44406. pagerUnlockAndRollback(pPager);
  44407. }
  44408. sqlite3EndBenignMalloc();
  44409. enable_simulated_io_errors();
  44410. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  44411. IOTRACE(("CLOSE %p\n", pPager))
  44412. sqlite3OsClose(pPager->jfd);
  44413. sqlite3OsClose(pPager->fd);
  44414. sqlite3PageFree(pTmp);
  44415. sqlite3PcacheClose(pPager->pPCache);
  44416. #ifdef SQLITE_HAS_CODEC
  44417. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  44418. #endif
  44419. assert( !pPager->aSavepoint && !pPager->pInJournal );
  44420. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  44421. sqlite3_free(pPager);
  44422. return SQLITE_OK;
  44423. }
  44424. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  44425. /*
  44426. ** Return the page number for page pPg.
  44427. */
  44428. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  44429. return pPg->pgno;
  44430. }
  44431. #endif
  44432. /*
  44433. ** Increment the reference count for page pPg.
  44434. */
  44435. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  44436. sqlite3PcacheRef(pPg);
  44437. }
  44438. /*
  44439. ** Sync the journal. In other words, make sure all the pages that have
  44440. ** been written to the journal have actually reached the surface of the
  44441. ** disk and can be restored in the event of a hot-journal rollback.
  44442. **
  44443. ** If the Pager.noSync flag is set, then this function is a no-op.
  44444. ** Otherwise, the actions required depend on the journal-mode and the
  44445. ** device characteristics of the file-system, as follows:
  44446. **
  44447. ** * If the journal file is an in-memory journal file, no action need
  44448. ** be taken.
  44449. **
  44450. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  44451. ** then the nRec field of the most recently written journal header
  44452. ** is updated to contain the number of journal records that have
  44453. ** been written following it. If the pager is operating in full-sync
  44454. ** mode, then the journal file is synced before this field is updated.
  44455. **
  44456. ** * If the device does not support the SEQUENTIAL property, then
  44457. ** journal file is synced.
  44458. **
  44459. ** Or, in pseudo-code:
  44460. **
  44461. ** if( NOT <in-memory journal> ){
  44462. ** if( NOT SAFE_APPEND ){
  44463. ** if( <full-sync mode> ) xSync(<journal file>);
  44464. ** <update nRec field>
  44465. ** }
  44466. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  44467. ** }
  44468. **
  44469. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  44470. ** page currently held in memory before returning SQLITE_OK. If an IO
  44471. ** error is encountered, then the IO error code is returned to the caller.
  44472. */
  44473. static int syncJournal(Pager *pPager, int newHdr){
  44474. int rc; /* Return code */
  44475. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44476. || pPager->eState==PAGER_WRITER_DBMOD
  44477. );
  44478. assert( assert_pager_state(pPager) );
  44479. assert( !pagerUseWal(pPager) );
  44480. rc = sqlite3PagerExclusiveLock(pPager);
  44481. if( rc!=SQLITE_OK ) return rc;
  44482. if( !pPager->noSync ){
  44483. assert( !pPager->tempFile );
  44484. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  44485. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  44486. assert( isOpen(pPager->jfd) );
  44487. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  44488. /* This block deals with an obscure problem. If the last connection
  44489. ** that wrote to this database was operating in persistent-journal
  44490. ** mode, then the journal file may at this point actually be larger
  44491. ** than Pager.journalOff bytes. If the next thing in the journal
  44492. ** file happens to be a journal-header (written as part of the
  44493. ** previous connection's transaction), and a crash or power-failure
  44494. ** occurs after nRec is updated but before this connection writes
  44495. ** anything else to the journal file (or commits/rolls back its
  44496. ** transaction), then SQLite may become confused when doing the
  44497. ** hot-journal rollback following recovery. It may roll back all
  44498. ** of this connections data, then proceed to rolling back the old,
  44499. ** out-of-date data that follows it. Database corruption.
  44500. **
  44501. ** To work around this, if the journal file does appear to contain
  44502. ** a valid header following Pager.journalOff, then write a 0x00
  44503. ** byte to the start of it to prevent it from being recognized.
  44504. **
  44505. ** Variable iNextHdrOffset is set to the offset at which this
  44506. ** problematic header will occur, if it exists. aMagic is used
  44507. ** as a temporary buffer to inspect the first couple of bytes of
  44508. ** the potential journal header.
  44509. */
  44510. i64 iNextHdrOffset;
  44511. u8 aMagic[8];
  44512. u8 zHeader[sizeof(aJournalMagic)+4];
  44513. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  44514. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  44515. iNextHdrOffset = journalHdrOffset(pPager);
  44516. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  44517. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  44518. static const u8 zerobyte = 0;
  44519. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  44520. }
  44521. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  44522. return rc;
  44523. }
  44524. /* Write the nRec value into the journal file header. If in
  44525. ** full-synchronous mode, sync the journal first. This ensures that
  44526. ** all data has really hit the disk before nRec is updated to mark
  44527. ** it as a candidate for rollback.
  44528. **
  44529. ** This is not required if the persistent media supports the
  44530. ** SAFE_APPEND property. Because in this case it is not possible
  44531. ** for garbage data to be appended to the file, the nRec field
  44532. ** is populated with 0xFFFFFFFF when the journal header is written
  44533. ** and never needs to be updated.
  44534. */
  44535. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  44536. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  44537. IOTRACE(("JSYNC %p\n", pPager))
  44538. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  44539. if( rc!=SQLITE_OK ) return rc;
  44540. }
  44541. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  44542. rc = sqlite3OsWrite(
  44543. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  44544. );
  44545. if( rc!=SQLITE_OK ) return rc;
  44546. }
  44547. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  44548. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  44549. IOTRACE(("JSYNC %p\n", pPager))
  44550. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  44551. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  44552. );
  44553. if( rc!=SQLITE_OK ) return rc;
  44554. }
  44555. pPager->journalHdr = pPager->journalOff;
  44556. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  44557. pPager->nRec = 0;
  44558. rc = writeJournalHdr(pPager);
  44559. if( rc!=SQLITE_OK ) return rc;
  44560. }
  44561. }else{
  44562. pPager->journalHdr = pPager->journalOff;
  44563. }
  44564. }
  44565. /* Unless the pager is in noSync mode, the journal file was just
  44566. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  44567. ** all pages.
  44568. */
  44569. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  44570. pPager->eState = PAGER_WRITER_DBMOD;
  44571. assert( assert_pager_state(pPager) );
  44572. return SQLITE_OK;
  44573. }
  44574. /*
  44575. ** The argument is the first in a linked list of dirty pages connected
  44576. ** by the PgHdr.pDirty pointer. This function writes each one of the
  44577. ** in-memory pages in the list to the database file. The argument may
  44578. ** be NULL, representing an empty list. In this case this function is
  44579. ** a no-op.
  44580. **
  44581. ** The pager must hold at least a RESERVED lock when this function
  44582. ** is called. Before writing anything to the database file, this lock
  44583. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  44584. ** SQLITE_BUSY is returned and no data is written to the database file.
  44585. **
  44586. ** If the pager is a temp-file pager and the actual file-system file
  44587. ** is not yet open, it is created and opened before any data is
  44588. ** written out.
  44589. **
  44590. ** Once the lock has been upgraded and, if necessary, the file opened,
  44591. ** the pages are written out to the database file in list order. Writing
  44592. ** a page is skipped if it meets either of the following criteria:
  44593. **
  44594. ** * The page number is greater than Pager.dbSize, or
  44595. ** * The PGHDR_DONT_WRITE flag is set on the page.
  44596. **
  44597. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  44598. ** is updated accordingly. If page 1 is written out, then the value cached
  44599. ** in Pager.dbFileVers[] is updated to match the new value stored in
  44600. ** the database file.
  44601. **
  44602. ** If everything is successful, SQLITE_OK is returned. If an IO error
  44603. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  44604. ** be obtained, SQLITE_BUSY is returned.
  44605. */
  44606. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  44607. int rc = SQLITE_OK; /* Return code */
  44608. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  44609. assert( !pagerUseWal(pPager) );
  44610. assert( pPager->eState==PAGER_WRITER_DBMOD );
  44611. assert( pPager->eLock==EXCLUSIVE_LOCK );
  44612. /* If the file is a temp-file has not yet been opened, open it now. It
  44613. ** is not possible for rc to be other than SQLITE_OK if this branch
  44614. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  44615. */
  44616. if( !isOpen(pPager->fd) ){
  44617. assert( pPager->tempFile && rc==SQLITE_OK );
  44618. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  44619. }
  44620. /* Before the first write, give the VFS a hint of what the final
  44621. ** file size will be.
  44622. */
  44623. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  44624. if( rc==SQLITE_OK
  44625. && pPager->dbHintSize<pPager->dbSize
  44626. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  44627. ){
  44628. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  44629. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  44630. pPager->dbHintSize = pPager->dbSize;
  44631. }
  44632. while( rc==SQLITE_OK && pList ){
  44633. Pgno pgno = pList->pgno;
  44634. /* If there are dirty pages in the page cache with page numbers greater
  44635. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  44636. ** make the file smaller (presumably by auto-vacuum code). Do not write
  44637. ** any such pages to the file.
  44638. **
  44639. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  44640. ** set (set by sqlite3PagerDontWrite()).
  44641. */
  44642. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  44643. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  44644. char *pData; /* Data to write */
  44645. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  44646. if( pList->pgno==1 ) pager_write_changecounter(pList);
  44647. /* Encode the database */
  44648. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  44649. /* Write out the page data. */
  44650. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  44651. /* If page 1 was just written, update Pager.dbFileVers to match
  44652. ** the value now stored in the database file. If writing this
  44653. ** page caused the database file to grow, update dbFileSize.
  44654. */
  44655. if( pgno==1 ){
  44656. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  44657. }
  44658. if( pgno>pPager->dbFileSize ){
  44659. pPager->dbFileSize = pgno;
  44660. }
  44661. pPager->aStat[PAGER_STAT_WRITE]++;
  44662. /* Update any backup objects copying the contents of this pager. */
  44663. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  44664. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  44665. PAGERID(pPager), pgno, pager_pagehash(pList)));
  44666. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  44667. PAGER_INCR(sqlite3_pager_writedb_count);
  44668. }else{
  44669. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  44670. }
  44671. pager_set_pagehash(pList);
  44672. pList = pList->pDirty;
  44673. }
  44674. return rc;
  44675. }
  44676. /*
  44677. ** Ensure that the sub-journal file is open. If it is already open, this
  44678. ** function is a no-op.
  44679. **
  44680. ** SQLITE_OK is returned if everything goes according to plan. An
  44681. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  44682. ** fails.
  44683. */
  44684. static int openSubJournal(Pager *pPager){
  44685. int rc = SQLITE_OK;
  44686. if( !isOpen(pPager->sjfd) ){
  44687. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  44688. sqlite3MemJournalOpen(pPager->sjfd);
  44689. }else{
  44690. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  44691. }
  44692. }
  44693. return rc;
  44694. }
  44695. /*
  44696. ** Append a record of the current state of page pPg to the sub-journal.
  44697. **
  44698. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  44699. ** for all open savepoints before returning.
  44700. **
  44701. ** This function returns SQLITE_OK if everything is successful, an IO
  44702. ** error code if the attempt to write to the sub-journal fails, or
  44703. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  44704. ** bitvec.
  44705. */
  44706. static int subjournalPage(PgHdr *pPg){
  44707. int rc = SQLITE_OK;
  44708. Pager *pPager = pPg->pPager;
  44709. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  44710. /* Open the sub-journal, if it has not already been opened */
  44711. assert( pPager->useJournal );
  44712. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  44713. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  44714. assert( pagerUseWal(pPager)
  44715. || pageInJournal(pPager, pPg)
  44716. || pPg->pgno>pPager->dbOrigSize
  44717. );
  44718. rc = openSubJournal(pPager);
  44719. /* If the sub-journal was opened successfully (or was already open),
  44720. ** write the journal record into the file. */
  44721. if( rc==SQLITE_OK ){
  44722. void *pData = pPg->pData;
  44723. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  44724. char *pData2;
  44725. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  44726. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  44727. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  44728. if( rc==SQLITE_OK ){
  44729. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  44730. }
  44731. }
  44732. }
  44733. if( rc==SQLITE_OK ){
  44734. pPager->nSubRec++;
  44735. assert( pPager->nSavepoint>0 );
  44736. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  44737. }
  44738. return rc;
  44739. }
  44740. static int subjournalPageIfRequired(PgHdr *pPg){
  44741. if( subjRequiresPage(pPg) ){
  44742. return subjournalPage(pPg);
  44743. }else{
  44744. return SQLITE_OK;
  44745. }
  44746. }
  44747. /*
  44748. ** This function is called by the pcache layer when it has reached some
  44749. ** soft memory limit. The first argument is a pointer to a Pager object
  44750. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  44751. ** database). The second argument is a reference to a page that is
  44752. ** currently dirty but has no outstanding references. The page
  44753. ** is always associated with the Pager object passed as the first
  44754. ** argument.
  44755. **
  44756. ** The job of this function is to make pPg clean by writing its contents
  44757. ** out to the database file, if possible. This may involve syncing the
  44758. ** journal file.
  44759. **
  44760. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  44761. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  44762. ** page clean, the IO error code is returned. If the page cannot be
  44763. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  44764. ** is returned by sqlite3PcacheMakeClean() is not called.
  44765. */
  44766. static int pagerStress(void *p, PgHdr *pPg){
  44767. Pager *pPager = (Pager *)p;
  44768. int rc = SQLITE_OK;
  44769. assert( pPg->pPager==pPager );
  44770. assert( pPg->flags&PGHDR_DIRTY );
  44771. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  44772. ** journal (and adding a new header) is not allowed. This occurs
  44773. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  44774. ** pages belonging to the same sector.
  44775. **
  44776. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  44777. ** regardless of whether or not a sync is required. This is set during
  44778. ** a rollback or by user request, respectively.
  44779. **
  44780. ** Spilling is also prohibited when in an error state since that could
  44781. ** lead to database corruption. In the current implementation it
  44782. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  44783. ** while in the error state, hence it is impossible for this routine to
  44784. ** be called in the error state. Nevertheless, we include a NEVER()
  44785. ** test for the error state as a safeguard against future changes.
  44786. */
  44787. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  44788. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  44789. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  44790. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  44791. if( pPager->doNotSpill
  44792. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  44793. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  44794. ){
  44795. return SQLITE_OK;
  44796. }
  44797. pPg->pDirty = 0;
  44798. if( pagerUseWal(pPager) ){
  44799. /* Write a single frame for this page to the log. */
  44800. rc = subjournalPageIfRequired(pPg);
  44801. if( rc==SQLITE_OK ){
  44802. rc = pagerWalFrames(pPager, pPg, 0, 0);
  44803. }
  44804. }else{
  44805. /* Sync the journal file if required. */
  44806. if( pPg->flags&PGHDR_NEED_SYNC
  44807. || pPager->eState==PAGER_WRITER_CACHEMOD
  44808. ){
  44809. rc = syncJournal(pPager, 1);
  44810. }
  44811. /* Write the contents of the page out to the database file. */
  44812. if( rc==SQLITE_OK ){
  44813. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  44814. rc = pager_write_pagelist(pPager, pPg);
  44815. }
  44816. }
  44817. /* Mark the page as clean. */
  44818. if( rc==SQLITE_OK ){
  44819. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  44820. sqlite3PcacheMakeClean(pPg);
  44821. }
  44822. return pager_error(pPager, rc);
  44823. }
  44824. /*
  44825. ** Flush all unreferenced dirty pages to disk.
  44826. */
  44827. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  44828. int rc = pPager->errCode;
  44829. if( !MEMDB ){
  44830. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  44831. assert( assert_pager_state(pPager) );
  44832. while( rc==SQLITE_OK && pList ){
  44833. PgHdr *pNext = pList->pDirty;
  44834. if( pList->nRef==0 ){
  44835. rc = pagerStress((void*)pPager, pList);
  44836. }
  44837. pList = pNext;
  44838. }
  44839. }
  44840. return rc;
  44841. }
  44842. /*
  44843. ** Allocate and initialize a new Pager object and put a pointer to it
  44844. ** in *ppPager. The pager should eventually be freed by passing it
  44845. ** to sqlite3PagerClose().
  44846. **
  44847. ** The zFilename argument is the path to the database file to open.
  44848. ** If zFilename is NULL then a randomly-named temporary file is created
  44849. ** and used as the file to be cached. Temporary files are be deleted
  44850. ** automatically when they are closed. If zFilename is ":memory:" then
  44851. ** all information is held in cache. It is never written to disk.
  44852. ** This can be used to implement an in-memory database.
  44853. **
  44854. ** The nExtra parameter specifies the number of bytes of space allocated
  44855. ** along with each page reference. This space is available to the user
  44856. ** via the sqlite3PagerGetExtra() API.
  44857. **
  44858. ** The flags argument is used to specify properties that affect the
  44859. ** operation of the pager. It should be passed some bitwise combination
  44860. ** of the PAGER_* flags.
  44861. **
  44862. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  44863. ** of the xOpen() method of the supplied VFS when opening files.
  44864. **
  44865. ** If the pager object is allocated and the specified file opened
  44866. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  44867. ** the new pager object. If an error occurs, *ppPager is set to NULL
  44868. ** and error code returned. This function may return SQLITE_NOMEM
  44869. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  44870. ** various SQLITE_IO_XXX errors.
  44871. */
  44872. SQLITE_PRIVATE int sqlite3PagerOpen(
  44873. sqlite3_vfs *pVfs, /* The virtual file system to use */
  44874. Pager **ppPager, /* OUT: Return the Pager structure here */
  44875. const char *zFilename, /* Name of the database file to open */
  44876. int nExtra, /* Extra bytes append to each in-memory page */
  44877. int flags, /* flags controlling this file */
  44878. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  44879. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  44880. ){
  44881. u8 *pPtr;
  44882. Pager *pPager = 0; /* Pager object to allocate and return */
  44883. int rc = SQLITE_OK; /* Return code */
  44884. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  44885. int memDb = 0; /* True if this is an in-memory file */
  44886. int readOnly = 0; /* True if this is a read-only file */
  44887. int journalFileSize; /* Bytes to allocate for each journal fd */
  44888. char *zPathname = 0; /* Full path to database file */
  44889. int nPathname = 0; /* Number of bytes in zPathname */
  44890. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  44891. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  44892. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  44893. const char *zUri = 0; /* URI args to copy */
  44894. int nUri = 0; /* Number of bytes of URI args at *zUri */
  44895. /* Figure out how much space is required for each journal file-handle
  44896. ** (there are two of them, the main journal and the sub-journal). This
  44897. ** is the maximum space required for an in-memory journal file handle
  44898. ** and a regular journal file-handle. Note that a "regular journal-handle"
  44899. ** may be a wrapper capable of caching the first portion of the journal
  44900. ** file in memory to implement the atomic-write optimization (see
  44901. ** source file journal.c).
  44902. */
  44903. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  44904. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  44905. }else{
  44906. journalFileSize = ROUND8(sqlite3MemJournalSize());
  44907. }
  44908. /* Set the output variable to NULL in case an error occurs. */
  44909. *ppPager = 0;
  44910. #ifndef SQLITE_OMIT_MEMORYDB
  44911. if( flags & PAGER_MEMORY ){
  44912. memDb = 1;
  44913. if( zFilename && zFilename[0] ){
  44914. zPathname = sqlite3DbStrDup(0, zFilename);
  44915. if( zPathname==0 ) return SQLITE_NOMEM;
  44916. nPathname = sqlite3Strlen30(zPathname);
  44917. zFilename = 0;
  44918. }
  44919. }
  44920. #endif
  44921. /* Compute and store the full pathname in an allocated buffer pointed
  44922. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  44923. ** leave both nPathname and zPathname set to 0.
  44924. */
  44925. if( zFilename && zFilename[0] ){
  44926. const char *z;
  44927. nPathname = pVfs->mxPathname+1;
  44928. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  44929. if( zPathname==0 ){
  44930. return SQLITE_NOMEM;
  44931. }
  44932. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  44933. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  44934. nPathname = sqlite3Strlen30(zPathname);
  44935. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  44936. while( *z ){
  44937. z += sqlite3Strlen30(z)+1;
  44938. z += sqlite3Strlen30(z)+1;
  44939. }
  44940. nUri = (int)(&z[1] - zUri);
  44941. assert( nUri>=0 );
  44942. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  44943. /* This branch is taken when the journal path required by
  44944. ** the database being opened will be more than pVfs->mxPathname
  44945. ** bytes in length. This means the database cannot be opened,
  44946. ** as it will not be possible to open the journal file or even
  44947. ** check for a hot-journal before reading.
  44948. */
  44949. rc = SQLITE_CANTOPEN_BKPT;
  44950. }
  44951. if( rc!=SQLITE_OK ){
  44952. sqlite3DbFree(0, zPathname);
  44953. return rc;
  44954. }
  44955. }
  44956. /* Allocate memory for the Pager structure, PCache object, the
  44957. ** three file descriptors, the database file name and the journal
  44958. ** file name. The layout in memory is as follows:
  44959. **
  44960. ** Pager object (sizeof(Pager) bytes)
  44961. ** PCache object (sqlite3PcacheSize() bytes)
  44962. ** Database file handle (pVfs->szOsFile bytes)
  44963. ** Sub-journal file handle (journalFileSize bytes)
  44964. ** Main journal file handle (journalFileSize bytes)
  44965. ** Database file name (nPathname+1 bytes)
  44966. ** Journal file name (nPathname+8+1 bytes)
  44967. */
  44968. pPtr = (u8 *)sqlite3MallocZero(
  44969. ROUND8(sizeof(*pPager)) + /* Pager structure */
  44970. ROUND8(pcacheSize) + /* PCache object */
  44971. ROUND8(pVfs->szOsFile) + /* The main db file */
  44972. journalFileSize * 2 + /* The two journal files */
  44973. nPathname + 1 + nUri + /* zFilename */
  44974. nPathname + 8 + 2 /* zJournal */
  44975. #ifndef SQLITE_OMIT_WAL
  44976. + nPathname + 4 + 2 /* zWal */
  44977. #endif
  44978. );
  44979. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  44980. if( !pPtr ){
  44981. sqlite3DbFree(0, zPathname);
  44982. return SQLITE_NOMEM;
  44983. }
  44984. pPager = (Pager*)(pPtr);
  44985. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  44986. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  44987. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  44988. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  44989. pPager->zFilename = (char*)(pPtr += journalFileSize);
  44990. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  44991. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  44992. if( zPathname ){
  44993. assert( nPathname>0 );
  44994. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  44995. memcpy(pPager->zFilename, zPathname, nPathname);
  44996. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  44997. memcpy(pPager->zJournal, zPathname, nPathname);
  44998. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  44999. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  45000. #ifndef SQLITE_OMIT_WAL
  45001. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  45002. memcpy(pPager->zWal, zPathname, nPathname);
  45003. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  45004. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  45005. #endif
  45006. sqlite3DbFree(0, zPathname);
  45007. }
  45008. pPager->pVfs = pVfs;
  45009. pPager->vfsFlags = vfsFlags;
  45010. /* Open the pager file.
  45011. */
  45012. if( zFilename && zFilename[0] ){
  45013. int fout = 0; /* VFS flags returned by xOpen() */
  45014. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  45015. assert( !memDb );
  45016. readOnly = (fout&SQLITE_OPEN_READONLY);
  45017. /* If the file was successfully opened for read/write access,
  45018. ** choose a default page size in case we have to create the
  45019. ** database file. The default page size is the maximum of:
  45020. **
  45021. ** + SQLITE_DEFAULT_PAGE_SIZE,
  45022. ** + The value returned by sqlite3OsSectorSize()
  45023. ** + The largest page size that can be written atomically.
  45024. */
  45025. if( rc==SQLITE_OK ){
  45026. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  45027. if( !readOnly ){
  45028. setSectorSize(pPager);
  45029. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  45030. if( szPageDflt<pPager->sectorSize ){
  45031. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  45032. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  45033. }else{
  45034. szPageDflt = (u32)pPager->sectorSize;
  45035. }
  45036. }
  45037. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  45038. {
  45039. int ii;
  45040. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  45041. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  45042. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  45043. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  45044. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  45045. szPageDflt = ii;
  45046. }
  45047. }
  45048. }
  45049. #endif
  45050. }
  45051. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  45052. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  45053. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  45054. vfsFlags |= SQLITE_OPEN_READONLY;
  45055. goto act_like_temp_file;
  45056. }
  45057. }
  45058. }else{
  45059. /* If a temporary file is requested, it is not opened immediately.
  45060. ** In this case we accept the default page size and delay actually
  45061. ** opening the file until the first call to OsWrite().
  45062. **
  45063. ** This branch is also run for an in-memory database. An in-memory
  45064. ** database is the same as a temp-file that is never written out to
  45065. ** disk and uses an in-memory rollback journal.
  45066. **
  45067. ** This branch also runs for files marked as immutable.
  45068. */
  45069. act_like_temp_file:
  45070. tempFile = 1;
  45071. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  45072. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  45073. pPager->noLock = 1; /* Do no locking */
  45074. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  45075. }
  45076. /* The following call to PagerSetPagesize() serves to set the value of
  45077. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  45078. */
  45079. if( rc==SQLITE_OK ){
  45080. assert( pPager->memDb==0 );
  45081. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  45082. testcase( rc!=SQLITE_OK );
  45083. }
  45084. /* Initialize the PCache object. */
  45085. if( rc==SQLITE_OK ){
  45086. assert( nExtra<1000 );
  45087. nExtra = ROUND8(nExtra);
  45088. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  45089. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  45090. }
  45091. /* If an error occurred above, free the Pager structure and close the file.
  45092. */
  45093. if( rc!=SQLITE_OK ){
  45094. sqlite3OsClose(pPager->fd);
  45095. sqlite3PageFree(pPager->pTmpSpace);
  45096. sqlite3_free(pPager);
  45097. return rc;
  45098. }
  45099. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  45100. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  45101. pPager->useJournal = (u8)useJournal;
  45102. /* pPager->stmtOpen = 0; */
  45103. /* pPager->stmtInUse = 0; */
  45104. /* pPager->nRef = 0; */
  45105. /* pPager->stmtSize = 0; */
  45106. /* pPager->stmtJSize = 0; */
  45107. /* pPager->nPage = 0; */
  45108. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  45109. /* pPager->state = PAGER_UNLOCK; */
  45110. /* pPager->errMask = 0; */
  45111. pPager->tempFile = (u8)tempFile;
  45112. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  45113. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  45114. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  45115. pPager->exclusiveMode = (u8)tempFile;
  45116. pPager->changeCountDone = pPager->tempFile;
  45117. pPager->memDb = (u8)memDb;
  45118. pPager->readOnly = (u8)readOnly;
  45119. assert( useJournal || pPager->tempFile );
  45120. pPager->noSync = pPager->tempFile;
  45121. if( pPager->noSync ){
  45122. assert( pPager->fullSync==0 );
  45123. assert( pPager->syncFlags==0 );
  45124. assert( pPager->walSyncFlags==0 );
  45125. assert( pPager->ckptSyncFlags==0 );
  45126. }else{
  45127. pPager->fullSync = 1;
  45128. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  45129. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  45130. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  45131. }
  45132. /* pPager->pFirst = 0; */
  45133. /* pPager->pFirstSynced = 0; */
  45134. /* pPager->pLast = 0; */
  45135. pPager->nExtra = (u16)nExtra;
  45136. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  45137. assert( isOpen(pPager->fd) || tempFile );
  45138. setSectorSize(pPager);
  45139. if( !useJournal ){
  45140. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  45141. }else if( memDb ){
  45142. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  45143. }
  45144. /* pPager->xBusyHandler = 0; */
  45145. /* pPager->pBusyHandlerArg = 0; */
  45146. pPager->xReiniter = xReinit;
  45147. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  45148. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  45149. *ppPager = pPager;
  45150. return SQLITE_OK;
  45151. }
  45152. /* Verify that the database file has not be deleted or renamed out from
  45153. ** under the pager. Return SQLITE_OK if the database is still were it ought
  45154. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  45155. ** code from sqlite3OsAccess()) if the database has gone missing.
  45156. */
  45157. static int databaseIsUnmoved(Pager *pPager){
  45158. int bHasMoved = 0;
  45159. int rc;
  45160. if( pPager->tempFile ) return SQLITE_OK;
  45161. if( pPager->dbSize==0 ) return SQLITE_OK;
  45162. assert( pPager->zFilename && pPager->zFilename[0] );
  45163. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  45164. if( rc==SQLITE_NOTFOUND ){
  45165. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  45166. ** has not been moved. That is the historical behavior of SQLite: prior to
  45167. ** version 3.8.3, it never checked */
  45168. rc = SQLITE_OK;
  45169. }else if( rc==SQLITE_OK && bHasMoved ){
  45170. rc = SQLITE_READONLY_DBMOVED;
  45171. }
  45172. return rc;
  45173. }
  45174. /*
  45175. ** This function is called after transitioning from PAGER_UNLOCK to
  45176. ** PAGER_SHARED state. It tests if there is a hot journal present in
  45177. ** the file-system for the given pager. A hot journal is one that
  45178. ** needs to be played back. According to this function, a hot-journal
  45179. ** file exists if the following criteria are met:
  45180. **
  45181. ** * The journal file exists in the file system, and
  45182. ** * No process holds a RESERVED or greater lock on the database file, and
  45183. ** * The database file itself is greater than 0 bytes in size, and
  45184. ** * The first byte of the journal file exists and is not 0x00.
  45185. **
  45186. ** If the current size of the database file is 0 but a journal file
  45187. ** exists, that is probably an old journal left over from a prior
  45188. ** database with the same name. In this case the journal file is
  45189. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  45190. ** is returned.
  45191. **
  45192. ** This routine does not check if there is a master journal filename
  45193. ** at the end of the file. If there is, and that master journal file
  45194. ** does not exist, then the journal file is not really hot. In this
  45195. ** case this routine will return a false-positive. The pager_playback()
  45196. ** routine will discover that the journal file is not really hot and
  45197. ** will not roll it back.
  45198. **
  45199. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  45200. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  45201. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  45202. ** to determine whether or not a hot-journal file exists, the IO error
  45203. ** code is returned and the value of *pExists is undefined.
  45204. */
  45205. static int hasHotJournal(Pager *pPager, int *pExists){
  45206. sqlite3_vfs * const pVfs = pPager->pVfs;
  45207. int rc = SQLITE_OK; /* Return code */
  45208. int exists = 1; /* True if a journal file is present */
  45209. int jrnlOpen = !!isOpen(pPager->jfd);
  45210. assert( pPager->useJournal );
  45211. assert( isOpen(pPager->fd) );
  45212. assert( pPager->eState==PAGER_OPEN );
  45213. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  45214. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  45215. ));
  45216. *pExists = 0;
  45217. if( !jrnlOpen ){
  45218. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  45219. }
  45220. if( rc==SQLITE_OK && exists ){
  45221. int locked = 0; /* True if some process holds a RESERVED lock */
  45222. /* Race condition here: Another process might have been holding the
  45223. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  45224. ** call above, but then delete the journal and drop the lock before
  45225. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  45226. ** is the case, this routine might think there is a hot journal when
  45227. ** in fact there is none. This results in a false-positive which will
  45228. ** be dealt with by the playback routine. Ticket #3883.
  45229. */
  45230. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  45231. if( rc==SQLITE_OK && !locked ){
  45232. Pgno nPage; /* Number of pages in database file */
  45233. rc = pagerPagecount(pPager, &nPage);
  45234. if( rc==SQLITE_OK ){
  45235. /* If the database is zero pages in size, that means that either (1) the
  45236. ** journal is a remnant from a prior database with the same name where
  45237. ** the database file but not the journal was deleted, or (2) the initial
  45238. ** transaction that populates a new database is being rolled back.
  45239. ** In either case, the journal file can be deleted. However, take care
  45240. ** not to delete the journal file if it is already open due to
  45241. ** journal_mode=PERSIST.
  45242. */
  45243. if( nPage==0 && !jrnlOpen ){
  45244. sqlite3BeginBenignMalloc();
  45245. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  45246. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  45247. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  45248. }
  45249. sqlite3EndBenignMalloc();
  45250. }else{
  45251. /* The journal file exists and no other connection has a reserved
  45252. ** or greater lock on the database file. Now check that there is
  45253. ** at least one non-zero bytes at the start of the journal file.
  45254. ** If there is, then we consider this journal to be hot. If not,
  45255. ** it can be ignored.
  45256. */
  45257. if( !jrnlOpen ){
  45258. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  45259. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  45260. }
  45261. if( rc==SQLITE_OK ){
  45262. u8 first = 0;
  45263. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  45264. if( rc==SQLITE_IOERR_SHORT_READ ){
  45265. rc = SQLITE_OK;
  45266. }
  45267. if( !jrnlOpen ){
  45268. sqlite3OsClose(pPager->jfd);
  45269. }
  45270. *pExists = (first!=0);
  45271. }else if( rc==SQLITE_CANTOPEN ){
  45272. /* If we cannot open the rollback journal file in order to see if
  45273. ** it has a zero header, that might be due to an I/O error, or
  45274. ** it might be due to the race condition described above and in
  45275. ** ticket #3883. Either way, assume that the journal is hot.
  45276. ** This might be a false positive. But if it is, then the
  45277. ** automatic journal playback and recovery mechanism will deal
  45278. ** with it under an EXCLUSIVE lock where we do not need to
  45279. ** worry so much with race conditions.
  45280. */
  45281. *pExists = 1;
  45282. rc = SQLITE_OK;
  45283. }
  45284. }
  45285. }
  45286. }
  45287. }
  45288. return rc;
  45289. }
  45290. /*
  45291. ** This function is called to obtain a shared lock on the database file.
  45292. ** It is illegal to call sqlite3PagerGet() until after this function
  45293. ** has been successfully called. If a shared-lock is already held when
  45294. ** this function is called, it is a no-op.
  45295. **
  45296. ** The following operations are also performed by this function.
  45297. **
  45298. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  45299. ** on the database file), then an attempt is made to obtain a
  45300. ** SHARED lock on the database file. Immediately after obtaining
  45301. ** the SHARED lock, the file-system is checked for a hot-journal,
  45302. ** which is played back if present. Following any hot-journal
  45303. ** rollback, the contents of the cache are validated by checking
  45304. ** the 'change-counter' field of the database file header and
  45305. ** discarded if they are found to be invalid.
  45306. **
  45307. ** 2) If the pager is running in exclusive-mode, and there are currently
  45308. ** no outstanding references to any pages, and is in the error state,
  45309. ** then an attempt is made to clear the error state by discarding
  45310. ** the contents of the page cache and rolling back any open journal
  45311. ** file.
  45312. **
  45313. ** If everything is successful, SQLITE_OK is returned. If an IO error
  45314. ** occurs while locking the database, checking for a hot-journal file or
  45315. ** rolling back a journal file, the IO error code is returned.
  45316. */
  45317. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  45318. int rc = SQLITE_OK; /* Return code */
  45319. /* This routine is only called from b-tree and only when there are no
  45320. ** outstanding pages. This implies that the pager state should either
  45321. ** be OPEN or READER. READER is only possible if the pager is or was in
  45322. ** exclusive access mode.
  45323. */
  45324. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  45325. assert( assert_pager_state(pPager) );
  45326. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  45327. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  45328. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  45329. int bHotJournal = 1; /* True if there exists a hot journal-file */
  45330. assert( !MEMDB );
  45331. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  45332. if( rc!=SQLITE_OK ){
  45333. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  45334. goto failed;
  45335. }
  45336. /* If a journal file exists, and there is no RESERVED lock on the
  45337. ** database file, then it either needs to be played back or deleted.
  45338. */
  45339. if( pPager->eLock<=SHARED_LOCK ){
  45340. rc = hasHotJournal(pPager, &bHotJournal);
  45341. }
  45342. if( rc!=SQLITE_OK ){
  45343. goto failed;
  45344. }
  45345. if( bHotJournal ){
  45346. if( pPager->readOnly ){
  45347. rc = SQLITE_READONLY_ROLLBACK;
  45348. goto failed;
  45349. }
  45350. /* Get an EXCLUSIVE lock on the database file. At this point it is
  45351. ** important that a RESERVED lock is not obtained on the way to the
  45352. ** EXCLUSIVE lock. If it were, another process might open the
  45353. ** database file, detect the RESERVED lock, and conclude that the
  45354. ** database is safe to read while this process is still rolling the
  45355. ** hot-journal back.
  45356. **
  45357. ** Because the intermediate RESERVED lock is not requested, any
  45358. ** other process attempting to access the database file will get to
  45359. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  45360. ** on the database file.
  45361. **
  45362. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  45363. ** downgraded to SHARED_LOCK before this function returns.
  45364. */
  45365. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  45366. if( rc!=SQLITE_OK ){
  45367. goto failed;
  45368. }
  45369. /* If it is not already open and the file exists on disk, open the
  45370. ** journal for read/write access. Write access is required because
  45371. ** in exclusive-access mode the file descriptor will be kept open
  45372. ** and possibly used for a transaction later on. Also, write-access
  45373. ** is usually required to finalize the journal in journal_mode=persist
  45374. ** mode (and also for journal_mode=truncate on some systems).
  45375. **
  45376. ** If the journal does not exist, it usually means that some
  45377. ** other connection managed to get in and roll it back before
  45378. ** this connection obtained the exclusive lock above. Or, it
  45379. ** may mean that the pager was in the error-state when this
  45380. ** function was called and the journal file does not exist.
  45381. */
  45382. if( !isOpen(pPager->jfd) ){
  45383. sqlite3_vfs * const pVfs = pPager->pVfs;
  45384. int bExists; /* True if journal file exists */
  45385. rc = sqlite3OsAccess(
  45386. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  45387. if( rc==SQLITE_OK && bExists ){
  45388. int fout = 0;
  45389. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  45390. assert( !pPager->tempFile );
  45391. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  45392. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  45393. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  45394. rc = SQLITE_CANTOPEN_BKPT;
  45395. sqlite3OsClose(pPager->jfd);
  45396. }
  45397. }
  45398. }
  45399. /* Playback and delete the journal. Drop the database write
  45400. ** lock and reacquire the read lock. Purge the cache before
  45401. ** playing back the hot-journal so that we don't end up with
  45402. ** an inconsistent cache. Sync the hot journal before playing
  45403. ** it back since the process that crashed and left the hot journal
  45404. ** probably did not sync it and we are required to always sync
  45405. ** the journal before playing it back.
  45406. */
  45407. if( isOpen(pPager->jfd) ){
  45408. assert( rc==SQLITE_OK );
  45409. rc = pagerSyncHotJournal(pPager);
  45410. if( rc==SQLITE_OK ){
  45411. rc = pager_playback(pPager, 1);
  45412. pPager->eState = PAGER_OPEN;
  45413. }
  45414. }else if( !pPager->exclusiveMode ){
  45415. pagerUnlockDb(pPager, SHARED_LOCK);
  45416. }
  45417. if( rc!=SQLITE_OK ){
  45418. /* This branch is taken if an error occurs while trying to open
  45419. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  45420. ** pager_unlock() routine will be called before returning to unlock
  45421. ** the file. If the unlock attempt fails, then Pager.eLock must be
  45422. ** set to UNKNOWN_LOCK (see the comment above the #define for
  45423. ** UNKNOWN_LOCK above for an explanation).
  45424. **
  45425. ** In order to get pager_unlock() to do this, set Pager.eState to
  45426. ** PAGER_ERROR now. This is not actually counted as a transition
  45427. ** to ERROR state in the state diagram at the top of this file,
  45428. ** since we know that the same call to pager_unlock() will very
  45429. ** shortly transition the pager object to the OPEN state. Calling
  45430. ** assert_pager_state() would fail now, as it should not be possible
  45431. ** to be in ERROR state when there are zero outstanding page
  45432. ** references.
  45433. */
  45434. pager_error(pPager, rc);
  45435. goto failed;
  45436. }
  45437. assert( pPager->eState==PAGER_OPEN );
  45438. assert( (pPager->eLock==SHARED_LOCK)
  45439. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  45440. );
  45441. }
  45442. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  45443. /* The shared-lock has just been acquired then check to
  45444. ** see if the database has been modified. If the database has changed,
  45445. ** flush the cache. The hasHeldSharedLock flag prevents this from
  45446. ** occurring on the very first access to a file, in order to save a
  45447. ** single unnecessary sqlite3OsRead() call at the start-up.
  45448. **
  45449. ** Database changes are detected by looking at 15 bytes beginning
  45450. ** at offset 24 into the file. The first 4 of these 16 bytes are
  45451. ** a 32-bit counter that is incremented with each change. The
  45452. ** other bytes change randomly with each file change when
  45453. ** a codec is in use.
  45454. **
  45455. ** There is a vanishingly small chance that a change will not be
  45456. ** detected. The chance of an undetected change is so small that
  45457. ** it can be neglected.
  45458. */
  45459. Pgno nPage = 0;
  45460. char dbFileVers[sizeof(pPager->dbFileVers)];
  45461. rc = pagerPagecount(pPager, &nPage);
  45462. if( rc ) goto failed;
  45463. if( nPage>0 ){
  45464. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  45465. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  45466. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  45467. goto failed;
  45468. }
  45469. }else{
  45470. memset(dbFileVers, 0, sizeof(dbFileVers));
  45471. }
  45472. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  45473. pager_reset(pPager);
  45474. /* Unmap the database file. It is possible that external processes
  45475. ** may have truncated the database file and then extended it back
  45476. ** to its original size while this process was not holding a lock.
  45477. ** In this case there may exist a Pager.pMap mapping that appears
  45478. ** to be the right size but is not actually valid. Avoid this
  45479. ** possibility by unmapping the db here. */
  45480. if( USEFETCH(pPager) ){
  45481. sqlite3OsUnfetch(pPager->fd, 0, 0);
  45482. }
  45483. }
  45484. }
  45485. /* If there is a WAL file in the file-system, open this database in WAL
  45486. ** mode. Otherwise, the following function call is a no-op.
  45487. */
  45488. rc = pagerOpenWalIfPresent(pPager);
  45489. #ifndef SQLITE_OMIT_WAL
  45490. assert( pPager->pWal==0 || rc==SQLITE_OK );
  45491. #endif
  45492. }
  45493. if( pagerUseWal(pPager) ){
  45494. assert( rc==SQLITE_OK );
  45495. rc = pagerBeginReadTransaction(pPager);
  45496. }
  45497. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  45498. rc = pagerPagecount(pPager, &pPager->dbSize);
  45499. }
  45500. failed:
  45501. if( rc!=SQLITE_OK ){
  45502. assert( !MEMDB );
  45503. pager_unlock(pPager);
  45504. assert( pPager->eState==PAGER_OPEN );
  45505. }else{
  45506. pPager->eState = PAGER_READER;
  45507. pPager->hasHeldSharedLock = 1;
  45508. }
  45509. return rc;
  45510. }
  45511. /*
  45512. ** If the reference count has reached zero, rollback any active
  45513. ** transaction and unlock the pager.
  45514. **
  45515. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  45516. ** the rollback journal, the unlock is not performed and there is
  45517. ** nothing to rollback, so this routine is a no-op.
  45518. */
  45519. static void pagerUnlockIfUnused(Pager *pPager){
  45520. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  45521. pagerUnlockAndRollback(pPager);
  45522. }
  45523. }
  45524. /*
  45525. ** Acquire a reference to page number pgno in pager pPager (a page
  45526. ** reference has type DbPage*). If the requested reference is
  45527. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  45528. **
  45529. ** If the requested page is already in the cache, it is returned.
  45530. ** Otherwise, a new page object is allocated and populated with data
  45531. ** read from the database file. In some cases, the pcache module may
  45532. ** choose not to allocate a new page object and may reuse an existing
  45533. ** object with no outstanding references.
  45534. **
  45535. ** The extra data appended to a page is always initialized to zeros the
  45536. ** first time a page is loaded into memory. If the page requested is
  45537. ** already in the cache when this function is called, then the extra
  45538. ** data is left as it was when the page object was last used.
  45539. **
  45540. ** If the database image is smaller than the requested page or if a
  45541. ** non-zero value is passed as the noContent parameter and the
  45542. ** requested page is not already stored in the cache, then no
  45543. ** actual disk read occurs. In this case the memory image of the
  45544. ** page is initialized to all zeros.
  45545. **
  45546. ** If noContent is true, it means that we do not care about the contents
  45547. ** of the page. This occurs in two scenarios:
  45548. **
  45549. ** a) When reading a free-list leaf page from the database, and
  45550. **
  45551. ** b) When a savepoint is being rolled back and we need to load
  45552. ** a new page into the cache to be filled with the data read
  45553. ** from the savepoint journal.
  45554. **
  45555. ** If noContent is true, then the data returned is zeroed instead of
  45556. ** being read from the database. Additionally, the bits corresponding
  45557. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  45558. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  45559. ** savepoints are set. This means if the page is made writable at any
  45560. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  45561. ** will not be journaled. This saves IO.
  45562. **
  45563. ** The acquisition might fail for several reasons. In all cases,
  45564. ** an appropriate error code is returned and *ppPage is set to NULL.
  45565. **
  45566. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  45567. ** to find a page in the in-memory cache first. If the page is not already
  45568. ** in memory, this routine goes to disk to read it in whereas Lookup()
  45569. ** just returns 0. This routine acquires a read-lock the first time it
  45570. ** has to go to disk, and could also playback an old journal if necessary.
  45571. ** Since Lookup() never goes to disk, it never has to deal with locks
  45572. ** or journal files.
  45573. */
  45574. SQLITE_PRIVATE int sqlite3PagerGet(
  45575. Pager *pPager, /* The pager open on the database file */
  45576. Pgno pgno, /* Page number to fetch */
  45577. DbPage **ppPage, /* Write a pointer to the page here */
  45578. int flags /* PAGER_GET_XXX flags */
  45579. ){
  45580. int rc = SQLITE_OK;
  45581. PgHdr *pPg = 0;
  45582. u32 iFrame = 0; /* Frame to read from WAL file */
  45583. const int noContent = (flags & PAGER_GET_NOCONTENT);
  45584. /* It is acceptable to use a read-only (mmap) page for any page except
  45585. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  45586. ** flag was specified by the caller. And so long as the db is not a
  45587. ** temporary or in-memory database. */
  45588. const int bMmapOk = (pgno>1 && USEFETCH(pPager)
  45589. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  45590. #ifdef SQLITE_HAS_CODEC
  45591. && pPager->xCodec==0
  45592. #endif
  45593. );
  45594. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  45595. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  45596. ** test in the previous statement, and avoid testing pgno==0 in the
  45597. ** common case where pgno is large. */
  45598. if( pgno<=1 && pgno==0 ){
  45599. return SQLITE_CORRUPT_BKPT;
  45600. }
  45601. assert( pPager->eState>=PAGER_READER );
  45602. assert( assert_pager_state(pPager) );
  45603. assert( noContent==0 || bMmapOk==0 );
  45604. assert( pPager->hasHeldSharedLock==1 );
  45605. /* If the pager is in the error state, return an error immediately.
  45606. ** Otherwise, request the page from the PCache layer. */
  45607. if( pPager->errCode!=SQLITE_OK ){
  45608. rc = pPager->errCode;
  45609. }else{
  45610. if( bMmapOk && pagerUseWal(pPager) ){
  45611. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  45612. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  45613. }
  45614. if( bMmapOk && iFrame==0 ){
  45615. void *pData = 0;
  45616. rc = sqlite3OsFetch(pPager->fd,
  45617. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  45618. );
  45619. if( rc==SQLITE_OK && pData ){
  45620. if( pPager->eState>PAGER_READER ){
  45621. pPg = sqlite3PagerLookup(pPager, pgno);
  45622. }
  45623. if( pPg==0 ){
  45624. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  45625. }else{
  45626. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  45627. }
  45628. if( pPg ){
  45629. assert( rc==SQLITE_OK );
  45630. *ppPage = pPg;
  45631. return SQLITE_OK;
  45632. }
  45633. }
  45634. if( rc!=SQLITE_OK ){
  45635. goto pager_acquire_err;
  45636. }
  45637. }
  45638. {
  45639. sqlite3_pcache_page *pBase;
  45640. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  45641. if( pBase==0 ){
  45642. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  45643. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  45644. if( pBase==0 ){
  45645. pPg = *ppPage = 0;
  45646. rc = SQLITE_NOMEM;
  45647. goto pager_acquire_err;
  45648. }
  45649. }
  45650. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  45651. assert( pPg!=0 );
  45652. }
  45653. }
  45654. if( rc!=SQLITE_OK ){
  45655. /* Either the call to sqlite3PcacheFetch() returned an error or the
  45656. ** pager was already in the error-state when this function was called.
  45657. ** Set pPg to 0 and jump to the exception handler. */
  45658. pPg = 0;
  45659. goto pager_acquire_err;
  45660. }
  45661. assert( pPg==(*ppPage) );
  45662. assert( pPg->pgno==pgno );
  45663. assert( pPg->pPager==pPager || pPg->pPager==0 );
  45664. if( pPg->pPager && !noContent ){
  45665. /* In this case the pcache already contains an initialized copy of
  45666. ** the page. Return without further ado. */
  45667. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  45668. pPager->aStat[PAGER_STAT_HIT]++;
  45669. return SQLITE_OK;
  45670. }else{
  45671. /* The pager cache has created a new page. Its content needs to
  45672. ** be initialized. */
  45673. pPg->pPager = pPager;
  45674. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  45675. ** number greater than this, or the unused locking-page, is requested. */
  45676. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  45677. rc = SQLITE_CORRUPT_BKPT;
  45678. goto pager_acquire_err;
  45679. }
  45680. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  45681. if( pgno>pPager->mxPgno ){
  45682. rc = SQLITE_FULL;
  45683. goto pager_acquire_err;
  45684. }
  45685. if( noContent ){
  45686. /* Failure to set the bits in the InJournal bit-vectors is benign.
  45687. ** It merely means that we might do some extra work to journal a
  45688. ** page that does not need to be journaled. Nevertheless, be sure
  45689. ** to test the case where a malloc error occurs while trying to set
  45690. ** a bit in a bit vector.
  45691. */
  45692. sqlite3BeginBenignMalloc();
  45693. if( pgno<=pPager->dbOrigSize ){
  45694. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  45695. testcase( rc==SQLITE_NOMEM );
  45696. }
  45697. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  45698. testcase( rc==SQLITE_NOMEM );
  45699. sqlite3EndBenignMalloc();
  45700. }
  45701. memset(pPg->pData, 0, pPager->pageSize);
  45702. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  45703. }else{
  45704. if( pagerUseWal(pPager) && bMmapOk==0 ){
  45705. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  45706. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  45707. }
  45708. assert( pPg->pPager==pPager );
  45709. pPager->aStat[PAGER_STAT_MISS]++;
  45710. rc = readDbPage(pPg, iFrame);
  45711. if( rc!=SQLITE_OK ){
  45712. goto pager_acquire_err;
  45713. }
  45714. }
  45715. pager_set_pagehash(pPg);
  45716. }
  45717. return SQLITE_OK;
  45718. pager_acquire_err:
  45719. assert( rc!=SQLITE_OK );
  45720. if( pPg ){
  45721. sqlite3PcacheDrop(pPg);
  45722. }
  45723. pagerUnlockIfUnused(pPager);
  45724. *ppPage = 0;
  45725. return rc;
  45726. }
  45727. /*
  45728. ** Acquire a page if it is already in the in-memory cache. Do
  45729. ** not read the page from disk. Return a pointer to the page,
  45730. ** or 0 if the page is not in cache.
  45731. **
  45732. ** See also sqlite3PagerGet(). The difference between this routine
  45733. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  45734. ** in the page if the page is not already in cache. This routine
  45735. ** returns NULL if the page is not in cache or if a disk I/O error
  45736. ** has ever happened.
  45737. */
  45738. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  45739. sqlite3_pcache_page *pPage;
  45740. assert( pPager!=0 );
  45741. assert( pgno!=0 );
  45742. assert( pPager->pPCache!=0 );
  45743. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  45744. assert( pPage==0 || pPager->hasHeldSharedLock );
  45745. if( pPage==0 ) return 0;
  45746. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  45747. }
  45748. /*
  45749. ** Release a page reference.
  45750. **
  45751. ** If the number of references to the page drop to zero, then the
  45752. ** page is added to the LRU list. When all references to all pages
  45753. ** are released, a rollback occurs and the lock on the database is
  45754. ** removed.
  45755. */
  45756. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  45757. Pager *pPager;
  45758. assert( pPg!=0 );
  45759. pPager = pPg->pPager;
  45760. if( pPg->flags & PGHDR_MMAP ){
  45761. pagerReleaseMapPage(pPg);
  45762. }else{
  45763. sqlite3PcacheRelease(pPg);
  45764. }
  45765. pagerUnlockIfUnused(pPager);
  45766. }
  45767. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  45768. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  45769. }
  45770. /*
  45771. ** This function is called at the start of every write transaction.
  45772. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  45773. ** file when this routine is called.
  45774. **
  45775. ** Open the journal file for pager pPager and write a journal header
  45776. ** to the start of it. If there are active savepoints, open the sub-journal
  45777. ** as well. This function is only used when the journal file is being
  45778. ** opened to write a rollback log for a transaction. It is not used
  45779. ** when opening a hot journal file to roll it back.
  45780. **
  45781. ** If the journal file is already open (as it may be in exclusive mode),
  45782. ** then this function just writes a journal header to the start of the
  45783. ** already open file.
  45784. **
  45785. ** Whether or not the journal file is opened by this function, the
  45786. ** Pager.pInJournal bitvec structure is allocated.
  45787. **
  45788. ** Return SQLITE_OK if everything is successful. Otherwise, return
  45789. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  45790. ** an IO error code if opening or writing the journal file fails.
  45791. */
  45792. static int pager_open_journal(Pager *pPager){
  45793. int rc = SQLITE_OK; /* Return code */
  45794. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  45795. assert( pPager->eState==PAGER_WRITER_LOCKED );
  45796. assert( assert_pager_state(pPager) );
  45797. assert( pPager->pInJournal==0 );
  45798. /* If already in the error state, this function is a no-op. But on
  45799. ** the other hand, this routine is never called if we are already in
  45800. ** an error state. */
  45801. if( NEVER(pPager->errCode) ) return pPager->errCode;
  45802. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  45803. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  45804. if( pPager->pInJournal==0 ){
  45805. return SQLITE_NOMEM;
  45806. }
  45807. /* Open the journal file if it is not already open. */
  45808. if( !isOpen(pPager->jfd) ){
  45809. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  45810. sqlite3MemJournalOpen(pPager->jfd);
  45811. }else{
  45812. const int flags = /* VFS flags to open journal file */
  45813. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  45814. (pPager->tempFile ?
  45815. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  45816. (SQLITE_OPEN_MAIN_JOURNAL)
  45817. );
  45818. /* Verify that the database still has the same name as it did when
  45819. ** it was originally opened. */
  45820. rc = databaseIsUnmoved(pPager);
  45821. if( rc==SQLITE_OK ){
  45822. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  45823. rc = sqlite3JournalOpen(
  45824. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  45825. );
  45826. #else
  45827. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  45828. #endif
  45829. }
  45830. }
  45831. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  45832. }
  45833. /* Write the first journal header to the journal file and open
  45834. ** the sub-journal if necessary.
  45835. */
  45836. if( rc==SQLITE_OK ){
  45837. /* TODO: Check if all of these are really required. */
  45838. pPager->nRec = 0;
  45839. pPager->journalOff = 0;
  45840. pPager->setMaster = 0;
  45841. pPager->journalHdr = 0;
  45842. rc = writeJournalHdr(pPager);
  45843. }
  45844. }
  45845. if( rc!=SQLITE_OK ){
  45846. sqlite3BitvecDestroy(pPager->pInJournal);
  45847. pPager->pInJournal = 0;
  45848. }else{
  45849. assert( pPager->eState==PAGER_WRITER_LOCKED );
  45850. pPager->eState = PAGER_WRITER_CACHEMOD;
  45851. }
  45852. return rc;
  45853. }
  45854. /*
  45855. ** Begin a write-transaction on the specified pager object. If a
  45856. ** write-transaction has already been opened, this function is a no-op.
  45857. **
  45858. ** If the exFlag argument is false, then acquire at least a RESERVED
  45859. ** lock on the database file. If exFlag is true, then acquire at least
  45860. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  45861. ** functions need be called.
  45862. **
  45863. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  45864. ** within this transaction will be opened as an in-memory file. This
  45865. ** has no effect if the sub-journal is already opened (as it may be when
  45866. ** running in exclusive mode) or if the transaction does not require a
  45867. ** sub-journal. If the subjInMemory argument is zero, then any required
  45868. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  45869. ** or using a temporary file otherwise.
  45870. */
  45871. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  45872. int rc = SQLITE_OK;
  45873. if( pPager->errCode ) return pPager->errCode;
  45874. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  45875. pPager->subjInMemory = (u8)subjInMemory;
  45876. if( ALWAYS(pPager->eState==PAGER_READER) ){
  45877. assert( pPager->pInJournal==0 );
  45878. if( pagerUseWal(pPager) ){
  45879. /* If the pager is configured to use locking_mode=exclusive, and an
  45880. ** exclusive lock on the database is not already held, obtain it now.
  45881. */
  45882. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  45883. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  45884. if( rc!=SQLITE_OK ){
  45885. return rc;
  45886. }
  45887. sqlite3WalExclusiveMode(pPager->pWal, 1);
  45888. }
  45889. /* Grab the write lock on the log file. If successful, upgrade to
  45890. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  45891. ** The busy-handler is not invoked if another connection already
  45892. ** holds the write-lock. If possible, the upper layer will call it.
  45893. */
  45894. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  45895. }else{
  45896. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  45897. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  45898. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  45899. ** lock, but not when obtaining the RESERVED lock.
  45900. */
  45901. rc = pagerLockDb(pPager, RESERVED_LOCK);
  45902. if( rc==SQLITE_OK && exFlag ){
  45903. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  45904. }
  45905. }
  45906. if( rc==SQLITE_OK ){
  45907. /* Change to WRITER_LOCKED state.
  45908. **
  45909. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  45910. ** when it has an open transaction, but never to DBMOD or FINISHED.
  45911. ** This is because in those states the code to roll back savepoint
  45912. ** transactions may copy data from the sub-journal into the database
  45913. ** file as well as into the page cache. Which would be incorrect in
  45914. ** WAL mode.
  45915. */
  45916. pPager->eState = PAGER_WRITER_LOCKED;
  45917. pPager->dbHintSize = pPager->dbSize;
  45918. pPager->dbFileSize = pPager->dbSize;
  45919. pPager->dbOrigSize = pPager->dbSize;
  45920. pPager->journalOff = 0;
  45921. }
  45922. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  45923. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  45924. assert( assert_pager_state(pPager) );
  45925. }
  45926. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  45927. return rc;
  45928. }
  45929. /*
  45930. ** Write page pPg onto the end of the rollback journal.
  45931. */
  45932. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  45933. Pager *pPager = pPg->pPager;
  45934. int rc;
  45935. u32 cksum;
  45936. char *pData2;
  45937. i64 iOff = pPager->journalOff;
  45938. /* We should never write to the journal file the page that
  45939. ** contains the database locks. The following assert verifies
  45940. ** that we do not. */
  45941. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  45942. assert( pPager->journalHdr<=pPager->journalOff );
  45943. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  45944. cksum = pager_cksum(pPager, (u8*)pData2);
  45945. /* Even if an IO or diskfull error occurs while journalling the
  45946. ** page in the block above, set the need-sync flag for the page.
  45947. ** Otherwise, when the transaction is rolled back, the logic in
  45948. ** playback_one_page() will think that the page needs to be restored
  45949. ** in the database file. And if an IO error occurs while doing so,
  45950. ** then corruption may follow.
  45951. */
  45952. pPg->flags |= PGHDR_NEED_SYNC;
  45953. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  45954. if( rc!=SQLITE_OK ) return rc;
  45955. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  45956. if( rc!=SQLITE_OK ) return rc;
  45957. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  45958. if( rc!=SQLITE_OK ) return rc;
  45959. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  45960. pPager->journalOff, pPager->pageSize));
  45961. PAGER_INCR(sqlite3_pager_writej_count);
  45962. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  45963. PAGERID(pPager), pPg->pgno,
  45964. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  45965. pPager->journalOff += 8 + pPager->pageSize;
  45966. pPager->nRec++;
  45967. assert( pPager->pInJournal!=0 );
  45968. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  45969. testcase( rc==SQLITE_NOMEM );
  45970. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  45971. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  45972. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  45973. return rc;
  45974. }
  45975. /*
  45976. ** Mark a single data page as writeable. The page is written into the
  45977. ** main journal or sub-journal as required. If the page is written into
  45978. ** one of the journals, the corresponding bit is set in the
  45979. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  45980. ** of any open savepoints as appropriate.
  45981. */
  45982. static int pager_write(PgHdr *pPg){
  45983. Pager *pPager = pPg->pPager;
  45984. int rc = SQLITE_OK;
  45985. /* This routine is not called unless a write-transaction has already
  45986. ** been started. The journal file may or may not be open at this point.
  45987. ** It is never called in the ERROR state.
  45988. */
  45989. assert( pPager->eState==PAGER_WRITER_LOCKED
  45990. || pPager->eState==PAGER_WRITER_CACHEMOD
  45991. || pPager->eState==PAGER_WRITER_DBMOD
  45992. );
  45993. assert( assert_pager_state(pPager) );
  45994. assert( pPager->errCode==0 );
  45995. assert( pPager->readOnly==0 );
  45996. CHECK_PAGE(pPg);
  45997. /* The journal file needs to be opened. Higher level routines have already
  45998. ** obtained the necessary locks to begin the write-transaction, but the
  45999. ** rollback journal might not yet be open. Open it now if this is the case.
  46000. **
  46001. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  46002. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  46003. ** an error might occur and the pager would end up in WRITER_LOCKED state
  46004. ** with pages marked as dirty in the cache.
  46005. */
  46006. if( pPager->eState==PAGER_WRITER_LOCKED ){
  46007. rc = pager_open_journal(pPager);
  46008. if( rc!=SQLITE_OK ) return rc;
  46009. }
  46010. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  46011. assert( assert_pager_state(pPager) );
  46012. /* Mark the page that is about to be modified as dirty. */
  46013. sqlite3PcacheMakeDirty(pPg);
  46014. /* If a rollback journal is in use, them make sure the page that is about
  46015. ** to change is in the rollback journal, or if the page is a new page off
  46016. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  46017. */
  46018. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  46019. if( pPager->pInJournal!=0
  46020. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  46021. ){
  46022. assert( pagerUseWal(pPager)==0 );
  46023. if( pPg->pgno<=pPager->dbOrigSize ){
  46024. rc = pagerAddPageToRollbackJournal(pPg);
  46025. if( rc!=SQLITE_OK ){
  46026. return rc;
  46027. }
  46028. }else{
  46029. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  46030. pPg->flags |= PGHDR_NEED_SYNC;
  46031. }
  46032. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  46033. PAGERID(pPager), pPg->pgno,
  46034. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  46035. }
  46036. }
  46037. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  46038. ** and before writing the page into the rollback journal. Wait until now,
  46039. ** after the page has been successfully journalled, before setting the
  46040. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  46041. */
  46042. pPg->flags |= PGHDR_WRITEABLE;
  46043. /* If the statement journal is open and the page is not in it,
  46044. ** then write the page into the statement journal.
  46045. */
  46046. if( pPager->nSavepoint>0 ){
  46047. rc = subjournalPageIfRequired(pPg);
  46048. }
  46049. /* Update the database size and return. */
  46050. if( pPager->dbSize<pPg->pgno ){
  46051. pPager->dbSize = pPg->pgno;
  46052. }
  46053. return rc;
  46054. }
  46055. /*
  46056. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  46057. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  46058. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  46059. ** a sector need to be journalled in case of a power loss in the middle of
  46060. ** a write.
  46061. **
  46062. ** Usually, the sector size is less than or equal to the page size, in which
  46063. ** case pages can be individually written. This routine only runs in the
  46064. ** exceptional case where the page size is smaller than the sector size.
  46065. */
  46066. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  46067. int rc = SQLITE_OK; /* Return code */
  46068. Pgno nPageCount; /* Total number of pages in database file */
  46069. Pgno pg1; /* First page of the sector pPg is located on. */
  46070. int nPage = 0; /* Number of pages starting at pg1 to journal */
  46071. int ii; /* Loop counter */
  46072. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  46073. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  46074. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  46075. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  46076. ** a journal header to be written between the pages journaled by
  46077. ** this function.
  46078. */
  46079. assert( !MEMDB );
  46080. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  46081. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  46082. /* This trick assumes that both the page-size and sector-size are
  46083. ** an integer power of 2. It sets variable pg1 to the identifier
  46084. ** of the first page of the sector pPg is located on.
  46085. */
  46086. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  46087. nPageCount = pPager->dbSize;
  46088. if( pPg->pgno>nPageCount ){
  46089. nPage = (pPg->pgno - pg1)+1;
  46090. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  46091. nPage = nPageCount+1-pg1;
  46092. }else{
  46093. nPage = nPagePerSector;
  46094. }
  46095. assert(nPage>0);
  46096. assert(pg1<=pPg->pgno);
  46097. assert((pg1+nPage)>pPg->pgno);
  46098. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  46099. Pgno pg = pg1+ii;
  46100. PgHdr *pPage;
  46101. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  46102. if( pg!=PAGER_MJ_PGNO(pPager) ){
  46103. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  46104. if( rc==SQLITE_OK ){
  46105. rc = pager_write(pPage);
  46106. if( pPage->flags&PGHDR_NEED_SYNC ){
  46107. needSync = 1;
  46108. }
  46109. sqlite3PagerUnrefNotNull(pPage);
  46110. }
  46111. }
  46112. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  46113. if( pPage->flags&PGHDR_NEED_SYNC ){
  46114. needSync = 1;
  46115. }
  46116. sqlite3PagerUnrefNotNull(pPage);
  46117. }
  46118. }
  46119. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  46120. ** starting at pg1, then it needs to be set for all of them. Because
  46121. ** writing to any of these nPage pages may damage the others, the
  46122. ** journal file must contain sync()ed copies of all of them
  46123. ** before any of them can be written out to the database file.
  46124. */
  46125. if( rc==SQLITE_OK && needSync ){
  46126. assert( !MEMDB );
  46127. for(ii=0; ii<nPage; ii++){
  46128. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  46129. if( pPage ){
  46130. pPage->flags |= PGHDR_NEED_SYNC;
  46131. sqlite3PagerUnrefNotNull(pPage);
  46132. }
  46133. }
  46134. }
  46135. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  46136. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  46137. return rc;
  46138. }
  46139. /*
  46140. ** Mark a data page as writeable. This routine must be called before
  46141. ** making changes to a page. The caller must check the return value
  46142. ** of this function and be careful not to change any page data unless
  46143. ** this routine returns SQLITE_OK.
  46144. **
  46145. ** The difference between this function and pager_write() is that this
  46146. ** function also deals with the special case where 2 or more pages
  46147. ** fit on a single disk sector. In this case all co-resident pages
  46148. ** must have been written to the journal file before returning.
  46149. **
  46150. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  46151. ** as appropriate. Otherwise, SQLITE_OK.
  46152. */
  46153. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  46154. Pager *pPager = pPg->pPager;
  46155. assert( (pPg->flags & PGHDR_MMAP)==0 );
  46156. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  46157. assert( assert_pager_state(pPager) );
  46158. if( pPager->errCode ){
  46159. return pPager->errCode;
  46160. }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  46161. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  46162. return SQLITE_OK;
  46163. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  46164. return pagerWriteLargeSector(pPg);
  46165. }else{
  46166. return pager_write(pPg);
  46167. }
  46168. }
  46169. /*
  46170. ** Return TRUE if the page given in the argument was previously passed
  46171. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  46172. ** to change the content of the page.
  46173. */
  46174. #ifndef NDEBUG
  46175. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  46176. return pPg->flags & PGHDR_WRITEABLE;
  46177. }
  46178. #endif
  46179. /*
  46180. ** A call to this routine tells the pager that it is not necessary to
  46181. ** write the information on page pPg back to the disk, even though
  46182. ** that page might be marked as dirty. This happens, for example, when
  46183. ** the page has been added as a leaf of the freelist and so its
  46184. ** content no longer matters.
  46185. **
  46186. ** The overlying software layer calls this routine when all of the data
  46187. ** on the given page is unused. The pager marks the page as clean so
  46188. ** that it does not get written to disk.
  46189. **
  46190. ** Tests show that this optimization can quadruple the speed of large
  46191. ** DELETE operations.
  46192. */
  46193. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  46194. Pager *pPager = pPg->pPager;
  46195. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  46196. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  46197. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  46198. pPg->flags |= PGHDR_DONT_WRITE;
  46199. pPg->flags &= ~PGHDR_WRITEABLE;
  46200. pager_set_pagehash(pPg);
  46201. }
  46202. }
  46203. /*
  46204. ** This routine is called to increment the value of the database file
  46205. ** change-counter, stored as a 4-byte big-endian integer starting at
  46206. ** byte offset 24 of the pager file. The secondary change counter at
  46207. ** 92 is also updated, as is the SQLite version number at offset 96.
  46208. **
  46209. ** But this only happens if the pPager->changeCountDone flag is false.
  46210. ** To avoid excess churning of page 1, the update only happens once.
  46211. ** See also the pager_write_changecounter() routine that does an
  46212. ** unconditional update of the change counters.
  46213. **
  46214. ** If the isDirectMode flag is zero, then this is done by calling
  46215. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  46216. ** page data. In this case the file will be updated when the current
  46217. ** transaction is committed.
  46218. **
  46219. ** The isDirectMode flag may only be non-zero if the library was compiled
  46220. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  46221. ** if isDirect is non-zero, then the database file is updated directly
  46222. ** by writing an updated version of page 1 using a call to the
  46223. ** sqlite3OsWrite() function.
  46224. */
  46225. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  46226. int rc = SQLITE_OK;
  46227. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  46228. || pPager->eState==PAGER_WRITER_DBMOD
  46229. );
  46230. assert( assert_pager_state(pPager) );
  46231. /* Declare and initialize constant integer 'isDirect'. If the
  46232. ** atomic-write optimization is enabled in this build, then isDirect
  46233. ** is initialized to the value passed as the isDirectMode parameter
  46234. ** to this function. Otherwise, it is always set to zero.
  46235. **
  46236. ** The idea is that if the atomic-write optimization is not
  46237. ** enabled at compile time, the compiler can omit the tests of
  46238. ** 'isDirect' below, as well as the block enclosed in the
  46239. ** "if( isDirect )" condition.
  46240. */
  46241. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  46242. # define DIRECT_MODE 0
  46243. assert( isDirectMode==0 );
  46244. UNUSED_PARAMETER(isDirectMode);
  46245. #else
  46246. # define DIRECT_MODE isDirectMode
  46247. #endif
  46248. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  46249. PgHdr *pPgHdr; /* Reference to page 1 */
  46250. assert( !pPager->tempFile && isOpen(pPager->fd) );
  46251. /* Open page 1 of the file for writing. */
  46252. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  46253. assert( pPgHdr==0 || rc==SQLITE_OK );
  46254. /* If page one was fetched successfully, and this function is not
  46255. ** operating in direct-mode, make page 1 writable. When not in
  46256. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  46257. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  46258. */
  46259. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  46260. rc = sqlite3PagerWrite(pPgHdr);
  46261. }
  46262. if( rc==SQLITE_OK ){
  46263. /* Actually do the update of the change counter */
  46264. pager_write_changecounter(pPgHdr);
  46265. /* If running in direct mode, write the contents of page 1 to the file. */
  46266. if( DIRECT_MODE ){
  46267. const void *zBuf;
  46268. assert( pPager->dbFileSize>0 );
  46269. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  46270. if( rc==SQLITE_OK ){
  46271. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  46272. pPager->aStat[PAGER_STAT_WRITE]++;
  46273. }
  46274. if( rc==SQLITE_OK ){
  46275. /* Update the pager's copy of the change-counter. Otherwise, the
  46276. ** next time a read transaction is opened the cache will be
  46277. ** flushed (as the change-counter values will not match). */
  46278. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  46279. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  46280. pPager->changeCountDone = 1;
  46281. }
  46282. }else{
  46283. pPager->changeCountDone = 1;
  46284. }
  46285. }
  46286. /* Release the page reference. */
  46287. sqlite3PagerUnref(pPgHdr);
  46288. }
  46289. return rc;
  46290. }
  46291. /*
  46292. ** Sync the database file to disk. This is a no-op for in-memory databases
  46293. ** or pages with the Pager.noSync flag set.
  46294. **
  46295. ** If successful, or if called on a pager for which it is a no-op, this
  46296. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  46297. */
  46298. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  46299. int rc = SQLITE_OK;
  46300. if( isOpen(pPager->fd) ){
  46301. void *pArg = (void*)zMaster;
  46302. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  46303. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  46304. }
  46305. if( rc==SQLITE_OK && !pPager->noSync ){
  46306. assert( !MEMDB );
  46307. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  46308. }
  46309. return rc;
  46310. }
  46311. /*
  46312. ** This function may only be called while a write-transaction is active in
  46313. ** rollback. If the connection is in WAL mode, this call is a no-op.
  46314. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  46315. ** the database file, an attempt is made to obtain one.
  46316. **
  46317. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  46318. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  46319. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  46320. ** returned.
  46321. */
  46322. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  46323. int rc = pPager->errCode;
  46324. assert( assert_pager_state(pPager) );
  46325. if( rc==SQLITE_OK ){
  46326. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  46327. || pPager->eState==PAGER_WRITER_DBMOD
  46328. || pPager->eState==PAGER_WRITER_LOCKED
  46329. );
  46330. assert( assert_pager_state(pPager) );
  46331. if( 0==pagerUseWal(pPager) ){
  46332. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  46333. }
  46334. }
  46335. return rc;
  46336. }
  46337. /*
  46338. ** Sync the database file for the pager pPager. zMaster points to the name
  46339. ** of a master journal file that should be written into the individual
  46340. ** journal file. zMaster may be NULL, which is interpreted as no master
  46341. ** journal (a single database transaction).
  46342. **
  46343. ** This routine ensures that:
  46344. **
  46345. ** * The database file change-counter is updated,
  46346. ** * the journal is synced (unless the atomic-write optimization is used),
  46347. ** * all dirty pages are written to the database file,
  46348. ** * the database file is truncated (if required), and
  46349. ** * the database file synced.
  46350. **
  46351. ** The only thing that remains to commit the transaction is to finalize
  46352. ** (delete, truncate or zero the first part of) the journal file (or
  46353. ** delete the master journal file if specified).
  46354. **
  46355. ** Note that if zMaster==NULL, this does not overwrite a previous value
  46356. ** passed to an sqlite3PagerCommitPhaseOne() call.
  46357. **
  46358. ** If the final parameter - noSync - is true, then the database file itself
  46359. ** is not synced. The caller must call sqlite3PagerSync() directly to
  46360. ** sync the database file before calling CommitPhaseTwo() to delete the
  46361. ** journal file in this case.
  46362. */
  46363. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  46364. Pager *pPager, /* Pager object */
  46365. const char *zMaster, /* If not NULL, the master journal name */
  46366. int noSync /* True to omit the xSync on the db file */
  46367. ){
  46368. int rc = SQLITE_OK; /* Return code */
  46369. assert( pPager->eState==PAGER_WRITER_LOCKED
  46370. || pPager->eState==PAGER_WRITER_CACHEMOD
  46371. || pPager->eState==PAGER_WRITER_DBMOD
  46372. || pPager->eState==PAGER_ERROR
  46373. );
  46374. assert( assert_pager_state(pPager) );
  46375. /* If a prior error occurred, report that error again. */
  46376. if( NEVER(pPager->errCode) ) return pPager->errCode;
  46377. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  46378. pPager->zFilename, zMaster, pPager->dbSize));
  46379. /* If no database changes have been made, return early. */
  46380. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  46381. if( MEMDB ){
  46382. /* If this is an in-memory db, or no pages have been written to, or this
  46383. ** function has already been called, it is mostly a no-op. However, any
  46384. ** backup in progress needs to be restarted.
  46385. */
  46386. sqlite3BackupRestart(pPager->pBackup);
  46387. }else{
  46388. if( pagerUseWal(pPager) ){
  46389. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  46390. PgHdr *pPageOne = 0;
  46391. if( pList==0 ){
  46392. /* Must have at least one page for the WAL commit flag.
  46393. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  46394. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  46395. pList = pPageOne;
  46396. pList->pDirty = 0;
  46397. }
  46398. assert( rc==SQLITE_OK );
  46399. if( ALWAYS(pList) ){
  46400. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  46401. }
  46402. sqlite3PagerUnref(pPageOne);
  46403. if( rc==SQLITE_OK ){
  46404. sqlite3PcacheCleanAll(pPager->pPCache);
  46405. }
  46406. }else{
  46407. /* The following block updates the change-counter. Exactly how it
  46408. ** does this depends on whether or not the atomic-update optimization
  46409. ** was enabled at compile time, and if this transaction meets the
  46410. ** runtime criteria to use the operation:
  46411. **
  46412. ** * The file-system supports the atomic-write property for
  46413. ** blocks of size page-size, and
  46414. ** * This commit is not part of a multi-file transaction, and
  46415. ** * Exactly one page has been modified and store in the journal file.
  46416. **
  46417. ** If the optimization was not enabled at compile time, then the
  46418. ** pager_incr_changecounter() function is called to update the change
  46419. ** counter in 'indirect-mode'. If the optimization is compiled in but
  46420. ** is not applicable to this transaction, call sqlite3JournalCreate()
  46421. ** to make sure the journal file has actually been created, then call
  46422. ** pager_incr_changecounter() to update the change-counter in indirect
  46423. ** mode.
  46424. **
  46425. ** Otherwise, if the optimization is both enabled and applicable,
  46426. ** then call pager_incr_changecounter() to update the change-counter
  46427. ** in 'direct' mode. In this case the journal file will never be
  46428. ** created for this transaction.
  46429. */
  46430. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  46431. PgHdr *pPg;
  46432. assert( isOpen(pPager->jfd)
  46433. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  46434. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  46435. );
  46436. if( !zMaster && isOpen(pPager->jfd)
  46437. && pPager->journalOff==jrnlBufferSize(pPager)
  46438. && pPager->dbSize>=pPager->dbOrigSize
  46439. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  46440. ){
  46441. /* Update the db file change counter via the direct-write method. The
  46442. ** following call will modify the in-memory representation of page 1
  46443. ** to include the updated change counter and then write page 1
  46444. ** directly to the database file. Because of the atomic-write
  46445. ** property of the host file-system, this is safe.
  46446. */
  46447. rc = pager_incr_changecounter(pPager, 1);
  46448. }else{
  46449. rc = sqlite3JournalCreate(pPager->jfd);
  46450. if( rc==SQLITE_OK ){
  46451. rc = pager_incr_changecounter(pPager, 0);
  46452. }
  46453. }
  46454. #else
  46455. rc = pager_incr_changecounter(pPager, 0);
  46456. #endif
  46457. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  46458. /* Write the master journal name into the journal file. If a master
  46459. ** journal file name has already been written to the journal file,
  46460. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  46461. */
  46462. rc = writeMasterJournal(pPager, zMaster);
  46463. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  46464. /* Sync the journal file and write all dirty pages to the database.
  46465. ** If the atomic-update optimization is being used, this sync will not
  46466. ** create the journal file or perform any real IO.
  46467. **
  46468. ** Because the change-counter page was just modified, unless the
  46469. ** atomic-update optimization is used it is almost certain that the
  46470. ** journal requires a sync here. However, in locking_mode=exclusive
  46471. ** on a system under memory pressure it is just possible that this is
  46472. ** not the case. In this case it is likely enough that the redundant
  46473. ** xSync() call will be changed to a no-op by the OS anyhow.
  46474. */
  46475. rc = syncJournal(pPager, 0);
  46476. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  46477. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  46478. if( rc!=SQLITE_OK ){
  46479. assert( rc!=SQLITE_IOERR_BLOCKED );
  46480. goto commit_phase_one_exit;
  46481. }
  46482. sqlite3PcacheCleanAll(pPager->pPCache);
  46483. /* If the file on disk is smaller than the database image, use
  46484. ** pager_truncate to grow the file here. This can happen if the database
  46485. ** image was extended as part of the current transaction and then the
  46486. ** last page in the db image moved to the free-list. In this case the
  46487. ** last page is never written out to disk, leaving the database file
  46488. ** undersized. Fix this now if it is the case. */
  46489. if( pPager->dbSize>pPager->dbFileSize ){
  46490. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  46491. assert( pPager->eState==PAGER_WRITER_DBMOD );
  46492. rc = pager_truncate(pPager, nNew);
  46493. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  46494. }
  46495. /* Finally, sync the database file. */
  46496. if( !noSync ){
  46497. rc = sqlite3PagerSync(pPager, zMaster);
  46498. }
  46499. IOTRACE(("DBSYNC %p\n", pPager))
  46500. }
  46501. }
  46502. commit_phase_one_exit:
  46503. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  46504. pPager->eState = PAGER_WRITER_FINISHED;
  46505. }
  46506. return rc;
  46507. }
  46508. /*
  46509. ** When this function is called, the database file has been completely
  46510. ** updated to reflect the changes made by the current transaction and
  46511. ** synced to disk. The journal file still exists in the file-system
  46512. ** though, and if a failure occurs at this point it will eventually
  46513. ** be used as a hot-journal and the current transaction rolled back.
  46514. **
  46515. ** This function finalizes the journal file, either by deleting,
  46516. ** truncating or partially zeroing it, so that it cannot be used
  46517. ** for hot-journal rollback. Once this is done the transaction is
  46518. ** irrevocably committed.
  46519. **
  46520. ** If an error occurs, an IO error code is returned and the pager
  46521. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  46522. */
  46523. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  46524. int rc = SQLITE_OK; /* Return code */
  46525. /* This routine should not be called if a prior error has occurred.
  46526. ** But if (due to a coding error elsewhere in the system) it does get
  46527. ** called, just return the same error code without doing anything. */
  46528. if( NEVER(pPager->errCode) ) return pPager->errCode;
  46529. assert( pPager->eState==PAGER_WRITER_LOCKED
  46530. || pPager->eState==PAGER_WRITER_FINISHED
  46531. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  46532. );
  46533. assert( assert_pager_state(pPager) );
  46534. /* An optimization. If the database was not actually modified during
  46535. ** this transaction, the pager is running in exclusive-mode and is
  46536. ** using persistent journals, then this function is a no-op.
  46537. **
  46538. ** The start of the journal file currently contains a single journal
  46539. ** header with the nRec field set to 0. If such a journal is used as
  46540. ** a hot-journal during hot-journal rollback, 0 changes will be made
  46541. ** to the database file. So there is no need to zero the journal
  46542. ** header. Since the pager is in exclusive mode, there is no need
  46543. ** to drop any locks either.
  46544. */
  46545. if( pPager->eState==PAGER_WRITER_LOCKED
  46546. && pPager->exclusiveMode
  46547. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  46548. ){
  46549. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  46550. pPager->eState = PAGER_READER;
  46551. return SQLITE_OK;
  46552. }
  46553. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  46554. pPager->iDataVersion++;
  46555. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  46556. return pager_error(pPager, rc);
  46557. }
  46558. /*
  46559. ** If a write transaction is open, then all changes made within the
  46560. ** transaction are reverted and the current write-transaction is closed.
  46561. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  46562. ** state if an error occurs.
  46563. **
  46564. ** If the pager is already in PAGER_ERROR state when this function is called,
  46565. ** it returns Pager.errCode immediately. No work is performed in this case.
  46566. **
  46567. ** Otherwise, in rollback mode, this function performs two functions:
  46568. **
  46569. ** 1) It rolls back the journal file, restoring all database file and
  46570. ** in-memory cache pages to the state they were in when the transaction
  46571. ** was opened, and
  46572. **
  46573. ** 2) It finalizes the journal file, so that it is not used for hot
  46574. ** rollback at any point in the future.
  46575. **
  46576. ** Finalization of the journal file (task 2) is only performed if the
  46577. ** rollback is successful.
  46578. **
  46579. ** In WAL mode, all cache-entries containing data modified within the
  46580. ** current transaction are either expelled from the cache or reverted to
  46581. ** their pre-transaction state by re-reading data from the database or
  46582. ** WAL files. The WAL transaction is then closed.
  46583. */
  46584. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  46585. int rc = SQLITE_OK; /* Return code */
  46586. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  46587. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  46588. ** the pager is already in the ERROR state, the rollback is not
  46589. ** attempted here. Instead, the error code is returned to the caller.
  46590. */
  46591. assert( assert_pager_state(pPager) );
  46592. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  46593. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  46594. if( pagerUseWal(pPager) ){
  46595. int rc2;
  46596. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  46597. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  46598. if( rc==SQLITE_OK ) rc = rc2;
  46599. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  46600. int eState = pPager->eState;
  46601. rc = pager_end_transaction(pPager, 0, 0);
  46602. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  46603. /* This can happen using journal_mode=off. Move the pager to the error
  46604. ** state to indicate that the contents of the cache may not be trusted.
  46605. ** Any active readers will get SQLITE_ABORT.
  46606. */
  46607. pPager->errCode = SQLITE_ABORT;
  46608. pPager->eState = PAGER_ERROR;
  46609. return rc;
  46610. }
  46611. }else{
  46612. rc = pager_playback(pPager, 0);
  46613. }
  46614. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  46615. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  46616. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  46617. || rc==SQLITE_CANTOPEN
  46618. );
  46619. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  46620. ** cache. So call pager_error() on the way out to make any error persistent.
  46621. */
  46622. return pager_error(pPager, rc);
  46623. }
  46624. /*
  46625. ** Return TRUE if the database file is opened read-only. Return FALSE
  46626. ** if the database is (in theory) writable.
  46627. */
  46628. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  46629. return pPager->readOnly;
  46630. }
  46631. #ifdef SQLITE_DEBUG
  46632. /*
  46633. ** Return the sum of the reference counts for all pages held by pPager.
  46634. */
  46635. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  46636. return sqlite3PcacheRefCount(pPager->pPCache);
  46637. }
  46638. #endif
  46639. /*
  46640. ** Return the approximate number of bytes of memory currently
  46641. ** used by the pager and its associated cache.
  46642. */
  46643. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  46644. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  46645. + 5*sizeof(void*);
  46646. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  46647. + sqlite3MallocSize(pPager)
  46648. + pPager->pageSize;
  46649. }
  46650. /*
  46651. ** Return the number of references to the specified page.
  46652. */
  46653. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  46654. return sqlite3PcachePageRefcount(pPage);
  46655. }
  46656. #ifdef SQLITE_TEST
  46657. /*
  46658. ** This routine is used for testing and analysis only.
  46659. */
  46660. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  46661. static int a[11];
  46662. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  46663. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  46664. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  46665. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  46666. a[4] = pPager->eState;
  46667. a[5] = pPager->errCode;
  46668. a[6] = pPager->aStat[PAGER_STAT_HIT];
  46669. a[7] = pPager->aStat[PAGER_STAT_MISS];
  46670. a[8] = 0; /* Used to be pPager->nOvfl */
  46671. a[9] = pPager->nRead;
  46672. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  46673. return a;
  46674. }
  46675. #endif
  46676. /*
  46677. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  46678. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  46679. ** current cache hit or miss count, according to the value of eStat. If the
  46680. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  46681. ** returning.
  46682. */
  46683. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  46684. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  46685. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  46686. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  46687. );
  46688. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  46689. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  46690. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  46691. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  46692. if( reset ){
  46693. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  46694. }
  46695. }
  46696. /*
  46697. ** Return true if this is an in-memory pager.
  46698. */
  46699. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  46700. return MEMDB;
  46701. }
  46702. /*
  46703. ** Check that there are at least nSavepoint savepoints open. If there are
  46704. ** currently less than nSavepoints open, then open one or more savepoints
  46705. ** to make up the difference. If the number of savepoints is already
  46706. ** equal to nSavepoint, then this function is a no-op.
  46707. **
  46708. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  46709. ** occurs while opening the sub-journal file, then an IO error code is
  46710. ** returned. Otherwise, SQLITE_OK.
  46711. */
  46712. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  46713. int rc = SQLITE_OK; /* Return code */
  46714. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  46715. int ii; /* Iterator variable */
  46716. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  46717. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  46718. assert( assert_pager_state(pPager) );
  46719. assert( nSavepoint>nCurrent && pPager->useJournal );
  46720. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  46721. ** if the allocation fails. Otherwise, zero the new portion in case a
  46722. ** malloc failure occurs while populating it in the for(...) loop below.
  46723. */
  46724. aNew = (PagerSavepoint *)sqlite3Realloc(
  46725. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  46726. );
  46727. if( !aNew ){
  46728. return SQLITE_NOMEM;
  46729. }
  46730. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  46731. pPager->aSavepoint = aNew;
  46732. /* Populate the PagerSavepoint structures just allocated. */
  46733. for(ii=nCurrent; ii<nSavepoint; ii++){
  46734. aNew[ii].nOrig = pPager->dbSize;
  46735. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  46736. aNew[ii].iOffset = pPager->journalOff;
  46737. }else{
  46738. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  46739. }
  46740. aNew[ii].iSubRec = pPager->nSubRec;
  46741. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  46742. if( !aNew[ii].pInSavepoint ){
  46743. return SQLITE_NOMEM;
  46744. }
  46745. if( pagerUseWal(pPager) ){
  46746. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  46747. }
  46748. pPager->nSavepoint = ii+1;
  46749. }
  46750. assert( pPager->nSavepoint==nSavepoint );
  46751. assertTruncateConstraint(pPager);
  46752. return rc;
  46753. }
  46754. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  46755. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  46756. assert( assert_pager_state(pPager) );
  46757. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  46758. return pagerOpenSavepoint(pPager, nSavepoint);
  46759. }else{
  46760. return SQLITE_OK;
  46761. }
  46762. }
  46763. /*
  46764. ** This function is called to rollback or release (commit) a savepoint.
  46765. ** The savepoint to release or rollback need not be the most recently
  46766. ** created savepoint.
  46767. **
  46768. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  46769. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  46770. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  46771. ** that have occurred since the specified savepoint was created.
  46772. **
  46773. ** The savepoint to rollback or release is identified by parameter
  46774. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  46775. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  46776. ** on the most recently created savepoint. If iSavepoint is greater than
  46777. ** (Pager.nSavepoint-1), then this function is a no-op.
  46778. **
  46779. ** If a negative value is passed to this function, then the current
  46780. ** transaction is rolled back. This is different to calling
  46781. ** sqlite3PagerRollback() because this function does not terminate
  46782. ** the transaction or unlock the database, it just restores the
  46783. ** contents of the database to its original state.
  46784. **
  46785. ** In any case, all savepoints with an index greater than iSavepoint
  46786. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  46787. ** then savepoint iSavepoint is also destroyed.
  46788. **
  46789. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  46790. ** or an IO error code if an IO error occurs while rolling back a
  46791. ** savepoint. If no errors occur, SQLITE_OK is returned.
  46792. */
  46793. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  46794. int rc = pPager->errCode; /* Return code */
  46795. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  46796. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  46797. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  46798. int ii; /* Iterator variable */
  46799. int nNew; /* Number of remaining savepoints after this op. */
  46800. /* Figure out how many savepoints will still be active after this
  46801. ** operation. Store this value in nNew. Then free resources associated
  46802. ** with any savepoints that are destroyed by this operation.
  46803. */
  46804. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  46805. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  46806. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  46807. }
  46808. pPager->nSavepoint = nNew;
  46809. /* If this is a release of the outermost savepoint, truncate
  46810. ** the sub-journal to zero bytes in size. */
  46811. if( op==SAVEPOINT_RELEASE ){
  46812. if( nNew==0 && isOpen(pPager->sjfd) ){
  46813. /* Only truncate if it is an in-memory sub-journal. */
  46814. if( sqlite3IsMemJournal(pPager->sjfd) ){
  46815. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  46816. assert( rc==SQLITE_OK );
  46817. }
  46818. pPager->nSubRec = 0;
  46819. }
  46820. }
  46821. /* Else this is a rollback operation, playback the specified savepoint.
  46822. ** If this is a temp-file, it is possible that the journal file has
  46823. ** not yet been opened. In this case there have been no changes to
  46824. ** the database file, so the playback operation can be skipped.
  46825. */
  46826. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  46827. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  46828. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  46829. assert(rc!=SQLITE_DONE);
  46830. }
  46831. }
  46832. return rc;
  46833. }
  46834. /*
  46835. ** Return the full pathname of the database file.
  46836. **
  46837. ** Except, if the pager is in-memory only, then return an empty string if
  46838. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  46839. ** used to report the filename to the user, for compatibility with legacy
  46840. ** behavior. But when the Btree needs to know the filename for matching to
  46841. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  46842. ** participate in shared-cache.
  46843. */
  46844. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  46845. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  46846. }
  46847. /*
  46848. ** Return the VFS structure for the pager.
  46849. */
  46850. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  46851. return pPager->pVfs;
  46852. }
  46853. /*
  46854. ** Return the file handle for the database file associated
  46855. ** with the pager. This might return NULL if the file has
  46856. ** not yet been opened.
  46857. */
  46858. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  46859. return pPager->fd;
  46860. }
  46861. /*
  46862. ** Return the file handle for the journal file (if it exists).
  46863. ** This will be either the rollback journal or the WAL file.
  46864. */
  46865. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  46866. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  46867. }
  46868. /*
  46869. ** Return the full pathname of the journal file.
  46870. */
  46871. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  46872. return pPager->zJournal;
  46873. }
  46874. /*
  46875. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  46876. ** if fsync()s are executed normally.
  46877. */
  46878. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  46879. return pPager->noSync;
  46880. }
  46881. #ifdef SQLITE_HAS_CODEC
  46882. /*
  46883. ** Set or retrieve the codec for this pager
  46884. */
  46885. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  46886. Pager *pPager,
  46887. void *(*xCodec)(void*,void*,Pgno,int),
  46888. void (*xCodecSizeChng)(void*,int,int),
  46889. void (*xCodecFree)(void*),
  46890. void *pCodec
  46891. ){
  46892. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  46893. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  46894. pPager->xCodecSizeChng = xCodecSizeChng;
  46895. pPager->xCodecFree = xCodecFree;
  46896. pPager->pCodec = pCodec;
  46897. pagerReportSize(pPager);
  46898. }
  46899. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  46900. return pPager->pCodec;
  46901. }
  46902. /*
  46903. ** This function is called by the wal module when writing page content
  46904. ** into the log file.
  46905. **
  46906. ** This function returns a pointer to a buffer containing the encrypted
  46907. ** page content. If a malloc fails, this function may return NULL.
  46908. */
  46909. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  46910. void *aData = 0;
  46911. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  46912. return aData;
  46913. }
  46914. /*
  46915. ** Return the current pager state
  46916. */
  46917. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  46918. return pPager->eState;
  46919. }
  46920. #endif /* SQLITE_HAS_CODEC */
  46921. #ifndef SQLITE_OMIT_AUTOVACUUM
  46922. /*
  46923. ** Move the page pPg to location pgno in the file.
  46924. **
  46925. ** There must be no references to the page previously located at
  46926. ** pgno (which we call pPgOld) though that page is allowed to be
  46927. ** in cache. If the page previously located at pgno is not already
  46928. ** in the rollback journal, it is not put there by by this routine.
  46929. **
  46930. ** References to the page pPg remain valid. Updating any
  46931. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  46932. ** allocated along with the page) is the responsibility of the caller.
  46933. **
  46934. ** A transaction must be active when this routine is called. It used to be
  46935. ** required that a statement transaction was not active, but this restriction
  46936. ** has been removed (CREATE INDEX needs to move a page when a statement
  46937. ** transaction is active).
  46938. **
  46939. ** If the fourth argument, isCommit, is non-zero, then this page is being
  46940. ** moved as part of a database reorganization just before the transaction
  46941. ** is being committed. In this case, it is guaranteed that the database page
  46942. ** pPg refers to will not be written to again within this transaction.
  46943. **
  46944. ** This function may return SQLITE_NOMEM or an IO error code if an error
  46945. ** occurs. Otherwise, it returns SQLITE_OK.
  46946. */
  46947. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  46948. PgHdr *pPgOld; /* The page being overwritten. */
  46949. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  46950. int rc; /* Return code */
  46951. Pgno origPgno; /* The original page number */
  46952. assert( pPg->nRef>0 );
  46953. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  46954. || pPager->eState==PAGER_WRITER_DBMOD
  46955. );
  46956. assert( assert_pager_state(pPager) );
  46957. /* In order to be able to rollback, an in-memory database must journal
  46958. ** the page we are moving from.
  46959. */
  46960. if( MEMDB ){
  46961. rc = sqlite3PagerWrite(pPg);
  46962. if( rc ) return rc;
  46963. }
  46964. /* If the page being moved is dirty and has not been saved by the latest
  46965. ** savepoint, then save the current contents of the page into the
  46966. ** sub-journal now. This is required to handle the following scenario:
  46967. **
  46968. ** BEGIN;
  46969. ** <journal page X, then modify it in memory>
  46970. ** SAVEPOINT one;
  46971. ** <Move page X to location Y>
  46972. ** ROLLBACK TO one;
  46973. **
  46974. ** If page X were not written to the sub-journal here, it would not
  46975. ** be possible to restore its contents when the "ROLLBACK TO one"
  46976. ** statement were is processed.
  46977. **
  46978. ** subjournalPage() may need to allocate space to store pPg->pgno into
  46979. ** one or more savepoint bitvecs. This is the reason this function
  46980. ** may return SQLITE_NOMEM.
  46981. */
  46982. if( (pPg->flags & PGHDR_DIRTY)!=0
  46983. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  46984. ){
  46985. return rc;
  46986. }
  46987. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  46988. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  46989. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  46990. /* If the journal needs to be sync()ed before page pPg->pgno can
  46991. ** be written to, store pPg->pgno in local variable needSyncPgno.
  46992. **
  46993. ** If the isCommit flag is set, there is no need to remember that
  46994. ** the journal needs to be sync()ed before database page pPg->pgno
  46995. ** can be written to. The caller has already promised not to write to it.
  46996. */
  46997. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  46998. needSyncPgno = pPg->pgno;
  46999. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  47000. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  47001. assert( pPg->flags&PGHDR_DIRTY );
  47002. }
  47003. /* If the cache contains a page with page-number pgno, remove it
  47004. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  47005. ** page pgno before the 'move' operation, it needs to be retained
  47006. ** for the page moved there.
  47007. */
  47008. pPg->flags &= ~PGHDR_NEED_SYNC;
  47009. pPgOld = sqlite3PagerLookup(pPager, pgno);
  47010. assert( !pPgOld || pPgOld->nRef==1 );
  47011. if( pPgOld ){
  47012. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  47013. if( MEMDB ){
  47014. /* Do not discard pages from an in-memory database since we might
  47015. ** need to rollback later. Just move the page out of the way. */
  47016. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  47017. }else{
  47018. sqlite3PcacheDrop(pPgOld);
  47019. }
  47020. }
  47021. origPgno = pPg->pgno;
  47022. sqlite3PcacheMove(pPg, pgno);
  47023. sqlite3PcacheMakeDirty(pPg);
  47024. /* For an in-memory database, make sure the original page continues
  47025. ** to exist, in case the transaction needs to roll back. Use pPgOld
  47026. ** as the original page since it has already been allocated.
  47027. */
  47028. if( MEMDB ){
  47029. assert( pPgOld );
  47030. sqlite3PcacheMove(pPgOld, origPgno);
  47031. sqlite3PagerUnrefNotNull(pPgOld);
  47032. }
  47033. if( needSyncPgno ){
  47034. /* If needSyncPgno is non-zero, then the journal file needs to be
  47035. ** sync()ed before any data is written to database file page needSyncPgno.
  47036. ** Currently, no such page exists in the page-cache and the
  47037. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  47038. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  47039. ** flag.
  47040. **
  47041. ** If the attempt to load the page into the page-cache fails, (due
  47042. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  47043. ** array. Otherwise, if the page is loaded and written again in
  47044. ** this transaction, it may be written to the database file before
  47045. ** it is synced into the journal file. This way, it may end up in
  47046. ** the journal file twice, but that is not a problem.
  47047. */
  47048. PgHdr *pPgHdr;
  47049. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  47050. if( rc!=SQLITE_OK ){
  47051. if( needSyncPgno<=pPager->dbOrigSize ){
  47052. assert( pPager->pTmpSpace!=0 );
  47053. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  47054. }
  47055. return rc;
  47056. }
  47057. pPgHdr->flags |= PGHDR_NEED_SYNC;
  47058. sqlite3PcacheMakeDirty(pPgHdr);
  47059. sqlite3PagerUnrefNotNull(pPgHdr);
  47060. }
  47061. return SQLITE_OK;
  47062. }
  47063. #endif
  47064. /*
  47065. ** The page handle passed as the first argument refers to a dirty page
  47066. ** with a page number other than iNew. This function changes the page's
  47067. ** page number to iNew and sets the value of the PgHdr.flags field to
  47068. ** the value passed as the third parameter.
  47069. */
  47070. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  47071. assert( pPg->pgno!=iNew );
  47072. pPg->flags = flags;
  47073. sqlite3PcacheMove(pPg, iNew);
  47074. }
  47075. /*
  47076. ** Return a pointer to the data for the specified page.
  47077. */
  47078. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  47079. assert( pPg->nRef>0 || pPg->pPager->memDb );
  47080. return pPg->pData;
  47081. }
  47082. /*
  47083. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  47084. ** allocated along with the specified page.
  47085. */
  47086. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  47087. return pPg->pExtra;
  47088. }
  47089. /*
  47090. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  47091. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  47092. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  47093. ** the locking-mode is set to the value specified.
  47094. **
  47095. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  47096. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  47097. ** locking-mode.
  47098. */
  47099. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  47100. assert( eMode==PAGER_LOCKINGMODE_QUERY
  47101. || eMode==PAGER_LOCKINGMODE_NORMAL
  47102. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  47103. assert( PAGER_LOCKINGMODE_QUERY<0 );
  47104. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  47105. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  47106. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  47107. pPager->exclusiveMode = (u8)eMode;
  47108. }
  47109. return (int)pPager->exclusiveMode;
  47110. }
  47111. /*
  47112. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  47113. **
  47114. ** PAGER_JOURNALMODE_DELETE
  47115. ** PAGER_JOURNALMODE_TRUNCATE
  47116. ** PAGER_JOURNALMODE_PERSIST
  47117. ** PAGER_JOURNALMODE_OFF
  47118. ** PAGER_JOURNALMODE_MEMORY
  47119. ** PAGER_JOURNALMODE_WAL
  47120. **
  47121. ** The journalmode is set to the value specified if the change is allowed.
  47122. ** The change may be disallowed for the following reasons:
  47123. **
  47124. ** * An in-memory database can only have its journal_mode set to _OFF
  47125. ** or _MEMORY.
  47126. **
  47127. ** * Temporary databases cannot have _WAL journalmode.
  47128. **
  47129. ** The returned indicate the current (possibly updated) journal-mode.
  47130. */
  47131. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  47132. u8 eOld = pPager->journalMode; /* Prior journalmode */
  47133. #ifdef SQLITE_DEBUG
  47134. /* The print_pager_state() routine is intended to be used by the debugger
  47135. ** only. We invoke it once here to suppress a compiler warning. */
  47136. print_pager_state(pPager);
  47137. #endif
  47138. /* The eMode parameter is always valid */
  47139. assert( eMode==PAGER_JOURNALMODE_DELETE
  47140. || eMode==PAGER_JOURNALMODE_TRUNCATE
  47141. || eMode==PAGER_JOURNALMODE_PERSIST
  47142. || eMode==PAGER_JOURNALMODE_OFF
  47143. || eMode==PAGER_JOURNALMODE_WAL
  47144. || eMode==PAGER_JOURNALMODE_MEMORY );
  47145. /* This routine is only called from the OP_JournalMode opcode, and
  47146. ** the logic there will never allow a temporary file to be changed
  47147. ** to WAL mode.
  47148. */
  47149. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  47150. /* Do allow the journalmode of an in-memory database to be set to
  47151. ** anything other than MEMORY or OFF
  47152. */
  47153. if( MEMDB ){
  47154. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  47155. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  47156. eMode = eOld;
  47157. }
  47158. }
  47159. if( eMode!=eOld ){
  47160. /* Change the journal mode. */
  47161. assert( pPager->eState!=PAGER_ERROR );
  47162. pPager->journalMode = (u8)eMode;
  47163. /* When transistioning from TRUNCATE or PERSIST to any other journal
  47164. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  47165. ** delete the journal file.
  47166. */
  47167. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  47168. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  47169. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  47170. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  47171. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  47172. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  47173. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  47174. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  47175. /* In this case we would like to delete the journal file. If it is
  47176. ** not possible, then that is not a problem. Deleting the journal file
  47177. ** here is an optimization only.
  47178. **
  47179. ** Before deleting the journal file, obtain a RESERVED lock on the
  47180. ** database file. This ensures that the journal file is not deleted
  47181. ** while it is in use by some other client.
  47182. */
  47183. sqlite3OsClose(pPager->jfd);
  47184. if( pPager->eLock>=RESERVED_LOCK ){
  47185. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  47186. }else{
  47187. int rc = SQLITE_OK;
  47188. int state = pPager->eState;
  47189. assert( state==PAGER_OPEN || state==PAGER_READER );
  47190. if( state==PAGER_OPEN ){
  47191. rc = sqlite3PagerSharedLock(pPager);
  47192. }
  47193. if( pPager->eState==PAGER_READER ){
  47194. assert( rc==SQLITE_OK );
  47195. rc = pagerLockDb(pPager, RESERVED_LOCK);
  47196. }
  47197. if( rc==SQLITE_OK ){
  47198. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  47199. }
  47200. if( rc==SQLITE_OK && state==PAGER_READER ){
  47201. pagerUnlockDb(pPager, SHARED_LOCK);
  47202. }else if( state==PAGER_OPEN ){
  47203. pager_unlock(pPager);
  47204. }
  47205. assert( state==pPager->eState );
  47206. }
  47207. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  47208. sqlite3OsClose(pPager->jfd);
  47209. }
  47210. }
  47211. /* Return the new journal mode */
  47212. return (int)pPager->journalMode;
  47213. }
  47214. /*
  47215. ** Return the current journal mode.
  47216. */
  47217. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  47218. return (int)pPager->journalMode;
  47219. }
  47220. /*
  47221. ** Return TRUE if the pager is in a state where it is OK to change the
  47222. ** journalmode. Journalmode changes can only happen when the database
  47223. ** is unmodified.
  47224. */
  47225. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  47226. assert( assert_pager_state(pPager) );
  47227. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  47228. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  47229. return 1;
  47230. }
  47231. /*
  47232. ** Get/set the size-limit used for persistent journal files.
  47233. **
  47234. ** Setting the size limit to -1 means no limit is enforced.
  47235. ** An attempt to set a limit smaller than -1 is a no-op.
  47236. */
  47237. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  47238. if( iLimit>=-1 ){
  47239. pPager->journalSizeLimit = iLimit;
  47240. sqlite3WalLimit(pPager->pWal, iLimit);
  47241. }
  47242. return pPager->journalSizeLimit;
  47243. }
  47244. /*
  47245. ** Return a pointer to the pPager->pBackup variable. The backup module
  47246. ** in backup.c maintains the content of this variable. This module
  47247. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  47248. ** sqlite3BackupUpdate() only.
  47249. */
  47250. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  47251. return &pPager->pBackup;
  47252. }
  47253. #ifndef SQLITE_OMIT_VACUUM
  47254. /*
  47255. ** Unless this is an in-memory or temporary database, clear the pager cache.
  47256. */
  47257. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  47258. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  47259. }
  47260. #endif
  47261. #ifndef SQLITE_OMIT_WAL
  47262. /*
  47263. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  47264. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  47265. ** or wal_blocking_checkpoint() API functions.
  47266. **
  47267. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  47268. */
  47269. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  47270. int rc = SQLITE_OK;
  47271. if( pPager->pWal ){
  47272. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  47273. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  47274. pPager->pBusyHandlerArg,
  47275. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  47276. pnLog, pnCkpt
  47277. );
  47278. }
  47279. return rc;
  47280. }
  47281. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  47282. return sqlite3WalCallback(pPager->pWal);
  47283. }
  47284. /*
  47285. ** Return true if the underlying VFS for the given pager supports the
  47286. ** primitives necessary for write-ahead logging.
  47287. */
  47288. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  47289. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  47290. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  47291. }
  47292. /*
  47293. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  47294. ** is obtained instead, immediately release it.
  47295. */
  47296. static int pagerExclusiveLock(Pager *pPager){
  47297. int rc; /* Return code */
  47298. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  47299. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  47300. if( rc!=SQLITE_OK ){
  47301. /* If the attempt to grab the exclusive lock failed, release the
  47302. ** pending lock that may have been obtained instead. */
  47303. pagerUnlockDb(pPager, SHARED_LOCK);
  47304. }
  47305. return rc;
  47306. }
  47307. /*
  47308. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  47309. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  47310. ** lock on the database file and use heap-memory to store the wal-index
  47311. ** in. Otherwise, use the normal shared-memory.
  47312. */
  47313. static int pagerOpenWal(Pager *pPager){
  47314. int rc = SQLITE_OK;
  47315. assert( pPager->pWal==0 && pPager->tempFile==0 );
  47316. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  47317. /* If the pager is already in exclusive-mode, the WAL module will use
  47318. ** heap-memory for the wal-index instead of the VFS shared-memory
  47319. ** implementation. Take the exclusive lock now, before opening the WAL
  47320. ** file, to make sure this is safe.
  47321. */
  47322. if( pPager->exclusiveMode ){
  47323. rc = pagerExclusiveLock(pPager);
  47324. }
  47325. /* Open the connection to the log file. If this operation fails,
  47326. ** (e.g. due to malloc() failure), return an error code.
  47327. */
  47328. if( rc==SQLITE_OK ){
  47329. rc = sqlite3WalOpen(pPager->pVfs,
  47330. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  47331. pPager->journalSizeLimit, &pPager->pWal
  47332. );
  47333. }
  47334. pagerFixMaplimit(pPager);
  47335. return rc;
  47336. }
  47337. /*
  47338. ** The caller must be holding a SHARED lock on the database file to call
  47339. ** this function.
  47340. **
  47341. ** If the pager passed as the first argument is open on a real database
  47342. ** file (not a temp file or an in-memory database), and the WAL file
  47343. ** is not already open, make an attempt to open it now. If successful,
  47344. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  47345. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  47346. ** not modified in either case.
  47347. **
  47348. ** If the pager is open on a temp-file (or in-memory database), or if
  47349. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  47350. ** without doing anything.
  47351. */
  47352. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  47353. Pager *pPager, /* Pager object */
  47354. int *pbOpen /* OUT: Set to true if call is a no-op */
  47355. ){
  47356. int rc = SQLITE_OK; /* Return code */
  47357. assert( assert_pager_state(pPager) );
  47358. assert( pPager->eState==PAGER_OPEN || pbOpen );
  47359. assert( pPager->eState==PAGER_READER || !pbOpen );
  47360. assert( pbOpen==0 || *pbOpen==0 );
  47361. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  47362. if( !pPager->tempFile && !pPager->pWal ){
  47363. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  47364. /* Close any rollback journal previously open */
  47365. sqlite3OsClose(pPager->jfd);
  47366. rc = pagerOpenWal(pPager);
  47367. if( rc==SQLITE_OK ){
  47368. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  47369. pPager->eState = PAGER_OPEN;
  47370. }
  47371. }else{
  47372. *pbOpen = 1;
  47373. }
  47374. return rc;
  47375. }
  47376. /*
  47377. ** This function is called to close the connection to the log file prior
  47378. ** to switching from WAL to rollback mode.
  47379. **
  47380. ** Before closing the log file, this function attempts to take an
  47381. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  47382. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  47383. ** If successful, the EXCLUSIVE lock is not released before returning.
  47384. */
  47385. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  47386. int rc = SQLITE_OK;
  47387. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  47388. /* If the log file is not already open, but does exist in the file-system,
  47389. ** it may need to be checkpointed before the connection can switch to
  47390. ** rollback mode. Open it now so this can happen.
  47391. */
  47392. if( !pPager->pWal ){
  47393. int logexists = 0;
  47394. rc = pagerLockDb(pPager, SHARED_LOCK);
  47395. if( rc==SQLITE_OK ){
  47396. rc = sqlite3OsAccess(
  47397. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  47398. );
  47399. }
  47400. if( rc==SQLITE_OK && logexists ){
  47401. rc = pagerOpenWal(pPager);
  47402. }
  47403. }
  47404. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  47405. ** the database file, the log and log-summary files will be deleted.
  47406. */
  47407. if( rc==SQLITE_OK && pPager->pWal ){
  47408. rc = pagerExclusiveLock(pPager);
  47409. if( rc==SQLITE_OK ){
  47410. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  47411. pPager->pageSize, (u8*)pPager->pTmpSpace);
  47412. pPager->pWal = 0;
  47413. pagerFixMaplimit(pPager);
  47414. }
  47415. }
  47416. return rc;
  47417. }
  47418. #ifdef SQLITE_ENABLE_SNAPSHOT
  47419. /*
  47420. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  47421. ** currently open. Otherwise, return an error.
  47422. */
  47423. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  47424. int rc = SQLITE_ERROR;
  47425. if( pPager->pWal ){
  47426. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  47427. }
  47428. return rc;
  47429. }
  47430. /*
  47431. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  47432. ** read transaction is opened, attempt to read from the snapshot it
  47433. ** identifies. If this is not a WAL database, return an error.
  47434. */
  47435. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  47436. int rc = SQLITE_OK;
  47437. if( pPager->pWal ){
  47438. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  47439. }else{
  47440. rc = SQLITE_ERROR;
  47441. }
  47442. return rc;
  47443. }
  47444. #endif /* SQLITE_ENABLE_SNAPSHOT */
  47445. #endif /* !SQLITE_OMIT_WAL */
  47446. #ifdef SQLITE_ENABLE_ZIPVFS
  47447. /*
  47448. ** A read-lock must be held on the pager when this function is called. If
  47449. ** the pager is in WAL mode and the WAL file currently contains one or more
  47450. ** frames, return the size in bytes of the page images stored within the
  47451. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  47452. ** is empty, return 0.
  47453. */
  47454. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  47455. assert( pPager->eState>=PAGER_READER );
  47456. return sqlite3WalFramesize(pPager->pWal);
  47457. }
  47458. #endif
  47459. #endif /* SQLITE_OMIT_DISKIO */
  47460. /************** End of pager.c ***********************************************/
  47461. /************** Begin file wal.c *********************************************/
  47462. /*
  47463. ** 2010 February 1
  47464. **
  47465. ** The author disclaims copyright to this source code. In place of
  47466. ** a legal notice, here is a blessing:
  47467. **
  47468. ** May you do good and not evil.
  47469. ** May you find forgiveness for yourself and forgive others.
  47470. ** May you share freely, never taking more than you give.
  47471. **
  47472. *************************************************************************
  47473. **
  47474. ** This file contains the implementation of a write-ahead log (WAL) used in
  47475. ** "journal_mode=WAL" mode.
  47476. **
  47477. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  47478. **
  47479. ** A WAL file consists of a header followed by zero or more "frames".
  47480. ** Each frame records the revised content of a single page from the
  47481. ** database file. All changes to the database are recorded by writing
  47482. ** frames into the WAL. Transactions commit when a frame is written that
  47483. ** contains a commit marker. A single WAL can and usually does record
  47484. ** multiple transactions. Periodically, the content of the WAL is
  47485. ** transferred back into the database file in an operation called a
  47486. ** "checkpoint".
  47487. **
  47488. ** A single WAL file can be used multiple times. In other words, the
  47489. ** WAL can fill up with frames and then be checkpointed and then new
  47490. ** frames can overwrite the old ones. A WAL always grows from beginning
  47491. ** toward the end. Checksums and counters attached to each frame are
  47492. ** used to determine which frames within the WAL are valid and which
  47493. ** are leftovers from prior checkpoints.
  47494. **
  47495. ** The WAL header is 32 bytes in size and consists of the following eight
  47496. ** big-endian 32-bit unsigned integer values:
  47497. **
  47498. ** 0: Magic number. 0x377f0682 or 0x377f0683
  47499. ** 4: File format version. Currently 3007000
  47500. ** 8: Database page size. Example: 1024
  47501. ** 12: Checkpoint sequence number
  47502. ** 16: Salt-1, random integer incremented with each checkpoint
  47503. ** 20: Salt-2, a different random integer changing with each ckpt
  47504. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  47505. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  47506. **
  47507. ** Immediately following the wal-header are zero or more frames. Each
  47508. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  47509. ** of page data. The frame-header is six big-endian 32-bit unsigned
  47510. ** integer values, as follows:
  47511. **
  47512. ** 0: Page number.
  47513. ** 4: For commit records, the size of the database image in pages
  47514. ** after the commit. For all other records, zero.
  47515. ** 8: Salt-1 (copied from the header)
  47516. ** 12: Salt-2 (copied from the header)
  47517. ** 16: Checksum-1.
  47518. ** 20: Checksum-2.
  47519. **
  47520. ** A frame is considered valid if and only if the following conditions are
  47521. ** true:
  47522. **
  47523. ** (1) The salt-1 and salt-2 values in the frame-header match
  47524. ** salt values in the wal-header
  47525. **
  47526. ** (2) The checksum values in the final 8 bytes of the frame-header
  47527. ** exactly match the checksum computed consecutively on the
  47528. ** WAL header and the first 8 bytes and the content of all frames
  47529. ** up to and including the current frame.
  47530. **
  47531. ** The checksum is computed using 32-bit big-endian integers if the
  47532. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  47533. ** is computed using little-endian if the magic number is 0x377f0682.
  47534. ** The checksum values are always stored in the frame header in a
  47535. ** big-endian format regardless of which byte order is used to compute
  47536. ** the checksum. The checksum is computed by interpreting the input as
  47537. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  47538. ** algorithm used for the checksum is as follows:
  47539. **
  47540. ** for i from 0 to n-1 step 2:
  47541. ** s0 += x[i] + s1;
  47542. ** s1 += x[i+1] + s0;
  47543. ** endfor
  47544. **
  47545. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  47546. ** in reverse order (the largest fibonacci weight occurs on the first element
  47547. ** of the sequence being summed.) The s1 value spans all 32-bit
  47548. ** terms of the sequence whereas s0 omits the final term.
  47549. **
  47550. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  47551. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  47552. ** The VFS.xSync operations serve as write barriers - all writes launched
  47553. ** before the xSync must complete before any write that launches after the
  47554. ** xSync begins.
  47555. **
  47556. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  47557. ** value is randomized. This prevents old and new frames in the WAL from
  47558. ** being considered valid at the same time and being checkpointing together
  47559. ** following a crash.
  47560. **
  47561. ** READER ALGORITHM
  47562. **
  47563. ** To read a page from the database (call it page number P), a reader
  47564. ** first checks the WAL to see if it contains page P. If so, then the
  47565. ** last valid instance of page P that is a followed by a commit frame
  47566. ** or is a commit frame itself becomes the value read. If the WAL
  47567. ** contains no copies of page P that are valid and which are a commit
  47568. ** frame or are followed by a commit frame, then page P is read from
  47569. ** the database file.
  47570. **
  47571. ** To start a read transaction, the reader records the index of the last
  47572. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  47573. ** for all subsequent read operations. New transactions can be appended
  47574. ** to the WAL, but as long as the reader uses its original mxFrame value
  47575. ** and ignores the newly appended content, it will see a consistent snapshot
  47576. ** of the database from a single point in time. This technique allows
  47577. ** multiple concurrent readers to view different versions of the database
  47578. ** content simultaneously.
  47579. **
  47580. ** The reader algorithm in the previous paragraphs works correctly, but
  47581. ** because frames for page P can appear anywhere within the WAL, the
  47582. ** reader has to scan the entire WAL looking for page P frames. If the
  47583. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  47584. ** and read performance suffers. To overcome this problem, a separate
  47585. ** data structure called the wal-index is maintained to expedite the
  47586. ** search for frames of a particular page.
  47587. **
  47588. ** WAL-INDEX FORMAT
  47589. **
  47590. ** Conceptually, the wal-index is shared memory, though VFS implementations
  47591. ** might choose to implement the wal-index using a mmapped file. Because
  47592. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  47593. ** on a network filesystem. All users of the database must be able to
  47594. ** share memory.
  47595. **
  47596. ** The wal-index is transient. After a crash, the wal-index can (and should
  47597. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  47598. ** to either truncate or zero the header of the wal-index when the last
  47599. ** connection to it closes. Because the wal-index is transient, it can
  47600. ** use an architecture-specific format; it does not have to be cross-platform.
  47601. ** Hence, unlike the database and WAL file formats which store all values
  47602. ** as big endian, the wal-index can store multi-byte values in the native
  47603. ** byte order of the host computer.
  47604. **
  47605. ** The purpose of the wal-index is to answer this question quickly: Given
  47606. ** a page number P and a maximum frame index M, return the index of the
  47607. ** last frame in the wal before frame M for page P in the WAL, or return
  47608. ** NULL if there are no frames for page P in the WAL prior to M.
  47609. **
  47610. ** The wal-index consists of a header region, followed by an one or
  47611. ** more index blocks.
  47612. **
  47613. ** The wal-index header contains the total number of frames within the WAL
  47614. ** in the mxFrame field.
  47615. **
  47616. ** Each index block except for the first contains information on
  47617. ** HASHTABLE_NPAGE frames. The first index block contains information on
  47618. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  47619. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  47620. ** first index block are the same size as all other index blocks in the
  47621. ** wal-index.
  47622. **
  47623. ** Each index block contains two sections, a page-mapping that contains the
  47624. ** database page number associated with each wal frame, and a hash-table
  47625. ** that allows readers to query an index block for a specific page number.
  47626. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  47627. ** for the first index block) 32-bit page numbers. The first entry in the
  47628. ** first index-block contains the database page number corresponding to the
  47629. ** first frame in the WAL file. The first entry in the second index block
  47630. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  47631. ** the log, and so on.
  47632. **
  47633. ** The last index block in a wal-index usually contains less than the full
  47634. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  47635. ** depending on the contents of the WAL file. This does not change the
  47636. ** allocated size of the page-mapping array - the page-mapping array merely
  47637. ** contains unused entries.
  47638. **
  47639. ** Even without using the hash table, the last frame for page P
  47640. ** can be found by scanning the page-mapping sections of each index block
  47641. ** starting with the last index block and moving toward the first, and
  47642. ** within each index block, starting at the end and moving toward the
  47643. ** beginning. The first entry that equals P corresponds to the frame
  47644. ** holding the content for that page.
  47645. **
  47646. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  47647. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  47648. ** hash table for each page number in the mapping section, so the hash
  47649. ** table is never more than half full. The expected number of collisions
  47650. ** prior to finding a match is 1. Each entry of the hash table is an
  47651. ** 1-based index of an entry in the mapping section of the same
  47652. ** index block. Let K be the 1-based index of the largest entry in
  47653. ** the mapping section. (For index blocks other than the last, K will
  47654. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  47655. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  47656. ** contain a value of 0.
  47657. **
  47658. ** To look for page P in the hash table, first compute a hash iKey on
  47659. ** P as follows:
  47660. **
  47661. ** iKey = (P * 383) % HASHTABLE_NSLOT
  47662. **
  47663. ** Then start scanning entries of the hash table, starting with iKey
  47664. ** (wrapping around to the beginning when the end of the hash table is
  47665. ** reached) until an unused hash slot is found. Let the first unused slot
  47666. ** be at index iUnused. (iUnused might be less than iKey if there was
  47667. ** wrap-around.) Because the hash table is never more than half full,
  47668. ** the search is guaranteed to eventually hit an unused entry. Let
  47669. ** iMax be the value between iKey and iUnused, closest to iUnused,
  47670. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  47671. ** no hash slot such that aHash[i]==p) then page P is not in the
  47672. ** current index block. Otherwise the iMax-th mapping entry of the
  47673. ** current index block corresponds to the last entry that references
  47674. ** page P.
  47675. **
  47676. ** A hash search begins with the last index block and moves toward the
  47677. ** first index block, looking for entries corresponding to page P. On
  47678. ** average, only two or three slots in each index block need to be
  47679. ** examined in order to either find the last entry for page P, or to
  47680. ** establish that no such entry exists in the block. Each index block
  47681. ** holds over 4000 entries. So two or three index blocks are sufficient
  47682. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  47683. ** comparisons (on average) suffice to either locate a frame in the
  47684. ** WAL or to establish that the frame does not exist in the WAL. This
  47685. ** is much faster than scanning the entire 10MB WAL.
  47686. **
  47687. ** Note that entries are added in order of increasing K. Hence, one
  47688. ** reader might be using some value K0 and a second reader that started
  47689. ** at a later time (after additional transactions were added to the WAL
  47690. ** and to the wal-index) might be using a different value K1, where K1>K0.
  47691. ** Both readers can use the same hash table and mapping section to get
  47692. ** the correct result. There may be entries in the hash table with
  47693. ** K>K0 but to the first reader, those entries will appear to be unused
  47694. ** slots in the hash table and so the first reader will get an answer as
  47695. ** if no values greater than K0 had ever been inserted into the hash table
  47696. ** in the first place - which is what reader one wants. Meanwhile, the
  47697. ** second reader using K1 will see additional values that were inserted
  47698. ** later, which is exactly what reader two wants.
  47699. **
  47700. ** When a rollback occurs, the value of K is decreased. Hash table entries
  47701. ** that correspond to frames greater than the new K value are removed
  47702. ** from the hash table at this point.
  47703. */
  47704. #ifndef SQLITE_OMIT_WAL
  47705. /* #include "wal.h" */
  47706. /*
  47707. ** Trace output macros
  47708. */
  47709. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  47710. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  47711. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  47712. #else
  47713. # define WALTRACE(X)
  47714. #endif
  47715. /*
  47716. ** The maximum (and only) versions of the wal and wal-index formats
  47717. ** that may be interpreted by this version of SQLite.
  47718. **
  47719. ** If a client begins recovering a WAL file and finds that (a) the checksum
  47720. ** values in the wal-header are correct and (b) the version field is not
  47721. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  47722. **
  47723. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  47724. ** checksum test is successful) and finds that the version field is not
  47725. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  47726. ** returns SQLITE_CANTOPEN.
  47727. */
  47728. #define WAL_MAX_VERSION 3007000
  47729. #define WALINDEX_MAX_VERSION 3007000
  47730. /*
  47731. ** Indices of various locking bytes. WAL_NREADER is the number
  47732. ** of available reader locks and should be at least 3. The default
  47733. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  47734. */
  47735. #define WAL_WRITE_LOCK 0
  47736. #define WAL_ALL_BUT_WRITE 1
  47737. #define WAL_CKPT_LOCK 1
  47738. #define WAL_RECOVER_LOCK 2
  47739. #define WAL_READ_LOCK(I) (3+(I))
  47740. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  47741. /* Object declarations */
  47742. typedef struct WalIndexHdr WalIndexHdr;
  47743. typedef struct WalIterator WalIterator;
  47744. typedef struct WalCkptInfo WalCkptInfo;
  47745. /*
  47746. ** The following object holds a copy of the wal-index header content.
  47747. **
  47748. ** The actual header in the wal-index consists of two copies of this
  47749. ** object followed by one instance of the WalCkptInfo object.
  47750. ** For all versions of SQLite through 3.10.0 and probably beyond,
  47751. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  47752. ** the total header size is 136 bytes.
  47753. **
  47754. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  47755. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  47756. ** added in 3.7.1 when support for 64K pages was added.
  47757. */
  47758. struct WalIndexHdr {
  47759. u32 iVersion; /* Wal-index version */
  47760. u32 unused; /* Unused (padding) field */
  47761. u32 iChange; /* Counter incremented each transaction */
  47762. u8 isInit; /* 1 when initialized */
  47763. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  47764. u16 szPage; /* Database page size in bytes. 1==64K */
  47765. u32 mxFrame; /* Index of last valid frame in the WAL */
  47766. u32 nPage; /* Size of database in pages */
  47767. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  47768. u32 aSalt[2]; /* Two salt values copied from WAL header */
  47769. u32 aCksum[2]; /* Checksum over all prior fields */
  47770. };
  47771. /*
  47772. ** A copy of the following object occurs in the wal-index immediately
  47773. ** following the second copy of the WalIndexHdr. This object stores
  47774. ** information used by checkpoint.
  47775. **
  47776. ** nBackfill is the number of frames in the WAL that have been written
  47777. ** back into the database. (We call the act of moving content from WAL to
  47778. ** database "backfilling".) The nBackfill number is never greater than
  47779. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  47780. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  47781. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  47782. ** mxFrame back to zero when the WAL is reset.
  47783. **
  47784. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  47785. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  47786. ** the nBackfillAttempted is set before any backfilling is done and the
  47787. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  47788. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  47789. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  47790. **
  47791. ** The aLock[] field is a set of bytes used for locking. These bytes should
  47792. ** never be read or written.
  47793. **
  47794. ** There is one entry in aReadMark[] for each reader lock. If a reader
  47795. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  47796. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  47797. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  47798. ** a special case; its value is never used and it exists as a place-holder
  47799. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  47800. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  47801. ** directly from the database.
  47802. **
  47803. ** The value of aReadMark[K] may only be changed by a thread that
  47804. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  47805. ** aReadMark[K] cannot changed while there is a reader is using that mark
  47806. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  47807. **
  47808. ** The checkpointer may only transfer frames from WAL to database where
  47809. ** the frame numbers are less than or equal to every aReadMark[] that is
  47810. ** in use (that is, every aReadMark[j] for which there is a corresponding
  47811. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  47812. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  47813. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  47814. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  47815. ** in the WAL has been backfilled into the database) then new readers
  47816. ** will choose aReadMark[0] which has value 0 and hence such reader will
  47817. ** get all their all content directly from the database file and ignore
  47818. ** the WAL.
  47819. **
  47820. ** Writers normally append new frames to the end of the WAL. However,
  47821. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  47822. ** written back into the database) and if no readers are using the WAL
  47823. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  47824. ** the writer will first "reset" the WAL back to the beginning and start
  47825. ** writing new content beginning at frame 1.
  47826. **
  47827. ** We assume that 32-bit loads are atomic and so no locks are needed in
  47828. ** order to read from any aReadMark[] entries.
  47829. */
  47830. struct WalCkptInfo {
  47831. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  47832. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  47833. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  47834. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  47835. u32 notUsed0; /* Available for future enhancements */
  47836. };
  47837. #define READMARK_NOT_USED 0xffffffff
  47838. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  47839. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  47840. ** only support mandatory file-locks, we do not read or write data
  47841. ** from the region of the file on which locks are applied.
  47842. */
  47843. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  47844. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  47845. /* Size of header before each frame in wal */
  47846. #define WAL_FRAME_HDRSIZE 24
  47847. /* Size of write ahead log header, including checksum. */
  47848. /* #define WAL_HDRSIZE 24 */
  47849. #define WAL_HDRSIZE 32
  47850. /* WAL magic value. Either this value, or the same value with the least
  47851. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  47852. ** big-endian format in the first 4 bytes of a WAL file.
  47853. **
  47854. ** If the LSB is set, then the checksums for each frame within the WAL
  47855. ** file are calculated by treating all data as an array of 32-bit
  47856. ** big-endian words. Otherwise, they are calculated by interpreting
  47857. ** all data as 32-bit little-endian words.
  47858. */
  47859. #define WAL_MAGIC 0x377f0682
  47860. /*
  47861. ** Return the offset of frame iFrame in the write-ahead log file,
  47862. ** assuming a database page size of szPage bytes. The offset returned
  47863. ** is to the start of the write-ahead log frame-header.
  47864. */
  47865. #define walFrameOffset(iFrame, szPage) ( \
  47866. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  47867. )
  47868. /*
  47869. ** An open write-ahead log file is represented by an instance of the
  47870. ** following object.
  47871. */
  47872. struct Wal {
  47873. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  47874. sqlite3_file *pDbFd; /* File handle for the database file */
  47875. sqlite3_file *pWalFd; /* File handle for WAL file */
  47876. u32 iCallback; /* Value to pass to log callback (or 0) */
  47877. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  47878. int nWiData; /* Size of array apWiData */
  47879. int szFirstBlock; /* Size of first block written to WAL file */
  47880. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  47881. u32 szPage; /* Database page size */
  47882. i16 readLock; /* Which read lock is being held. -1 for none */
  47883. u8 syncFlags; /* Flags to use to sync header writes */
  47884. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  47885. u8 writeLock; /* True if in a write transaction */
  47886. u8 ckptLock; /* True if holding a checkpoint lock */
  47887. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  47888. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  47889. u8 syncHeader; /* Fsync the WAL header if true */
  47890. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  47891. WalIndexHdr hdr; /* Wal-index header for current transaction */
  47892. u32 minFrame; /* Ignore wal frames before this one */
  47893. const char *zWalName; /* Name of WAL file */
  47894. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  47895. #ifdef SQLITE_DEBUG
  47896. u8 lockError; /* True if a locking error has occurred */
  47897. #endif
  47898. #ifdef SQLITE_ENABLE_SNAPSHOT
  47899. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  47900. #endif
  47901. };
  47902. /*
  47903. ** Candidate values for Wal.exclusiveMode.
  47904. */
  47905. #define WAL_NORMAL_MODE 0
  47906. #define WAL_EXCLUSIVE_MODE 1
  47907. #define WAL_HEAPMEMORY_MODE 2
  47908. /*
  47909. ** Possible values for WAL.readOnly
  47910. */
  47911. #define WAL_RDWR 0 /* Normal read/write connection */
  47912. #define WAL_RDONLY 1 /* The WAL file is readonly */
  47913. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  47914. /*
  47915. ** Each page of the wal-index mapping contains a hash-table made up of
  47916. ** an array of HASHTABLE_NSLOT elements of the following type.
  47917. */
  47918. typedef u16 ht_slot;
  47919. /*
  47920. ** This structure is used to implement an iterator that loops through
  47921. ** all frames in the WAL in database page order. Where two or more frames
  47922. ** correspond to the same database page, the iterator visits only the
  47923. ** frame most recently written to the WAL (in other words, the frame with
  47924. ** the largest index).
  47925. **
  47926. ** The internals of this structure are only accessed by:
  47927. **
  47928. ** walIteratorInit() - Create a new iterator,
  47929. ** walIteratorNext() - Step an iterator,
  47930. ** walIteratorFree() - Free an iterator.
  47931. **
  47932. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  47933. */
  47934. struct WalIterator {
  47935. int iPrior; /* Last result returned from the iterator */
  47936. int nSegment; /* Number of entries in aSegment[] */
  47937. struct WalSegment {
  47938. int iNext; /* Next slot in aIndex[] not yet returned */
  47939. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  47940. u32 *aPgno; /* Array of page numbers. */
  47941. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  47942. int iZero; /* Frame number associated with aPgno[0] */
  47943. } aSegment[1]; /* One for every 32KB page in the wal-index */
  47944. };
  47945. /*
  47946. ** Define the parameters of the hash tables in the wal-index file. There
  47947. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  47948. ** wal-index.
  47949. **
  47950. ** Changing any of these constants will alter the wal-index format and
  47951. ** create incompatibilities.
  47952. */
  47953. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  47954. #define HASHTABLE_HASH_1 383 /* Should be prime */
  47955. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  47956. /*
  47957. ** The block of page numbers associated with the first hash-table in a
  47958. ** wal-index is smaller than usual. This is so that there is a complete
  47959. ** hash-table on each aligned 32KB page of the wal-index.
  47960. */
  47961. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  47962. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  47963. #define WALINDEX_PGSZ ( \
  47964. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  47965. )
  47966. /*
  47967. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  47968. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  47969. ** numbered from zero.
  47970. **
  47971. ** If this call is successful, *ppPage is set to point to the wal-index
  47972. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  47973. ** then an SQLite error code is returned and *ppPage is set to 0.
  47974. */
  47975. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  47976. int rc = SQLITE_OK;
  47977. /* Enlarge the pWal->apWiData[] array if required */
  47978. if( pWal->nWiData<=iPage ){
  47979. int nByte = sizeof(u32*)*(iPage+1);
  47980. volatile u32 **apNew;
  47981. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  47982. if( !apNew ){
  47983. *ppPage = 0;
  47984. return SQLITE_NOMEM;
  47985. }
  47986. memset((void*)&apNew[pWal->nWiData], 0,
  47987. sizeof(u32*)*(iPage+1-pWal->nWiData));
  47988. pWal->apWiData = apNew;
  47989. pWal->nWiData = iPage+1;
  47990. }
  47991. /* Request a pointer to the required page from the VFS */
  47992. if( pWal->apWiData[iPage]==0 ){
  47993. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  47994. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  47995. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  47996. }else{
  47997. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  47998. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  47999. );
  48000. if( rc==SQLITE_READONLY ){
  48001. pWal->readOnly |= WAL_SHM_RDONLY;
  48002. rc = SQLITE_OK;
  48003. }
  48004. }
  48005. }
  48006. *ppPage = pWal->apWiData[iPage];
  48007. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  48008. return rc;
  48009. }
  48010. /*
  48011. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  48012. */
  48013. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  48014. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  48015. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  48016. }
  48017. /*
  48018. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  48019. */
  48020. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  48021. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  48022. return (volatile WalIndexHdr*)pWal->apWiData[0];
  48023. }
  48024. /*
  48025. ** The argument to this macro must be of type u32. On a little-endian
  48026. ** architecture, it returns the u32 value that results from interpreting
  48027. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  48028. ** returns the value that would be produced by interpreting the 4 bytes
  48029. ** of the input value as a little-endian integer.
  48030. */
  48031. #define BYTESWAP32(x) ( \
  48032. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  48033. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  48034. )
  48035. /*
  48036. ** Generate or extend an 8 byte checksum based on the data in
  48037. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  48038. ** initial values of 0 and 0 if aIn==NULL).
  48039. **
  48040. ** The checksum is written back into aOut[] before returning.
  48041. **
  48042. ** nByte must be a positive multiple of 8.
  48043. */
  48044. static void walChecksumBytes(
  48045. int nativeCksum, /* True for native byte-order, false for non-native */
  48046. u8 *a, /* Content to be checksummed */
  48047. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  48048. const u32 *aIn, /* Initial checksum value input */
  48049. u32 *aOut /* OUT: Final checksum value output */
  48050. ){
  48051. u32 s1, s2;
  48052. u32 *aData = (u32 *)a;
  48053. u32 *aEnd = (u32 *)&a[nByte];
  48054. if( aIn ){
  48055. s1 = aIn[0];
  48056. s2 = aIn[1];
  48057. }else{
  48058. s1 = s2 = 0;
  48059. }
  48060. assert( nByte>=8 );
  48061. assert( (nByte&0x00000007)==0 );
  48062. if( nativeCksum ){
  48063. do {
  48064. s1 += *aData++ + s2;
  48065. s2 += *aData++ + s1;
  48066. }while( aData<aEnd );
  48067. }else{
  48068. do {
  48069. s1 += BYTESWAP32(aData[0]) + s2;
  48070. s2 += BYTESWAP32(aData[1]) + s1;
  48071. aData += 2;
  48072. }while( aData<aEnd );
  48073. }
  48074. aOut[0] = s1;
  48075. aOut[1] = s2;
  48076. }
  48077. static void walShmBarrier(Wal *pWal){
  48078. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  48079. sqlite3OsShmBarrier(pWal->pDbFd);
  48080. }
  48081. }
  48082. /*
  48083. ** Write the header information in pWal->hdr into the wal-index.
  48084. **
  48085. ** The checksum on pWal->hdr is updated before it is written.
  48086. */
  48087. static void walIndexWriteHdr(Wal *pWal){
  48088. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  48089. const int nCksum = offsetof(WalIndexHdr, aCksum);
  48090. assert( pWal->writeLock );
  48091. pWal->hdr.isInit = 1;
  48092. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  48093. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  48094. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  48095. walShmBarrier(pWal);
  48096. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  48097. }
  48098. /*
  48099. ** This function encodes a single frame header and writes it to a buffer
  48100. ** supplied by the caller. A frame-header is made up of a series of
  48101. ** 4-byte big-endian integers, as follows:
  48102. **
  48103. ** 0: Page number.
  48104. ** 4: For commit records, the size of the database image in pages
  48105. ** after the commit. For all other records, zero.
  48106. ** 8: Salt-1 (copied from the wal-header)
  48107. ** 12: Salt-2 (copied from the wal-header)
  48108. ** 16: Checksum-1.
  48109. ** 20: Checksum-2.
  48110. */
  48111. static void walEncodeFrame(
  48112. Wal *pWal, /* The write-ahead log */
  48113. u32 iPage, /* Database page number for frame */
  48114. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  48115. u8 *aData, /* Pointer to page data */
  48116. u8 *aFrame /* OUT: Write encoded frame here */
  48117. ){
  48118. int nativeCksum; /* True for native byte-order checksums */
  48119. u32 *aCksum = pWal->hdr.aFrameCksum;
  48120. assert( WAL_FRAME_HDRSIZE==24 );
  48121. sqlite3Put4byte(&aFrame[0], iPage);
  48122. sqlite3Put4byte(&aFrame[4], nTruncate);
  48123. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  48124. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  48125. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  48126. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  48127. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  48128. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  48129. }
  48130. /*
  48131. ** Check to see if the frame with header in aFrame[] and content
  48132. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  48133. ** *pnTruncate and return true. Return if the frame is not valid.
  48134. */
  48135. static int walDecodeFrame(
  48136. Wal *pWal, /* The write-ahead log */
  48137. u32 *piPage, /* OUT: Database page number for frame */
  48138. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  48139. u8 *aData, /* Pointer to page data (for checksum) */
  48140. u8 *aFrame /* Frame data */
  48141. ){
  48142. int nativeCksum; /* True for native byte-order checksums */
  48143. u32 *aCksum = pWal->hdr.aFrameCksum;
  48144. u32 pgno; /* Page number of the frame */
  48145. assert( WAL_FRAME_HDRSIZE==24 );
  48146. /* A frame is only valid if the salt values in the frame-header
  48147. ** match the salt values in the wal-header.
  48148. */
  48149. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  48150. return 0;
  48151. }
  48152. /* A frame is only valid if the page number is creater than zero.
  48153. */
  48154. pgno = sqlite3Get4byte(&aFrame[0]);
  48155. if( pgno==0 ){
  48156. return 0;
  48157. }
  48158. /* A frame is only valid if a checksum of the WAL header,
  48159. ** all prior frams, the first 16 bytes of this frame-header,
  48160. ** and the frame-data matches the checksum in the last 8
  48161. ** bytes of this frame-header.
  48162. */
  48163. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  48164. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  48165. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  48166. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  48167. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  48168. ){
  48169. /* Checksum failed. */
  48170. return 0;
  48171. }
  48172. /* If we reach this point, the frame is valid. Return the page number
  48173. ** and the new database size.
  48174. */
  48175. *piPage = pgno;
  48176. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  48177. return 1;
  48178. }
  48179. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  48180. /*
  48181. ** Names of locks. This routine is used to provide debugging output and is not
  48182. ** a part of an ordinary build.
  48183. */
  48184. static const char *walLockName(int lockIdx){
  48185. if( lockIdx==WAL_WRITE_LOCK ){
  48186. return "WRITE-LOCK";
  48187. }else if( lockIdx==WAL_CKPT_LOCK ){
  48188. return "CKPT-LOCK";
  48189. }else if( lockIdx==WAL_RECOVER_LOCK ){
  48190. return "RECOVER-LOCK";
  48191. }else{
  48192. static char zName[15];
  48193. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  48194. lockIdx-WAL_READ_LOCK(0));
  48195. return zName;
  48196. }
  48197. }
  48198. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  48199. /*
  48200. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  48201. ** A lock cannot be moved directly between shared and exclusive - it must go
  48202. ** through the unlocked state first.
  48203. **
  48204. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  48205. */
  48206. static int walLockShared(Wal *pWal, int lockIdx){
  48207. int rc;
  48208. if( pWal->exclusiveMode ) return SQLITE_OK;
  48209. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  48210. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  48211. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  48212. walLockName(lockIdx), rc ? "failed" : "ok"));
  48213. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  48214. return rc;
  48215. }
  48216. static void walUnlockShared(Wal *pWal, int lockIdx){
  48217. if( pWal->exclusiveMode ) return;
  48218. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  48219. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  48220. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  48221. }
  48222. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  48223. int rc;
  48224. if( pWal->exclusiveMode ) return SQLITE_OK;
  48225. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  48226. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  48227. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  48228. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  48229. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  48230. return rc;
  48231. }
  48232. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  48233. if( pWal->exclusiveMode ) return;
  48234. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  48235. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  48236. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  48237. walLockName(lockIdx), n));
  48238. }
  48239. /*
  48240. ** Compute a hash on a page number. The resulting hash value must land
  48241. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  48242. ** the hash to the next value in the event of a collision.
  48243. */
  48244. static int walHash(u32 iPage){
  48245. assert( iPage>0 );
  48246. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  48247. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  48248. }
  48249. static int walNextHash(int iPriorHash){
  48250. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  48251. }
  48252. /*
  48253. ** Return pointers to the hash table and page number array stored on
  48254. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  48255. ** numbered starting from 0.
  48256. **
  48257. ** Set output variable *paHash to point to the start of the hash table
  48258. ** in the wal-index file. Set *piZero to one less than the frame
  48259. ** number of the first frame indexed by this hash table. If a
  48260. ** slot in the hash table is set to N, it refers to frame number
  48261. ** (*piZero+N) in the log.
  48262. **
  48263. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  48264. ** first frame indexed by the hash table, frame (*piZero+1).
  48265. */
  48266. static int walHashGet(
  48267. Wal *pWal, /* WAL handle */
  48268. int iHash, /* Find the iHash'th table */
  48269. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  48270. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  48271. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  48272. ){
  48273. int rc; /* Return code */
  48274. volatile u32 *aPgno;
  48275. rc = walIndexPage(pWal, iHash, &aPgno);
  48276. assert( rc==SQLITE_OK || iHash>0 );
  48277. if( rc==SQLITE_OK ){
  48278. u32 iZero;
  48279. volatile ht_slot *aHash;
  48280. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  48281. if( iHash==0 ){
  48282. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  48283. iZero = 0;
  48284. }else{
  48285. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  48286. }
  48287. *paPgno = &aPgno[-1];
  48288. *paHash = aHash;
  48289. *piZero = iZero;
  48290. }
  48291. return rc;
  48292. }
  48293. /*
  48294. ** Return the number of the wal-index page that contains the hash-table
  48295. ** and page-number array that contain entries corresponding to WAL frame
  48296. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  48297. ** are numbered starting from 0.
  48298. */
  48299. static int walFramePage(u32 iFrame){
  48300. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  48301. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  48302. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  48303. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  48304. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  48305. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  48306. );
  48307. return iHash;
  48308. }
  48309. /*
  48310. ** Return the page number associated with frame iFrame in this WAL.
  48311. */
  48312. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  48313. int iHash = walFramePage(iFrame);
  48314. if( iHash==0 ){
  48315. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  48316. }
  48317. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  48318. }
  48319. /*
  48320. ** Remove entries from the hash table that point to WAL slots greater
  48321. ** than pWal->hdr.mxFrame.
  48322. **
  48323. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  48324. ** to a rollback or savepoint.
  48325. **
  48326. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  48327. ** updated. Any later hash tables will be automatically cleared when
  48328. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  48329. ** actually needed.
  48330. */
  48331. static void walCleanupHash(Wal *pWal){
  48332. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  48333. volatile u32 *aPgno = 0; /* Page number array for hash table */
  48334. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  48335. int iLimit = 0; /* Zero values greater than this */
  48336. int nByte; /* Number of bytes to zero in aPgno[] */
  48337. int i; /* Used to iterate through aHash[] */
  48338. assert( pWal->writeLock );
  48339. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  48340. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  48341. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  48342. if( pWal->hdr.mxFrame==0 ) return;
  48343. /* Obtain pointers to the hash-table and page-number array containing
  48344. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  48345. ** that the page said hash-table and array reside on is already mapped.
  48346. */
  48347. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  48348. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  48349. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  48350. /* Zero all hash-table entries that correspond to frame numbers greater
  48351. ** than pWal->hdr.mxFrame.
  48352. */
  48353. iLimit = pWal->hdr.mxFrame - iZero;
  48354. assert( iLimit>0 );
  48355. for(i=0; i<HASHTABLE_NSLOT; i++){
  48356. if( aHash[i]>iLimit ){
  48357. aHash[i] = 0;
  48358. }
  48359. }
  48360. /* Zero the entries in the aPgno array that correspond to frames with
  48361. ** frame numbers greater than pWal->hdr.mxFrame.
  48362. */
  48363. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  48364. memset((void *)&aPgno[iLimit+1], 0, nByte);
  48365. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  48366. /* Verify that the every entry in the mapping region is still reachable
  48367. ** via the hash table even after the cleanup.
  48368. */
  48369. if( iLimit ){
  48370. int j; /* Loop counter */
  48371. int iKey; /* Hash key */
  48372. for(j=1; j<=iLimit; j++){
  48373. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  48374. if( aHash[iKey]==j ) break;
  48375. }
  48376. assert( aHash[iKey]==j );
  48377. }
  48378. }
  48379. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  48380. }
  48381. /*
  48382. ** Set an entry in the wal-index that will map database page number
  48383. ** pPage into WAL frame iFrame.
  48384. */
  48385. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  48386. int rc; /* Return code */
  48387. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  48388. volatile u32 *aPgno = 0; /* Page number array */
  48389. volatile ht_slot *aHash = 0; /* Hash table */
  48390. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  48391. /* Assuming the wal-index file was successfully mapped, populate the
  48392. ** page number array and hash table entry.
  48393. */
  48394. if( rc==SQLITE_OK ){
  48395. int iKey; /* Hash table key */
  48396. int idx; /* Value to write to hash-table slot */
  48397. int nCollide; /* Number of hash collisions */
  48398. idx = iFrame - iZero;
  48399. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  48400. /* If this is the first entry to be added to this hash-table, zero the
  48401. ** entire hash table and aPgno[] array before proceeding.
  48402. */
  48403. if( idx==1 ){
  48404. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  48405. memset((void*)&aPgno[1], 0, nByte);
  48406. }
  48407. /* If the entry in aPgno[] is already set, then the previous writer
  48408. ** must have exited unexpectedly in the middle of a transaction (after
  48409. ** writing one or more dirty pages to the WAL to free up memory).
  48410. ** Remove the remnants of that writers uncommitted transaction from
  48411. ** the hash-table before writing any new entries.
  48412. */
  48413. if( aPgno[idx] ){
  48414. walCleanupHash(pWal);
  48415. assert( !aPgno[idx] );
  48416. }
  48417. /* Write the aPgno[] array entry and the hash-table slot. */
  48418. nCollide = idx;
  48419. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  48420. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  48421. }
  48422. aPgno[idx] = iPage;
  48423. aHash[iKey] = (ht_slot)idx;
  48424. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  48425. /* Verify that the number of entries in the hash table exactly equals
  48426. ** the number of entries in the mapping region.
  48427. */
  48428. {
  48429. int i; /* Loop counter */
  48430. int nEntry = 0; /* Number of entries in the hash table */
  48431. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  48432. assert( nEntry==idx );
  48433. }
  48434. /* Verify that the every entry in the mapping region is reachable
  48435. ** via the hash table. This turns out to be a really, really expensive
  48436. ** thing to check, so only do this occasionally - not on every
  48437. ** iteration.
  48438. */
  48439. if( (idx&0x3ff)==0 ){
  48440. int i; /* Loop counter */
  48441. for(i=1; i<=idx; i++){
  48442. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  48443. if( aHash[iKey]==i ) break;
  48444. }
  48445. assert( aHash[iKey]==i );
  48446. }
  48447. }
  48448. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  48449. }
  48450. return rc;
  48451. }
  48452. /*
  48453. ** Recover the wal-index by reading the write-ahead log file.
  48454. **
  48455. ** This routine first tries to establish an exclusive lock on the
  48456. ** wal-index to prevent other threads/processes from doing anything
  48457. ** with the WAL or wal-index while recovery is running. The
  48458. ** WAL_RECOVER_LOCK is also held so that other threads will know
  48459. ** that this thread is running recovery. If unable to establish
  48460. ** the necessary locks, this routine returns SQLITE_BUSY.
  48461. */
  48462. static int walIndexRecover(Wal *pWal){
  48463. int rc; /* Return Code */
  48464. i64 nSize; /* Size of log file */
  48465. u32 aFrameCksum[2] = {0, 0};
  48466. int iLock; /* Lock offset to lock for checkpoint */
  48467. int nLock; /* Number of locks to hold */
  48468. /* Obtain an exclusive lock on all byte in the locking range not already
  48469. ** locked by the caller. The caller is guaranteed to have locked the
  48470. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  48471. ** If successful, the same bytes that are locked here are unlocked before
  48472. ** this function returns.
  48473. */
  48474. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  48475. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  48476. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  48477. assert( pWal->writeLock );
  48478. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  48479. nLock = SQLITE_SHM_NLOCK - iLock;
  48480. rc = walLockExclusive(pWal, iLock, nLock);
  48481. if( rc ){
  48482. return rc;
  48483. }
  48484. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  48485. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  48486. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  48487. if( rc!=SQLITE_OK ){
  48488. goto recovery_error;
  48489. }
  48490. if( nSize>WAL_HDRSIZE ){
  48491. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  48492. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  48493. int szFrame; /* Number of bytes in buffer aFrame[] */
  48494. u8 *aData; /* Pointer to data part of aFrame buffer */
  48495. int iFrame; /* Index of last frame read */
  48496. i64 iOffset; /* Next offset to read from log file */
  48497. int szPage; /* Page size according to the log */
  48498. u32 magic; /* Magic value read from WAL header */
  48499. u32 version; /* Magic value read from WAL header */
  48500. int isValid; /* True if this frame is valid */
  48501. /* Read in the WAL header. */
  48502. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  48503. if( rc!=SQLITE_OK ){
  48504. goto recovery_error;
  48505. }
  48506. /* If the database page size is not a power of two, or is greater than
  48507. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  48508. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  48509. ** WAL file.
  48510. */
  48511. magic = sqlite3Get4byte(&aBuf[0]);
  48512. szPage = sqlite3Get4byte(&aBuf[8]);
  48513. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  48514. || szPage&(szPage-1)
  48515. || szPage>SQLITE_MAX_PAGE_SIZE
  48516. || szPage<512
  48517. ){
  48518. goto finished;
  48519. }
  48520. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  48521. pWal->szPage = szPage;
  48522. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  48523. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  48524. /* Verify that the WAL header checksum is correct */
  48525. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  48526. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  48527. );
  48528. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  48529. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  48530. ){
  48531. goto finished;
  48532. }
  48533. /* Verify that the version number on the WAL format is one that
  48534. ** are able to understand */
  48535. version = sqlite3Get4byte(&aBuf[4]);
  48536. if( version!=WAL_MAX_VERSION ){
  48537. rc = SQLITE_CANTOPEN_BKPT;
  48538. goto finished;
  48539. }
  48540. /* Malloc a buffer to read frames into. */
  48541. szFrame = szPage + WAL_FRAME_HDRSIZE;
  48542. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  48543. if( !aFrame ){
  48544. rc = SQLITE_NOMEM;
  48545. goto recovery_error;
  48546. }
  48547. aData = &aFrame[WAL_FRAME_HDRSIZE];
  48548. /* Read all frames from the log file. */
  48549. iFrame = 0;
  48550. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  48551. u32 pgno; /* Database page number for frame */
  48552. u32 nTruncate; /* dbsize field from frame header */
  48553. /* Read and decode the next log frame. */
  48554. iFrame++;
  48555. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  48556. if( rc!=SQLITE_OK ) break;
  48557. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  48558. if( !isValid ) break;
  48559. rc = walIndexAppend(pWal, iFrame, pgno);
  48560. if( rc!=SQLITE_OK ) break;
  48561. /* If nTruncate is non-zero, this is a commit record. */
  48562. if( nTruncate ){
  48563. pWal->hdr.mxFrame = iFrame;
  48564. pWal->hdr.nPage = nTruncate;
  48565. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  48566. testcase( szPage<=32768 );
  48567. testcase( szPage>=65536 );
  48568. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  48569. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  48570. }
  48571. }
  48572. sqlite3_free(aFrame);
  48573. }
  48574. finished:
  48575. if( rc==SQLITE_OK ){
  48576. volatile WalCkptInfo *pInfo;
  48577. int i;
  48578. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  48579. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  48580. walIndexWriteHdr(pWal);
  48581. /* Reset the checkpoint-header. This is safe because this thread is
  48582. ** currently holding locks that exclude all other readers, writers and
  48583. ** checkpointers.
  48584. */
  48585. pInfo = walCkptInfo(pWal);
  48586. pInfo->nBackfill = 0;
  48587. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  48588. pInfo->aReadMark[0] = 0;
  48589. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  48590. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  48591. /* If more than one frame was recovered from the log file, report an
  48592. ** event via sqlite3_log(). This is to help with identifying performance
  48593. ** problems caused by applications routinely shutting down without
  48594. ** checkpointing the log file.
  48595. */
  48596. if( pWal->hdr.nPage ){
  48597. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  48598. "recovered %d frames from WAL file %s",
  48599. pWal->hdr.mxFrame, pWal->zWalName
  48600. );
  48601. }
  48602. }
  48603. recovery_error:
  48604. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  48605. walUnlockExclusive(pWal, iLock, nLock);
  48606. return rc;
  48607. }
  48608. /*
  48609. ** Close an open wal-index.
  48610. */
  48611. static void walIndexClose(Wal *pWal, int isDelete){
  48612. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  48613. int i;
  48614. for(i=0; i<pWal->nWiData; i++){
  48615. sqlite3_free((void *)pWal->apWiData[i]);
  48616. pWal->apWiData[i] = 0;
  48617. }
  48618. }else{
  48619. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  48620. }
  48621. }
  48622. /*
  48623. ** Open a connection to the WAL file zWalName. The database file must
  48624. ** already be opened on connection pDbFd. The buffer that zWalName points
  48625. ** to must remain valid for the lifetime of the returned Wal* handle.
  48626. **
  48627. ** A SHARED lock should be held on the database file when this function
  48628. ** is called. The purpose of this SHARED lock is to prevent any other
  48629. ** client from unlinking the WAL or wal-index file. If another process
  48630. ** were to do this just after this client opened one of these files, the
  48631. ** system would be badly broken.
  48632. **
  48633. ** If the log file is successfully opened, SQLITE_OK is returned and
  48634. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  48635. ** an SQLite error code is returned and *ppWal is left unmodified.
  48636. */
  48637. SQLITE_PRIVATE int sqlite3WalOpen(
  48638. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  48639. sqlite3_file *pDbFd, /* The open database file */
  48640. const char *zWalName, /* Name of the WAL file */
  48641. int bNoShm, /* True to run in heap-memory mode */
  48642. i64 mxWalSize, /* Truncate WAL to this size on reset */
  48643. Wal **ppWal /* OUT: Allocated Wal handle */
  48644. ){
  48645. int rc; /* Return Code */
  48646. Wal *pRet; /* Object to allocate and return */
  48647. int flags; /* Flags passed to OsOpen() */
  48648. assert( zWalName && zWalName[0] );
  48649. assert( pDbFd );
  48650. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  48651. ** this source file. Verify that the #defines of the locking byte offsets
  48652. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  48653. ** For that matter, if the lock offset ever changes from its initial design
  48654. ** value of 120, we need to know that so there is an assert() to check it.
  48655. */
  48656. assert( 120==WALINDEX_LOCK_OFFSET );
  48657. assert( 136==WALINDEX_HDR_SIZE );
  48658. #ifdef WIN_SHM_BASE
  48659. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  48660. #endif
  48661. #ifdef UNIX_SHM_BASE
  48662. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  48663. #endif
  48664. /* Allocate an instance of struct Wal to return. */
  48665. *ppWal = 0;
  48666. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  48667. if( !pRet ){
  48668. return SQLITE_NOMEM;
  48669. }
  48670. pRet->pVfs = pVfs;
  48671. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  48672. pRet->pDbFd = pDbFd;
  48673. pRet->readLock = -1;
  48674. pRet->mxWalSize = mxWalSize;
  48675. pRet->zWalName = zWalName;
  48676. pRet->syncHeader = 1;
  48677. pRet->padToSectorBoundary = 1;
  48678. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  48679. /* Open file handle on the write-ahead log file. */
  48680. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  48681. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  48682. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  48683. pRet->readOnly = WAL_RDONLY;
  48684. }
  48685. if( rc!=SQLITE_OK ){
  48686. walIndexClose(pRet, 0);
  48687. sqlite3OsClose(pRet->pWalFd);
  48688. sqlite3_free(pRet);
  48689. }else{
  48690. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  48691. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  48692. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  48693. pRet->padToSectorBoundary = 0;
  48694. }
  48695. *ppWal = pRet;
  48696. WALTRACE(("WAL%d: opened\n", pRet));
  48697. }
  48698. return rc;
  48699. }
  48700. /*
  48701. ** Change the size to which the WAL file is trucated on each reset.
  48702. */
  48703. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  48704. if( pWal ) pWal->mxWalSize = iLimit;
  48705. }
  48706. /*
  48707. ** Find the smallest page number out of all pages held in the WAL that
  48708. ** has not been returned by any prior invocation of this method on the
  48709. ** same WalIterator object. Write into *piFrame the frame index where
  48710. ** that page was last written into the WAL. Write into *piPage the page
  48711. ** number.
  48712. **
  48713. ** Return 0 on success. If there are no pages in the WAL with a page
  48714. ** number larger than *piPage, then return 1.
  48715. */
  48716. static int walIteratorNext(
  48717. WalIterator *p, /* Iterator */
  48718. u32 *piPage, /* OUT: The page number of the next page */
  48719. u32 *piFrame /* OUT: Wal frame index of next page */
  48720. ){
  48721. u32 iMin; /* Result pgno must be greater than iMin */
  48722. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  48723. int i; /* For looping through segments */
  48724. iMin = p->iPrior;
  48725. assert( iMin<0xffffffff );
  48726. for(i=p->nSegment-1; i>=0; i--){
  48727. struct WalSegment *pSegment = &p->aSegment[i];
  48728. while( pSegment->iNext<pSegment->nEntry ){
  48729. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  48730. if( iPg>iMin ){
  48731. if( iPg<iRet ){
  48732. iRet = iPg;
  48733. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  48734. }
  48735. break;
  48736. }
  48737. pSegment->iNext++;
  48738. }
  48739. }
  48740. *piPage = p->iPrior = iRet;
  48741. return (iRet==0xFFFFFFFF);
  48742. }
  48743. /*
  48744. ** This function merges two sorted lists into a single sorted list.
  48745. **
  48746. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  48747. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  48748. ** is guaranteed for all J<K:
  48749. **
  48750. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  48751. ** aContent[aRight[J]] < aContent[aRight[K]]
  48752. **
  48753. ** This routine overwrites aRight[] with a new (probably longer) sequence
  48754. ** of indices such that the aRight[] contains every index that appears in
  48755. ** either aLeft[] or the old aRight[] and such that the second condition
  48756. ** above is still met.
  48757. **
  48758. ** The aContent[aLeft[X]] values will be unique for all X. And the
  48759. ** aContent[aRight[X]] values will be unique too. But there might be
  48760. ** one or more combinations of X and Y such that
  48761. **
  48762. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  48763. **
  48764. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  48765. */
  48766. static void walMerge(
  48767. const u32 *aContent, /* Pages in wal - keys for the sort */
  48768. ht_slot *aLeft, /* IN: Left hand input list */
  48769. int nLeft, /* IN: Elements in array *paLeft */
  48770. ht_slot **paRight, /* IN/OUT: Right hand input list */
  48771. int *pnRight, /* IN/OUT: Elements in *paRight */
  48772. ht_slot *aTmp /* Temporary buffer */
  48773. ){
  48774. int iLeft = 0; /* Current index in aLeft */
  48775. int iRight = 0; /* Current index in aRight */
  48776. int iOut = 0; /* Current index in output buffer */
  48777. int nRight = *pnRight;
  48778. ht_slot *aRight = *paRight;
  48779. assert( nLeft>0 && nRight>0 );
  48780. while( iRight<nRight || iLeft<nLeft ){
  48781. ht_slot logpage;
  48782. Pgno dbpage;
  48783. if( (iLeft<nLeft)
  48784. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  48785. ){
  48786. logpage = aLeft[iLeft++];
  48787. }else{
  48788. logpage = aRight[iRight++];
  48789. }
  48790. dbpage = aContent[logpage];
  48791. aTmp[iOut++] = logpage;
  48792. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  48793. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  48794. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  48795. }
  48796. *paRight = aLeft;
  48797. *pnRight = iOut;
  48798. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  48799. }
  48800. /*
  48801. ** Sort the elements in list aList using aContent[] as the sort key.
  48802. ** Remove elements with duplicate keys, preferring to keep the
  48803. ** larger aList[] values.
  48804. **
  48805. ** The aList[] entries are indices into aContent[]. The values in
  48806. ** aList[] are to be sorted so that for all J<K:
  48807. **
  48808. ** aContent[aList[J]] < aContent[aList[K]]
  48809. **
  48810. ** For any X and Y such that
  48811. **
  48812. ** aContent[aList[X]] == aContent[aList[Y]]
  48813. **
  48814. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  48815. ** the smaller.
  48816. */
  48817. static void walMergesort(
  48818. const u32 *aContent, /* Pages in wal */
  48819. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  48820. ht_slot *aList, /* IN/OUT: List to sort */
  48821. int *pnList /* IN/OUT: Number of elements in aList[] */
  48822. ){
  48823. struct Sublist {
  48824. int nList; /* Number of elements in aList */
  48825. ht_slot *aList; /* Pointer to sub-list content */
  48826. };
  48827. const int nList = *pnList; /* Size of input list */
  48828. int nMerge = 0; /* Number of elements in list aMerge */
  48829. ht_slot *aMerge = 0; /* List to be merged */
  48830. int iList; /* Index into input list */
  48831. u32 iSub = 0; /* Index into aSub array */
  48832. struct Sublist aSub[13]; /* Array of sub-lists */
  48833. memset(aSub, 0, sizeof(aSub));
  48834. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  48835. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  48836. for(iList=0; iList<nList; iList++){
  48837. nMerge = 1;
  48838. aMerge = &aList[iList];
  48839. for(iSub=0; iList & (1<<iSub); iSub++){
  48840. struct Sublist *p;
  48841. assert( iSub<ArraySize(aSub) );
  48842. p = &aSub[iSub];
  48843. assert( p->aList && p->nList<=(1<<iSub) );
  48844. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  48845. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  48846. }
  48847. aSub[iSub].aList = aMerge;
  48848. aSub[iSub].nList = nMerge;
  48849. }
  48850. for(iSub++; iSub<ArraySize(aSub); iSub++){
  48851. if( nList & (1<<iSub) ){
  48852. struct Sublist *p;
  48853. assert( iSub<ArraySize(aSub) );
  48854. p = &aSub[iSub];
  48855. assert( p->nList<=(1<<iSub) );
  48856. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  48857. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  48858. }
  48859. }
  48860. assert( aMerge==aList );
  48861. *pnList = nMerge;
  48862. #ifdef SQLITE_DEBUG
  48863. {
  48864. int i;
  48865. for(i=1; i<*pnList; i++){
  48866. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  48867. }
  48868. }
  48869. #endif
  48870. }
  48871. /*
  48872. ** Free an iterator allocated by walIteratorInit().
  48873. */
  48874. static void walIteratorFree(WalIterator *p){
  48875. sqlite3_free(p);
  48876. }
  48877. /*
  48878. ** Construct a WalInterator object that can be used to loop over all
  48879. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  48880. ** lock.
  48881. **
  48882. ** On success, make *pp point to the newly allocated WalInterator object
  48883. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  48884. ** returns an error, the value of *pp is undefined.
  48885. **
  48886. ** The calling routine should invoke walIteratorFree() to destroy the
  48887. ** WalIterator object when it has finished with it.
  48888. */
  48889. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  48890. WalIterator *p; /* Return value */
  48891. int nSegment; /* Number of segments to merge */
  48892. u32 iLast; /* Last frame in log */
  48893. int nByte; /* Number of bytes to allocate */
  48894. int i; /* Iterator variable */
  48895. ht_slot *aTmp; /* Temp space used by merge-sort */
  48896. int rc = SQLITE_OK; /* Return Code */
  48897. /* This routine only runs while holding the checkpoint lock. And
  48898. ** it only runs if there is actually content in the log (mxFrame>0).
  48899. */
  48900. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  48901. iLast = pWal->hdr.mxFrame;
  48902. /* Allocate space for the WalIterator object. */
  48903. nSegment = walFramePage(iLast) + 1;
  48904. nByte = sizeof(WalIterator)
  48905. + (nSegment-1)*sizeof(struct WalSegment)
  48906. + iLast*sizeof(ht_slot);
  48907. p = (WalIterator *)sqlite3_malloc64(nByte);
  48908. if( !p ){
  48909. return SQLITE_NOMEM;
  48910. }
  48911. memset(p, 0, nByte);
  48912. p->nSegment = nSegment;
  48913. /* Allocate temporary space used by the merge-sort routine. This block
  48914. ** of memory will be freed before this function returns.
  48915. */
  48916. aTmp = (ht_slot *)sqlite3_malloc64(
  48917. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  48918. );
  48919. if( !aTmp ){
  48920. rc = SQLITE_NOMEM;
  48921. }
  48922. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  48923. volatile ht_slot *aHash;
  48924. u32 iZero;
  48925. volatile u32 *aPgno;
  48926. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  48927. if( rc==SQLITE_OK ){
  48928. int j; /* Counter variable */
  48929. int nEntry; /* Number of entries in this segment */
  48930. ht_slot *aIndex; /* Sorted index for this segment */
  48931. aPgno++;
  48932. if( (i+1)==nSegment ){
  48933. nEntry = (int)(iLast - iZero);
  48934. }else{
  48935. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  48936. }
  48937. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  48938. iZero++;
  48939. for(j=0; j<nEntry; j++){
  48940. aIndex[j] = (ht_slot)j;
  48941. }
  48942. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  48943. p->aSegment[i].iZero = iZero;
  48944. p->aSegment[i].nEntry = nEntry;
  48945. p->aSegment[i].aIndex = aIndex;
  48946. p->aSegment[i].aPgno = (u32 *)aPgno;
  48947. }
  48948. }
  48949. sqlite3_free(aTmp);
  48950. if( rc!=SQLITE_OK ){
  48951. walIteratorFree(p);
  48952. }
  48953. *pp = p;
  48954. return rc;
  48955. }
  48956. /*
  48957. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  48958. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  48959. ** busy-handler function. Invoke it and retry the lock until either the
  48960. ** lock is successfully obtained or the busy-handler returns 0.
  48961. */
  48962. static int walBusyLock(
  48963. Wal *pWal, /* WAL connection */
  48964. int (*xBusy)(void*), /* Function to call when busy */
  48965. void *pBusyArg, /* Context argument for xBusyHandler */
  48966. int lockIdx, /* Offset of first byte to lock */
  48967. int n /* Number of bytes to lock */
  48968. ){
  48969. int rc;
  48970. do {
  48971. rc = walLockExclusive(pWal, lockIdx, n);
  48972. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  48973. return rc;
  48974. }
  48975. /*
  48976. ** The cache of the wal-index header must be valid to call this function.
  48977. ** Return the page-size in bytes used by the database.
  48978. */
  48979. static int walPagesize(Wal *pWal){
  48980. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  48981. }
  48982. /*
  48983. ** The following is guaranteed when this function is called:
  48984. **
  48985. ** a) the WRITER lock is held,
  48986. ** b) the entire log file has been checkpointed, and
  48987. ** c) any existing readers are reading exclusively from the database
  48988. ** file - there are no readers that may attempt to read a frame from
  48989. ** the log file.
  48990. **
  48991. ** This function updates the shared-memory structures so that the next
  48992. ** client to write to the database (which may be this one) does so by
  48993. ** writing frames into the start of the log file.
  48994. **
  48995. ** The value of parameter salt1 is used as the aSalt[1] value in the
  48996. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  48997. ** one obtained from sqlite3_randomness()).
  48998. */
  48999. static void walRestartHdr(Wal *pWal, u32 salt1){
  49000. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  49001. int i; /* Loop counter */
  49002. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  49003. pWal->nCkpt++;
  49004. pWal->hdr.mxFrame = 0;
  49005. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  49006. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  49007. walIndexWriteHdr(pWal);
  49008. pInfo->nBackfill = 0;
  49009. pInfo->nBackfillAttempted = 0;
  49010. pInfo->aReadMark[1] = 0;
  49011. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  49012. assert( pInfo->aReadMark[0]==0 );
  49013. }
  49014. /*
  49015. ** Copy as much content as we can from the WAL back into the database file
  49016. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  49017. **
  49018. ** The amount of information copies from WAL to database might be limited
  49019. ** by active readers. This routine will never overwrite a database page
  49020. ** that a concurrent reader might be using.
  49021. **
  49022. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  49023. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  49024. ** checkpoints are always run by a background thread or background
  49025. ** process, foreground threads will never block on a lengthy fsync call.
  49026. **
  49027. ** Fsync is called on the WAL before writing content out of the WAL and
  49028. ** into the database. This ensures that if the new content is persistent
  49029. ** in the WAL and can be recovered following a power-loss or hard reset.
  49030. **
  49031. ** Fsync is also called on the database file if (and only if) the entire
  49032. ** WAL content is copied into the database file. This second fsync makes
  49033. ** it safe to delete the WAL since the new content will persist in the
  49034. ** database file.
  49035. **
  49036. ** This routine uses and updates the nBackfill field of the wal-index header.
  49037. ** This is the only routine that will increase the value of nBackfill.
  49038. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  49039. ** its value.)
  49040. **
  49041. ** The caller must be holding sufficient locks to ensure that no other
  49042. ** checkpoint is running (in any other thread or process) at the same
  49043. ** time.
  49044. */
  49045. static int walCheckpoint(
  49046. Wal *pWal, /* Wal connection */
  49047. int eMode, /* One of PASSIVE, FULL or RESTART */
  49048. int (*xBusy)(void*), /* Function to call when busy */
  49049. void *pBusyArg, /* Context argument for xBusyHandler */
  49050. int sync_flags, /* Flags for OsSync() (or 0) */
  49051. u8 *zBuf /* Temporary buffer to use */
  49052. ){
  49053. int rc = SQLITE_OK; /* Return code */
  49054. int szPage; /* Database page-size */
  49055. WalIterator *pIter = 0; /* Wal iterator context */
  49056. u32 iDbpage = 0; /* Next database page to write */
  49057. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  49058. u32 mxSafeFrame; /* Max frame that can be backfilled */
  49059. u32 mxPage; /* Max database page to write */
  49060. int i; /* Loop counter */
  49061. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  49062. szPage = walPagesize(pWal);
  49063. testcase( szPage<=32768 );
  49064. testcase( szPage>=65536 );
  49065. pInfo = walCkptInfo(pWal);
  49066. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  49067. /* Allocate the iterator */
  49068. rc = walIteratorInit(pWal, &pIter);
  49069. if( rc!=SQLITE_OK ){
  49070. return rc;
  49071. }
  49072. assert( pIter );
  49073. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  49074. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  49075. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  49076. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  49077. ** safe to write into the database. Frames beyond mxSafeFrame might
  49078. ** overwrite database pages that are in use by active readers and thus
  49079. ** cannot be backfilled from the WAL.
  49080. */
  49081. mxSafeFrame = pWal->hdr.mxFrame;
  49082. mxPage = pWal->hdr.nPage;
  49083. for(i=1; i<WAL_NREADER; i++){
  49084. /* Thread-sanitizer reports that the following is an unsafe read,
  49085. ** as some other thread may be in the process of updating the value
  49086. ** of the aReadMark[] slot. The assumption here is that if that is
  49087. ** happening, the other client may only be increasing the value,
  49088. ** not decreasing it. So assuming either that either the "old" or
  49089. ** "new" version of the value is read, and not some arbitrary value
  49090. ** that would never be written by a real client, things are still
  49091. ** safe. */
  49092. u32 y = pInfo->aReadMark[i];
  49093. if( mxSafeFrame>y ){
  49094. assert( y<=pWal->hdr.mxFrame );
  49095. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  49096. if( rc==SQLITE_OK ){
  49097. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  49098. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  49099. }else if( rc==SQLITE_BUSY ){
  49100. mxSafeFrame = y;
  49101. xBusy = 0;
  49102. }else{
  49103. goto walcheckpoint_out;
  49104. }
  49105. }
  49106. }
  49107. if( pInfo->nBackfill<mxSafeFrame
  49108. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  49109. ){
  49110. i64 nSize; /* Current size of database file */
  49111. u32 nBackfill = pInfo->nBackfill;
  49112. pInfo->nBackfillAttempted = mxSafeFrame;
  49113. /* Sync the WAL to disk */
  49114. if( sync_flags ){
  49115. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  49116. }
  49117. /* If the database may grow as a result of this checkpoint, hint
  49118. ** about the eventual size of the db file to the VFS layer.
  49119. */
  49120. if( rc==SQLITE_OK ){
  49121. i64 nReq = ((i64)mxPage * szPage);
  49122. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  49123. if( rc==SQLITE_OK && nSize<nReq ){
  49124. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  49125. }
  49126. }
  49127. /* Iterate through the contents of the WAL, copying data to the db file */
  49128. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  49129. i64 iOffset;
  49130. assert( walFramePgno(pWal, iFrame)==iDbpage );
  49131. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  49132. continue;
  49133. }
  49134. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  49135. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  49136. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  49137. if( rc!=SQLITE_OK ) break;
  49138. iOffset = (iDbpage-1)*(i64)szPage;
  49139. testcase( IS_BIG_INT(iOffset) );
  49140. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  49141. if( rc!=SQLITE_OK ) break;
  49142. }
  49143. /* If work was actually accomplished... */
  49144. if( rc==SQLITE_OK ){
  49145. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  49146. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  49147. testcase( IS_BIG_INT(szDb) );
  49148. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  49149. if( rc==SQLITE_OK && sync_flags ){
  49150. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  49151. }
  49152. }
  49153. if( rc==SQLITE_OK ){
  49154. pInfo->nBackfill = mxSafeFrame;
  49155. }
  49156. }
  49157. /* Release the reader lock held while backfilling */
  49158. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  49159. }
  49160. if( rc==SQLITE_BUSY ){
  49161. /* Reset the return code so as not to report a checkpoint failure
  49162. ** just because there are active readers. */
  49163. rc = SQLITE_OK;
  49164. }
  49165. }
  49166. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  49167. ** entire wal file has been copied into the database file, then block
  49168. ** until all readers have finished using the wal file. This ensures that
  49169. ** the next process to write to the database restarts the wal file.
  49170. */
  49171. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  49172. assert( pWal->writeLock );
  49173. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  49174. rc = SQLITE_BUSY;
  49175. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  49176. u32 salt1;
  49177. sqlite3_randomness(4, &salt1);
  49178. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  49179. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  49180. if( rc==SQLITE_OK ){
  49181. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  49182. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  49183. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  49184. ** truncates the log file to zero bytes just prior to a
  49185. ** successful return.
  49186. **
  49187. ** In theory, it might be safe to do this without updating the
  49188. ** wal-index header in shared memory, as all subsequent reader or
  49189. ** writer clients should see that the entire log file has been
  49190. ** checkpointed and behave accordingly. This seems unsafe though,
  49191. ** as it would leave the system in a state where the contents of
  49192. ** the wal-index header do not match the contents of the
  49193. ** file-system. To avoid this, update the wal-index header to
  49194. ** indicate that the log file contains zero valid frames. */
  49195. walRestartHdr(pWal, salt1);
  49196. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  49197. }
  49198. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  49199. }
  49200. }
  49201. }
  49202. walcheckpoint_out:
  49203. walIteratorFree(pIter);
  49204. return rc;
  49205. }
  49206. /*
  49207. ** If the WAL file is currently larger than nMax bytes in size, truncate
  49208. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  49209. */
  49210. static void walLimitSize(Wal *pWal, i64 nMax){
  49211. i64 sz;
  49212. int rx;
  49213. sqlite3BeginBenignMalloc();
  49214. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  49215. if( rx==SQLITE_OK && (sz > nMax ) ){
  49216. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  49217. }
  49218. sqlite3EndBenignMalloc();
  49219. if( rx ){
  49220. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  49221. }
  49222. }
  49223. /*
  49224. ** Close a connection to a log file.
  49225. */
  49226. SQLITE_PRIVATE int sqlite3WalClose(
  49227. Wal *pWal, /* Wal to close */
  49228. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  49229. int nBuf,
  49230. u8 *zBuf /* Buffer of at least nBuf bytes */
  49231. ){
  49232. int rc = SQLITE_OK;
  49233. if( pWal ){
  49234. int isDelete = 0; /* True to unlink wal and wal-index files */
  49235. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  49236. ** ordinary, rollback-mode locking methods, this guarantees that the
  49237. ** connection associated with this log file is the only connection to
  49238. ** the database. In this case checkpoint the database and unlink both
  49239. ** the wal and wal-index files.
  49240. **
  49241. ** The EXCLUSIVE lock is not released before returning.
  49242. */
  49243. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  49244. if( rc==SQLITE_OK ){
  49245. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  49246. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  49247. }
  49248. rc = sqlite3WalCheckpoint(
  49249. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  49250. );
  49251. if( rc==SQLITE_OK ){
  49252. int bPersist = -1;
  49253. sqlite3OsFileControlHint(
  49254. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  49255. );
  49256. if( bPersist!=1 ){
  49257. /* Try to delete the WAL file if the checkpoint completed and
  49258. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  49259. ** mode (!bPersist) */
  49260. isDelete = 1;
  49261. }else if( pWal->mxWalSize>=0 ){
  49262. /* Try to truncate the WAL file to zero bytes if the checkpoint
  49263. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  49264. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  49265. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  49266. ** to zero bytes as truncating to the journal_size_limit might
  49267. ** leave a corrupt WAL file on disk. */
  49268. walLimitSize(pWal, 0);
  49269. }
  49270. }
  49271. }
  49272. walIndexClose(pWal, isDelete);
  49273. sqlite3OsClose(pWal->pWalFd);
  49274. if( isDelete ){
  49275. sqlite3BeginBenignMalloc();
  49276. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  49277. sqlite3EndBenignMalloc();
  49278. }
  49279. WALTRACE(("WAL%p: closed\n", pWal));
  49280. sqlite3_free((void *)pWal->apWiData);
  49281. sqlite3_free(pWal);
  49282. }
  49283. return rc;
  49284. }
  49285. /*
  49286. ** Try to read the wal-index header. Return 0 on success and 1 if
  49287. ** there is a problem.
  49288. **
  49289. ** The wal-index is in shared memory. Another thread or process might
  49290. ** be writing the header at the same time this procedure is trying to
  49291. ** read it, which might result in inconsistency. A dirty read is detected
  49292. ** by verifying that both copies of the header are the same and also by
  49293. ** a checksum on the header.
  49294. **
  49295. ** If and only if the read is consistent and the header is different from
  49296. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  49297. ** and *pChanged is set to 1.
  49298. **
  49299. ** If the checksum cannot be verified return non-zero. If the header
  49300. ** is read successfully and the checksum verified, return zero.
  49301. */
  49302. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  49303. u32 aCksum[2]; /* Checksum on the header content */
  49304. WalIndexHdr h1, h2; /* Two copies of the header content */
  49305. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  49306. /* The first page of the wal-index must be mapped at this point. */
  49307. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  49308. /* Read the header. This might happen concurrently with a write to the
  49309. ** same area of shared memory on a different CPU in a SMP,
  49310. ** meaning it is possible that an inconsistent snapshot is read
  49311. ** from the file. If this happens, return non-zero.
  49312. **
  49313. ** There are two copies of the header at the beginning of the wal-index.
  49314. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  49315. ** Memory barriers are used to prevent the compiler or the hardware from
  49316. ** reordering the reads and writes.
  49317. */
  49318. aHdr = walIndexHdr(pWal);
  49319. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  49320. walShmBarrier(pWal);
  49321. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  49322. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  49323. return 1; /* Dirty read */
  49324. }
  49325. if( h1.isInit==0 ){
  49326. return 1; /* Malformed header - probably all zeros */
  49327. }
  49328. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  49329. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  49330. return 1; /* Checksum does not match */
  49331. }
  49332. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  49333. *pChanged = 1;
  49334. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  49335. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  49336. testcase( pWal->szPage<=32768 );
  49337. testcase( pWal->szPage>=65536 );
  49338. }
  49339. /* The header was successfully read. Return zero. */
  49340. return 0;
  49341. }
  49342. /*
  49343. ** Read the wal-index header from the wal-index and into pWal->hdr.
  49344. ** If the wal-header appears to be corrupt, try to reconstruct the
  49345. ** wal-index from the WAL before returning.
  49346. **
  49347. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  49348. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  49349. ** to 0.
  49350. **
  49351. ** If the wal-index header is successfully read, return SQLITE_OK.
  49352. ** Otherwise an SQLite error code.
  49353. */
  49354. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  49355. int rc; /* Return code */
  49356. int badHdr; /* True if a header read failed */
  49357. volatile u32 *page0; /* Chunk of wal-index containing header */
  49358. /* Ensure that page 0 of the wal-index (the page that contains the
  49359. ** wal-index header) is mapped. Return early if an error occurs here.
  49360. */
  49361. assert( pChanged );
  49362. rc = walIndexPage(pWal, 0, &page0);
  49363. if( rc!=SQLITE_OK ){
  49364. return rc;
  49365. };
  49366. assert( page0 || pWal->writeLock==0 );
  49367. /* If the first page of the wal-index has been mapped, try to read the
  49368. ** wal-index header immediately, without holding any lock. This usually
  49369. ** works, but may fail if the wal-index header is corrupt or currently
  49370. ** being modified by another thread or process.
  49371. */
  49372. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  49373. /* If the first attempt failed, it might have been due to a race
  49374. ** with a writer. So get a WRITE lock and try again.
  49375. */
  49376. assert( badHdr==0 || pWal->writeLock==0 );
  49377. if( badHdr ){
  49378. if( pWal->readOnly & WAL_SHM_RDONLY ){
  49379. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  49380. walUnlockShared(pWal, WAL_WRITE_LOCK);
  49381. rc = SQLITE_READONLY_RECOVERY;
  49382. }
  49383. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  49384. pWal->writeLock = 1;
  49385. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  49386. badHdr = walIndexTryHdr(pWal, pChanged);
  49387. if( badHdr ){
  49388. /* If the wal-index header is still malformed even while holding
  49389. ** a WRITE lock, it can only mean that the header is corrupted and
  49390. ** needs to be reconstructed. So run recovery to do exactly that.
  49391. */
  49392. rc = walIndexRecover(pWal);
  49393. *pChanged = 1;
  49394. }
  49395. }
  49396. pWal->writeLock = 0;
  49397. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  49398. }
  49399. }
  49400. /* If the header is read successfully, check the version number to make
  49401. ** sure the wal-index was not constructed with some future format that
  49402. ** this version of SQLite cannot understand.
  49403. */
  49404. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  49405. rc = SQLITE_CANTOPEN_BKPT;
  49406. }
  49407. return rc;
  49408. }
  49409. /*
  49410. ** This is the value that walTryBeginRead returns when it needs to
  49411. ** be retried.
  49412. */
  49413. #define WAL_RETRY (-1)
  49414. /*
  49415. ** Attempt to start a read transaction. This might fail due to a race or
  49416. ** other transient condition. When that happens, it returns WAL_RETRY to
  49417. ** indicate to the caller that it is safe to retry immediately.
  49418. **
  49419. ** On success return SQLITE_OK. On a permanent failure (such an
  49420. ** I/O error or an SQLITE_BUSY because another process is running
  49421. ** recovery) return a positive error code.
  49422. **
  49423. ** The useWal parameter is true to force the use of the WAL and disable
  49424. ** the case where the WAL is bypassed because it has been completely
  49425. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  49426. ** to make a copy of the wal-index header into pWal->hdr. If the
  49427. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  49428. ** to the caller that the local paget cache is obsolete and needs to be
  49429. ** flushed.) When useWal==1, the wal-index header is assumed to already
  49430. ** be loaded and the pChanged parameter is unused.
  49431. **
  49432. ** The caller must set the cnt parameter to the number of prior calls to
  49433. ** this routine during the current read attempt that returned WAL_RETRY.
  49434. ** This routine will start taking more aggressive measures to clear the
  49435. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  49436. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  49437. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  49438. ** and is not honoring the locking protocol. There is a vanishingly small
  49439. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  49440. ** bad luck when there is lots of contention for the wal-index, but that
  49441. ** possibility is so small that it can be safely neglected, we believe.
  49442. **
  49443. ** On success, this routine obtains a read lock on
  49444. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  49445. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  49446. ** that means the Wal does not hold any read lock. The reader must not
  49447. ** access any database page that is modified by a WAL frame up to and
  49448. ** including frame number aReadMark[pWal->readLock]. The reader will
  49449. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  49450. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  49451. ** completely and get all content directly from the database file.
  49452. ** If the useWal parameter is 1 then the WAL will never be ignored and
  49453. ** this routine will always set pWal->readLock>0 on success.
  49454. ** When the read transaction is completed, the caller must release the
  49455. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  49456. **
  49457. ** This routine uses the nBackfill and aReadMark[] fields of the header
  49458. ** to select a particular WAL_READ_LOCK() that strives to let the
  49459. ** checkpoint process do as much work as possible. This routine might
  49460. ** update values of the aReadMark[] array in the header, but if it does
  49461. ** so it takes care to hold an exclusive lock on the corresponding
  49462. ** WAL_READ_LOCK() while changing values.
  49463. */
  49464. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  49465. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  49466. u32 mxReadMark; /* Largest aReadMark[] value */
  49467. int mxI; /* Index of largest aReadMark[] value */
  49468. int i; /* Loop counter */
  49469. int rc = SQLITE_OK; /* Return code */
  49470. u32 mxFrame; /* Wal frame to lock to */
  49471. assert( pWal->readLock<0 ); /* Not currently locked */
  49472. /* Take steps to avoid spinning forever if there is a protocol error.
  49473. **
  49474. ** Circumstances that cause a RETRY should only last for the briefest
  49475. ** instances of time. No I/O or other system calls are done while the
  49476. ** locks are held, so the locks should not be held for very long. But
  49477. ** if we are unlucky, another process that is holding a lock might get
  49478. ** paged out or take a page-fault that is time-consuming to resolve,
  49479. ** during the few nanoseconds that it is holding the lock. In that case,
  49480. ** it might take longer than normal for the lock to free.
  49481. **
  49482. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  49483. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  49484. ** is more of a scheduler yield than an actual delay. But on the 10th
  49485. ** an subsequent retries, the delays start becoming longer and longer,
  49486. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  49487. ** The total delay time before giving up is less than 10 seconds.
  49488. */
  49489. if( cnt>5 ){
  49490. int nDelay = 1; /* Pause time in microseconds */
  49491. if( cnt>100 ){
  49492. VVA_ONLY( pWal->lockError = 1; )
  49493. return SQLITE_PROTOCOL;
  49494. }
  49495. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  49496. sqlite3OsSleep(pWal->pVfs, nDelay);
  49497. }
  49498. if( !useWal ){
  49499. rc = walIndexReadHdr(pWal, pChanged);
  49500. if( rc==SQLITE_BUSY ){
  49501. /* If there is not a recovery running in another thread or process
  49502. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  49503. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  49504. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  49505. ** would be technically correct. But the race is benign since with
  49506. ** WAL_RETRY this routine will be called again and will probably be
  49507. ** right on the second iteration.
  49508. */
  49509. if( pWal->apWiData[0]==0 ){
  49510. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  49511. ** We assume this is a transient condition, so return WAL_RETRY. The
  49512. ** xShmMap() implementation used by the default unix and win32 VFS
  49513. ** modules may return SQLITE_BUSY due to a race condition in the
  49514. ** code that determines whether or not the shared-memory region
  49515. ** must be zeroed before the requested page is returned.
  49516. */
  49517. rc = WAL_RETRY;
  49518. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  49519. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  49520. rc = WAL_RETRY;
  49521. }else if( rc==SQLITE_BUSY ){
  49522. rc = SQLITE_BUSY_RECOVERY;
  49523. }
  49524. }
  49525. if( rc!=SQLITE_OK ){
  49526. return rc;
  49527. }
  49528. }
  49529. pInfo = walCkptInfo(pWal);
  49530. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  49531. #ifdef SQLITE_ENABLE_SNAPSHOT
  49532. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
  49533. || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
  49534. #endif
  49535. ){
  49536. /* The WAL has been completely backfilled (or it is empty).
  49537. ** and can be safely ignored.
  49538. */
  49539. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  49540. walShmBarrier(pWal);
  49541. if( rc==SQLITE_OK ){
  49542. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  49543. /* It is not safe to allow the reader to continue here if frames
  49544. ** may have been appended to the log before READ_LOCK(0) was obtained.
  49545. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  49546. ** which implies that the database file contains a trustworthy
  49547. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  49548. ** happening, this is usually correct.
  49549. **
  49550. ** However, if frames have been appended to the log (or if the log
  49551. ** is wrapped and written for that matter) before the READ_LOCK(0)
  49552. ** is obtained, that is not necessarily true. A checkpointer may
  49553. ** have started to backfill the appended frames but crashed before
  49554. ** it finished. Leaving a corrupt image in the database file.
  49555. */
  49556. walUnlockShared(pWal, WAL_READ_LOCK(0));
  49557. return WAL_RETRY;
  49558. }
  49559. pWal->readLock = 0;
  49560. return SQLITE_OK;
  49561. }else if( rc!=SQLITE_BUSY ){
  49562. return rc;
  49563. }
  49564. }
  49565. /* If we get this far, it means that the reader will want to use
  49566. ** the WAL to get at content from recent commits. The job now is
  49567. ** to select one of the aReadMark[] entries that is closest to
  49568. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  49569. */
  49570. mxReadMark = 0;
  49571. mxI = 0;
  49572. mxFrame = pWal->hdr.mxFrame;
  49573. #ifdef SQLITE_ENABLE_SNAPSHOT
  49574. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  49575. mxFrame = pWal->pSnapshot->mxFrame;
  49576. }
  49577. #endif
  49578. for(i=1; i<WAL_NREADER; i++){
  49579. u32 thisMark = pInfo->aReadMark[i];
  49580. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  49581. assert( thisMark!=READMARK_NOT_USED );
  49582. mxReadMark = thisMark;
  49583. mxI = i;
  49584. }
  49585. }
  49586. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  49587. && (mxReadMark<mxFrame || mxI==0)
  49588. ){
  49589. for(i=1; i<WAL_NREADER; i++){
  49590. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  49591. if( rc==SQLITE_OK ){
  49592. mxReadMark = pInfo->aReadMark[i] = mxFrame;
  49593. mxI = i;
  49594. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  49595. break;
  49596. }else if( rc!=SQLITE_BUSY ){
  49597. return rc;
  49598. }
  49599. }
  49600. }
  49601. if( mxI==0 ){
  49602. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  49603. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  49604. }
  49605. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  49606. if( rc ){
  49607. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  49608. }
  49609. /* Now that the read-lock has been obtained, check that neither the
  49610. ** value in the aReadMark[] array or the contents of the wal-index
  49611. ** header have changed.
  49612. **
  49613. ** It is necessary to check that the wal-index header did not change
  49614. ** between the time it was read and when the shared-lock was obtained
  49615. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  49616. ** that the log file may have been wrapped by a writer, or that frames
  49617. ** that occur later in the log than pWal->hdr.mxFrame may have been
  49618. ** copied into the database by a checkpointer. If either of these things
  49619. ** happened, then reading the database with the current value of
  49620. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  49621. ** instead.
  49622. **
  49623. ** Before checking that the live wal-index header has not changed
  49624. ** since it was read, set Wal.minFrame to the first frame in the wal
  49625. ** file that has not yet been checkpointed. This client will not need
  49626. ** to read any frames earlier than minFrame from the wal file - they
  49627. ** can be safely read directly from the database file.
  49628. **
  49629. ** Because a ShmBarrier() call is made between taking the copy of
  49630. ** nBackfill and checking that the wal-header in shared-memory still
  49631. ** matches the one cached in pWal->hdr, it is guaranteed that the
  49632. ** checkpointer that set nBackfill was not working with a wal-index
  49633. ** header newer than that cached in pWal->hdr. If it were, that could
  49634. ** cause a problem. The checkpointer could omit to checkpoint
  49635. ** a version of page X that lies before pWal->minFrame (call that version
  49636. ** A) on the basis that there is a newer version (version B) of the same
  49637. ** page later in the wal file. But if version B happens to like past
  49638. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  49639. ** that it can read version A from the database file. However, since
  49640. ** we can guarantee that the checkpointer that set nBackfill could not
  49641. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  49642. */
  49643. pWal->minFrame = pInfo->nBackfill+1;
  49644. walShmBarrier(pWal);
  49645. if( pInfo->aReadMark[mxI]!=mxReadMark
  49646. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  49647. ){
  49648. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  49649. return WAL_RETRY;
  49650. }else{
  49651. assert( mxReadMark<=pWal->hdr.mxFrame );
  49652. pWal->readLock = (i16)mxI;
  49653. }
  49654. return rc;
  49655. }
  49656. /*
  49657. ** Begin a read transaction on the database.
  49658. **
  49659. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  49660. ** it takes a snapshot of the state of the WAL and wal-index for the current
  49661. ** instant in time. The current thread will continue to use this snapshot.
  49662. ** Other threads might append new content to the WAL and wal-index but
  49663. ** that extra content is ignored by the current thread.
  49664. **
  49665. ** If the database contents have changes since the previous read
  49666. ** transaction, then *pChanged is set to 1 before returning. The
  49667. ** Pager layer will use this to know that is cache is stale and
  49668. ** needs to be flushed.
  49669. */
  49670. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  49671. int rc; /* Return code */
  49672. int cnt = 0; /* Number of TryBeginRead attempts */
  49673. #ifdef SQLITE_ENABLE_SNAPSHOT
  49674. int bChanged = 0;
  49675. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  49676. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  49677. bChanged = 1;
  49678. }
  49679. #endif
  49680. do{
  49681. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  49682. }while( rc==WAL_RETRY );
  49683. testcase( (rc&0xff)==SQLITE_BUSY );
  49684. testcase( (rc&0xff)==SQLITE_IOERR );
  49685. testcase( rc==SQLITE_PROTOCOL );
  49686. testcase( rc==SQLITE_OK );
  49687. #ifdef SQLITE_ENABLE_SNAPSHOT
  49688. if( rc==SQLITE_OK ){
  49689. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  49690. /* At this point the client has a lock on an aReadMark[] slot holding
  49691. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  49692. ** is populated with the wal-index header corresponding to the head
  49693. ** of the wal file. Verify that pSnapshot is still valid before
  49694. ** continuing. Reasons why pSnapshot might no longer be valid:
  49695. **
  49696. ** (1) The WAL file has been reset since the snapshot was taken.
  49697. ** In this case, the salt will have changed.
  49698. **
  49699. ** (2) A checkpoint as been attempted that wrote frames past
  49700. ** pSnapshot->mxFrame into the database file. Note that the
  49701. ** checkpoint need not have completed for this to cause problems.
  49702. */
  49703. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  49704. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  49705. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  49706. /* It is possible that there is a checkpointer thread running
  49707. ** concurrent with this code. If this is the case, it may be that the
  49708. ** checkpointer has already determined that it will checkpoint
  49709. ** snapshot X, where X is later in the wal file than pSnapshot, but
  49710. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  49711. ** its intent. To avoid the race condition this leads to, ensure that
  49712. ** there is no checkpointer process by taking a shared CKPT lock
  49713. ** before checking pInfo->nBackfillAttempted. */
  49714. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  49715. if( rc==SQLITE_OK ){
  49716. /* Check that the wal file has not been wrapped. Assuming that it has
  49717. ** not, also check that no checkpointer has attempted to checkpoint any
  49718. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  49719. ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
  49720. ** with *pSnapshot and set *pChanged as appropriate for opening the
  49721. ** snapshot. */
  49722. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  49723. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  49724. ){
  49725. assert( pWal->readLock>0 );
  49726. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  49727. *pChanged = bChanged;
  49728. }else{
  49729. rc = SQLITE_BUSY_SNAPSHOT;
  49730. }
  49731. /* Release the shared CKPT lock obtained above. */
  49732. walUnlockShared(pWal, WAL_CKPT_LOCK);
  49733. }
  49734. if( rc!=SQLITE_OK ){
  49735. sqlite3WalEndReadTransaction(pWal);
  49736. }
  49737. }
  49738. }
  49739. #endif
  49740. return rc;
  49741. }
  49742. /*
  49743. ** Finish with a read transaction. All this does is release the
  49744. ** read-lock.
  49745. */
  49746. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  49747. sqlite3WalEndWriteTransaction(pWal);
  49748. if( pWal->readLock>=0 ){
  49749. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  49750. pWal->readLock = -1;
  49751. }
  49752. }
  49753. /*
  49754. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  49755. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  49756. ** to zero.
  49757. **
  49758. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  49759. ** error does occur, the final value of *piRead is undefined.
  49760. */
  49761. SQLITE_PRIVATE int sqlite3WalFindFrame(
  49762. Wal *pWal, /* WAL handle */
  49763. Pgno pgno, /* Database page number to read data for */
  49764. u32 *piRead /* OUT: Frame number (or zero) */
  49765. ){
  49766. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  49767. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  49768. int iHash; /* Used to loop through N hash tables */
  49769. int iMinHash;
  49770. /* This routine is only be called from within a read transaction. */
  49771. assert( pWal->readLock>=0 || pWal->lockError );
  49772. /* If the "last page" field of the wal-index header snapshot is 0, then
  49773. ** no data will be read from the wal under any circumstances. Return early
  49774. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  49775. ** then the WAL is ignored by the reader so return early, as if the
  49776. ** WAL were empty.
  49777. */
  49778. if( iLast==0 || pWal->readLock==0 ){
  49779. *piRead = 0;
  49780. return SQLITE_OK;
  49781. }
  49782. /* Search the hash table or tables for an entry matching page number
  49783. ** pgno. Each iteration of the following for() loop searches one
  49784. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  49785. **
  49786. ** This code might run concurrently to the code in walIndexAppend()
  49787. ** that adds entries to the wal-index (and possibly to this hash
  49788. ** table). This means the value just read from the hash
  49789. ** slot (aHash[iKey]) may have been added before or after the
  49790. ** current read transaction was opened. Values added after the
  49791. ** read transaction was opened may have been written incorrectly -
  49792. ** i.e. these slots may contain garbage data. However, we assume
  49793. ** that any slots written before the current read transaction was
  49794. ** opened remain unmodified.
  49795. **
  49796. ** For the reasons above, the if(...) condition featured in the inner
  49797. ** loop of the following block is more stringent that would be required
  49798. ** if we had exclusive access to the hash-table:
  49799. **
  49800. ** (aPgno[iFrame]==pgno):
  49801. ** This condition filters out normal hash-table collisions.
  49802. **
  49803. ** (iFrame<=iLast):
  49804. ** This condition filters out entries that were added to the hash
  49805. ** table after the current read-transaction had started.
  49806. */
  49807. iMinHash = walFramePage(pWal->minFrame);
  49808. for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
  49809. volatile ht_slot *aHash; /* Pointer to hash table */
  49810. volatile u32 *aPgno; /* Pointer to array of page numbers */
  49811. u32 iZero; /* Frame number corresponding to aPgno[0] */
  49812. int iKey; /* Hash slot index */
  49813. int nCollide; /* Number of hash collisions remaining */
  49814. int rc; /* Error code */
  49815. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  49816. if( rc!=SQLITE_OK ){
  49817. return rc;
  49818. }
  49819. nCollide = HASHTABLE_NSLOT;
  49820. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  49821. u32 iFrame = aHash[iKey] + iZero;
  49822. if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
  49823. assert( iFrame>iRead || CORRUPT_DB );
  49824. iRead = iFrame;
  49825. }
  49826. if( (nCollide--)==0 ){
  49827. return SQLITE_CORRUPT_BKPT;
  49828. }
  49829. }
  49830. }
  49831. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  49832. /* If expensive assert() statements are available, do a linear search
  49833. ** of the wal-index file content. Make sure the results agree with the
  49834. ** result obtained using the hash indexes above. */
  49835. {
  49836. u32 iRead2 = 0;
  49837. u32 iTest;
  49838. assert( pWal->minFrame>0 );
  49839. for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
  49840. if( walFramePgno(pWal, iTest)==pgno ){
  49841. iRead2 = iTest;
  49842. break;
  49843. }
  49844. }
  49845. assert( iRead==iRead2 );
  49846. }
  49847. #endif
  49848. *piRead = iRead;
  49849. return SQLITE_OK;
  49850. }
  49851. /*
  49852. ** Read the contents of frame iRead from the wal file into buffer pOut
  49853. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  49854. ** error code otherwise.
  49855. */
  49856. SQLITE_PRIVATE int sqlite3WalReadFrame(
  49857. Wal *pWal, /* WAL handle */
  49858. u32 iRead, /* Frame to read */
  49859. int nOut, /* Size of buffer pOut in bytes */
  49860. u8 *pOut /* Buffer to write page data to */
  49861. ){
  49862. int sz;
  49863. i64 iOffset;
  49864. sz = pWal->hdr.szPage;
  49865. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  49866. testcase( sz<=32768 );
  49867. testcase( sz>=65536 );
  49868. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  49869. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  49870. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  49871. }
  49872. /*
  49873. ** Return the size of the database in pages (or zero, if unknown).
  49874. */
  49875. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  49876. if( pWal && ALWAYS(pWal->readLock>=0) ){
  49877. return pWal->hdr.nPage;
  49878. }
  49879. return 0;
  49880. }
  49881. /*
  49882. ** This function starts a write transaction on the WAL.
  49883. **
  49884. ** A read transaction must have already been started by a prior call
  49885. ** to sqlite3WalBeginReadTransaction().
  49886. **
  49887. ** If another thread or process has written into the database since
  49888. ** the read transaction was started, then it is not possible for this
  49889. ** thread to write as doing so would cause a fork. So this routine
  49890. ** returns SQLITE_BUSY in that case and no write transaction is started.
  49891. **
  49892. ** There can only be a single writer active at a time.
  49893. */
  49894. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  49895. int rc;
  49896. /* Cannot start a write transaction without first holding a read
  49897. ** transaction. */
  49898. assert( pWal->readLock>=0 );
  49899. if( pWal->readOnly ){
  49900. return SQLITE_READONLY;
  49901. }
  49902. /* Only one writer allowed at a time. Get the write lock. Return
  49903. ** SQLITE_BUSY if unable.
  49904. */
  49905. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  49906. if( rc ){
  49907. return rc;
  49908. }
  49909. pWal->writeLock = 1;
  49910. /* If another connection has written to the database file since the
  49911. ** time the read transaction on this connection was started, then
  49912. ** the write is disallowed.
  49913. */
  49914. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  49915. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  49916. pWal->writeLock = 0;
  49917. rc = SQLITE_BUSY_SNAPSHOT;
  49918. }
  49919. return rc;
  49920. }
  49921. /*
  49922. ** End a write transaction. The commit has already been done. This
  49923. ** routine merely releases the lock.
  49924. */
  49925. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  49926. if( pWal->writeLock ){
  49927. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  49928. pWal->writeLock = 0;
  49929. pWal->truncateOnCommit = 0;
  49930. }
  49931. return SQLITE_OK;
  49932. }
  49933. /*
  49934. ** If any data has been written (but not committed) to the log file, this
  49935. ** function moves the write-pointer back to the start of the transaction.
  49936. **
  49937. ** Additionally, the callback function is invoked for each frame written
  49938. ** to the WAL since the start of the transaction. If the callback returns
  49939. ** other than SQLITE_OK, it is not invoked again and the error code is
  49940. ** returned to the caller.
  49941. **
  49942. ** Otherwise, if the callback function does not return an error, this
  49943. ** function returns SQLITE_OK.
  49944. */
  49945. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  49946. int rc = SQLITE_OK;
  49947. if( ALWAYS(pWal->writeLock) ){
  49948. Pgno iMax = pWal->hdr.mxFrame;
  49949. Pgno iFrame;
  49950. /* Restore the clients cache of the wal-index header to the state it
  49951. ** was in before the client began writing to the database.
  49952. */
  49953. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  49954. for(iFrame=pWal->hdr.mxFrame+1;
  49955. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  49956. iFrame++
  49957. ){
  49958. /* This call cannot fail. Unless the page for which the page number
  49959. ** is passed as the second argument is (a) in the cache and
  49960. ** (b) has an outstanding reference, then xUndo is either a no-op
  49961. ** (if (a) is false) or simply expels the page from the cache (if (b)
  49962. ** is false).
  49963. **
  49964. ** If the upper layer is doing a rollback, it is guaranteed that there
  49965. ** are no outstanding references to any page other than page 1. And
  49966. ** page 1 is never written to the log until the transaction is
  49967. ** committed. As a result, the call to xUndo may not fail.
  49968. */
  49969. assert( walFramePgno(pWal, iFrame)!=1 );
  49970. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  49971. }
  49972. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  49973. }
  49974. return rc;
  49975. }
  49976. /*
  49977. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  49978. ** values. This function populates the array with values required to
  49979. ** "rollback" the write position of the WAL handle back to the current
  49980. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  49981. */
  49982. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  49983. assert( pWal->writeLock );
  49984. aWalData[0] = pWal->hdr.mxFrame;
  49985. aWalData[1] = pWal->hdr.aFrameCksum[0];
  49986. aWalData[2] = pWal->hdr.aFrameCksum[1];
  49987. aWalData[3] = pWal->nCkpt;
  49988. }
  49989. /*
  49990. ** Move the write position of the WAL back to the point identified by
  49991. ** the values in the aWalData[] array. aWalData must point to an array
  49992. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  49993. ** by a call to WalSavepoint().
  49994. */
  49995. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  49996. int rc = SQLITE_OK;
  49997. assert( pWal->writeLock );
  49998. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  49999. if( aWalData[3]!=pWal->nCkpt ){
  50000. /* This savepoint was opened immediately after the write-transaction
  50001. ** was started. Right after that, the writer decided to wrap around
  50002. ** to the start of the log. Update the savepoint values to match.
  50003. */
  50004. aWalData[0] = 0;
  50005. aWalData[3] = pWal->nCkpt;
  50006. }
  50007. if( aWalData[0]<pWal->hdr.mxFrame ){
  50008. pWal->hdr.mxFrame = aWalData[0];
  50009. pWal->hdr.aFrameCksum[0] = aWalData[1];
  50010. pWal->hdr.aFrameCksum[1] = aWalData[2];
  50011. walCleanupHash(pWal);
  50012. }
  50013. return rc;
  50014. }
  50015. /*
  50016. ** This function is called just before writing a set of frames to the log
  50017. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  50018. ** to the current log file, it is possible to overwrite the start of the
  50019. ** existing log file with the new frames (i.e. "reset" the log). If so,
  50020. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  50021. ** unchanged.
  50022. **
  50023. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  50024. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  50025. ** if an error occurs.
  50026. */
  50027. static int walRestartLog(Wal *pWal){
  50028. int rc = SQLITE_OK;
  50029. int cnt;
  50030. if( pWal->readLock==0 ){
  50031. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  50032. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  50033. if( pInfo->nBackfill>0 ){
  50034. u32 salt1;
  50035. sqlite3_randomness(4, &salt1);
  50036. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  50037. if( rc==SQLITE_OK ){
  50038. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  50039. ** readers are currently using the WAL), then the transactions
  50040. ** frames will overwrite the start of the existing log. Update the
  50041. ** wal-index header to reflect this.
  50042. **
  50043. ** In theory it would be Ok to update the cache of the header only
  50044. ** at this point. But updating the actual wal-index header is also
  50045. ** safe and means there is no special case for sqlite3WalUndo()
  50046. ** to handle if this transaction is rolled back. */
  50047. walRestartHdr(pWal, salt1);
  50048. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  50049. }else if( rc!=SQLITE_BUSY ){
  50050. return rc;
  50051. }
  50052. }
  50053. walUnlockShared(pWal, WAL_READ_LOCK(0));
  50054. pWal->readLock = -1;
  50055. cnt = 0;
  50056. do{
  50057. int notUsed;
  50058. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  50059. }while( rc==WAL_RETRY );
  50060. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  50061. testcase( (rc&0xff)==SQLITE_IOERR );
  50062. testcase( rc==SQLITE_PROTOCOL );
  50063. testcase( rc==SQLITE_OK );
  50064. }
  50065. return rc;
  50066. }
  50067. /*
  50068. ** Information about the current state of the WAL file and where
  50069. ** the next fsync should occur - passed from sqlite3WalFrames() into
  50070. ** walWriteToLog().
  50071. */
  50072. typedef struct WalWriter {
  50073. Wal *pWal; /* The complete WAL information */
  50074. sqlite3_file *pFd; /* The WAL file to which we write */
  50075. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  50076. int syncFlags; /* Flags for the fsync */
  50077. int szPage; /* Size of one page */
  50078. } WalWriter;
  50079. /*
  50080. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  50081. ** Do a sync when crossing the p->iSyncPoint boundary.
  50082. **
  50083. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  50084. ** first write the part before iSyncPoint, then sync, then write the
  50085. ** rest.
  50086. */
  50087. static int walWriteToLog(
  50088. WalWriter *p, /* WAL to write to */
  50089. void *pContent, /* Content to be written */
  50090. int iAmt, /* Number of bytes to write */
  50091. sqlite3_int64 iOffset /* Start writing at this offset */
  50092. ){
  50093. int rc;
  50094. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  50095. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  50096. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  50097. if( rc ) return rc;
  50098. iOffset += iFirstAmt;
  50099. iAmt -= iFirstAmt;
  50100. pContent = (void*)(iFirstAmt + (char*)pContent);
  50101. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  50102. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  50103. if( iAmt==0 || rc ) return rc;
  50104. }
  50105. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  50106. return rc;
  50107. }
  50108. /*
  50109. ** Write out a single frame of the WAL
  50110. */
  50111. static int walWriteOneFrame(
  50112. WalWriter *p, /* Where to write the frame */
  50113. PgHdr *pPage, /* The page of the frame to be written */
  50114. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  50115. sqlite3_int64 iOffset /* Byte offset at which to write */
  50116. ){
  50117. int rc; /* Result code from subfunctions */
  50118. void *pData; /* Data actually written */
  50119. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  50120. #if defined(SQLITE_HAS_CODEC)
  50121. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  50122. #else
  50123. pData = pPage->pData;
  50124. #endif
  50125. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  50126. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  50127. if( rc ) return rc;
  50128. /* Write the page data */
  50129. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  50130. return rc;
  50131. }
  50132. /*
  50133. ** Write a set of frames to the log. The caller must hold the write-lock
  50134. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  50135. */
  50136. SQLITE_PRIVATE int sqlite3WalFrames(
  50137. Wal *pWal, /* Wal handle to write to */
  50138. int szPage, /* Database page-size in bytes */
  50139. PgHdr *pList, /* List of dirty pages to write */
  50140. Pgno nTruncate, /* Database size after this commit */
  50141. int isCommit, /* True if this is a commit */
  50142. int sync_flags /* Flags to pass to OsSync() (or 0) */
  50143. ){
  50144. int rc; /* Used to catch return codes */
  50145. u32 iFrame; /* Next frame address */
  50146. PgHdr *p; /* Iterator to run through pList with. */
  50147. PgHdr *pLast = 0; /* Last frame in list */
  50148. int nExtra = 0; /* Number of extra copies of last page */
  50149. int szFrame; /* The size of a single frame */
  50150. i64 iOffset; /* Next byte to write in WAL file */
  50151. WalWriter w; /* The writer */
  50152. assert( pList );
  50153. assert( pWal->writeLock );
  50154. /* If this frame set completes a transaction, then nTruncate>0. If
  50155. ** nTruncate==0 then this frame set does not complete the transaction. */
  50156. assert( (isCommit!=0)==(nTruncate!=0) );
  50157. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  50158. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  50159. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  50160. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  50161. }
  50162. #endif
  50163. /* See if it is possible to write these frames into the start of the
  50164. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  50165. */
  50166. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  50167. return rc;
  50168. }
  50169. /* If this is the first frame written into the log, write the WAL
  50170. ** header to the start of the WAL file. See comments at the top of
  50171. ** this source file for a description of the WAL header format.
  50172. */
  50173. iFrame = pWal->hdr.mxFrame;
  50174. if( iFrame==0 ){
  50175. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  50176. u32 aCksum[2]; /* Checksum for wal-header */
  50177. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  50178. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  50179. sqlite3Put4byte(&aWalHdr[8], szPage);
  50180. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  50181. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  50182. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  50183. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  50184. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  50185. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  50186. pWal->szPage = szPage;
  50187. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  50188. pWal->hdr.aFrameCksum[0] = aCksum[0];
  50189. pWal->hdr.aFrameCksum[1] = aCksum[1];
  50190. pWal->truncateOnCommit = 1;
  50191. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  50192. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  50193. if( rc!=SQLITE_OK ){
  50194. return rc;
  50195. }
  50196. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  50197. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  50198. ** an out-of-order write following a WAL restart could result in
  50199. ** database corruption. See the ticket:
  50200. **
  50201. ** http://localhost:591/sqlite/info/ff5be73dee
  50202. */
  50203. if( pWal->syncHeader && sync_flags ){
  50204. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  50205. if( rc ) return rc;
  50206. }
  50207. }
  50208. assert( (int)pWal->szPage==szPage );
  50209. /* Setup information needed to write frames into the WAL */
  50210. w.pWal = pWal;
  50211. w.pFd = pWal->pWalFd;
  50212. w.iSyncPoint = 0;
  50213. w.syncFlags = sync_flags;
  50214. w.szPage = szPage;
  50215. iOffset = walFrameOffset(iFrame+1, szPage);
  50216. szFrame = szPage + WAL_FRAME_HDRSIZE;
  50217. /* Write all frames into the log file exactly once */
  50218. for(p=pList; p; p=p->pDirty){
  50219. int nDbSize; /* 0 normally. Positive == commit flag */
  50220. iFrame++;
  50221. assert( iOffset==walFrameOffset(iFrame, szPage) );
  50222. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  50223. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  50224. if( rc ) return rc;
  50225. pLast = p;
  50226. iOffset += szFrame;
  50227. }
  50228. /* If this is the end of a transaction, then we might need to pad
  50229. ** the transaction and/or sync the WAL file.
  50230. **
  50231. ** Padding and syncing only occur if this set of frames complete a
  50232. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  50233. ** or synchronous==OFF, then no padding or syncing are needed.
  50234. **
  50235. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  50236. ** needed and only the sync is done. If padding is needed, then the
  50237. ** final frame is repeated (with its commit mark) until the next sector
  50238. ** boundary is crossed. Only the part of the WAL prior to the last
  50239. ** sector boundary is synced; the part of the last frame that extends
  50240. ** past the sector boundary is written after the sync.
  50241. */
  50242. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  50243. if( pWal->padToSectorBoundary ){
  50244. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  50245. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  50246. while( iOffset<w.iSyncPoint ){
  50247. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  50248. if( rc ) return rc;
  50249. iOffset += szFrame;
  50250. nExtra++;
  50251. }
  50252. }else{
  50253. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  50254. }
  50255. }
  50256. /* If this frame set completes the first transaction in the WAL and
  50257. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  50258. ** journal size limit, if possible.
  50259. */
  50260. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  50261. i64 sz = pWal->mxWalSize;
  50262. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  50263. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  50264. }
  50265. walLimitSize(pWal, sz);
  50266. pWal->truncateOnCommit = 0;
  50267. }
  50268. /* Append data to the wal-index. It is not necessary to lock the
  50269. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  50270. ** guarantees that there are no other writers, and no data that may
  50271. ** be in use by existing readers is being overwritten.
  50272. */
  50273. iFrame = pWal->hdr.mxFrame;
  50274. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  50275. iFrame++;
  50276. rc = walIndexAppend(pWal, iFrame, p->pgno);
  50277. }
  50278. while( rc==SQLITE_OK && nExtra>0 ){
  50279. iFrame++;
  50280. nExtra--;
  50281. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  50282. }
  50283. if( rc==SQLITE_OK ){
  50284. /* Update the private copy of the header. */
  50285. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  50286. testcase( szPage<=32768 );
  50287. testcase( szPage>=65536 );
  50288. pWal->hdr.mxFrame = iFrame;
  50289. if( isCommit ){
  50290. pWal->hdr.iChange++;
  50291. pWal->hdr.nPage = nTruncate;
  50292. }
  50293. /* If this is a commit, update the wal-index header too. */
  50294. if( isCommit ){
  50295. walIndexWriteHdr(pWal);
  50296. pWal->iCallback = iFrame;
  50297. }
  50298. }
  50299. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  50300. return rc;
  50301. }
  50302. /*
  50303. ** This routine is called to implement sqlite3_wal_checkpoint() and
  50304. ** related interfaces.
  50305. **
  50306. ** Obtain a CHECKPOINT lock and then backfill as much information as
  50307. ** we can from WAL into the database.
  50308. **
  50309. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  50310. ** callback. In this case this function runs a blocking checkpoint.
  50311. */
  50312. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  50313. Wal *pWal, /* Wal connection */
  50314. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  50315. int (*xBusy)(void*), /* Function to call when busy */
  50316. void *pBusyArg, /* Context argument for xBusyHandler */
  50317. int sync_flags, /* Flags to sync db file with (or 0) */
  50318. int nBuf, /* Size of temporary buffer */
  50319. u8 *zBuf, /* Temporary buffer to use */
  50320. int *pnLog, /* OUT: Number of frames in WAL */
  50321. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  50322. ){
  50323. int rc; /* Return code */
  50324. int isChanged = 0; /* True if a new wal-index header is loaded */
  50325. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  50326. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  50327. assert( pWal->ckptLock==0 );
  50328. assert( pWal->writeLock==0 );
  50329. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  50330. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  50331. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  50332. if( pWal->readOnly ) return SQLITE_READONLY;
  50333. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  50334. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  50335. ** "checkpoint" lock on the database file. */
  50336. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  50337. if( rc ){
  50338. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  50339. ** checkpoint operation at the same time, the lock cannot be obtained and
  50340. ** SQLITE_BUSY is returned.
  50341. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  50342. ** it will not be invoked in this case.
  50343. */
  50344. testcase( rc==SQLITE_BUSY );
  50345. testcase( xBusy!=0 );
  50346. return rc;
  50347. }
  50348. pWal->ckptLock = 1;
  50349. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  50350. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  50351. ** file.
  50352. **
  50353. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  50354. ** immediately, and a busy-handler is configured, it is invoked and the
  50355. ** writer lock retried until either the busy-handler returns 0 or the
  50356. ** lock is successfully obtained.
  50357. */
  50358. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  50359. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  50360. if( rc==SQLITE_OK ){
  50361. pWal->writeLock = 1;
  50362. }else if( rc==SQLITE_BUSY ){
  50363. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  50364. xBusy2 = 0;
  50365. rc = SQLITE_OK;
  50366. }
  50367. }
  50368. /* Read the wal-index header. */
  50369. if( rc==SQLITE_OK ){
  50370. rc = walIndexReadHdr(pWal, &isChanged);
  50371. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  50372. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  50373. }
  50374. }
  50375. /* Copy data from the log to the database file. */
  50376. if( rc==SQLITE_OK ){
  50377. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  50378. rc = SQLITE_CORRUPT_BKPT;
  50379. }else{
  50380. rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  50381. }
  50382. /* If no error occurred, set the output variables. */
  50383. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  50384. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  50385. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  50386. }
  50387. }
  50388. if( isChanged ){
  50389. /* If a new wal-index header was loaded before the checkpoint was
  50390. ** performed, then the pager-cache associated with pWal is now
  50391. ** out of date. So zero the cached wal-index header to ensure that
  50392. ** next time the pager opens a snapshot on this database it knows that
  50393. ** the cache needs to be reset.
  50394. */
  50395. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  50396. }
  50397. /* Release the locks. */
  50398. sqlite3WalEndWriteTransaction(pWal);
  50399. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  50400. pWal->ckptLock = 0;
  50401. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  50402. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  50403. }
  50404. /* Return the value to pass to a sqlite3_wal_hook callback, the
  50405. ** number of frames in the WAL at the point of the last commit since
  50406. ** sqlite3WalCallback() was called. If no commits have occurred since
  50407. ** the last call, then return 0.
  50408. */
  50409. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  50410. u32 ret = 0;
  50411. if( pWal ){
  50412. ret = pWal->iCallback;
  50413. pWal->iCallback = 0;
  50414. }
  50415. return (int)ret;
  50416. }
  50417. /*
  50418. ** This function is called to change the WAL subsystem into or out
  50419. ** of locking_mode=EXCLUSIVE.
  50420. **
  50421. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  50422. ** into locking_mode=NORMAL. This means that we must acquire a lock
  50423. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  50424. ** or if the acquisition of the lock fails, then return 0. If the
  50425. ** transition out of exclusive-mode is successful, return 1. This
  50426. ** operation must occur while the pager is still holding the exclusive
  50427. ** lock on the main database file.
  50428. **
  50429. ** If op is one, then change from locking_mode=NORMAL into
  50430. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  50431. ** be released. Return 1 if the transition is made and 0 if the
  50432. ** WAL is already in exclusive-locking mode - meaning that this
  50433. ** routine is a no-op. The pager must already hold the exclusive lock
  50434. ** on the main database file before invoking this operation.
  50435. **
  50436. ** If op is negative, then do a dry-run of the op==1 case but do
  50437. ** not actually change anything. The pager uses this to see if it
  50438. ** should acquire the database exclusive lock prior to invoking
  50439. ** the op==1 case.
  50440. */
  50441. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  50442. int rc;
  50443. assert( pWal->writeLock==0 );
  50444. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  50445. /* pWal->readLock is usually set, but might be -1 if there was a
  50446. ** prior error while attempting to acquire are read-lock. This cannot
  50447. ** happen if the connection is actually in exclusive mode (as no xShmLock
  50448. ** locks are taken in this case). Nor should the pager attempt to
  50449. ** upgrade to exclusive-mode following such an error.
  50450. */
  50451. assert( pWal->readLock>=0 || pWal->lockError );
  50452. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  50453. if( op==0 ){
  50454. if( pWal->exclusiveMode ){
  50455. pWal->exclusiveMode = 0;
  50456. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  50457. pWal->exclusiveMode = 1;
  50458. }
  50459. rc = pWal->exclusiveMode==0;
  50460. }else{
  50461. /* Already in locking_mode=NORMAL */
  50462. rc = 0;
  50463. }
  50464. }else if( op>0 ){
  50465. assert( pWal->exclusiveMode==0 );
  50466. assert( pWal->readLock>=0 );
  50467. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  50468. pWal->exclusiveMode = 1;
  50469. rc = 1;
  50470. }else{
  50471. rc = pWal->exclusiveMode==0;
  50472. }
  50473. return rc;
  50474. }
  50475. /*
  50476. ** Return true if the argument is non-NULL and the WAL module is using
  50477. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  50478. ** WAL module is using shared-memory, return false.
  50479. */
  50480. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  50481. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  50482. }
  50483. #ifdef SQLITE_ENABLE_SNAPSHOT
  50484. /* Create a snapshot object. The content of a snapshot is opaque to
  50485. ** every other subsystem, so the WAL module can put whatever it needs
  50486. ** in the object.
  50487. */
  50488. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  50489. int rc = SQLITE_OK;
  50490. WalIndexHdr *pRet;
  50491. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  50492. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  50493. if( pRet==0 ){
  50494. rc = SQLITE_NOMEM;
  50495. }else{
  50496. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  50497. *ppSnapshot = (sqlite3_snapshot*)pRet;
  50498. }
  50499. return rc;
  50500. }
  50501. /* Try to open on pSnapshot when the next read-transaction starts
  50502. */
  50503. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  50504. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  50505. }
  50506. #endif /* SQLITE_ENABLE_SNAPSHOT */
  50507. #ifdef SQLITE_ENABLE_ZIPVFS
  50508. /*
  50509. ** If the argument is not NULL, it points to a Wal object that holds a
  50510. ** read-lock. This function returns the database page-size if it is known,
  50511. ** or zero if it is not (or if pWal is NULL).
  50512. */
  50513. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  50514. assert( pWal==0 || pWal->readLock>=0 );
  50515. return (pWal ? pWal->szPage : 0);
  50516. }
  50517. #endif
  50518. /* Return the sqlite3_file object for the WAL file
  50519. */
  50520. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  50521. return pWal->pWalFd;
  50522. }
  50523. #endif /* #ifndef SQLITE_OMIT_WAL */
  50524. /************** End of wal.c *************************************************/
  50525. /************** Begin file btmutex.c *****************************************/
  50526. /*
  50527. ** 2007 August 27
  50528. **
  50529. ** The author disclaims copyright to this source code. In place of
  50530. ** a legal notice, here is a blessing:
  50531. **
  50532. ** May you do good and not evil.
  50533. ** May you find forgiveness for yourself and forgive others.
  50534. ** May you share freely, never taking more than you give.
  50535. **
  50536. *************************************************************************
  50537. **
  50538. ** This file contains code used to implement mutexes on Btree objects.
  50539. ** This code really belongs in btree.c. But btree.c is getting too
  50540. ** big and we want to break it down some. This packaged seemed like
  50541. ** a good breakout.
  50542. */
  50543. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  50544. /************** Begin file btreeInt.h ****************************************/
  50545. /*
  50546. ** 2004 April 6
  50547. **
  50548. ** The author disclaims copyright to this source code. In place of
  50549. ** a legal notice, here is a blessing:
  50550. **
  50551. ** May you do good and not evil.
  50552. ** May you find forgiveness for yourself and forgive others.
  50553. ** May you share freely, never taking more than you give.
  50554. **
  50555. *************************************************************************
  50556. ** This file implements an external (disk-based) database using BTrees.
  50557. ** For a detailed discussion of BTrees, refer to
  50558. **
  50559. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  50560. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  50561. ** Publishing Company, Reading, Massachusetts.
  50562. **
  50563. ** The basic idea is that each page of the file contains N database
  50564. ** entries and N+1 pointers to subpages.
  50565. **
  50566. ** ----------------------------------------------------------------
  50567. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  50568. ** ----------------------------------------------------------------
  50569. **
  50570. ** All of the keys on the page that Ptr(0) points to have values less
  50571. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  50572. ** values greater than Key(0) and less than Key(1). All of the keys
  50573. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  50574. ** so forth.
  50575. **
  50576. ** Finding a particular key requires reading O(log(M)) pages from the
  50577. ** disk where M is the number of entries in the tree.
  50578. **
  50579. ** In this implementation, a single file can hold one or more separate
  50580. ** BTrees. Each BTree is identified by the index of its root page. The
  50581. ** key and data for any entry are combined to form the "payload". A
  50582. ** fixed amount of payload can be carried directly on the database
  50583. ** page. If the payload is larger than the preset amount then surplus
  50584. ** bytes are stored on overflow pages. The payload for an entry
  50585. ** and the preceding pointer are combined to form a "Cell". Each
  50586. ** page has a small header which contains the Ptr(N) pointer and other
  50587. ** information such as the size of key and data.
  50588. **
  50589. ** FORMAT DETAILS
  50590. **
  50591. ** The file is divided into pages. The first page is called page 1,
  50592. ** the second is page 2, and so forth. A page number of zero indicates
  50593. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  50594. ** Each page can be either a btree page, a freelist page, an overflow
  50595. ** page, or a pointer-map page.
  50596. **
  50597. ** The first page is always a btree page. The first 100 bytes of the first
  50598. ** page contain a special header (the "file header") that describes the file.
  50599. ** The format of the file header is as follows:
  50600. **
  50601. ** OFFSET SIZE DESCRIPTION
  50602. ** 0 16 Header string: "SQLite format 3\000"
  50603. ** 16 2 Page size in bytes. (1 means 65536)
  50604. ** 18 1 File format write version
  50605. ** 19 1 File format read version
  50606. ** 20 1 Bytes of unused space at the end of each page
  50607. ** 21 1 Max embedded payload fraction (must be 64)
  50608. ** 22 1 Min embedded payload fraction (must be 32)
  50609. ** 23 1 Min leaf payload fraction (must be 32)
  50610. ** 24 4 File change counter
  50611. ** 28 4 Reserved for future use
  50612. ** 32 4 First freelist page
  50613. ** 36 4 Number of freelist pages in the file
  50614. ** 40 60 15 4-byte meta values passed to higher layers
  50615. **
  50616. ** 40 4 Schema cookie
  50617. ** 44 4 File format of schema layer
  50618. ** 48 4 Size of page cache
  50619. ** 52 4 Largest root-page (auto/incr_vacuum)
  50620. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  50621. ** 60 4 User version
  50622. ** 64 4 Incremental vacuum mode
  50623. ** 68 4 Application-ID
  50624. ** 72 20 unused
  50625. ** 92 4 The version-valid-for number
  50626. ** 96 4 SQLITE_VERSION_NUMBER
  50627. **
  50628. ** All of the integer values are big-endian (most significant byte first).
  50629. **
  50630. ** The file change counter is incremented when the database is changed
  50631. ** This counter allows other processes to know when the file has changed
  50632. ** and thus when they need to flush their cache.
  50633. **
  50634. ** The max embedded payload fraction is the amount of the total usable
  50635. ** space in a page that can be consumed by a single cell for standard
  50636. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  50637. ** is to limit the maximum cell size so that at least 4 cells will fit
  50638. ** on one page. Thus the default max embedded payload fraction is 64.
  50639. **
  50640. ** If the payload for a cell is larger than the max payload, then extra
  50641. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  50642. ** as many bytes as possible are moved into the overflow pages without letting
  50643. ** the cell size drop below the min embedded payload fraction.
  50644. **
  50645. ** The min leaf payload fraction is like the min embedded payload fraction
  50646. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  50647. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  50648. ** not specified in the header.
  50649. **
  50650. ** Each btree pages is divided into three sections: The header, the
  50651. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  50652. ** file header that occurs before the page header.
  50653. **
  50654. ** |----------------|
  50655. ** | file header | 100 bytes. Page 1 only.
  50656. ** |----------------|
  50657. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  50658. ** |----------------|
  50659. ** | cell pointer | | 2 bytes per cell. Sorted order.
  50660. ** | array | | Grows downward
  50661. ** | | v
  50662. ** |----------------|
  50663. ** | unallocated |
  50664. ** | space |
  50665. ** |----------------| ^ Grows upwards
  50666. ** | cell content | | Arbitrary order interspersed with freeblocks.
  50667. ** | area | | and free space fragments.
  50668. ** |----------------|
  50669. **
  50670. ** The page headers looks like this:
  50671. **
  50672. ** OFFSET SIZE DESCRIPTION
  50673. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  50674. ** 1 2 byte offset to the first freeblock
  50675. ** 3 2 number of cells on this page
  50676. ** 5 2 first byte of the cell content area
  50677. ** 7 1 number of fragmented free bytes
  50678. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  50679. **
  50680. ** The flags define the format of this btree page. The leaf flag means that
  50681. ** this page has no children. The zerodata flag means that this page carries
  50682. ** only keys and no data. The intkey flag means that the key is an integer
  50683. ** which is stored in the key size entry of the cell header rather than in
  50684. ** the payload area.
  50685. **
  50686. ** The cell pointer array begins on the first byte after the page header.
  50687. ** The cell pointer array contains zero or more 2-byte numbers which are
  50688. ** offsets from the beginning of the page to the cell content in the cell
  50689. ** content area. The cell pointers occur in sorted order. The system strives
  50690. ** to keep free space after the last cell pointer so that new cells can
  50691. ** be easily added without having to defragment the page.
  50692. **
  50693. ** Cell content is stored at the very end of the page and grows toward the
  50694. ** beginning of the page.
  50695. **
  50696. ** Unused space within the cell content area is collected into a linked list of
  50697. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  50698. ** to the first freeblock is given in the header. Freeblocks occur in
  50699. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  50700. ** any group of 3 or fewer unused bytes in the cell content area cannot
  50701. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  50702. ** a fragment. The total number of bytes in all fragments is recorded.
  50703. ** in the page header at offset 7.
  50704. **
  50705. ** SIZE DESCRIPTION
  50706. ** 2 Byte offset of the next freeblock
  50707. ** 2 Bytes in this freeblock
  50708. **
  50709. ** Cells are of variable length. Cells are stored in the cell content area at
  50710. ** the end of the page. Pointers to the cells are in the cell pointer array
  50711. ** that immediately follows the page header. Cells is not necessarily
  50712. ** contiguous or in order, but cell pointers are contiguous and in order.
  50713. **
  50714. ** Cell content makes use of variable length integers. A variable
  50715. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  50716. ** byte are used. The integer consists of all bytes that have bit 8 set and
  50717. ** the first byte with bit 8 clear. The most significant byte of the integer
  50718. ** appears first. A variable-length integer may not be more than 9 bytes long.
  50719. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  50720. ** allows a 64-bit integer to be encoded in 9 bytes.
  50721. **
  50722. ** 0x00 becomes 0x00000000
  50723. ** 0x7f becomes 0x0000007f
  50724. ** 0x81 0x00 becomes 0x00000080
  50725. ** 0x82 0x00 becomes 0x00000100
  50726. ** 0x80 0x7f becomes 0x0000007f
  50727. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  50728. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  50729. **
  50730. ** Variable length integers are used for rowids and to hold the number of
  50731. ** bytes of key and data in a btree cell.
  50732. **
  50733. ** The content of a cell looks like this:
  50734. **
  50735. ** SIZE DESCRIPTION
  50736. ** 4 Page number of the left child. Omitted if leaf flag is set.
  50737. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  50738. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  50739. ** * Payload
  50740. ** 4 First page of the overflow chain. Omitted if no overflow
  50741. **
  50742. ** Overflow pages form a linked list. Each page except the last is completely
  50743. ** filled with data (pagesize - 4 bytes). The last page can have as little
  50744. ** as 1 byte of data.
  50745. **
  50746. ** SIZE DESCRIPTION
  50747. ** 4 Page number of next overflow page
  50748. ** * Data
  50749. **
  50750. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  50751. ** file header points to the first in a linked list of trunk page. Each trunk
  50752. ** page points to multiple leaf pages. The content of a leaf page is
  50753. ** unspecified. A trunk page looks like this:
  50754. **
  50755. ** SIZE DESCRIPTION
  50756. ** 4 Page number of next trunk page
  50757. ** 4 Number of leaf pointers on this page
  50758. ** * zero or more pages numbers of leaves
  50759. */
  50760. /* #include "sqliteInt.h" */
  50761. /* The following value is the maximum cell size assuming a maximum page
  50762. ** size give above.
  50763. */
  50764. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  50765. /* The maximum number of cells on a single page of the database. This
  50766. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  50767. ** plus 2 bytes for the index to the cell in the page header). Such
  50768. ** small cells will be rare, but they are possible.
  50769. */
  50770. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  50771. /* Forward declarations */
  50772. typedef struct MemPage MemPage;
  50773. typedef struct BtLock BtLock;
  50774. typedef struct CellInfo CellInfo;
  50775. /*
  50776. ** This is a magic string that appears at the beginning of every
  50777. ** SQLite database in order to identify the file as a real database.
  50778. **
  50779. ** You can change this value at compile-time by specifying a
  50780. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  50781. ** header must be exactly 16 bytes including the zero-terminator so
  50782. ** the string itself should be 15 characters long. If you change
  50783. ** the header, then your custom library will not be able to read
  50784. ** databases generated by the standard tools and the standard tools
  50785. ** will not be able to read databases created by your custom library.
  50786. */
  50787. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  50788. # define SQLITE_FILE_HEADER "SQLite format 3"
  50789. #endif
  50790. /*
  50791. ** Page type flags. An ORed combination of these flags appear as the
  50792. ** first byte of on-disk image of every BTree page.
  50793. */
  50794. #define PTF_INTKEY 0x01
  50795. #define PTF_ZERODATA 0x02
  50796. #define PTF_LEAFDATA 0x04
  50797. #define PTF_LEAF 0x08
  50798. /*
  50799. ** As each page of the file is loaded into memory, an instance of the following
  50800. ** structure is appended and initialized to zero. This structure stores
  50801. ** information about the page that is decoded from the raw file page.
  50802. **
  50803. ** The pParent field points back to the parent page. This allows us to
  50804. ** walk up the BTree from any leaf to the root. Care must be taken to
  50805. ** unref() the parent page pointer when this page is no longer referenced.
  50806. ** The pageDestructor() routine handles that chore.
  50807. **
  50808. ** Access to all fields of this structure is controlled by the mutex
  50809. ** stored in MemPage.pBt->mutex.
  50810. */
  50811. struct MemPage {
  50812. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  50813. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  50814. u8 intKey; /* True if table b-trees. False for index b-trees */
  50815. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  50816. u8 noPayload; /* True if internal intKey page (thus w/o data) */
  50817. u8 leaf; /* True if a leaf page */
  50818. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  50819. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  50820. u8 max1bytePayload; /* min(maxLocal,127) */
  50821. u8 bBusy; /* Prevent endless loops on corrupt database files */
  50822. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  50823. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  50824. u16 cellOffset; /* Index in aData of first cell pointer */
  50825. u16 nFree; /* Number of free bytes on the page */
  50826. u16 nCell; /* Number of cells on this page, local and ovfl */
  50827. u16 maskPage; /* Mask for page offset */
  50828. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  50829. ** non-overflow cell */
  50830. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  50831. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  50832. u8 *aData; /* Pointer to disk image of the page data */
  50833. u8 *aDataEnd; /* One byte past the end of usable data */
  50834. u8 *aCellIdx; /* The cell index area */
  50835. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  50836. DbPage *pDbPage; /* Pager page handle */
  50837. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  50838. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  50839. Pgno pgno; /* Page number for this page */
  50840. };
  50841. /*
  50842. ** The in-memory image of a disk page has the auxiliary information appended
  50843. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  50844. ** that extra information.
  50845. */
  50846. #define EXTRA_SIZE sizeof(MemPage)
  50847. /*
  50848. ** A linked list of the following structures is stored at BtShared.pLock.
  50849. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  50850. ** is opened on the table with root page BtShared.iTable. Locks are removed
  50851. ** from this list when a transaction is committed or rolled back, or when
  50852. ** a btree handle is closed.
  50853. */
  50854. struct BtLock {
  50855. Btree *pBtree; /* Btree handle holding this lock */
  50856. Pgno iTable; /* Root page of table */
  50857. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  50858. BtLock *pNext; /* Next in BtShared.pLock list */
  50859. };
  50860. /* Candidate values for BtLock.eLock */
  50861. #define READ_LOCK 1
  50862. #define WRITE_LOCK 2
  50863. /* A Btree handle
  50864. **
  50865. ** A database connection contains a pointer to an instance of
  50866. ** this object for every database file that it has open. This structure
  50867. ** is opaque to the database connection. The database connection cannot
  50868. ** see the internals of this structure and only deals with pointers to
  50869. ** this structure.
  50870. **
  50871. ** For some database files, the same underlying database cache might be
  50872. ** shared between multiple connections. In that case, each connection
  50873. ** has it own instance of this object. But each instance of this object
  50874. ** points to the same BtShared object. The database cache and the
  50875. ** schema associated with the database file are all contained within
  50876. ** the BtShared object.
  50877. **
  50878. ** All fields in this structure are accessed under sqlite3.mutex.
  50879. ** The pBt pointer itself may not be changed while there exists cursors
  50880. ** in the referenced BtShared that point back to this Btree since those
  50881. ** cursors have to go through this Btree to find their BtShared and
  50882. ** they often do so without holding sqlite3.mutex.
  50883. */
  50884. struct Btree {
  50885. sqlite3 *db; /* The database connection holding this btree */
  50886. BtShared *pBt; /* Sharable content of this btree */
  50887. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  50888. u8 sharable; /* True if we can share pBt with another db */
  50889. u8 locked; /* True if db currently has pBt locked */
  50890. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  50891. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  50892. int nBackup; /* Number of backup operations reading this btree */
  50893. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  50894. Btree *pNext; /* List of other sharable Btrees from the same db */
  50895. Btree *pPrev; /* Back pointer of the same list */
  50896. #ifndef SQLITE_OMIT_SHARED_CACHE
  50897. BtLock lock; /* Object used to lock page 1 */
  50898. #endif
  50899. };
  50900. /*
  50901. ** Btree.inTrans may take one of the following values.
  50902. **
  50903. ** If the shared-data extension is enabled, there may be multiple users
  50904. ** of the Btree structure. At most one of these may open a write transaction,
  50905. ** but any number may have active read transactions.
  50906. */
  50907. #define TRANS_NONE 0
  50908. #define TRANS_READ 1
  50909. #define TRANS_WRITE 2
  50910. /*
  50911. ** An instance of this object represents a single database file.
  50912. **
  50913. ** A single database file can be in use at the same time by two
  50914. ** or more database connections. When two or more connections are
  50915. ** sharing the same database file, each connection has it own
  50916. ** private Btree object for the file and each of those Btrees points
  50917. ** to this one BtShared object. BtShared.nRef is the number of
  50918. ** connections currently sharing this database file.
  50919. **
  50920. ** Fields in this structure are accessed under the BtShared.mutex
  50921. ** mutex, except for nRef and pNext which are accessed under the
  50922. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  50923. ** may not be modified once it is initially set as long as nRef>0.
  50924. ** The pSchema field may be set once under BtShared.mutex and
  50925. ** thereafter is unchanged as long as nRef>0.
  50926. **
  50927. ** isPending:
  50928. **
  50929. ** If a BtShared client fails to obtain a write-lock on a database
  50930. ** table (because there exists one or more read-locks on the table),
  50931. ** the shared-cache enters 'pending-lock' state and isPending is
  50932. ** set to true.
  50933. **
  50934. ** The shared-cache leaves the 'pending lock' state when either of
  50935. ** the following occur:
  50936. **
  50937. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  50938. ** 2) The number of locks held by other connections drops to zero.
  50939. **
  50940. ** while in the 'pending-lock' state, no connection may start a new
  50941. ** transaction.
  50942. **
  50943. ** This feature is included to help prevent writer-starvation.
  50944. */
  50945. struct BtShared {
  50946. Pager *pPager; /* The page cache */
  50947. sqlite3 *db; /* Database connection currently using this Btree */
  50948. BtCursor *pCursor; /* A list of all open cursors */
  50949. MemPage *pPage1; /* First page of the database */
  50950. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  50951. #ifndef SQLITE_OMIT_AUTOVACUUM
  50952. u8 autoVacuum; /* True if auto-vacuum is enabled */
  50953. u8 incrVacuum; /* True if incr-vacuum is enabled */
  50954. u8 bDoTruncate; /* True to truncate db on commit */
  50955. #endif
  50956. u8 inTransaction; /* Transaction state */
  50957. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  50958. #ifdef SQLITE_HAS_CODEC
  50959. u8 optimalReserve; /* Desired amount of reserved space per page */
  50960. #endif
  50961. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  50962. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  50963. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  50964. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  50965. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  50966. u32 pageSize; /* Total number of bytes on a page */
  50967. u32 usableSize; /* Number of usable bytes on each page */
  50968. int nTransaction; /* Number of open transactions (read + write) */
  50969. u32 nPage; /* Number of pages in the database */
  50970. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  50971. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  50972. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  50973. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  50974. #ifndef SQLITE_OMIT_SHARED_CACHE
  50975. int nRef; /* Number of references to this structure */
  50976. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  50977. BtLock *pLock; /* List of locks held on this shared-btree struct */
  50978. Btree *pWriter; /* Btree with currently open write transaction */
  50979. #endif
  50980. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  50981. };
  50982. /*
  50983. ** Allowed values for BtShared.btsFlags
  50984. */
  50985. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  50986. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  50987. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  50988. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  50989. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  50990. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  50991. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  50992. /*
  50993. ** An instance of the following structure is used to hold information
  50994. ** about a cell. The parseCellPtr() function fills in this structure
  50995. ** based on information extract from the raw disk page.
  50996. */
  50997. struct CellInfo {
  50998. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  50999. u8 *pPayload; /* Pointer to the start of payload */
  51000. u32 nPayload; /* Bytes of payload */
  51001. u16 nLocal; /* Amount of payload held locally, not on overflow */
  51002. u16 nSize; /* Size of the cell content on the main b-tree page */
  51003. };
  51004. /*
  51005. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  51006. ** this will be declared corrupt. This value is calculated based on a
  51007. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  51008. ** root-node and 3 for all other internal nodes.
  51009. **
  51010. ** If a tree that appears to be taller than this is encountered, it is
  51011. ** assumed that the database is corrupt.
  51012. */
  51013. #define BTCURSOR_MAX_DEPTH 20
  51014. /*
  51015. ** A cursor is a pointer to a particular entry within a particular
  51016. ** b-tree within a database file.
  51017. **
  51018. ** The entry is identified by its MemPage and the index in
  51019. ** MemPage.aCell[] of the entry.
  51020. **
  51021. ** A single database file can be shared by two more database connections,
  51022. ** but cursors cannot be shared. Each cursor is associated with a
  51023. ** particular database connection identified BtCursor.pBtree.db.
  51024. **
  51025. ** Fields in this structure are accessed under the BtShared.mutex
  51026. ** found at self->pBt->mutex.
  51027. **
  51028. ** skipNext meaning:
  51029. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  51030. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  51031. ** eState==FAULT: Cursor fault with skipNext as error code.
  51032. */
  51033. struct BtCursor {
  51034. Btree *pBtree; /* The Btree to which this cursor belongs */
  51035. BtShared *pBt; /* The BtShared this cursor points to */
  51036. BtCursor *pNext; /* Forms a linked list of all cursors */
  51037. Pgno *aOverflow; /* Cache of overflow page locations */
  51038. CellInfo info; /* A parse of the cell we are pointing at */
  51039. i64 nKey; /* Size of pKey, or last integer key */
  51040. void *pKey; /* Saved key that was cursor last known position */
  51041. Pgno pgnoRoot; /* The root page of this tree */
  51042. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  51043. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  51044. ** Error code if eState==CURSOR_FAULT */
  51045. u8 curFlags; /* zero or more BTCF_* flags defined below */
  51046. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  51047. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  51048. u8 hints; /* As configured by CursorSetHints() */
  51049. /* All fields above are zeroed when the cursor is allocated. See
  51050. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  51051. ** initialized. */
  51052. i8 iPage; /* Index of current page in apPage */
  51053. u8 curIntKey; /* Value of apPage[0]->intKey */
  51054. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  51055. void *padding1; /* Make object size a multiple of 16 */
  51056. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  51057. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  51058. };
  51059. /*
  51060. ** Legal values for BtCursor.curFlags
  51061. */
  51062. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  51063. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  51064. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  51065. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  51066. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  51067. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  51068. /*
  51069. ** Potential values for BtCursor.eState.
  51070. **
  51071. ** CURSOR_INVALID:
  51072. ** Cursor does not point to a valid entry. This can happen (for example)
  51073. ** because the table is empty or because BtreeCursorFirst() has not been
  51074. ** called.
  51075. **
  51076. ** CURSOR_VALID:
  51077. ** Cursor points to a valid entry. getPayload() etc. may be called.
  51078. **
  51079. ** CURSOR_SKIPNEXT:
  51080. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  51081. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  51082. ** operation should be a no-op.
  51083. **
  51084. ** CURSOR_REQUIRESEEK:
  51085. ** The table that this cursor was opened on still exists, but has been
  51086. ** modified since the cursor was last used. The cursor position is saved
  51087. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  51088. ** this state, restoreCursorPosition() can be called to attempt to
  51089. ** seek the cursor to the saved position.
  51090. **
  51091. ** CURSOR_FAULT:
  51092. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  51093. ** on a different connection that shares the BtShared cache with this
  51094. ** cursor. The error has left the cache in an inconsistent state.
  51095. ** Do nothing else with this cursor. Any attempt to use the cursor
  51096. ** should return the error code stored in BtCursor.skipNext
  51097. */
  51098. #define CURSOR_INVALID 0
  51099. #define CURSOR_VALID 1
  51100. #define CURSOR_SKIPNEXT 2
  51101. #define CURSOR_REQUIRESEEK 3
  51102. #define CURSOR_FAULT 4
  51103. /*
  51104. ** The database page the PENDING_BYTE occupies. This page is never used.
  51105. */
  51106. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  51107. /*
  51108. ** These macros define the location of the pointer-map entry for a
  51109. ** database page. The first argument to each is the number of usable
  51110. ** bytes on each page of the database (often 1024). The second is the
  51111. ** page number to look up in the pointer map.
  51112. **
  51113. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  51114. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  51115. ** the offset of the requested map entry.
  51116. **
  51117. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  51118. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  51119. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  51120. ** this test.
  51121. */
  51122. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  51123. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  51124. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  51125. /*
  51126. ** The pointer map is a lookup table that identifies the parent page for
  51127. ** each child page in the database file. The parent page is the page that
  51128. ** contains a pointer to the child. Every page in the database contains
  51129. ** 0 or 1 parent pages. (In this context 'database page' refers
  51130. ** to any page that is not part of the pointer map itself.) Each pointer map
  51131. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  51132. ** The PTRMAP_XXX identifiers below are the valid types.
  51133. **
  51134. ** The purpose of the pointer map is to facility moving pages from one
  51135. ** position in the file to another as part of autovacuum. When a page
  51136. ** is moved, the pointer in its parent must be updated to point to the
  51137. ** new location. The pointer map is used to locate the parent page quickly.
  51138. **
  51139. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  51140. ** used in this case.
  51141. **
  51142. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  51143. ** is not used in this case.
  51144. **
  51145. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  51146. ** overflow pages. The page number identifies the page that
  51147. ** contains the cell with a pointer to this overflow page.
  51148. **
  51149. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  51150. ** overflow pages. The page-number identifies the previous
  51151. ** page in the overflow page list.
  51152. **
  51153. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  51154. ** identifies the parent page in the btree.
  51155. */
  51156. #define PTRMAP_ROOTPAGE 1
  51157. #define PTRMAP_FREEPAGE 2
  51158. #define PTRMAP_OVERFLOW1 3
  51159. #define PTRMAP_OVERFLOW2 4
  51160. #define PTRMAP_BTREE 5
  51161. /* A bunch of assert() statements to check the transaction state variables
  51162. ** of handle p (type Btree*) are internally consistent.
  51163. */
  51164. #define btreeIntegrity(p) \
  51165. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  51166. assert( p->pBt->inTransaction>=p->inTrans );
  51167. /*
  51168. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  51169. ** if the database supports auto-vacuum or not. Because it is used
  51170. ** within an expression that is an argument to another macro
  51171. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  51172. ** So, this macro is defined instead.
  51173. */
  51174. #ifndef SQLITE_OMIT_AUTOVACUUM
  51175. #define ISAUTOVACUUM (pBt->autoVacuum)
  51176. #else
  51177. #define ISAUTOVACUUM 0
  51178. #endif
  51179. /*
  51180. ** This structure is passed around through all the sanity checking routines
  51181. ** in order to keep track of some global state information.
  51182. **
  51183. ** The aRef[] array is allocated so that there is 1 bit for each page in
  51184. ** the database. As the integrity-check proceeds, for each page used in
  51185. ** the database the corresponding bit is set. This allows integrity-check to
  51186. ** detect pages that are used twice and orphaned pages (both of which
  51187. ** indicate corruption).
  51188. */
  51189. typedef struct IntegrityCk IntegrityCk;
  51190. struct IntegrityCk {
  51191. BtShared *pBt; /* The tree being checked out */
  51192. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  51193. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  51194. Pgno nPage; /* Number of pages in the database */
  51195. int mxErr; /* Stop accumulating errors when this reaches zero */
  51196. int nErr; /* Number of messages written to zErrMsg so far */
  51197. int mallocFailed; /* A memory allocation error has occurred */
  51198. const char *zPfx; /* Error message prefix */
  51199. int v1, v2; /* Values for up to two %d fields in zPfx */
  51200. StrAccum errMsg; /* Accumulate the error message text here */
  51201. u32 *heap; /* Min-heap used for analyzing cell coverage */
  51202. };
  51203. /*
  51204. ** Routines to read or write a two- and four-byte big-endian integer values.
  51205. */
  51206. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  51207. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  51208. #define get4byte sqlite3Get4byte
  51209. #define put4byte sqlite3Put4byte
  51210. /*
  51211. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  51212. ** two-byte aligned address. get2bytea() is only used for accessing the
  51213. ** cell addresses in a btree header.
  51214. */
  51215. #if SQLITE_BYTEORDER==4321
  51216. # define get2byteAligned(x) (*(u16*)(x))
  51217. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  51218. && GCC_VERSION>=4008000
  51219. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  51220. #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
  51221. && defined(_MSC_VER) && _MSC_VER>=1300
  51222. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  51223. #else
  51224. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  51225. #endif
  51226. /************** End of btreeInt.h ********************************************/
  51227. /************** Continuing where we left off in btmutex.c ********************/
  51228. #ifndef SQLITE_OMIT_SHARED_CACHE
  51229. #if SQLITE_THREADSAFE
  51230. /*
  51231. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  51232. ** set BtShared.db to the database handle associated with p and the
  51233. ** p->locked boolean to true.
  51234. */
  51235. static void lockBtreeMutex(Btree *p){
  51236. assert( p->locked==0 );
  51237. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  51238. assert( sqlite3_mutex_held(p->db->mutex) );
  51239. sqlite3_mutex_enter(p->pBt->mutex);
  51240. p->pBt->db = p->db;
  51241. p->locked = 1;
  51242. }
  51243. /*
  51244. ** Release the BtShared mutex associated with B-Tree handle p and
  51245. ** clear the p->locked boolean.
  51246. */
  51247. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  51248. BtShared *pBt = p->pBt;
  51249. assert( p->locked==1 );
  51250. assert( sqlite3_mutex_held(pBt->mutex) );
  51251. assert( sqlite3_mutex_held(p->db->mutex) );
  51252. assert( p->db==pBt->db );
  51253. sqlite3_mutex_leave(pBt->mutex);
  51254. p->locked = 0;
  51255. }
  51256. /* Forward reference */
  51257. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  51258. /*
  51259. ** Enter a mutex on the given BTree object.
  51260. **
  51261. ** If the object is not sharable, then no mutex is ever required
  51262. ** and this routine is a no-op. The underlying mutex is non-recursive.
  51263. ** But we keep a reference count in Btree.wantToLock so the behavior
  51264. ** of this interface is recursive.
  51265. **
  51266. ** To avoid deadlocks, multiple Btrees are locked in the same order
  51267. ** by all database connections. The p->pNext is a list of other
  51268. ** Btrees belonging to the same database connection as the p Btree
  51269. ** which need to be locked after p. If we cannot get a lock on
  51270. ** p, then first unlock all of the others on p->pNext, then wait
  51271. ** for the lock to become available on p, then relock all of the
  51272. ** subsequent Btrees that desire a lock.
  51273. */
  51274. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  51275. /* Some basic sanity checking on the Btree. The list of Btrees
  51276. ** connected by pNext and pPrev should be in sorted order by
  51277. ** Btree.pBt value. All elements of the list should belong to
  51278. ** the same connection. Only shared Btrees are on the list. */
  51279. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  51280. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  51281. assert( p->pNext==0 || p->pNext->db==p->db );
  51282. assert( p->pPrev==0 || p->pPrev->db==p->db );
  51283. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  51284. /* Check for locking consistency */
  51285. assert( !p->locked || p->wantToLock>0 );
  51286. assert( p->sharable || p->wantToLock==0 );
  51287. /* We should already hold a lock on the database connection */
  51288. assert( sqlite3_mutex_held(p->db->mutex) );
  51289. /* Unless the database is sharable and unlocked, then BtShared.db
  51290. ** should already be set correctly. */
  51291. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  51292. if( !p->sharable ) return;
  51293. p->wantToLock++;
  51294. if( p->locked ) return;
  51295. btreeLockCarefully(p);
  51296. }
  51297. /* This is a helper function for sqlite3BtreeLock(). By moving
  51298. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  51299. ** into this routine, we avoid unnecessary stack pointer changes
  51300. ** and thus help the sqlite3BtreeLock() routine to run much faster
  51301. ** in the common case.
  51302. */
  51303. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  51304. Btree *pLater;
  51305. /* In most cases, we should be able to acquire the lock we
  51306. ** want without having to go through the ascending lock
  51307. ** procedure that follows. Just be sure not to block.
  51308. */
  51309. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  51310. p->pBt->db = p->db;
  51311. p->locked = 1;
  51312. return;
  51313. }
  51314. /* To avoid deadlock, first release all locks with a larger
  51315. ** BtShared address. Then acquire our lock. Then reacquire
  51316. ** the other BtShared locks that we used to hold in ascending
  51317. ** order.
  51318. */
  51319. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  51320. assert( pLater->sharable );
  51321. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  51322. assert( !pLater->locked || pLater->wantToLock>0 );
  51323. if( pLater->locked ){
  51324. unlockBtreeMutex(pLater);
  51325. }
  51326. }
  51327. lockBtreeMutex(p);
  51328. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  51329. if( pLater->wantToLock ){
  51330. lockBtreeMutex(pLater);
  51331. }
  51332. }
  51333. }
  51334. /*
  51335. ** Exit the recursive mutex on a Btree.
  51336. */
  51337. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  51338. assert( sqlite3_mutex_held(p->db->mutex) );
  51339. if( p->sharable ){
  51340. assert( p->wantToLock>0 );
  51341. p->wantToLock--;
  51342. if( p->wantToLock==0 ){
  51343. unlockBtreeMutex(p);
  51344. }
  51345. }
  51346. }
  51347. #ifndef NDEBUG
  51348. /*
  51349. ** Return true if the BtShared mutex is held on the btree, or if the
  51350. ** B-Tree is not marked as sharable.
  51351. **
  51352. ** This routine is used only from within assert() statements.
  51353. */
  51354. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  51355. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  51356. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  51357. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  51358. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  51359. return (p->sharable==0 || p->locked);
  51360. }
  51361. #endif
  51362. #ifndef SQLITE_OMIT_INCRBLOB
  51363. /*
  51364. ** Enter and leave a mutex on a Btree given a cursor owned by that
  51365. ** Btree. These entry points are used by incremental I/O and can be
  51366. ** omitted if that module is not used.
  51367. */
  51368. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  51369. sqlite3BtreeEnter(pCur->pBtree);
  51370. }
  51371. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  51372. sqlite3BtreeLeave(pCur->pBtree);
  51373. }
  51374. #endif /* SQLITE_OMIT_INCRBLOB */
  51375. /*
  51376. ** Enter the mutex on every Btree associated with a database
  51377. ** connection. This is needed (for example) prior to parsing
  51378. ** a statement since we will be comparing table and column names
  51379. ** against all schemas and we do not want those schemas being
  51380. ** reset out from under us.
  51381. **
  51382. ** There is a corresponding leave-all procedures.
  51383. **
  51384. ** Enter the mutexes in accending order by BtShared pointer address
  51385. ** to avoid the possibility of deadlock when two threads with
  51386. ** two or more btrees in common both try to lock all their btrees
  51387. ** at the same instant.
  51388. */
  51389. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  51390. int i;
  51391. Btree *p;
  51392. assert( sqlite3_mutex_held(db->mutex) );
  51393. for(i=0; i<db->nDb; i++){
  51394. p = db->aDb[i].pBt;
  51395. if( p ) sqlite3BtreeEnter(p);
  51396. }
  51397. }
  51398. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  51399. int i;
  51400. Btree *p;
  51401. assert( sqlite3_mutex_held(db->mutex) );
  51402. for(i=0; i<db->nDb; i++){
  51403. p = db->aDb[i].pBt;
  51404. if( p ) sqlite3BtreeLeave(p);
  51405. }
  51406. }
  51407. /*
  51408. ** Return true if a particular Btree requires a lock. Return FALSE if
  51409. ** no lock is ever required since it is not sharable.
  51410. */
  51411. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  51412. return p->sharable;
  51413. }
  51414. #ifndef NDEBUG
  51415. /*
  51416. ** Return true if the current thread holds the database connection
  51417. ** mutex and all required BtShared mutexes.
  51418. **
  51419. ** This routine is used inside assert() statements only.
  51420. */
  51421. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  51422. int i;
  51423. if( !sqlite3_mutex_held(db->mutex) ){
  51424. return 0;
  51425. }
  51426. for(i=0; i<db->nDb; i++){
  51427. Btree *p;
  51428. p = db->aDb[i].pBt;
  51429. if( p && p->sharable &&
  51430. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  51431. return 0;
  51432. }
  51433. }
  51434. return 1;
  51435. }
  51436. #endif /* NDEBUG */
  51437. #ifndef NDEBUG
  51438. /*
  51439. ** Return true if the correct mutexes are held for accessing the
  51440. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  51441. ** access are:
  51442. **
  51443. ** (1) The mutex on db
  51444. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  51445. **
  51446. ** If pSchema is not NULL, then iDb is computed from pSchema and
  51447. ** db using sqlite3SchemaToIndex().
  51448. */
  51449. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  51450. Btree *p;
  51451. assert( db!=0 );
  51452. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  51453. assert( iDb>=0 && iDb<db->nDb );
  51454. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  51455. if( iDb==1 ) return 1;
  51456. p = db->aDb[iDb].pBt;
  51457. assert( p!=0 );
  51458. return p->sharable==0 || p->locked==1;
  51459. }
  51460. #endif /* NDEBUG */
  51461. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  51462. /*
  51463. ** The following are special cases for mutex enter routines for use
  51464. ** in single threaded applications that use shared cache. Except for
  51465. ** these two routines, all mutex operations are no-ops in that case and
  51466. ** are null #defines in btree.h.
  51467. **
  51468. ** If shared cache is disabled, then all btree mutex routines, including
  51469. ** the ones below, are no-ops and are null #defines in btree.h.
  51470. */
  51471. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  51472. p->pBt->db = p->db;
  51473. }
  51474. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  51475. int i;
  51476. for(i=0; i<db->nDb; i++){
  51477. Btree *p = db->aDb[i].pBt;
  51478. if( p ){
  51479. p->pBt->db = p->db;
  51480. }
  51481. }
  51482. }
  51483. #endif /* if SQLITE_THREADSAFE */
  51484. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  51485. /************** End of btmutex.c *********************************************/
  51486. /************** Begin file btree.c *******************************************/
  51487. /*
  51488. ** 2004 April 6
  51489. **
  51490. ** The author disclaims copyright to this source code. In place of
  51491. ** a legal notice, here is a blessing:
  51492. **
  51493. ** May you do good and not evil.
  51494. ** May you find forgiveness for yourself and forgive others.
  51495. ** May you share freely, never taking more than you give.
  51496. **
  51497. *************************************************************************
  51498. ** This file implements an external (disk-based) database using BTrees.
  51499. ** See the header comment on "btreeInt.h" for additional information.
  51500. ** Including a description of file format and an overview of operation.
  51501. */
  51502. /* #include "btreeInt.h" */
  51503. /*
  51504. ** The header string that appears at the beginning of every
  51505. ** SQLite database.
  51506. */
  51507. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  51508. /*
  51509. ** Set this global variable to 1 to enable tracing using the TRACE
  51510. ** macro.
  51511. */
  51512. #if 0
  51513. int sqlite3BtreeTrace=1; /* True to enable tracing */
  51514. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  51515. #else
  51516. # define TRACE(X)
  51517. #endif
  51518. /*
  51519. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  51520. ** But if the value is zero, make it 65536.
  51521. **
  51522. ** This routine is used to extract the "offset to cell content area" value
  51523. ** from the header of a btree page. If the page size is 65536 and the page
  51524. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  51525. ** This routine makes the necessary adjustment to 65536.
  51526. */
  51527. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  51528. /*
  51529. ** Values passed as the 5th argument to allocateBtreePage()
  51530. */
  51531. #define BTALLOC_ANY 0 /* Allocate any page */
  51532. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  51533. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  51534. /*
  51535. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  51536. ** defined, or 0 if it is. For example:
  51537. **
  51538. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  51539. */
  51540. #ifndef SQLITE_OMIT_AUTOVACUUM
  51541. #define IfNotOmitAV(expr) (expr)
  51542. #else
  51543. #define IfNotOmitAV(expr) 0
  51544. #endif
  51545. #ifndef SQLITE_OMIT_SHARED_CACHE
  51546. /*
  51547. ** A list of BtShared objects that are eligible for participation
  51548. ** in shared cache. This variable has file scope during normal builds,
  51549. ** but the test harness needs to access it so we make it global for
  51550. ** test builds.
  51551. **
  51552. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  51553. */
  51554. #ifdef SQLITE_TEST
  51555. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  51556. #else
  51557. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  51558. #endif
  51559. #endif /* SQLITE_OMIT_SHARED_CACHE */
  51560. #ifndef SQLITE_OMIT_SHARED_CACHE
  51561. /*
  51562. ** Enable or disable the shared pager and schema features.
  51563. **
  51564. ** This routine has no effect on existing database connections.
  51565. ** The shared cache setting effects only future calls to
  51566. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  51567. */
  51568. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
  51569. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  51570. return SQLITE_OK;
  51571. }
  51572. #endif
  51573. #ifdef SQLITE_OMIT_SHARED_CACHE
  51574. /*
  51575. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  51576. ** and clearAllSharedCacheTableLocks()
  51577. ** manipulate entries in the BtShared.pLock linked list used to store
  51578. ** shared-cache table level locks. If the library is compiled with the
  51579. ** shared-cache feature disabled, then there is only ever one user
  51580. ** of each BtShared structure and so this locking is not necessary.
  51581. ** So define the lock related functions as no-ops.
  51582. */
  51583. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  51584. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  51585. #define clearAllSharedCacheTableLocks(a)
  51586. #define downgradeAllSharedCacheTableLocks(a)
  51587. #define hasSharedCacheTableLock(a,b,c,d) 1
  51588. #define hasReadConflicts(a, b) 0
  51589. #endif
  51590. #ifndef SQLITE_OMIT_SHARED_CACHE
  51591. #ifdef SQLITE_DEBUG
  51592. /*
  51593. **** This function is only used as part of an assert() statement. ***
  51594. **
  51595. ** Check to see if pBtree holds the required locks to read or write to the
  51596. ** table with root page iRoot. Return 1 if it does and 0 if not.
  51597. **
  51598. ** For example, when writing to a table with root-page iRoot via
  51599. ** Btree connection pBtree:
  51600. **
  51601. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  51602. **
  51603. ** When writing to an index that resides in a sharable database, the
  51604. ** caller should have first obtained a lock specifying the root page of
  51605. ** the corresponding table. This makes things a bit more complicated,
  51606. ** as this module treats each table as a separate structure. To determine
  51607. ** the table corresponding to the index being written, this
  51608. ** function has to search through the database schema.
  51609. **
  51610. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  51611. ** hold a write-lock on the schema table (root page 1). This is also
  51612. ** acceptable.
  51613. */
  51614. static int hasSharedCacheTableLock(
  51615. Btree *pBtree, /* Handle that must hold lock */
  51616. Pgno iRoot, /* Root page of b-tree */
  51617. int isIndex, /* True if iRoot is the root of an index b-tree */
  51618. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  51619. ){
  51620. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  51621. Pgno iTab = 0;
  51622. BtLock *pLock;
  51623. /* If this database is not shareable, or if the client is reading
  51624. ** and has the read-uncommitted flag set, then no lock is required.
  51625. ** Return true immediately.
  51626. */
  51627. if( (pBtree->sharable==0)
  51628. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  51629. ){
  51630. return 1;
  51631. }
  51632. /* If the client is reading or writing an index and the schema is
  51633. ** not loaded, then it is too difficult to actually check to see if
  51634. ** the correct locks are held. So do not bother - just return true.
  51635. ** This case does not come up very often anyhow.
  51636. */
  51637. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  51638. return 1;
  51639. }
  51640. /* Figure out the root-page that the lock should be held on. For table
  51641. ** b-trees, this is just the root page of the b-tree being read or
  51642. ** written. For index b-trees, it is the root page of the associated
  51643. ** table. */
  51644. if( isIndex ){
  51645. HashElem *p;
  51646. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  51647. Index *pIdx = (Index *)sqliteHashData(p);
  51648. if( pIdx->tnum==(int)iRoot ){
  51649. if( iTab ){
  51650. /* Two or more indexes share the same root page. There must
  51651. ** be imposter tables. So just return true. The assert is not
  51652. ** useful in that case. */
  51653. return 1;
  51654. }
  51655. iTab = pIdx->pTable->tnum;
  51656. }
  51657. }
  51658. }else{
  51659. iTab = iRoot;
  51660. }
  51661. /* Search for the required lock. Either a write-lock on root-page iTab, a
  51662. ** write-lock on the schema table, or (if the client is reading) a
  51663. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  51664. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  51665. if( pLock->pBtree==pBtree
  51666. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  51667. && pLock->eLock>=eLockType
  51668. ){
  51669. return 1;
  51670. }
  51671. }
  51672. /* Failed to find the required lock. */
  51673. return 0;
  51674. }
  51675. #endif /* SQLITE_DEBUG */
  51676. #ifdef SQLITE_DEBUG
  51677. /*
  51678. **** This function may be used as part of assert() statements only. ****
  51679. **
  51680. ** Return true if it would be illegal for pBtree to write into the
  51681. ** table or index rooted at iRoot because other shared connections are
  51682. ** simultaneously reading that same table or index.
  51683. **
  51684. ** It is illegal for pBtree to write if some other Btree object that
  51685. ** shares the same BtShared object is currently reading or writing
  51686. ** the iRoot table. Except, if the other Btree object has the
  51687. ** read-uncommitted flag set, then it is OK for the other object to
  51688. ** have a read cursor.
  51689. **
  51690. ** For example, before writing to any part of the table or index
  51691. ** rooted at page iRoot, one should call:
  51692. **
  51693. ** assert( !hasReadConflicts(pBtree, iRoot) );
  51694. */
  51695. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  51696. BtCursor *p;
  51697. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  51698. if( p->pgnoRoot==iRoot
  51699. && p->pBtree!=pBtree
  51700. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  51701. ){
  51702. return 1;
  51703. }
  51704. }
  51705. return 0;
  51706. }
  51707. #endif /* #ifdef SQLITE_DEBUG */
  51708. /*
  51709. ** Query to see if Btree handle p may obtain a lock of type eLock
  51710. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  51711. ** SQLITE_OK if the lock may be obtained (by calling
  51712. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  51713. */
  51714. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  51715. BtShared *pBt = p->pBt;
  51716. BtLock *pIter;
  51717. assert( sqlite3BtreeHoldsMutex(p) );
  51718. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  51719. assert( p->db!=0 );
  51720. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  51721. /* If requesting a write-lock, then the Btree must have an open write
  51722. ** transaction on this file. And, obviously, for this to be so there
  51723. ** must be an open write transaction on the file itself.
  51724. */
  51725. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  51726. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  51727. /* This routine is a no-op if the shared-cache is not enabled */
  51728. if( !p->sharable ){
  51729. return SQLITE_OK;
  51730. }
  51731. /* If some other connection is holding an exclusive lock, the
  51732. ** requested lock may not be obtained.
  51733. */
  51734. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  51735. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  51736. return SQLITE_LOCKED_SHAREDCACHE;
  51737. }
  51738. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  51739. /* The condition (pIter->eLock!=eLock) in the following if(...)
  51740. ** statement is a simplification of:
  51741. **
  51742. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  51743. **
  51744. ** since we know that if eLock==WRITE_LOCK, then no other connection
  51745. ** may hold a WRITE_LOCK on any table in this file (since there can
  51746. ** only be a single writer).
  51747. */
  51748. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  51749. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  51750. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  51751. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  51752. if( eLock==WRITE_LOCK ){
  51753. assert( p==pBt->pWriter );
  51754. pBt->btsFlags |= BTS_PENDING;
  51755. }
  51756. return SQLITE_LOCKED_SHAREDCACHE;
  51757. }
  51758. }
  51759. return SQLITE_OK;
  51760. }
  51761. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  51762. #ifndef SQLITE_OMIT_SHARED_CACHE
  51763. /*
  51764. ** Add a lock on the table with root-page iTable to the shared-btree used
  51765. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  51766. ** WRITE_LOCK.
  51767. **
  51768. ** This function assumes the following:
  51769. **
  51770. ** (a) The specified Btree object p is connected to a sharable
  51771. ** database (one with the BtShared.sharable flag set), and
  51772. **
  51773. ** (b) No other Btree objects hold a lock that conflicts
  51774. ** with the requested lock (i.e. querySharedCacheTableLock() has
  51775. ** already been called and returned SQLITE_OK).
  51776. **
  51777. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  51778. ** is returned if a malloc attempt fails.
  51779. */
  51780. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  51781. BtShared *pBt = p->pBt;
  51782. BtLock *pLock = 0;
  51783. BtLock *pIter;
  51784. assert( sqlite3BtreeHoldsMutex(p) );
  51785. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  51786. assert( p->db!=0 );
  51787. /* A connection with the read-uncommitted flag set will never try to
  51788. ** obtain a read-lock using this function. The only read-lock obtained
  51789. ** by a connection in read-uncommitted mode is on the sqlite_master
  51790. ** table, and that lock is obtained in BtreeBeginTrans(). */
  51791. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  51792. /* This function should only be called on a sharable b-tree after it
  51793. ** has been determined that no other b-tree holds a conflicting lock. */
  51794. assert( p->sharable );
  51795. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  51796. /* First search the list for an existing lock on this table. */
  51797. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  51798. if( pIter->iTable==iTable && pIter->pBtree==p ){
  51799. pLock = pIter;
  51800. break;
  51801. }
  51802. }
  51803. /* If the above search did not find a BtLock struct associating Btree p
  51804. ** with table iTable, allocate one and link it into the list.
  51805. */
  51806. if( !pLock ){
  51807. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  51808. if( !pLock ){
  51809. return SQLITE_NOMEM;
  51810. }
  51811. pLock->iTable = iTable;
  51812. pLock->pBtree = p;
  51813. pLock->pNext = pBt->pLock;
  51814. pBt->pLock = pLock;
  51815. }
  51816. /* Set the BtLock.eLock variable to the maximum of the current lock
  51817. ** and the requested lock. This means if a write-lock was already held
  51818. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  51819. */
  51820. assert( WRITE_LOCK>READ_LOCK );
  51821. if( eLock>pLock->eLock ){
  51822. pLock->eLock = eLock;
  51823. }
  51824. return SQLITE_OK;
  51825. }
  51826. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  51827. #ifndef SQLITE_OMIT_SHARED_CACHE
  51828. /*
  51829. ** Release all the table locks (locks obtained via calls to
  51830. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  51831. **
  51832. ** This function assumes that Btree p has an open read or write
  51833. ** transaction. If it does not, then the BTS_PENDING flag
  51834. ** may be incorrectly cleared.
  51835. */
  51836. static void clearAllSharedCacheTableLocks(Btree *p){
  51837. BtShared *pBt = p->pBt;
  51838. BtLock **ppIter = &pBt->pLock;
  51839. assert( sqlite3BtreeHoldsMutex(p) );
  51840. assert( p->sharable || 0==*ppIter );
  51841. assert( p->inTrans>0 );
  51842. while( *ppIter ){
  51843. BtLock *pLock = *ppIter;
  51844. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  51845. assert( pLock->pBtree->inTrans>=pLock->eLock );
  51846. if( pLock->pBtree==p ){
  51847. *ppIter = pLock->pNext;
  51848. assert( pLock->iTable!=1 || pLock==&p->lock );
  51849. if( pLock->iTable!=1 ){
  51850. sqlite3_free(pLock);
  51851. }
  51852. }else{
  51853. ppIter = &pLock->pNext;
  51854. }
  51855. }
  51856. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  51857. if( pBt->pWriter==p ){
  51858. pBt->pWriter = 0;
  51859. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  51860. }else if( pBt->nTransaction==2 ){
  51861. /* This function is called when Btree p is concluding its
  51862. ** transaction. If there currently exists a writer, and p is not
  51863. ** that writer, then the number of locks held by connections other
  51864. ** than the writer must be about to drop to zero. In this case
  51865. ** set the BTS_PENDING flag to 0.
  51866. **
  51867. ** If there is not currently a writer, then BTS_PENDING must
  51868. ** be zero already. So this next line is harmless in that case.
  51869. */
  51870. pBt->btsFlags &= ~BTS_PENDING;
  51871. }
  51872. }
  51873. /*
  51874. ** This function changes all write-locks held by Btree p into read-locks.
  51875. */
  51876. static void downgradeAllSharedCacheTableLocks(Btree *p){
  51877. BtShared *pBt = p->pBt;
  51878. if( pBt->pWriter==p ){
  51879. BtLock *pLock;
  51880. pBt->pWriter = 0;
  51881. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  51882. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  51883. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  51884. pLock->eLock = READ_LOCK;
  51885. }
  51886. }
  51887. }
  51888. #endif /* SQLITE_OMIT_SHARED_CACHE */
  51889. static void releasePage(MemPage *pPage); /* Forward reference */
  51890. /*
  51891. ***** This routine is used inside of assert() only ****
  51892. **
  51893. ** Verify that the cursor holds the mutex on its BtShared
  51894. */
  51895. #ifdef SQLITE_DEBUG
  51896. static int cursorHoldsMutex(BtCursor *p){
  51897. return sqlite3_mutex_held(p->pBt->mutex);
  51898. }
  51899. #endif
  51900. /*
  51901. ** Invalidate the overflow cache of the cursor passed as the first argument.
  51902. ** on the shared btree structure pBt.
  51903. */
  51904. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  51905. /*
  51906. ** Invalidate the overflow page-list cache for all cursors opened
  51907. ** on the shared btree structure pBt.
  51908. */
  51909. static void invalidateAllOverflowCache(BtShared *pBt){
  51910. BtCursor *p;
  51911. assert( sqlite3_mutex_held(pBt->mutex) );
  51912. for(p=pBt->pCursor; p; p=p->pNext){
  51913. invalidateOverflowCache(p);
  51914. }
  51915. }
  51916. #ifndef SQLITE_OMIT_INCRBLOB
  51917. /*
  51918. ** This function is called before modifying the contents of a table
  51919. ** to invalidate any incrblob cursors that are open on the
  51920. ** row or one of the rows being modified.
  51921. **
  51922. ** If argument isClearTable is true, then the entire contents of the
  51923. ** table is about to be deleted. In this case invalidate all incrblob
  51924. ** cursors open on any row within the table with root-page pgnoRoot.
  51925. **
  51926. ** Otherwise, if argument isClearTable is false, then the row with
  51927. ** rowid iRow is being replaced or deleted. In this case invalidate
  51928. ** only those incrblob cursors open on that specific row.
  51929. */
  51930. static void invalidateIncrblobCursors(
  51931. Btree *pBtree, /* The database file to check */
  51932. i64 iRow, /* The rowid that might be changing */
  51933. int isClearTable /* True if all rows are being deleted */
  51934. ){
  51935. BtCursor *p;
  51936. if( pBtree->hasIncrblobCur==0 ) return;
  51937. assert( sqlite3BtreeHoldsMutex(pBtree) );
  51938. pBtree->hasIncrblobCur = 0;
  51939. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  51940. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  51941. pBtree->hasIncrblobCur = 1;
  51942. if( isClearTable || p->info.nKey==iRow ){
  51943. p->eState = CURSOR_INVALID;
  51944. }
  51945. }
  51946. }
  51947. }
  51948. #else
  51949. /* Stub function when INCRBLOB is omitted */
  51950. #define invalidateIncrblobCursors(x,y,z)
  51951. #endif /* SQLITE_OMIT_INCRBLOB */
  51952. /*
  51953. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  51954. ** when a page that previously contained data becomes a free-list leaf
  51955. ** page.
  51956. **
  51957. ** The BtShared.pHasContent bitvec exists to work around an obscure
  51958. ** bug caused by the interaction of two useful IO optimizations surrounding
  51959. ** free-list leaf pages:
  51960. **
  51961. ** 1) When all data is deleted from a page and the page becomes
  51962. ** a free-list leaf page, the page is not written to the database
  51963. ** (as free-list leaf pages contain no meaningful data). Sometimes
  51964. ** such a page is not even journalled (as it will not be modified,
  51965. ** why bother journalling it?).
  51966. **
  51967. ** 2) When a free-list leaf page is reused, its content is not read
  51968. ** from the database or written to the journal file (why should it
  51969. ** be, if it is not at all meaningful?).
  51970. **
  51971. ** By themselves, these optimizations work fine and provide a handy
  51972. ** performance boost to bulk delete or insert operations. However, if
  51973. ** a page is moved to the free-list and then reused within the same
  51974. ** transaction, a problem comes up. If the page is not journalled when
  51975. ** it is moved to the free-list and it is also not journalled when it
  51976. ** is extracted from the free-list and reused, then the original data
  51977. ** may be lost. In the event of a rollback, it may not be possible
  51978. ** to restore the database to its original configuration.
  51979. **
  51980. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  51981. ** moved to become a free-list leaf page, the corresponding bit is
  51982. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  51983. ** optimization 2 above is omitted if the corresponding bit is already
  51984. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  51985. ** at the end of every transaction.
  51986. */
  51987. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  51988. int rc = SQLITE_OK;
  51989. if( !pBt->pHasContent ){
  51990. assert( pgno<=pBt->nPage );
  51991. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  51992. if( !pBt->pHasContent ){
  51993. rc = SQLITE_NOMEM;
  51994. }
  51995. }
  51996. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  51997. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  51998. }
  51999. return rc;
  52000. }
  52001. /*
  52002. ** Query the BtShared.pHasContent vector.
  52003. **
  52004. ** This function is called when a free-list leaf page is removed from the
  52005. ** free-list for reuse. It returns false if it is safe to retrieve the
  52006. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  52007. */
  52008. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  52009. Bitvec *p = pBt->pHasContent;
  52010. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  52011. }
  52012. /*
  52013. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  52014. ** invoked at the conclusion of each write-transaction.
  52015. */
  52016. static void btreeClearHasContent(BtShared *pBt){
  52017. sqlite3BitvecDestroy(pBt->pHasContent);
  52018. pBt->pHasContent = 0;
  52019. }
  52020. /*
  52021. ** Release all of the apPage[] pages for a cursor.
  52022. */
  52023. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  52024. int i;
  52025. for(i=0; i<=pCur->iPage; i++){
  52026. releasePage(pCur->apPage[i]);
  52027. pCur->apPage[i] = 0;
  52028. }
  52029. pCur->iPage = -1;
  52030. }
  52031. /*
  52032. ** The cursor passed as the only argument must point to a valid entry
  52033. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  52034. ** function saves the current cursor key in variables pCur->nKey and
  52035. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  52036. ** code otherwise.
  52037. **
  52038. ** If the cursor is open on an intkey table, then the integer key
  52039. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  52040. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  52041. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  52042. ** the key.
  52043. */
  52044. static int saveCursorKey(BtCursor *pCur){
  52045. int rc;
  52046. assert( CURSOR_VALID==pCur->eState );
  52047. assert( 0==pCur->pKey );
  52048. assert( cursorHoldsMutex(pCur) );
  52049. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  52050. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  52051. /* If this is an intKey table, then the above call to BtreeKeySize()
  52052. ** stores the integer key in pCur->nKey. In this case this value is
  52053. ** all that is required. Otherwise, if pCur is not open on an intKey
  52054. ** table, then malloc space for and store the pCur->nKey bytes of key
  52055. ** data. */
  52056. if( 0==pCur->curIntKey ){
  52057. void *pKey = sqlite3Malloc( pCur->nKey );
  52058. if( pKey ){
  52059. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  52060. if( rc==SQLITE_OK ){
  52061. pCur->pKey = pKey;
  52062. }else{
  52063. sqlite3_free(pKey);
  52064. }
  52065. }else{
  52066. rc = SQLITE_NOMEM;
  52067. }
  52068. }
  52069. assert( !pCur->curIntKey || !pCur->pKey );
  52070. return rc;
  52071. }
  52072. /*
  52073. ** Save the current cursor position in the variables BtCursor.nKey
  52074. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  52075. **
  52076. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  52077. ** prior to calling this routine.
  52078. */
  52079. static int saveCursorPosition(BtCursor *pCur){
  52080. int rc;
  52081. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  52082. assert( 0==pCur->pKey );
  52083. assert( cursorHoldsMutex(pCur) );
  52084. if( pCur->eState==CURSOR_SKIPNEXT ){
  52085. pCur->eState = CURSOR_VALID;
  52086. }else{
  52087. pCur->skipNext = 0;
  52088. }
  52089. rc = saveCursorKey(pCur);
  52090. if( rc==SQLITE_OK ){
  52091. btreeReleaseAllCursorPages(pCur);
  52092. pCur->eState = CURSOR_REQUIRESEEK;
  52093. }
  52094. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  52095. return rc;
  52096. }
  52097. /* Forward reference */
  52098. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  52099. /*
  52100. ** Save the positions of all cursors (except pExcept) that are open on
  52101. ** the table with root-page iRoot. "Saving the cursor position" means that
  52102. ** the location in the btree is remembered in such a way that it can be
  52103. ** moved back to the same spot after the btree has been modified. This
  52104. ** routine is called just before cursor pExcept is used to modify the
  52105. ** table, for example in BtreeDelete() or BtreeInsert().
  52106. **
  52107. ** If there are two or more cursors on the same btree, then all such
  52108. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  52109. ** routine enforces that rule. This routine only needs to be called in
  52110. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  52111. **
  52112. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  52113. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  52114. ** pointless call to this routine.
  52115. **
  52116. ** Implementation note: This routine merely checks to see if any cursors
  52117. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  52118. ** event that cursors are in need to being saved.
  52119. */
  52120. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  52121. BtCursor *p;
  52122. assert( sqlite3_mutex_held(pBt->mutex) );
  52123. assert( pExcept==0 || pExcept->pBt==pBt );
  52124. for(p=pBt->pCursor; p; p=p->pNext){
  52125. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  52126. }
  52127. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  52128. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  52129. return SQLITE_OK;
  52130. }
  52131. /* This helper routine to saveAllCursors does the actual work of saving
  52132. ** the cursors if and when a cursor is found that actually requires saving.
  52133. ** The common case is that no cursors need to be saved, so this routine is
  52134. ** broken out from its caller to avoid unnecessary stack pointer movement.
  52135. */
  52136. static int SQLITE_NOINLINE saveCursorsOnList(
  52137. BtCursor *p, /* The first cursor that needs saving */
  52138. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  52139. BtCursor *pExcept /* Do not save this cursor */
  52140. ){
  52141. do{
  52142. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  52143. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  52144. int rc = saveCursorPosition(p);
  52145. if( SQLITE_OK!=rc ){
  52146. return rc;
  52147. }
  52148. }else{
  52149. testcase( p->iPage>0 );
  52150. btreeReleaseAllCursorPages(p);
  52151. }
  52152. }
  52153. p = p->pNext;
  52154. }while( p );
  52155. return SQLITE_OK;
  52156. }
  52157. /*
  52158. ** Clear the current cursor position.
  52159. */
  52160. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  52161. assert( cursorHoldsMutex(pCur) );
  52162. sqlite3_free(pCur->pKey);
  52163. pCur->pKey = 0;
  52164. pCur->eState = CURSOR_INVALID;
  52165. }
  52166. /*
  52167. ** In this version of BtreeMoveto, pKey is a packed index record
  52168. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  52169. ** record and then call BtreeMovetoUnpacked() to do the work.
  52170. */
  52171. static int btreeMoveto(
  52172. BtCursor *pCur, /* Cursor open on the btree to be searched */
  52173. const void *pKey, /* Packed key if the btree is an index */
  52174. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  52175. int bias, /* Bias search to the high end */
  52176. int *pRes /* Write search results here */
  52177. ){
  52178. int rc; /* Status code */
  52179. UnpackedRecord *pIdxKey; /* Unpacked index key */
  52180. char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
  52181. char *pFree = 0;
  52182. if( pKey ){
  52183. assert( nKey==(i64)(int)nKey );
  52184. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  52185. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  52186. );
  52187. if( pIdxKey==0 ) return SQLITE_NOMEM;
  52188. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  52189. if( pIdxKey->nField==0 ){
  52190. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  52191. return SQLITE_CORRUPT_BKPT;
  52192. }
  52193. }else{
  52194. pIdxKey = 0;
  52195. }
  52196. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  52197. if( pFree ){
  52198. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  52199. }
  52200. return rc;
  52201. }
  52202. /*
  52203. ** Restore the cursor to the position it was in (or as close to as possible)
  52204. ** when saveCursorPosition() was called. Note that this call deletes the
  52205. ** saved position info stored by saveCursorPosition(), so there can be
  52206. ** at most one effective restoreCursorPosition() call after each
  52207. ** saveCursorPosition().
  52208. */
  52209. static int btreeRestoreCursorPosition(BtCursor *pCur){
  52210. int rc;
  52211. int skipNext;
  52212. assert( cursorHoldsMutex(pCur) );
  52213. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  52214. if( pCur->eState==CURSOR_FAULT ){
  52215. return pCur->skipNext;
  52216. }
  52217. pCur->eState = CURSOR_INVALID;
  52218. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  52219. if( rc==SQLITE_OK ){
  52220. sqlite3_free(pCur->pKey);
  52221. pCur->pKey = 0;
  52222. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  52223. pCur->skipNext |= skipNext;
  52224. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  52225. pCur->eState = CURSOR_SKIPNEXT;
  52226. }
  52227. }
  52228. return rc;
  52229. }
  52230. #define restoreCursorPosition(p) \
  52231. (p->eState>=CURSOR_REQUIRESEEK ? \
  52232. btreeRestoreCursorPosition(p) : \
  52233. SQLITE_OK)
  52234. /*
  52235. ** Determine whether or not a cursor has moved from the position where
  52236. ** it was last placed, or has been invalidated for any other reason.
  52237. ** Cursors can move when the row they are pointing at is deleted out
  52238. ** from under them, for example. Cursor might also move if a btree
  52239. ** is rebalanced.
  52240. **
  52241. ** Calling this routine with a NULL cursor pointer returns false.
  52242. **
  52243. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  52244. ** back to where it ought to be if this routine returns true.
  52245. */
  52246. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  52247. return pCur->eState!=CURSOR_VALID;
  52248. }
  52249. /*
  52250. ** This routine restores a cursor back to its original position after it
  52251. ** has been moved by some outside activity (such as a btree rebalance or
  52252. ** a row having been deleted out from under the cursor).
  52253. **
  52254. ** On success, the *pDifferentRow parameter is false if the cursor is left
  52255. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  52256. ** was pointing to has been deleted, forcing the cursor to point to some
  52257. ** nearby row.
  52258. **
  52259. ** This routine should only be called for a cursor that just returned
  52260. ** TRUE from sqlite3BtreeCursorHasMoved().
  52261. */
  52262. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  52263. int rc;
  52264. assert( pCur!=0 );
  52265. assert( pCur->eState!=CURSOR_VALID );
  52266. rc = restoreCursorPosition(pCur);
  52267. if( rc ){
  52268. *pDifferentRow = 1;
  52269. return rc;
  52270. }
  52271. if( pCur->eState!=CURSOR_VALID ){
  52272. *pDifferentRow = 1;
  52273. }else{
  52274. assert( pCur->skipNext==0 );
  52275. *pDifferentRow = 0;
  52276. }
  52277. return SQLITE_OK;
  52278. }
  52279. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  52280. /*
  52281. ** Provide hints to the cursor. The particular hint given (and the type
  52282. ** and number of the varargs parameters) is determined by the eHintType
  52283. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  52284. */
  52285. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  52286. /* Used only by system that substitute their own storage engine */
  52287. }
  52288. #endif
  52289. /*
  52290. ** Provide flag hints to the cursor.
  52291. */
  52292. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  52293. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  52294. pCur->hints = x;
  52295. }
  52296. #ifndef SQLITE_OMIT_AUTOVACUUM
  52297. /*
  52298. ** Given a page number of a regular database page, return the page
  52299. ** number for the pointer-map page that contains the entry for the
  52300. ** input page number.
  52301. **
  52302. ** Return 0 (not a valid page) for pgno==1 since there is
  52303. ** no pointer map associated with page 1. The integrity_check logic
  52304. ** requires that ptrmapPageno(*,1)!=1.
  52305. */
  52306. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  52307. int nPagesPerMapPage;
  52308. Pgno iPtrMap, ret;
  52309. assert( sqlite3_mutex_held(pBt->mutex) );
  52310. if( pgno<2 ) return 0;
  52311. nPagesPerMapPage = (pBt->usableSize/5)+1;
  52312. iPtrMap = (pgno-2)/nPagesPerMapPage;
  52313. ret = (iPtrMap*nPagesPerMapPage) + 2;
  52314. if( ret==PENDING_BYTE_PAGE(pBt) ){
  52315. ret++;
  52316. }
  52317. return ret;
  52318. }
  52319. /*
  52320. ** Write an entry into the pointer map.
  52321. **
  52322. ** This routine updates the pointer map entry for page number 'key'
  52323. ** so that it maps to type 'eType' and parent page number 'pgno'.
  52324. **
  52325. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  52326. ** a no-op. If an error occurs, the appropriate error code is written
  52327. ** into *pRC.
  52328. */
  52329. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  52330. DbPage *pDbPage; /* The pointer map page */
  52331. u8 *pPtrmap; /* The pointer map data */
  52332. Pgno iPtrmap; /* The pointer map page number */
  52333. int offset; /* Offset in pointer map page */
  52334. int rc; /* Return code from subfunctions */
  52335. if( *pRC ) return;
  52336. assert( sqlite3_mutex_held(pBt->mutex) );
  52337. /* The master-journal page number must never be used as a pointer map page */
  52338. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  52339. assert( pBt->autoVacuum );
  52340. if( key==0 ){
  52341. *pRC = SQLITE_CORRUPT_BKPT;
  52342. return;
  52343. }
  52344. iPtrmap = PTRMAP_PAGENO(pBt, key);
  52345. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  52346. if( rc!=SQLITE_OK ){
  52347. *pRC = rc;
  52348. return;
  52349. }
  52350. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  52351. if( offset<0 ){
  52352. *pRC = SQLITE_CORRUPT_BKPT;
  52353. goto ptrmap_exit;
  52354. }
  52355. assert( offset <= (int)pBt->usableSize-5 );
  52356. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  52357. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  52358. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  52359. *pRC= rc = sqlite3PagerWrite(pDbPage);
  52360. if( rc==SQLITE_OK ){
  52361. pPtrmap[offset] = eType;
  52362. put4byte(&pPtrmap[offset+1], parent);
  52363. }
  52364. }
  52365. ptrmap_exit:
  52366. sqlite3PagerUnref(pDbPage);
  52367. }
  52368. /*
  52369. ** Read an entry from the pointer map.
  52370. **
  52371. ** This routine retrieves the pointer map entry for page 'key', writing
  52372. ** the type and parent page number to *pEType and *pPgno respectively.
  52373. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  52374. */
  52375. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  52376. DbPage *pDbPage; /* The pointer map page */
  52377. int iPtrmap; /* Pointer map page index */
  52378. u8 *pPtrmap; /* Pointer map page data */
  52379. int offset; /* Offset of entry in pointer map */
  52380. int rc;
  52381. assert( sqlite3_mutex_held(pBt->mutex) );
  52382. iPtrmap = PTRMAP_PAGENO(pBt, key);
  52383. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  52384. if( rc!=0 ){
  52385. return rc;
  52386. }
  52387. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  52388. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  52389. if( offset<0 ){
  52390. sqlite3PagerUnref(pDbPage);
  52391. return SQLITE_CORRUPT_BKPT;
  52392. }
  52393. assert( offset <= (int)pBt->usableSize-5 );
  52394. assert( pEType!=0 );
  52395. *pEType = pPtrmap[offset];
  52396. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  52397. sqlite3PagerUnref(pDbPage);
  52398. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  52399. return SQLITE_OK;
  52400. }
  52401. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  52402. #define ptrmapPut(w,x,y,z,rc)
  52403. #define ptrmapGet(w,x,y,z) SQLITE_OK
  52404. #define ptrmapPutOvflPtr(x, y, rc)
  52405. #endif
  52406. /*
  52407. ** Given a btree page and a cell index (0 means the first cell on
  52408. ** the page, 1 means the second cell, and so forth) return a pointer
  52409. ** to the cell content.
  52410. **
  52411. ** findCellPastPtr() does the same except it skips past the initial
  52412. ** 4-byte child pointer found on interior pages, if there is one.
  52413. **
  52414. ** This routine works only for pages that do not contain overflow cells.
  52415. */
  52416. #define findCell(P,I) \
  52417. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  52418. #define findCellPastPtr(P,I) \
  52419. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  52420. /*
  52421. ** This is common tail processing for btreeParseCellPtr() and
  52422. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  52423. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  52424. ** structure.
  52425. */
  52426. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  52427. MemPage *pPage, /* Page containing the cell */
  52428. u8 *pCell, /* Pointer to the cell text. */
  52429. CellInfo *pInfo /* Fill in this structure */
  52430. ){
  52431. /* If the payload will not fit completely on the local page, we have
  52432. ** to decide how much to store locally and how much to spill onto
  52433. ** overflow pages. The strategy is to minimize the amount of unused
  52434. ** space on overflow pages while keeping the amount of local storage
  52435. ** in between minLocal and maxLocal.
  52436. **
  52437. ** Warning: changing the way overflow payload is distributed in any
  52438. ** way will result in an incompatible file format.
  52439. */
  52440. int minLocal; /* Minimum amount of payload held locally */
  52441. int maxLocal; /* Maximum amount of payload held locally */
  52442. int surplus; /* Overflow payload available for local storage */
  52443. minLocal = pPage->minLocal;
  52444. maxLocal = pPage->maxLocal;
  52445. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  52446. testcase( surplus==maxLocal );
  52447. testcase( surplus==maxLocal+1 );
  52448. if( surplus <= maxLocal ){
  52449. pInfo->nLocal = (u16)surplus;
  52450. }else{
  52451. pInfo->nLocal = (u16)minLocal;
  52452. }
  52453. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  52454. }
  52455. /*
  52456. ** The following routines are implementations of the MemPage.xParseCell()
  52457. ** method.
  52458. **
  52459. ** Parse a cell content block and fill in the CellInfo structure.
  52460. **
  52461. ** btreeParseCellPtr() => table btree leaf nodes
  52462. ** btreeParseCellNoPayload() => table btree internal nodes
  52463. ** btreeParseCellPtrIndex() => index btree nodes
  52464. **
  52465. ** There is also a wrapper function btreeParseCell() that works for
  52466. ** all MemPage types and that references the cell by index rather than
  52467. ** by pointer.
  52468. */
  52469. static void btreeParseCellPtrNoPayload(
  52470. MemPage *pPage, /* Page containing the cell */
  52471. u8 *pCell, /* Pointer to the cell text. */
  52472. CellInfo *pInfo /* Fill in this structure */
  52473. ){
  52474. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52475. assert( pPage->leaf==0 );
  52476. assert( pPage->noPayload );
  52477. assert( pPage->childPtrSize==4 );
  52478. #ifndef SQLITE_DEBUG
  52479. UNUSED_PARAMETER(pPage);
  52480. #endif
  52481. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  52482. pInfo->nPayload = 0;
  52483. pInfo->nLocal = 0;
  52484. pInfo->pPayload = 0;
  52485. return;
  52486. }
  52487. static void btreeParseCellPtr(
  52488. MemPage *pPage, /* Page containing the cell */
  52489. u8 *pCell, /* Pointer to the cell text. */
  52490. CellInfo *pInfo /* Fill in this structure */
  52491. ){
  52492. u8 *pIter; /* For scanning through pCell */
  52493. u32 nPayload; /* Number of bytes of cell payload */
  52494. u64 iKey; /* Extracted Key value */
  52495. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52496. assert( pPage->leaf==0 || pPage->leaf==1 );
  52497. assert( pPage->intKeyLeaf || pPage->noPayload );
  52498. assert( pPage->noPayload==0 );
  52499. assert( pPage->intKeyLeaf );
  52500. assert( pPage->childPtrSize==0 );
  52501. pIter = pCell;
  52502. /* The next block of code is equivalent to:
  52503. **
  52504. ** pIter += getVarint32(pIter, nPayload);
  52505. **
  52506. ** The code is inlined to avoid a function call.
  52507. */
  52508. nPayload = *pIter;
  52509. if( nPayload>=0x80 ){
  52510. u8 *pEnd = &pIter[8];
  52511. nPayload &= 0x7f;
  52512. do{
  52513. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  52514. }while( (*pIter)>=0x80 && pIter<pEnd );
  52515. }
  52516. pIter++;
  52517. /* The next block of code is equivalent to:
  52518. **
  52519. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  52520. **
  52521. ** The code is inlined to avoid a function call.
  52522. */
  52523. iKey = *pIter;
  52524. if( iKey>=0x80 ){
  52525. u8 *pEnd = &pIter[7];
  52526. iKey &= 0x7f;
  52527. while(1){
  52528. iKey = (iKey<<7) | (*++pIter & 0x7f);
  52529. if( (*pIter)<0x80 ) break;
  52530. if( pIter>=pEnd ){
  52531. iKey = (iKey<<8) | *++pIter;
  52532. break;
  52533. }
  52534. }
  52535. }
  52536. pIter++;
  52537. pInfo->nKey = *(i64*)&iKey;
  52538. pInfo->nPayload = nPayload;
  52539. pInfo->pPayload = pIter;
  52540. testcase( nPayload==pPage->maxLocal );
  52541. testcase( nPayload==pPage->maxLocal+1 );
  52542. if( nPayload<=pPage->maxLocal ){
  52543. /* This is the (easy) common case where the entire payload fits
  52544. ** on the local page. No overflow is required.
  52545. */
  52546. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  52547. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  52548. pInfo->nLocal = (u16)nPayload;
  52549. }else{
  52550. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  52551. }
  52552. }
  52553. static void btreeParseCellPtrIndex(
  52554. MemPage *pPage, /* Page containing the cell */
  52555. u8 *pCell, /* Pointer to the cell text. */
  52556. CellInfo *pInfo /* Fill in this structure */
  52557. ){
  52558. u8 *pIter; /* For scanning through pCell */
  52559. u32 nPayload; /* Number of bytes of cell payload */
  52560. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52561. assert( pPage->leaf==0 || pPage->leaf==1 );
  52562. assert( pPage->intKeyLeaf==0 );
  52563. assert( pPage->noPayload==0 );
  52564. pIter = pCell + pPage->childPtrSize;
  52565. nPayload = *pIter;
  52566. if( nPayload>=0x80 ){
  52567. u8 *pEnd = &pIter[8];
  52568. nPayload &= 0x7f;
  52569. do{
  52570. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  52571. }while( *(pIter)>=0x80 && pIter<pEnd );
  52572. }
  52573. pIter++;
  52574. pInfo->nKey = nPayload;
  52575. pInfo->nPayload = nPayload;
  52576. pInfo->pPayload = pIter;
  52577. testcase( nPayload==pPage->maxLocal );
  52578. testcase( nPayload==pPage->maxLocal+1 );
  52579. if( nPayload<=pPage->maxLocal ){
  52580. /* This is the (easy) common case where the entire payload fits
  52581. ** on the local page. No overflow is required.
  52582. */
  52583. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  52584. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  52585. pInfo->nLocal = (u16)nPayload;
  52586. }else{
  52587. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  52588. }
  52589. }
  52590. static void btreeParseCell(
  52591. MemPage *pPage, /* Page containing the cell */
  52592. int iCell, /* The cell index. First cell is 0 */
  52593. CellInfo *pInfo /* Fill in this structure */
  52594. ){
  52595. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  52596. }
  52597. /*
  52598. ** The following routines are implementations of the MemPage.xCellSize
  52599. ** method.
  52600. **
  52601. ** Compute the total number of bytes that a Cell needs in the cell
  52602. ** data area of the btree-page. The return number includes the cell
  52603. ** data header and the local payload, but not any overflow page or
  52604. ** the space used by the cell pointer.
  52605. **
  52606. ** cellSizePtrNoPayload() => table internal nodes
  52607. ** cellSizePtr() => all index nodes & table leaf nodes
  52608. */
  52609. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  52610. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  52611. u8 *pEnd; /* End mark for a varint */
  52612. u32 nSize; /* Size value to return */
  52613. #ifdef SQLITE_DEBUG
  52614. /* The value returned by this function should always be the same as
  52615. ** the (CellInfo.nSize) value found by doing a full parse of the
  52616. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  52617. ** this function verifies that this invariant is not violated. */
  52618. CellInfo debuginfo;
  52619. pPage->xParseCell(pPage, pCell, &debuginfo);
  52620. #endif
  52621. assert( pPage->noPayload==0 );
  52622. nSize = *pIter;
  52623. if( nSize>=0x80 ){
  52624. pEnd = &pIter[8];
  52625. nSize &= 0x7f;
  52626. do{
  52627. nSize = (nSize<<7) | (*++pIter & 0x7f);
  52628. }while( *(pIter)>=0x80 && pIter<pEnd );
  52629. }
  52630. pIter++;
  52631. if( pPage->intKey ){
  52632. /* pIter now points at the 64-bit integer key value, a variable length
  52633. ** integer. The following block moves pIter to point at the first byte
  52634. ** past the end of the key value. */
  52635. pEnd = &pIter[9];
  52636. while( (*pIter++)&0x80 && pIter<pEnd );
  52637. }
  52638. testcase( nSize==pPage->maxLocal );
  52639. testcase( nSize==pPage->maxLocal+1 );
  52640. if( nSize<=pPage->maxLocal ){
  52641. nSize += (u32)(pIter - pCell);
  52642. if( nSize<4 ) nSize = 4;
  52643. }else{
  52644. int minLocal = pPage->minLocal;
  52645. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  52646. testcase( nSize==pPage->maxLocal );
  52647. testcase( nSize==pPage->maxLocal+1 );
  52648. if( nSize>pPage->maxLocal ){
  52649. nSize = minLocal;
  52650. }
  52651. nSize += 4 + (u16)(pIter - pCell);
  52652. }
  52653. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  52654. return (u16)nSize;
  52655. }
  52656. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  52657. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  52658. u8 *pEnd; /* End mark for a varint */
  52659. #ifdef SQLITE_DEBUG
  52660. /* The value returned by this function should always be the same as
  52661. ** the (CellInfo.nSize) value found by doing a full parse of the
  52662. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  52663. ** this function verifies that this invariant is not violated. */
  52664. CellInfo debuginfo;
  52665. pPage->xParseCell(pPage, pCell, &debuginfo);
  52666. #else
  52667. UNUSED_PARAMETER(pPage);
  52668. #endif
  52669. assert( pPage->childPtrSize==4 );
  52670. pEnd = pIter + 9;
  52671. while( (*pIter++)&0x80 && pIter<pEnd );
  52672. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  52673. return (u16)(pIter - pCell);
  52674. }
  52675. #ifdef SQLITE_DEBUG
  52676. /* This variation on cellSizePtr() is used inside of assert() statements
  52677. ** only. */
  52678. static u16 cellSize(MemPage *pPage, int iCell){
  52679. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  52680. }
  52681. #endif
  52682. #ifndef SQLITE_OMIT_AUTOVACUUM
  52683. /*
  52684. ** If the cell pCell, part of page pPage contains a pointer
  52685. ** to an overflow page, insert an entry into the pointer-map
  52686. ** for the overflow page.
  52687. */
  52688. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  52689. CellInfo info;
  52690. if( *pRC ) return;
  52691. assert( pCell!=0 );
  52692. pPage->xParseCell(pPage, pCell, &info);
  52693. if( info.nLocal<info.nPayload ){
  52694. Pgno ovfl = get4byte(&pCell[info.nSize-4]);
  52695. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  52696. }
  52697. }
  52698. #endif
  52699. /*
  52700. ** Defragment the page given. All Cells are moved to the
  52701. ** end of the page and all free space is collected into one
  52702. ** big FreeBlk that occurs in between the header and cell
  52703. ** pointer array and the cell content area.
  52704. **
  52705. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  52706. ** b-tree page so that there are no freeblocks or fragment bytes, all
  52707. ** unused bytes are contained in the unallocated space region, and all
  52708. ** cells are packed tightly at the end of the page.
  52709. */
  52710. static int defragmentPage(MemPage *pPage){
  52711. int i; /* Loop counter */
  52712. int pc; /* Address of the i-th cell */
  52713. int hdr; /* Offset to the page header */
  52714. int size; /* Size of a cell */
  52715. int usableSize; /* Number of usable bytes on a page */
  52716. int cellOffset; /* Offset to the cell pointer array */
  52717. int cbrk; /* Offset to the cell content area */
  52718. int nCell; /* Number of cells on the page */
  52719. unsigned char *data; /* The page data */
  52720. unsigned char *temp; /* Temp area for cell content */
  52721. unsigned char *src; /* Source of content */
  52722. int iCellFirst; /* First allowable cell index */
  52723. int iCellLast; /* Last possible cell index */
  52724. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52725. assert( pPage->pBt!=0 );
  52726. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  52727. assert( pPage->nOverflow==0 );
  52728. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52729. temp = 0;
  52730. src = data = pPage->aData;
  52731. hdr = pPage->hdrOffset;
  52732. cellOffset = pPage->cellOffset;
  52733. nCell = pPage->nCell;
  52734. assert( nCell==get2byte(&data[hdr+3]) );
  52735. usableSize = pPage->pBt->usableSize;
  52736. cbrk = usableSize;
  52737. iCellFirst = cellOffset + 2*nCell;
  52738. iCellLast = usableSize - 4;
  52739. for(i=0; i<nCell; i++){
  52740. u8 *pAddr; /* The i-th cell pointer */
  52741. pAddr = &data[cellOffset + i*2];
  52742. pc = get2byte(pAddr);
  52743. testcase( pc==iCellFirst );
  52744. testcase( pc==iCellLast );
  52745. /* These conditions have already been verified in btreeInitPage()
  52746. ** if PRAGMA cell_size_check=ON.
  52747. */
  52748. if( pc<iCellFirst || pc>iCellLast ){
  52749. return SQLITE_CORRUPT_BKPT;
  52750. }
  52751. assert( pc>=iCellFirst && pc<=iCellLast );
  52752. size = pPage->xCellSize(pPage, &src[pc]);
  52753. cbrk -= size;
  52754. if( cbrk<iCellFirst || pc+size>usableSize ){
  52755. return SQLITE_CORRUPT_BKPT;
  52756. }
  52757. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  52758. testcase( cbrk+size==usableSize );
  52759. testcase( pc+size==usableSize );
  52760. put2byte(pAddr, cbrk);
  52761. if( temp==0 ){
  52762. int x;
  52763. if( cbrk==pc ) continue;
  52764. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  52765. x = get2byte(&data[hdr+5]);
  52766. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  52767. src = temp;
  52768. }
  52769. memcpy(&data[cbrk], &src[pc], size);
  52770. }
  52771. assert( cbrk>=iCellFirst );
  52772. put2byte(&data[hdr+5], cbrk);
  52773. data[hdr+1] = 0;
  52774. data[hdr+2] = 0;
  52775. data[hdr+7] = 0;
  52776. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  52777. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52778. if( cbrk-iCellFirst!=pPage->nFree ){
  52779. return SQLITE_CORRUPT_BKPT;
  52780. }
  52781. return SQLITE_OK;
  52782. }
  52783. /*
  52784. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  52785. ** size. If one can be found, return a pointer to the space and remove it
  52786. ** from the free-list.
  52787. **
  52788. ** If no suitable space can be found on the free-list, return NULL.
  52789. **
  52790. ** This function may detect corruption within pPg. If corruption is
  52791. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  52792. **
  52793. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  52794. ** will be ignored if adding the extra space to the fragmentation count
  52795. ** causes the fragmentation count to exceed 60.
  52796. */
  52797. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  52798. const int hdr = pPg->hdrOffset;
  52799. u8 * const aData = pPg->aData;
  52800. int iAddr = hdr + 1;
  52801. int pc = get2byte(&aData[iAddr]);
  52802. int x;
  52803. int usableSize = pPg->pBt->usableSize;
  52804. assert( pc>0 );
  52805. do{
  52806. int size; /* Size of the free slot */
  52807. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  52808. ** increasing offset. */
  52809. if( pc>usableSize-4 || pc<iAddr+4 ){
  52810. *pRc = SQLITE_CORRUPT_BKPT;
  52811. return 0;
  52812. }
  52813. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  52814. ** freeblock form a big-endian integer which is the size of the freeblock
  52815. ** in bytes, including the 4-byte header. */
  52816. size = get2byte(&aData[pc+2]);
  52817. if( (x = size - nByte)>=0 ){
  52818. testcase( x==4 );
  52819. testcase( x==3 );
  52820. if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
  52821. *pRc = SQLITE_CORRUPT_BKPT;
  52822. return 0;
  52823. }else if( x<4 ){
  52824. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  52825. ** number of bytes in fragments may not exceed 60. */
  52826. if( aData[hdr+7]>57 ) return 0;
  52827. /* Remove the slot from the free-list. Update the number of
  52828. ** fragmented bytes within the page. */
  52829. memcpy(&aData[iAddr], &aData[pc], 2);
  52830. aData[hdr+7] += (u8)x;
  52831. }else{
  52832. /* The slot remains on the free-list. Reduce its size to account
  52833. ** for the portion used by the new allocation. */
  52834. put2byte(&aData[pc+2], x);
  52835. }
  52836. return &aData[pc + x];
  52837. }
  52838. iAddr = pc;
  52839. pc = get2byte(&aData[pc]);
  52840. }while( pc );
  52841. return 0;
  52842. }
  52843. /*
  52844. ** Allocate nByte bytes of space from within the B-Tree page passed
  52845. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  52846. ** of the first byte of allocated space. Return either SQLITE_OK or
  52847. ** an error code (usually SQLITE_CORRUPT).
  52848. **
  52849. ** The caller guarantees that there is sufficient space to make the
  52850. ** allocation. This routine might need to defragment in order to bring
  52851. ** all the space together, however. This routine will avoid using
  52852. ** the first two bytes past the cell pointer area since presumably this
  52853. ** allocation is being made in order to insert a new cell, so we will
  52854. ** also end up needing a new cell pointer.
  52855. */
  52856. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  52857. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  52858. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  52859. int top; /* First byte of cell content area */
  52860. int rc = SQLITE_OK; /* Integer return code */
  52861. int gap; /* First byte of gap between cell pointers and cell content */
  52862. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52863. assert( pPage->pBt );
  52864. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52865. assert( nByte>=0 ); /* Minimum cell size is 4 */
  52866. assert( pPage->nFree>=nByte );
  52867. assert( pPage->nOverflow==0 );
  52868. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  52869. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  52870. gap = pPage->cellOffset + 2*pPage->nCell;
  52871. assert( gap<=65536 );
  52872. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  52873. ** and the reserved space is zero (the usual value for reserved space)
  52874. ** then the cell content offset of an empty page wants to be 65536.
  52875. ** However, that integer is too large to be stored in a 2-byte unsigned
  52876. ** integer, so a value of 0 is used in its place. */
  52877. top = get2byte(&data[hdr+5]);
  52878. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  52879. if( gap>top ){
  52880. if( top==0 && pPage->pBt->usableSize==65536 ){
  52881. top = 65536;
  52882. }else{
  52883. return SQLITE_CORRUPT_BKPT;
  52884. }
  52885. }
  52886. /* If there is enough space between gap and top for one more cell pointer
  52887. ** array entry offset, and if the freelist is not empty, then search the
  52888. ** freelist looking for a free slot big enough to satisfy the request.
  52889. */
  52890. testcase( gap+2==top );
  52891. testcase( gap+1==top );
  52892. testcase( gap==top );
  52893. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  52894. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  52895. if( pSpace ){
  52896. assert( pSpace>=data && (pSpace - data)<65536 );
  52897. *pIdx = (int)(pSpace - data);
  52898. return SQLITE_OK;
  52899. }else if( rc ){
  52900. return rc;
  52901. }
  52902. }
  52903. /* The request could not be fulfilled using a freelist slot. Check
  52904. ** to see if defragmentation is necessary.
  52905. */
  52906. testcase( gap+2+nByte==top );
  52907. if( gap+2+nByte>top ){
  52908. assert( pPage->nCell>0 || CORRUPT_DB );
  52909. rc = defragmentPage(pPage);
  52910. if( rc ) return rc;
  52911. top = get2byteNotZero(&data[hdr+5]);
  52912. assert( gap+nByte<=top );
  52913. }
  52914. /* Allocate memory from the gap in between the cell pointer array
  52915. ** and the cell content area. The btreeInitPage() call has already
  52916. ** validated the freelist. Given that the freelist is valid, there
  52917. ** is no way that the allocation can extend off the end of the page.
  52918. ** The assert() below verifies the previous sentence.
  52919. */
  52920. top -= nByte;
  52921. put2byte(&data[hdr+5], top);
  52922. assert( top+nByte <= (int)pPage->pBt->usableSize );
  52923. *pIdx = top;
  52924. return SQLITE_OK;
  52925. }
  52926. /*
  52927. ** Return a section of the pPage->aData to the freelist.
  52928. ** The first byte of the new free block is pPage->aData[iStart]
  52929. ** and the size of the block is iSize bytes.
  52930. **
  52931. ** Adjacent freeblocks are coalesced.
  52932. **
  52933. ** Note that even though the freeblock list was checked by btreeInitPage(),
  52934. ** that routine will not detect overlap between cells or freeblocks. Nor
  52935. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  52936. ** at the end of the page. So do additional corruption checks inside this
  52937. ** routine and return SQLITE_CORRUPT if any problems are found.
  52938. */
  52939. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  52940. u16 iPtr; /* Address of ptr to next freeblock */
  52941. u16 iFreeBlk; /* Address of the next freeblock */
  52942. u8 hdr; /* Page header size. 0 or 100 */
  52943. u8 nFrag = 0; /* Reduction in fragmentation */
  52944. u16 iOrigSize = iSize; /* Original value of iSize */
  52945. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  52946. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  52947. unsigned char *data = pPage->aData; /* Page content */
  52948. assert( pPage->pBt!=0 );
  52949. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52950. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  52951. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  52952. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52953. assert( iSize>=4 ); /* Minimum cell size is 4 */
  52954. assert( iStart<=iLast );
  52955. /* Overwrite deleted information with zeros when the secure_delete
  52956. ** option is enabled */
  52957. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  52958. memset(&data[iStart], 0, iSize);
  52959. }
  52960. /* The list of freeblocks must be in ascending order. Find the
  52961. ** spot on the list where iStart should be inserted.
  52962. */
  52963. hdr = pPage->hdrOffset;
  52964. iPtr = hdr + 1;
  52965. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  52966. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  52967. }else{
  52968. while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
  52969. if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
  52970. iPtr = iFreeBlk;
  52971. }
  52972. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  52973. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  52974. /* At this point:
  52975. ** iFreeBlk: First freeblock after iStart, or zero if none
  52976. ** iPtr: The address of a pointer to iFreeBlk
  52977. **
  52978. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  52979. */
  52980. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  52981. nFrag = iFreeBlk - iEnd;
  52982. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  52983. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  52984. if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
  52985. iSize = iEnd - iStart;
  52986. iFreeBlk = get2byte(&data[iFreeBlk]);
  52987. }
  52988. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  52989. ** pointer in the page header) then check to see if iStart should be
  52990. ** coalesced onto the end of iPtr.
  52991. */
  52992. if( iPtr>hdr+1 ){
  52993. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  52994. if( iPtrEnd+3>=iStart ){
  52995. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  52996. nFrag += iStart - iPtrEnd;
  52997. iSize = iEnd - iPtr;
  52998. iStart = iPtr;
  52999. }
  53000. }
  53001. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  53002. data[hdr+7] -= nFrag;
  53003. }
  53004. if( iStart==get2byte(&data[hdr+5]) ){
  53005. /* The new freeblock is at the beginning of the cell content area,
  53006. ** so just extend the cell content area rather than create another
  53007. ** freelist entry */
  53008. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  53009. put2byte(&data[hdr+1], iFreeBlk);
  53010. put2byte(&data[hdr+5], iEnd);
  53011. }else{
  53012. /* Insert the new freeblock into the freelist */
  53013. put2byte(&data[iPtr], iStart);
  53014. put2byte(&data[iStart], iFreeBlk);
  53015. put2byte(&data[iStart+2], iSize);
  53016. }
  53017. pPage->nFree += iOrigSize;
  53018. return SQLITE_OK;
  53019. }
  53020. /*
  53021. ** Decode the flags byte (the first byte of the header) for a page
  53022. ** and initialize fields of the MemPage structure accordingly.
  53023. **
  53024. ** Only the following combinations are supported. Anything different
  53025. ** indicates a corrupt database files:
  53026. **
  53027. ** PTF_ZERODATA
  53028. ** PTF_ZERODATA | PTF_LEAF
  53029. ** PTF_LEAFDATA | PTF_INTKEY
  53030. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  53031. */
  53032. static int decodeFlags(MemPage *pPage, int flagByte){
  53033. BtShared *pBt; /* A copy of pPage->pBt */
  53034. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  53035. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53036. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  53037. flagByte &= ~PTF_LEAF;
  53038. pPage->childPtrSize = 4-4*pPage->leaf;
  53039. pPage->xCellSize = cellSizePtr;
  53040. pBt = pPage->pBt;
  53041. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  53042. /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
  53043. ** table b-tree page. */
  53044. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  53045. /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
  53046. ** table b-tree page. */
  53047. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  53048. pPage->intKey = 1;
  53049. if( pPage->leaf ){
  53050. pPage->intKeyLeaf = 1;
  53051. pPage->noPayload = 0;
  53052. pPage->xParseCell = btreeParseCellPtr;
  53053. }else{
  53054. pPage->intKeyLeaf = 0;
  53055. pPage->noPayload = 1;
  53056. pPage->xCellSize = cellSizePtrNoPayload;
  53057. pPage->xParseCell = btreeParseCellPtrNoPayload;
  53058. }
  53059. pPage->maxLocal = pBt->maxLeaf;
  53060. pPage->minLocal = pBt->minLeaf;
  53061. }else if( flagByte==PTF_ZERODATA ){
  53062. /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
  53063. ** index b-tree page. */
  53064. assert( (PTF_ZERODATA)==2 );
  53065. /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
  53066. ** index b-tree page. */
  53067. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  53068. pPage->intKey = 0;
  53069. pPage->intKeyLeaf = 0;
  53070. pPage->noPayload = 0;
  53071. pPage->xParseCell = btreeParseCellPtrIndex;
  53072. pPage->maxLocal = pBt->maxLocal;
  53073. pPage->minLocal = pBt->minLocal;
  53074. }else{
  53075. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  53076. ** an error. */
  53077. return SQLITE_CORRUPT_BKPT;
  53078. }
  53079. pPage->max1bytePayload = pBt->max1bytePayload;
  53080. return SQLITE_OK;
  53081. }
  53082. /*
  53083. ** Initialize the auxiliary information for a disk block.
  53084. **
  53085. ** Return SQLITE_OK on success. If we see that the page does
  53086. ** not contain a well-formed database page, then return
  53087. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  53088. ** guarantee that the page is well-formed. It only shows that
  53089. ** we failed to detect any corruption.
  53090. */
  53091. static int btreeInitPage(MemPage *pPage){
  53092. assert( pPage->pBt!=0 );
  53093. assert( pPage->pBt->db!=0 );
  53094. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53095. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  53096. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  53097. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  53098. if( !pPage->isInit ){
  53099. u16 pc; /* Address of a freeblock within pPage->aData[] */
  53100. u8 hdr; /* Offset to beginning of page header */
  53101. u8 *data; /* Equal to pPage->aData */
  53102. BtShared *pBt; /* The main btree structure */
  53103. int usableSize; /* Amount of usable space on each page */
  53104. u16 cellOffset; /* Offset from start of page to first cell pointer */
  53105. int nFree; /* Number of unused bytes on the page */
  53106. int top; /* First byte of the cell content area */
  53107. int iCellFirst; /* First allowable cell or freeblock offset */
  53108. int iCellLast; /* Last possible cell or freeblock offset */
  53109. pBt = pPage->pBt;
  53110. hdr = pPage->hdrOffset;
  53111. data = pPage->aData;
  53112. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  53113. ** the b-tree page type. */
  53114. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  53115. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  53116. pPage->maskPage = (u16)(pBt->pageSize - 1);
  53117. pPage->nOverflow = 0;
  53118. usableSize = pBt->usableSize;
  53119. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  53120. pPage->aDataEnd = &data[usableSize];
  53121. pPage->aCellIdx = &data[cellOffset];
  53122. pPage->aDataOfst = &data[pPage->childPtrSize];
  53123. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  53124. ** the start of the cell content area. A zero value for this integer is
  53125. ** interpreted as 65536. */
  53126. top = get2byteNotZero(&data[hdr+5]);
  53127. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  53128. ** number of cells on the page. */
  53129. pPage->nCell = get2byte(&data[hdr+3]);
  53130. if( pPage->nCell>MX_CELL(pBt) ){
  53131. /* To many cells for a single page. The page must be corrupt */
  53132. return SQLITE_CORRUPT_BKPT;
  53133. }
  53134. testcase( pPage->nCell==MX_CELL(pBt) );
  53135. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  53136. ** possible for a root page of a table that contains no rows) then the
  53137. ** offset to the cell content area will equal the page size minus the
  53138. ** bytes of reserved space. */
  53139. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  53140. /* A malformed database page might cause us to read past the end
  53141. ** of page when parsing a cell.
  53142. **
  53143. ** The following block of code checks early to see if a cell extends
  53144. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  53145. ** returned if it does.
  53146. */
  53147. iCellFirst = cellOffset + 2*pPage->nCell;
  53148. iCellLast = usableSize - 4;
  53149. if( pBt->db->flags & SQLITE_CellSizeCk ){
  53150. int i; /* Index into the cell pointer array */
  53151. int sz; /* Size of a cell */
  53152. if( !pPage->leaf ) iCellLast--;
  53153. for(i=0; i<pPage->nCell; i++){
  53154. pc = get2byteAligned(&data[cellOffset+i*2]);
  53155. testcase( pc==iCellFirst );
  53156. testcase( pc==iCellLast );
  53157. if( pc<iCellFirst || pc>iCellLast ){
  53158. return SQLITE_CORRUPT_BKPT;
  53159. }
  53160. sz = pPage->xCellSize(pPage, &data[pc]);
  53161. testcase( pc+sz==usableSize );
  53162. if( pc+sz>usableSize ){
  53163. return SQLITE_CORRUPT_BKPT;
  53164. }
  53165. }
  53166. if( !pPage->leaf ) iCellLast++;
  53167. }
  53168. /* Compute the total free space on the page
  53169. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  53170. ** start of the first freeblock on the page, or is zero if there are no
  53171. ** freeblocks. */
  53172. pc = get2byte(&data[hdr+1]);
  53173. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  53174. while( pc>0 ){
  53175. u16 next, size;
  53176. if( pc<iCellFirst || pc>iCellLast ){
  53177. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  53178. ** always be at least one cell before the first freeblock.
  53179. **
  53180. ** Or, the freeblock is off the end of the page
  53181. */
  53182. return SQLITE_CORRUPT_BKPT;
  53183. }
  53184. next = get2byte(&data[pc]);
  53185. size = get2byte(&data[pc+2]);
  53186. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  53187. /* Free blocks must be in ascending order. And the last byte of
  53188. ** the free-block must lie on the database page. */
  53189. return SQLITE_CORRUPT_BKPT;
  53190. }
  53191. nFree = nFree + size;
  53192. pc = next;
  53193. }
  53194. /* At this point, nFree contains the sum of the offset to the start
  53195. ** of the cell-content area plus the number of free bytes within
  53196. ** the cell-content area. If this is greater than the usable-size
  53197. ** of the page, then the page must be corrupted. This check also
  53198. ** serves to verify that the offset to the start of the cell-content
  53199. ** area, according to the page header, lies within the page.
  53200. */
  53201. if( nFree>usableSize ){
  53202. return SQLITE_CORRUPT_BKPT;
  53203. }
  53204. pPage->nFree = (u16)(nFree - iCellFirst);
  53205. pPage->isInit = 1;
  53206. }
  53207. return SQLITE_OK;
  53208. }
  53209. /*
  53210. ** Set up a raw page so that it looks like a database page holding
  53211. ** no entries.
  53212. */
  53213. static void zeroPage(MemPage *pPage, int flags){
  53214. unsigned char *data = pPage->aData;
  53215. BtShared *pBt = pPage->pBt;
  53216. u8 hdr = pPage->hdrOffset;
  53217. u16 first;
  53218. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  53219. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  53220. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  53221. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  53222. assert( sqlite3_mutex_held(pBt->mutex) );
  53223. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  53224. memset(&data[hdr], 0, pBt->usableSize - hdr);
  53225. }
  53226. data[hdr] = (char)flags;
  53227. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  53228. memset(&data[hdr+1], 0, 4);
  53229. data[hdr+7] = 0;
  53230. put2byte(&data[hdr+5], pBt->usableSize);
  53231. pPage->nFree = (u16)(pBt->usableSize - first);
  53232. decodeFlags(pPage, flags);
  53233. pPage->cellOffset = first;
  53234. pPage->aDataEnd = &data[pBt->usableSize];
  53235. pPage->aCellIdx = &data[first];
  53236. pPage->aDataOfst = &data[pPage->childPtrSize];
  53237. pPage->nOverflow = 0;
  53238. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  53239. pPage->maskPage = (u16)(pBt->pageSize - 1);
  53240. pPage->nCell = 0;
  53241. pPage->isInit = 1;
  53242. }
  53243. /*
  53244. ** Convert a DbPage obtained from the pager into a MemPage used by
  53245. ** the btree layer.
  53246. */
  53247. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  53248. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  53249. if( pgno!=pPage->pgno ){
  53250. pPage->aData = sqlite3PagerGetData(pDbPage);
  53251. pPage->pDbPage = pDbPage;
  53252. pPage->pBt = pBt;
  53253. pPage->pgno = pgno;
  53254. pPage->hdrOffset = pgno==1 ? 100 : 0;
  53255. }
  53256. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  53257. return pPage;
  53258. }
  53259. /*
  53260. ** Get a page from the pager. Initialize the MemPage.pBt and
  53261. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  53262. **
  53263. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  53264. ** about the content of the page at this time. So do not go to the disk
  53265. ** to fetch the content. Just fill in the content with zeros for now.
  53266. ** If in the future we call sqlite3PagerWrite() on this page, that
  53267. ** means we have started to be concerned about content and the disk
  53268. ** read should occur at that point.
  53269. */
  53270. static int btreeGetPage(
  53271. BtShared *pBt, /* The btree */
  53272. Pgno pgno, /* Number of the page to fetch */
  53273. MemPage **ppPage, /* Return the page in this parameter */
  53274. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  53275. ){
  53276. int rc;
  53277. DbPage *pDbPage;
  53278. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  53279. assert( sqlite3_mutex_held(pBt->mutex) );
  53280. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  53281. if( rc ) return rc;
  53282. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  53283. return SQLITE_OK;
  53284. }
  53285. /*
  53286. ** Retrieve a page from the pager cache. If the requested page is not
  53287. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  53288. ** MemPage.aData elements if needed.
  53289. */
  53290. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  53291. DbPage *pDbPage;
  53292. assert( sqlite3_mutex_held(pBt->mutex) );
  53293. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  53294. if( pDbPage ){
  53295. return btreePageFromDbPage(pDbPage, pgno, pBt);
  53296. }
  53297. return 0;
  53298. }
  53299. /*
  53300. ** Return the size of the database file in pages. If there is any kind of
  53301. ** error, return ((unsigned int)-1).
  53302. */
  53303. static Pgno btreePagecount(BtShared *pBt){
  53304. return pBt->nPage;
  53305. }
  53306. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  53307. assert( sqlite3BtreeHoldsMutex(p) );
  53308. assert( ((p->pBt->nPage)&0x8000000)==0 );
  53309. return btreePagecount(p->pBt);
  53310. }
  53311. /*
  53312. ** Get a page from the pager and initialize it.
  53313. **
  53314. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  53315. ** call. Do additional sanity checking on the page in this case.
  53316. ** And if the fetch fails, this routine must decrement pCur->iPage.
  53317. **
  53318. ** The page is fetched as read-write unless pCur is not NULL and is
  53319. ** a read-only cursor.
  53320. **
  53321. ** If an error occurs, then *ppPage is undefined. It
  53322. ** may remain unchanged, or it may be set to an invalid value.
  53323. */
  53324. static int getAndInitPage(
  53325. BtShared *pBt, /* The database file */
  53326. Pgno pgno, /* Number of the page to get */
  53327. MemPage **ppPage, /* Write the page pointer here */
  53328. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  53329. int bReadOnly /* True for a read-only page */
  53330. ){
  53331. int rc;
  53332. DbPage *pDbPage;
  53333. assert( sqlite3_mutex_held(pBt->mutex) );
  53334. assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
  53335. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  53336. assert( pCur==0 || pCur->iPage>0 );
  53337. if( pgno>btreePagecount(pBt) ){
  53338. rc = SQLITE_CORRUPT_BKPT;
  53339. goto getAndInitPage_error;
  53340. }
  53341. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  53342. if( rc ){
  53343. goto getAndInitPage_error;
  53344. }
  53345. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  53346. if( (*ppPage)->isInit==0 ){
  53347. btreePageFromDbPage(pDbPage, pgno, pBt);
  53348. rc = btreeInitPage(*ppPage);
  53349. if( rc!=SQLITE_OK ){
  53350. releasePage(*ppPage);
  53351. goto getAndInitPage_error;
  53352. }
  53353. }
  53354. assert( (*ppPage)->pgno==pgno );
  53355. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  53356. /* If obtaining a child page for a cursor, we must verify that the page is
  53357. ** compatible with the root page. */
  53358. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  53359. rc = SQLITE_CORRUPT_BKPT;
  53360. releasePage(*ppPage);
  53361. goto getAndInitPage_error;
  53362. }
  53363. return SQLITE_OK;
  53364. getAndInitPage_error:
  53365. if( pCur ) pCur->iPage--;
  53366. testcase( pgno==0 );
  53367. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  53368. return rc;
  53369. }
  53370. /*
  53371. ** Release a MemPage. This should be called once for each prior
  53372. ** call to btreeGetPage.
  53373. */
  53374. static void releasePageNotNull(MemPage *pPage){
  53375. assert( pPage->aData );
  53376. assert( pPage->pBt );
  53377. assert( pPage->pDbPage!=0 );
  53378. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  53379. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  53380. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53381. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  53382. }
  53383. static void releasePage(MemPage *pPage){
  53384. if( pPage ) releasePageNotNull(pPage);
  53385. }
  53386. /*
  53387. ** Get an unused page.
  53388. **
  53389. ** This works just like btreeGetPage() with the addition:
  53390. **
  53391. ** * If the page is already in use for some other purpose, immediately
  53392. ** release it and return an SQLITE_CURRUPT error.
  53393. ** * Make sure the isInit flag is clear
  53394. */
  53395. static int btreeGetUnusedPage(
  53396. BtShared *pBt, /* The btree */
  53397. Pgno pgno, /* Number of the page to fetch */
  53398. MemPage **ppPage, /* Return the page in this parameter */
  53399. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  53400. ){
  53401. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  53402. if( rc==SQLITE_OK ){
  53403. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  53404. releasePage(*ppPage);
  53405. *ppPage = 0;
  53406. return SQLITE_CORRUPT_BKPT;
  53407. }
  53408. (*ppPage)->isInit = 0;
  53409. }else{
  53410. *ppPage = 0;
  53411. }
  53412. return rc;
  53413. }
  53414. /*
  53415. ** During a rollback, when the pager reloads information into the cache
  53416. ** so that the cache is restored to its original state at the start of
  53417. ** the transaction, for each page restored this routine is called.
  53418. **
  53419. ** This routine needs to reset the extra data section at the end of the
  53420. ** page to agree with the restored data.
  53421. */
  53422. static void pageReinit(DbPage *pData){
  53423. MemPage *pPage;
  53424. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  53425. assert( sqlite3PagerPageRefcount(pData)>0 );
  53426. if( pPage->isInit ){
  53427. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53428. pPage->isInit = 0;
  53429. if( sqlite3PagerPageRefcount(pData)>1 ){
  53430. /* pPage might not be a btree page; it might be an overflow page
  53431. ** or ptrmap page or a free page. In those cases, the following
  53432. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  53433. ** But no harm is done by this. And it is very important that
  53434. ** btreeInitPage() be called on every btree page so we make
  53435. ** the call for every page that comes in for re-initing. */
  53436. btreeInitPage(pPage);
  53437. }
  53438. }
  53439. }
  53440. /*
  53441. ** Invoke the busy handler for a btree.
  53442. */
  53443. static int btreeInvokeBusyHandler(void *pArg){
  53444. BtShared *pBt = (BtShared*)pArg;
  53445. assert( pBt->db );
  53446. assert( sqlite3_mutex_held(pBt->db->mutex) );
  53447. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  53448. }
  53449. /*
  53450. ** Open a database file.
  53451. **
  53452. ** zFilename is the name of the database file. If zFilename is NULL
  53453. ** then an ephemeral database is created. The ephemeral database might
  53454. ** be exclusively in memory, or it might use a disk-based memory cache.
  53455. ** Either way, the ephemeral database will be automatically deleted
  53456. ** when sqlite3BtreeClose() is called.
  53457. **
  53458. ** If zFilename is ":memory:" then an in-memory database is created
  53459. ** that is automatically destroyed when it is closed.
  53460. **
  53461. ** The "flags" parameter is a bitmask that might contain bits like
  53462. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  53463. **
  53464. ** If the database is already opened in the same database connection
  53465. ** and we are in shared cache mode, then the open will fail with an
  53466. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  53467. ** objects in the same database connection since doing so will lead
  53468. ** to problems with locking.
  53469. */
  53470. SQLITE_PRIVATE int sqlite3BtreeOpen(
  53471. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  53472. const char *zFilename, /* Name of the file containing the BTree database */
  53473. sqlite3 *db, /* Associated database handle */
  53474. Btree **ppBtree, /* Pointer to new Btree object written here */
  53475. int flags, /* Options */
  53476. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  53477. ){
  53478. BtShared *pBt = 0; /* Shared part of btree structure */
  53479. Btree *p; /* Handle to return */
  53480. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  53481. int rc = SQLITE_OK; /* Result code from this function */
  53482. u8 nReserve; /* Byte of unused space on each page */
  53483. unsigned char zDbHeader[100]; /* Database header content */
  53484. /* True if opening an ephemeral, temporary database */
  53485. const int isTempDb = zFilename==0 || zFilename[0]==0;
  53486. /* Set the variable isMemdb to true for an in-memory database, or
  53487. ** false for a file-based database.
  53488. */
  53489. #ifdef SQLITE_OMIT_MEMORYDB
  53490. const int isMemdb = 0;
  53491. #else
  53492. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  53493. || (isTempDb && sqlite3TempInMemory(db))
  53494. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  53495. #endif
  53496. assert( db!=0 );
  53497. assert( pVfs!=0 );
  53498. assert( sqlite3_mutex_held(db->mutex) );
  53499. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  53500. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  53501. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  53502. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  53503. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  53504. if( isMemdb ){
  53505. flags |= BTREE_MEMORY;
  53506. }
  53507. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  53508. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  53509. }
  53510. p = sqlite3MallocZero(sizeof(Btree));
  53511. if( !p ){
  53512. return SQLITE_NOMEM;
  53513. }
  53514. p->inTrans = TRANS_NONE;
  53515. p->db = db;
  53516. #ifndef SQLITE_OMIT_SHARED_CACHE
  53517. p->lock.pBtree = p;
  53518. p->lock.iTable = 1;
  53519. #endif
  53520. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  53521. /*
  53522. ** If this Btree is a candidate for shared cache, try to find an
  53523. ** existing BtShared object that we can share with
  53524. */
  53525. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  53526. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  53527. int nFilename = sqlite3Strlen30(zFilename)+1;
  53528. int nFullPathname = pVfs->mxPathname+1;
  53529. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  53530. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  53531. p->sharable = 1;
  53532. if( !zFullPathname ){
  53533. sqlite3_free(p);
  53534. return SQLITE_NOMEM;
  53535. }
  53536. if( isMemdb ){
  53537. memcpy(zFullPathname, zFilename, nFilename);
  53538. }else{
  53539. rc = sqlite3OsFullPathname(pVfs, zFilename,
  53540. nFullPathname, zFullPathname);
  53541. if( rc ){
  53542. sqlite3_free(zFullPathname);
  53543. sqlite3_free(p);
  53544. return rc;
  53545. }
  53546. }
  53547. #if SQLITE_THREADSAFE
  53548. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  53549. sqlite3_mutex_enter(mutexOpen);
  53550. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  53551. sqlite3_mutex_enter(mutexShared);
  53552. #endif
  53553. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  53554. assert( pBt->nRef>0 );
  53555. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  53556. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  53557. int iDb;
  53558. for(iDb=db->nDb-1; iDb>=0; iDb--){
  53559. Btree *pExisting = db->aDb[iDb].pBt;
  53560. if( pExisting && pExisting->pBt==pBt ){
  53561. sqlite3_mutex_leave(mutexShared);
  53562. sqlite3_mutex_leave(mutexOpen);
  53563. sqlite3_free(zFullPathname);
  53564. sqlite3_free(p);
  53565. return SQLITE_CONSTRAINT;
  53566. }
  53567. }
  53568. p->pBt = pBt;
  53569. pBt->nRef++;
  53570. break;
  53571. }
  53572. }
  53573. sqlite3_mutex_leave(mutexShared);
  53574. sqlite3_free(zFullPathname);
  53575. }
  53576. #ifdef SQLITE_DEBUG
  53577. else{
  53578. /* In debug mode, we mark all persistent databases as sharable
  53579. ** even when they are not. This exercises the locking code and
  53580. ** gives more opportunity for asserts(sqlite3_mutex_held())
  53581. ** statements to find locking problems.
  53582. */
  53583. p->sharable = 1;
  53584. }
  53585. #endif
  53586. }
  53587. #endif
  53588. if( pBt==0 ){
  53589. /*
  53590. ** The following asserts make sure that structures used by the btree are
  53591. ** the right size. This is to guard against size changes that result
  53592. ** when compiling on a different architecture.
  53593. */
  53594. assert( sizeof(i64)==8 );
  53595. assert( sizeof(u64)==8 );
  53596. assert( sizeof(u32)==4 );
  53597. assert( sizeof(u16)==2 );
  53598. assert( sizeof(Pgno)==4 );
  53599. pBt = sqlite3MallocZero( sizeof(*pBt) );
  53600. if( pBt==0 ){
  53601. rc = SQLITE_NOMEM;
  53602. goto btree_open_out;
  53603. }
  53604. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  53605. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  53606. if( rc==SQLITE_OK ){
  53607. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  53608. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  53609. }
  53610. if( rc!=SQLITE_OK ){
  53611. goto btree_open_out;
  53612. }
  53613. pBt->openFlags = (u8)flags;
  53614. pBt->db = db;
  53615. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  53616. p->pBt = pBt;
  53617. pBt->pCursor = 0;
  53618. pBt->pPage1 = 0;
  53619. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  53620. #ifdef SQLITE_SECURE_DELETE
  53621. pBt->btsFlags |= BTS_SECURE_DELETE;
  53622. #endif
  53623. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  53624. ** determined by the 2-byte integer located at an offset of 16 bytes from
  53625. ** the beginning of the database file. */
  53626. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  53627. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  53628. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  53629. pBt->pageSize = 0;
  53630. #ifndef SQLITE_OMIT_AUTOVACUUM
  53631. /* If the magic name ":memory:" will create an in-memory database, then
  53632. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  53633. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  53634. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  53635. ** regular file-name. In this case the auto-vacuum applies as per normal.
  53636. */
  53637. if( zFilename && !isMemdb ){
  53638. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  53639. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  53640. }
  53641. #endif
  53642. nReserve = 0;
  53643. }else{
  53644. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  53645. ** determined by the one-byte unsigned integer found at an offset of 20
  53646. ** into the database file header. */
  53647. nReserve = zDbHeader[20];
  53648. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  53649. #ifndef SQLITE_OMIT_AUTOVACUUM
  53650. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  53651. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  53652. #endif
  53653. }
  53654. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  53655. if( rc ) goto btree_open_out;
  53656. pBt->usableSize = pBt->pageSize - nReserve;
  53657. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  53658. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  53659. /* Add the new BtShared object to the linked list sharable BtShareds.
  53660. */
  53661. if( p->sharable ){
  53662. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  53663. pBt->nRef = 1;
  53664. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  53665. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  53666. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  53667. if( pBt->mutex==0 ){
  53668. rc = SQLITE_NOMEM;
  53669. db->mallocFailed = 0;
  53670. goto btree_open_out;
  53671. }
  53672. }
  53673. sqlite3_mutex_enter(mutexShared);
  53674. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  53675. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  53676. sqlite3_mutex_leave(mutexShared);
  53677. }
  53678. #endif
  53679. }
  53680. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  53681. /* If the new Btree uses a sharable pBtShared, then link the new
  53682. ** Btree into the list of all sharable Btrees for the same connection.
  53683. ** The list is kept in ascending order by pBt address.
  53684. */
  53685. if( p->sharable ){
  53686. int i;
  53687. Btree *pSib;
  53688. for(i=0; i<db->nDb; i++){
  53689. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  53690. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  53691. if( p->pBt<pSib->pBt ){
  53692. p->pNext = pSib;
  53693. p->pPrev = 0;
  53694. pSib->pPrev = p;
  53695. }else{
  53696. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  53697. pSib = pSib->pNext;
  53698. }
  53699. p->pNext = pSib->pNext;
  53700. p->pPrev = pSib;
  53701. if( p->pNext ){
  53702. p->pNext->pPrev = p;
  53703. }
  53704. pSib->pNext = p;
  53705. }
  53706. break;
  53707. }
  53708. }
  53709. }
  53710. #endif
  53711. *ppBtree = p;
  53712. btree_open_out:
  53713. if( rc!=SQLITE_OK ){
  53714. if( pBt && pBt->pPager ){
  53715. sqlite3PagerClose(pBt->pPager);
  53716. }
  53717. sqlite3_free(pBt);
  53718. sqlite3_free(p);
  53719. *ppBtree = 0;
  53720. }else{
  53721. /* If the B-Tree was successfully opened, set the pager-cache size to the
  53722. ** default value. Except, when opening on an existing shared pager-cache,
  53723. ** do not change the pager-cache size.
  53724. */
  53725. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  53726. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  53727. }
  53728. }
  53729. if( mutexOpen ){
  53730. assert( sqlite3_mutex_held(mutexOpen) );
  53731. sqlite3_mutex_leave(mutexOpen);
  53732. }
  53733. return rc;
  53734. }
  53735. /*
  53736. ** Decrement the BtShared.nRef counter. When it reaches zero,
  53737. ** remove the BtShared structure from the sharing list. Return
  53738. ** true if the BtShared.nRef counter reaches zero and return
  53739. ** false if it is still positive.
  53740. */
  53741. static int removeFromSharingList(BtShared *pBt){
  53742. #ifndef SQLITE_OMIT_SHARED_CACHE
  53743. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  53744. BtShared *pList;
  53745. int removed = 0;
  53746. assert( sqlite3_mutex_notheld(pBt->mutex) );
  53747. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  53748. sqlite3_mutex_enter(pMaster);
  53749. pBt->nRef--;
  53750. if( pBt->nRef<=0 ){
  53751. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  53752. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  53753. }else{
  53754. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  53755. while( ALWAYS(pList) && pList->pNext!=pBt ){
  53756. pList=pList->pNext;
  53757. }
  53758. if( ALWAYS(pList) ){
  53759. pList->pNext = pBt->pNext;
  53760. }
  53761. }
  53762. if( SQLITE_THREADSAFE ){
  53763. sqlite3_mutex_free(pBt->mutex);
  53764. }
  53765. removed = 1;
  53766. }
  53767. sqlite3_mutex_leave(pMaster);
  53768. return removed;
  53769. #else
  53770. return 1;
  53771. #endif
  53772. }
  53773. /*
  53774. ** Make sure pBt->pTmpSpace points to an allocation of
  53775. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  53776. ** pointer.
  53777. */
  53778. static void allocateTempSpace(BtShared *pBt){
  53779. if( !pBt->pTmpSpace ){
  53780. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  53781. /* One of the uses of pBt->pTmpSpace is to format cells before
  53782. ** inserting them into a leaf page (function fillInCell()). If
  53783. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  53784. ** by the various routines that manipulate binary cells. Which
  53785. ** can mean that fillInCell() only initializes the first 2 or 3
  53786. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  53787. ** it into a database page. This is not actually a problem, but it
  53788. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  53789. ** data is passed to system call write(). So to avoid this error,
  53790. ** zero the first 4 bytes of temp space here.
  53791. **
  53792. ** Also: Provide four bytes of initialized space before the
  53793. ** beginning of pTmpSpace as an area available to prepend the
  53794. ** left-child pointer to the beginning of a cell.
  53795. */
  53796. if( pBt->pTmpSpace ){
  53797. memset(pBt->pTmpSpace, 0, 8);
  53798. pBt->pTmpSpace += 4;
  53799. }
  53800. }
  53801. }
  53802. /*
  53803. ** Free the pBt->pTmpSpace allocation
  53804. */
  53805. static void freeTempSpace(BtShared *pBt){
  53806. if( pBt->pTmpSpace ){
  53807. pBt->pTmpSpace -= 4;
  53808. sqlite3PageFree(pBt->pTmpSpace);
  53809. pBt->pTmpSpace = 0;
  53810. }
  53811. }
  53812. /*
  53813. ** Close an open database and invalidate all cursors.
  53814. */
  53815. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  53816. BtShared *pBt = p->pBt;
  53817. BtCursor *pCur;
  53818. /* Close all cursors opened via this handle. */
  53819. assert( sqlite3_mutex_held(p->db->mutex) );
  53820. sqlite3BtreeEnter(p);
  53821. pCur = pBt->pCursor;
  53822. while( pCur ){
  53823. BtCursor *pTmp = pCur;
  53824. pCur = pCur->pNext;
  53825. if( pTmp->pBtree==p ){
  53826. sqlite3BtreeCloseCursor(pTmp);
  53827. }
  53828. }
  53829. /* Rollback any active transaction and free the handle structure.
  53830. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  53831. ** this handle.
  53832. */
  53833. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  53834. sqlite3BtreeLeave(p);
  53835. /* If there are still other outstanding references to the shared-btree
  53836. ** structure, return now. The remainder of this procedure cleans
  53837. ** up the shared-btree.
  53838. */
  53839. assert( p->wantToLock==0 && p->locked==0 );
  53840. if( !p->sharable || removeFromSharingList(pBt) ){
  53841. /* The pBt is no longer on the sharing list, so we can access
  53842. ** it without having to hold the mutex.
  53843. **
  53844. ** Clean out and delete the BtShared object.
  53845. */
  53846. assert( !pBt->pCursor );
  53847. sqlite3PagerClose(pBt->pPager);
  53848. if( pBt->xFreeSchema && pBt->pSchema ){
  53849. pBt->xFreeSchema(pBt->pSchema);
  53850. }
  53851. sqlite3DbFree(0, pBt->pSchema);
  53852. freeTempSpace(pBt);
  53853. sqlite3_free(pBt);
  53854. }
  53855. #ifndef SQLITE_OMIT_SHARED_CACHE
  53856. assert( p->wantToLock==0 );
  53857. assert( p->locked==0 );
  53858. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  53859. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  53860. #endif
  53861. sqlite3_free(p);
  53862. return SQLITE_OK;
  53863. }
  53864. /*
  53865. ** Change the "soft" limit on the number of pages in the cache.
  53866. ** Unused and unmodified pages will be recycled when the number of
  53867. ** pages in the cache exceeds this soft limit. But the size of the
  53868. ** cache is allowed to grow larger than this limit if it contains
  53869. ** dirty pages or pages still in active use.
  53870. */
  53871. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  53872. BtShared *pBt = p->pBt;
  53873. assert( sqlite3_mutex_held(p->db->mutex) );
  53874. sqlite3BtreeEnter(p);
  53875. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  53876. sqlite3BtreeLeave(p);
  53877. return SQLITE_OK;
  53878. }
  53879. /*
  53880. ** Change the "spill" limit on the number of pages in the cache.
  53881. ** If the number of pages exceeds this limit during a write transaction,
  53882. ** the pager might attempt to "spill" pages to the journal early in
  53883. ** order to free up memory.
  53884. **
  53885. ** The value returned is the current spill size. If zero is passed
  53886. ** as an argument, no changes are made to the spill size setting, so
  53887. ** using mxPage of 0 is a way to query the current spill size.
  53888. */
  53889. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  53890. BtShared *pBt = p->pBt;
  53891. int res;
  53892. assert( sqlite3_mutex_held(p->db->mutex) );
  53893. sqlite3BtreeEnter(p);
  53894. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  53895. sqlite3BtreeLeave(p);
  53896. return res;
  53897. }
  53898. #if SQLITE_MAX_MMAP_SIZE>0
  53899. /*
  53900. ** Change the limit on the amount of the database file that may be
  53901. ** memory mapped.
  53902. */
  53903. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  53904. BtShared *pBt = p->pBt;
  53905. assert( sqlite3_mutex_held(p->db->mutex) );
  53906. sqlite3BtreeEnter(p);
  53907. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  53908. sqlite3BtreeLeave(p);
  53909. return SQLITE_OK;
  53910. }
  53911. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  53912. /*
  53913. ** Change the way data is synced to disk in order to increase or decrease
  53914. ** how well the database resists damage due to OS crashes and power
  53915. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  53916. ** there is a high probability of damage) Level 2 is the default. There
  53917. ** is a very low but non-zero probability of damage. Level 3 reduces the
  53918. ** probability of damage to near zero but with a write performance reduction.
  53919. */
  53920. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  53921. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  53922. Btree *p, /* The btree to set the safety level on */
  53923. unsigned pgFlags /* Various PAGER_* flags */
  53924. ){
  53925. BtShared *pBt = p->pBt;
  53926. assert( sqlite3_mutex_held(p->db->mutex) );
  53927. sqlite3BtreeEnter(p);
  53928. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  53929. sqlite3BtreeLeave(p);
  53930. return SQLITE_OK;
  53931. }
  53932. #endif
  53933. /*
  53934. ** Return TRUE if the given btree is set to safety level 1. In other
  53935. ** words, return TRUE if no sync() occurs on the disk files.
  53936. */
  53937. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  53938. BtShared *pBt = p->pBt;
  53939. int rc;
  53940. assert( sqlite3_mutex_held(p->db->mutex) );
  53941. sqlite3BtreeEnter(p);
  53942. assert( pBt && pBt->pPager );
  53943. rc = sqlite3PagerNosync(pBt->pPager);
  53944. sqlite3BtreeLeave(p);
  53945. return rc;
  53946. }
  53947. /*
  53948. ** Change the default pages size and the number of reserved bytes per page.
  53949. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  53950. ** without changing anything.
  53951. **
  53952. ** The page size must be a power of 2 between 512 and 65536. If the page
  53953. ** size supplied does not meet this constraint then the page size is not
  53954. ** changed.
  53955. **
  53956. ** Page sizes are constrained to be a power of two so that the region
  53957. ** of the database file used for locking (beginning at PENDING_BYTE,
  53958. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  53959. ** at the beginning of a page.
  53960. **
  53961. ** If parameter nReserve is less than zero, then the number of reserved
  53962. ** bytes per page is left unchanged.
  53963. **
  53964. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  53965. ** and autovacuum mode can no longer be changed.
  53966. */
  53967. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  53968. int rc = SQLITE_OK;
  53969. BtShared *pBt = p->pBt;
  53970. assert( nReserve>=-1 && nReserve<=255 );
  53971. sqlite3BtreeEnter(p);
  53972. #if SQLITE_HAS_CODEC
  53973. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  53974. #endif
  53975. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  53976. sqlite3BtreeLeave(p);
  53977. return SQLITE_READONLY;
  53978. }
  53979. if( nReserve<0 ){
  53980. nReserve = pBt->pageSize - pBt->usableSize;
  53981. }
  53982. assert( nReserve>=0 && nReserve<=255 );
  53983. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  53984. ((pageSize-1)&pageSize)==0 ){
  53985. assert( (pageSize & 7)==0 );
  53986. assert( !pBt->pCursor );
  53987. pBt->pageSize = (u32)pageSize;
  53988. freeTempSpace(pBt);
  53989. }
  53990. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  53991. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  53992. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  53993. sqlite3BtreeLeave(p);
  53994. return rc;
  53995. }
  53996. /*
  53997. ** Return the currently defined page size
  53998. */
  53999. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  54000. return p->pBt->pageSize;
  54001. }
  54002. /*
  54003. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  54004. ** may only be called if it is guaranteed that the b-tree mutex is already
  54005. ** held.
  54006. **
  54007. ** This is useful in one special case in the backup API code where it is
  54008. ** known that the shared b-tree mutex is held, but the mutex on the
  54009. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  54010. ** were to be called, it might collide with some other operation on the
  54011. ** database handle that owns *p, causing undefined behavior.
  54012. */
  54013. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  54014. int n;
  54015. assert( sqlite3_mutex_held(p->pBt->mutex) );
  54016. n = p->pBt->pageSize - p->pBt->usableSize;
  54017. return n;
  54018. }
  54019. /*
  54020. ** Return the number of bytes of space at the end of every page that
  54021. ** are intentually left unused. This is the "reserved" space that is
  54022. ** sometimes used by extensions.
  54023. **
  54024. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  54025. ** greater of the current reserved space and the maximum requested
  54026. ** reserve space.
  54027. */
  54028. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  54029. int n;
  54030. sqlite3BtreeEnter(p);
  54031. n = sqlite3BtreeGetReserveNoMutex(p);
  54032. #ifdef SQLITE_HAS_CODEC
  54033. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  54034. #endif
  54035. sqlite3BtreeLeave(p);
  54036. return n;
  54037. }
  54038. /*
  54039. ** Set the maximum page count for a database if mxPage is positive.
  54040. ** No changes are made if mxPage is 0 or negative.
  54041. ** Regardless of the value of mxPage, return the maximum page count.
  54042. */
  54043. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  54044. int n;
  54045. sqlite3BtreeEnter(p);
  54046. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  54047. sqlite3BtreeLeave(p);
  54048. return n;
  54049. }
  54050. /*
  54051. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  54052. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  54053. ** setting after the change.
  54054. */
  54055. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  54056. int b;
  54057. if( p==0 ) return 0;
  54058. sqlite3BtreeEnter(p);
  54059. if( newFlag>=0 ){
  54060. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  54061. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  54062. }
  54063. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  54064. sqlite3BtreeLeave(p);
  54065. return b;
  54066. }
  54067. /*
  54068. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  54069. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  54070. ** is disabled. The default value for the auto-vacuum property is
  54071. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  54072. */
  54073. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  54074. #ifdef SQLITE_OMIT_AUTOVACUUM
  54075. return SQLITE_READONLY;
  54076. #else
  54077. BtShared *pBt = p->pBt;
  54078. int rc = SQLITE_OK;
  54079. u8 av = (u8)autoVacuum;
  54080. sqlite3BtreeEnter(p);
  54081. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  54082. rc = SQLITE_READONLY;
  54083. }else{
  54084. pBt->autoVacuum = av ?1:0;
  54085. pBt->incrVacuum = av==2 ?1:0;
  54086. }
  54087. sqlite3BtreeLeave(p);
  54088. return rc;
  54089. #endif
  54090. }
  54091. /*
  54092. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  54093. ** enabled 1 is returned. Otherwise 0.
  54094. */
  54095. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  54096. #ifdef SQLITE_OMIT_AUTOVACUUM
  54097. return BTREE_AUTOVACUUM_NONE;
  54098. #else
  54099. int rc;
  54100. sqlite3BtreeEnter(p);
  54101. rc = (
  54102. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  54103. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  54104. BTREE_AUTOVACUUM_INCR
  54105. );
  54106. sqlite3BtreeLeave(p);
  54107. return rc;
  54108. #endif
  54109. }
  54110. /*
  54111. ** Get a reference to pPage1 of the database file. This will
  54112. ** also acquire a readlock on that file.
  54113. **
  54114. ** SQLITE_OK is returned on success. If the file is not a
  54115. ** well-formed database file, then SQLITE_CORRUPT is returned.
  54116. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  54117. ** is returned if we run out of memory.
  54118. */
  54119. static int lockBtree(BtShared *pBt){
  54120. int rc; /* Result code from subfunctions */
  54121. MemPage *pPage1; /* Page 1 of the database file */
  54122. int nPage; /* Number of pages in the database */
  54123. int nPageFile = 0; /* Number of pages in the database file */
  54124. int nPageHeader; /* Number of pages in the database according to hdr */
  54125. assert( sqlite3_mutex_held(pBt->mutex) );
  54126. assert( pBt->pPage1==0 );
  54127. rc = sqlite3PagerSharedLock(pBt->pPager);
  54128. if( rc!=SQLITE_OK ) return rc;
  54129. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  54130. if( rc!=SQLITE_OK ) return rc;
  54131. /* Do some checking to help insure the file we opened really is
  54132. ** a valid database file.
  54133. */
  54134. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  54135. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  54136. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  54137. nPage = nPageFile;
  54138. }
  54139. if( nPage>0 ){
  54140. u32 pageSize;
  54141. u32 usableSize;
  54142. u8 *page1 = pPage1->aData;
  54143. rc = SQLITE_NOTADB;
  54144. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  54145. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  54146. ** 61 74 20 33 00. */
  54147. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  54148. goto page1_init_failed;
  54149. }
  54150. #ifdef SQLITE_OMIT_WAL
  54151. if( page1[18]>1 ){
  54152. pBt->btsFlags |= BTS_READ_ONLY;
  54153. }
  54154. if( page1[19]>1 ){
  54155. goto page1_init_failed;
  54156. }
  54157. #else
  54158. if( page1[18]>2 ){
  54159. pBt->btsFlags |= BTS_READ_ONLY;
  54160. }
  54161. if( page1[19]>2 ){
  54162. goto page1_init_failed;
  54163. }
  54164. /* If the write version is set to 2, this database should be accessed
  54165. ** in WAL mode. If the log is not already open, open it now. Then
  54166. ** return SQLITE_OK and return without populating BtShared.pPage1.
  54167. ** The caller detects this and calls this function again. This is
  54168. ** required as the version of page 1 currently in the page1 buffer
  54169. ** may not be the latest version - there may be a newer one in the log
  54170. ** file.
  54171. */
  54172. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  54173. int isOpen = 0;
  54174. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  54175. if( rc!=SQLITE_OK ){
  54176. goto page1_init_failed;
  54177. }else if( isOpen==0 ){
  54178. releasePage(pPage1);
  54179. return SQLITE_OK;
  54180. }
  54181. rc = SQLITE_NOTADB;
  54182. }
  54183. #endif
  54184. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  54185. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  54186. **
  54187. ** The original design allowed these amounts to vary, but as of
  54188. ** version 3.6.0, we require them to be fixed.
  54189. */
  54190. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  54191. goto page1_init_failed;
  54192. }
  54193. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  54194. ** determined by the 2-byte integer located at an offset of 16 bytes from
  54195. ** the beginning of the database file. */
  54196. pageSize = (page1[16]<<8) | (page1[17]<<16);
  54197. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  54198. ** between 512 and 65536 inclusive. */
  54199. if( ((pageSize-1)&pageSize)!=0
  54200. || pageSize>SQLITE_MAX_PAGE_SIZE
  54201. || pageSize<=256
  54202. ){
  54203. goto page1_init_failed;
  54204. }
  54205. assert( (pageSize & 7)==0 );
  54206. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  54207. ** integer at offset 20 is the number of bytes of space at the end of
  54208. ** each page to reserve for extensions.
  54209. **
  54210. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  54211. ** determined by the one-byte unsigned integer found at an offset of 20
  54212. ** into the database file header. */
  54213. usableSize = pageSize - page1[20];
  54214. if( (u32)pageSize!=pBt->pageSize ){
  54215. /* After reading the first page of the database assuming a page size
  54216. ** of BtShared.pageSize, we have discovered that the page-size is
  54217. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  54218. ** zero and return SQLITE_OK. The caller will call this function
  54219. ** again with the correct page-size.
  54220. */
  54221. releasePage(pPage1);
  54222. pBt->usableSize = usableSize;
  54223. pBt->pageSize = pageSize;
  54224. freeTempSpace(pBt);
  54225. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  54226. pageSize-usableSize);
  54227. return rc;
  54228. }
  54229. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  54230. rc = SQLITE_CORRUPT_BKPT;
  54231. goto page1_init_failed;
  54232. }
  54233. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  54234. ** be less than 480. In other words, if the page size is 512, then the
  54235. ** reserved space size cannot exceed 32. */
  54236. if( usableSize<480 ){
  54237. goto page1_init_failed;
  54238. }
  54239. pBt->pageSize = pageSize;
  54240. pBt->usableSize = usableSize;
  54241. #ifndef SQLITE_OMIT_AUTOVACUUM
  54242. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  54243. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  54244. #endif
  54245. }
  54246. /* maxLocal is the maximum amount of payload to store locally for
  54247. ** a cell. Make sure it is small enough so that at least minFanout
  54248. ** cells can will fit on one page. We assume a 10-byte page header.
  54249. ** Besides the payload, the cell must store:
  54250. ** 2-byte pointer to the cell
  54251. ** 4-byte child pointer
  54252. ** 9-byte nKey value
  54253. ** 4-byte nData value
  54254. ** 4-byte overflow page pointer
  54255. ** So a cell consists of a 2-byte pointer, a header which is as much as
  54256. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  54257. ** page pointer.
  54258. */
  54259. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  54260. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  54261. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  54262. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  54263. if( pBt->maxLocal>127 ){
  54264. pBt->max1bytePayload = 127;
  54265. }else{
  54266. pBt->max1bytePayload = (u8)pBt->maxLocal;
  54267. }
  54268. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  54269. pBt->pPage1 = pPage1;
  54270. pBt->nPage = nPage;
  54271. return SQLITE_OK;
  54272. page1_init_failed:
  54273. releasePage(pPage1);
  54274. pBt->pPage1 = 0;
  54275. return rc;
  54276. }
  54277. #ifndef NDEBUG
  54278. /*
  54279. ** Return the number of cursors open on pBt. This is for use
  54280. ** in assert() expressions, so it is only compiled if NDEBUG is not
  54281. ** defined.
  54282. **
  54283. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  54284. ** false then all cursors are counted.
  54285. **
  54286. ** For the purposes of this routine, a cursor is any cursor that
  54287. ** is capable of reading or writing to the database. Cursors that
  54288. ** have been tripped into the CURSOR_FAULT state are not counted.
  54289. */
  54290. static int countValidCursors(BtShared *pBt, int wrOnly){
  54291. BtCursor *pCur;
  54292. int r = 0;
  54293. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  54294. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  54295. && pCur->eState!=CURSOR_FAULT ) r++;
  54296. }
  54297. return r;
  54298. }
  54299. #endif
  54300. /*
  54301. ** If there are no outstanding cursors and we are not in the middle
  54302. ** of a transaction but there is a read lock on the database, then
  54303. ** this routine unrefs the first page of the database file which
  54304. ** has the effect of releasing the read lock.
  54305. **
  54306. ** If there is a transaction in progress, this routine is a no-op.
  54307. */
  54308. static void unlockBtreeIfUnused(BtShared *pBt){
  54309. assert( sqlite3_mutex_held(pBt->mutex) );
  54310. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  54311. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  54312. MemPage *pPage1 = pBt->pPage1;
  54313. assert( pPage1->aData );
  54314. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  54315. pBt->pPage1 = 0;
  54316. releasePageNotNull(pPage1);
  54317. }
  54318. }
  54319. /*
  54320. ** If pBt points to an empty file then convert that empty file
  54321. ** into a new empty database by initializing the first page of
  54322. ** the database.
  54323. */
  54324. static int newDatabase(BtShared *pBt){
  54325. MemPage *pP1;
  54326. unsigned char *data;
  54327. int rc;
  54328. assert( sqlite3_mutex_held(pBt->mutex) );
  54329. if( pBt->nPage>0 ){
  54330. return SQLITE_OK;
  54331. }
  54332. pP1 = pBt->pPage1;
  54333. assert( pP1!=0 );
  54334. data = pP1->aData;
  54335. rc = sqlite3PagerWrite(pP1->pDbPage);
  54336. if( rc ) return rc;
  54337. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  54338. assert( sizeof(zMagicHeader)==16 );
  54339. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  54340. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  54341. data[18] = 1;
  54342. data[19] = 1;
  54343. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  54344. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  54345. data[21] = 64;
  54346. data[22] = 32;
  54347. data[23] = 32;
  54348. memset(&data[24], 0, 100-24);
  54349. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  54350. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  54351. #ifndef SQLITE_OMIT_AUTOVACUUM
  54352. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  54353. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  54354. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  54355. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  54356. #endif
  54357. pBt->nPage = 1;
  54358. data[31] = 1;
  54359. return SQLITE_OK;
  54360. }
  54361. /*
  54362. ** Initialize the first page of the database file (creating a database
  54363. ** consisting of a single page and no schema objects). Return SQLITE_OK
  54364. ** if successful, or an SQLite error code otherwise.
  54365. */
  54366. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  54367. int rc;
  54368. sqlite3BtreeEnter(p);
  54369. p->pBt->nPage = 0;
  54370. rc = newDatabase(p->pBt);
  54371. sqlite3BtreeLeave(p);
  54372. return rc;
  54373. }
  54374. /*
  54375. ** Attempt to start a new transaction. A write-transaction
  54376. ** is started if the second argument is nonzero, otherwise a read-
  54377. ** transaction. If the second argument is 2 or more and exclusive
  54378. ** transaction is started, meaning that no other process is allowed
  54379. ** to access the database. A preexisting transaction may not be
  54380. ** upgraded to exclusive by calling this routine a second time - the
  54381. ** exclusivity flag only works for a new transaction.
  54382. **
  54383. ** A write-transaction must be started before attempting any
  54384. ** changes to the database. None of the following routines
  54385. ** will work unless a transaction is started first:
  54386. **
  54387. ** sqlite3BtreeCreateTable()
  54388. ** sqlite3BtreeCreateIndex()
  54389. ** sqlite3BtreeClearTable()
  54390. ** sqlite3BtreeDropTable()
  54391. ** sqlite3BtreeInsert()
  54392. ** sqlite3BtreeDelete()
  54393. ** sqlite3BtreeUpdateMeta()
  54394. **
  54395. ** If an initial attempt to acquire the lock fails because of lock contention
  54396. ** and the database was previously unlocked, then invoke the busy handler
  54397. ** if there is one. But if there was previously a read-lock, do not
  54398. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  54399. ** returned when there is already a read-lock in order to avoid a deadlock.
  54400. **
  54401. ** Suppose there are two processes A and B. A has a read lock and B has
  54402. ** a reserved lock. B tries to promote to exclusive but is blocked because
  54403. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  54404. ** One or the other of the two processes must give way or there can be
  54405. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  54406. ** when A already has a read lock, we encourage A to give up and let B
  54407. ** proceed.
  54408. */
  54409. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  54410. sqlite3 *pBlock = 0;
  54411. BtShared *pBt = p->pBt;
  54412. int rc = SQLITE_OK;
  54413. sqlite3BtreeEnter(p);
  54414. btreeIntegrity(p);
  54415. /* If the btree is already in a write-transaction, or it
  54416. ** is already in a read-transaction and a read-transaction
  54417. ** is requested, this is a no-op.
  54418. */
  54419. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  54420. goto trans_begun;
  54421. }
  54422. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  54423. /* Write transactions are not possible on a read-only database */
  54424. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  54425. rc = SQLITE_READONLY;
  54426. goto trans_begun;
  54427. }
  54428. #ifndef SQLITE_OMIT_SHARED_CACHE
  54429. /* If another database handle has already opened a write transaction
  54430. ** on this shared-btree structure and a second write transaction is
  54431. ** requested, return SQLITE_LOCKED.
  54432. */
  54433. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  54434. || (pBt->btsFlags & BTS_PENDING)!=0
  54435. ){
  54436. pBlock = pBt->pWriter->db;
  54437. }else if( wrflag>1 ){
  54438. BtLock *pIter;
  54439. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  54440. if( pIter->pBtree!=p ){
  54441. pBlock = pIter->pBtree->db;
  54442. break;
  54443. }
  54444. }
  54445. }
  54446. if( pBlock ){
  54447. sqlite3ConnectionBlocked(p->db, pBlock);
  54448. rc = SQLITE_LOCKED_SHAREDCACHE;
  54449. goto trans_begun;
  54450. }
  54451. #endif
  54452. /* Any read-only or read-write transaction implies a read-lock on
  54453. ** page 1. So if some other shared-cache client already has a write-lock
  54454. ** on page 1, the transaction cannot be opened. */
  54455. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  54456. if( SQLITE_OK!=rc ) goto trans_begun;
  54457. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  54458. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  54459. do {
  54460. /* Call lockBtree() until either pBt->pPage1 is populated or
  54461. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  54462. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  54463. ** reading page 1 it discovers that the page-size of the database
  54464. ** file is not pBt->pageSize. In this case lockBtree() will update
  54465. ** pBt->pageSize to the page-size of the file on disk.
  54466. */
  54467. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  54468. if( rc==SQLITE_OK && wrflag ){
  54469. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  54470. rc = SQLITE_READONLY;
  54471. }else{
  54472. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  54473. if( rc==SQLITE_OK ){
  54474. rc = newDatabase(pBt);
  54475. }
  54476. }
  54477. }
  54478. if( rc!=SQLITE_OK ){
  54479. unlockBtreeIfUnused(pBt);
  54480. }
  54481. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  54482. btreeInvokeBusyHandler(pBt) );
  54483. if( rc==SQLITE_OK ){
  54484. if( p->inTrans==TRANS_NONE ){
  54485. pBt->nTransaction++;
  54486. #ifndef SQLITE_OMIT_SHARED_CACHE
  54487. if( p->sharable ){
  54488. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  54489. p->lock.eLock = READ_LOCK;
  54490. p->lock.pNext = pBt->pLock;
  54491. pBt->pLock = &p->lock;
  54492. }
  54493. #endif
  54494. }
  54495. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  54496. if( p->inTrans>pBt->inTransaction ){
  54497. pBt->inTransaction = p->inTrans;
  54498. }
  54499. if( wrflag ){
  54500. MemPage *pPage1 = pBt->pPage1;
  54501. #ifndef SQLITE_OMIT_SHARED_CACHE
  54502. assert( !pBt->pWriter );
  54503. pBt->pWriter = p;
  54504. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  54505. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  54506. #endif
  54507. /* If the db-size header field is incorrect (as it may be if an old
  54508. ** client has been writing the database file), update it now. Doing
  54509. ** this sooner rather than later means the database size can safely
  54510. ** re-read the database size from page 1 if a savepoint or transaction
  54511. ** rollback occurs within the transaction.
  54512. */
  54513. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  54514. rc = sqlite3PagerWrite(pPage1->pDbPage);
  54515. if( rc==SQLITE_OK ){
  54516. put4byte(&pPage1->aData[28], pBt->nPage);
  54517. }
  54518. }
  54519. }
  54520. }
  54521. trans_begun:
  54522. if( rc==SQLITE_OK && wrflag ){
  54523. /* This call makes sure that the pager has the correct number of
  54524. ** open savepoints. If the second parameter is greater than 0 and
  54525. ** the sub-journal is not already open, then it will be opened here.
  54526. */
  54527. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  54528. }
  54529. btreeIntegrity(p);
  54530. sqlite3BtreeLeave(p);
  54531. return rc;
  54532. }
  54533. #ifndef SQLITE_OMIT_AUTOVACUUM
  54534. /*
  54535. ** Set the pointer-map entries for all children of page pPage. Also, if
  54536. ** pPage contains cells that point to overflow pages, set the pointer
  54537. ** map entries for the overflow pages as well.
  54538. */
  54539. static int setChildPtrmaps(MemPage *pPage){
  54540. int i; /* Counter variable */
  54541. int nCell; /* Number of cells in page pPage */
  54542. int rc; /* Return code */
  54543. BtShared *pBt = pPage->pBt;
  54544. u8 isInitOrig = pPage->isInit;
  54545. Pgno pgno = pPage->pgno;
  54546. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54547. rc = btreeInitPage(pPage);
  54548. if( rc!=SQLITE_OK ){
  54549. goto set_child_ptrmaps_out;
  54550. }
  54551. nCell = pPage->nCell;
  54552. for(i=0; i<nCell; i++){
  54553. u8 *pCell = findCell(pPage, i);
  54554. ptrmapPutOvflPtr(pPage, pCell, &rc);
  54555. if( !pPage->leaf ){
  54556. Pgno childPgno = get4byte(pCell);
  54557. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  54558. }
  54559. }
  54560. if( !pPage->leaf ){
  54561. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  54562. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  54563. }
  54564. set_child_ptrmaps_out:
  54565. pPage->isInit = isInitOrig;
  54566. return rc;
  54567. }
  54568. /*
  54569. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  54570. ** that it points to iTo. Parameter eType describes the type of pointer to
  54571. ** be modified, as follows:
  54572. **
  54573. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  54574. ** page of pPage.
  54575. **
  54576. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  54577. ** page pointed to by one of the cells on pPage.
  54578. **
  54579. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  54580. ** overflow page in the list.
  54581. */
  54582. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  54583. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54584. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54585. if( eType==PTRMAP_OVERFLOW2 ){
  54586. /* The pointer is always the first 4 bytes of the page in this case. */
  54587. if( get4byte(pPage->aData)!=iFrom ){
  54588. return SQLITE_CORRUPT_BKPT;
  54589. }
  54590. put4byte(pPage->aData, iTo);
  54591. }else{
  54592. u8 isInitOrig = pPage->isInit;
  54593. int i;
  54594. int nCell;
  54595. int rc;
  54596. rc = btreeInitPage(pPage);
  54597. if( rc ) return rc;
  54598. nCell = pPage->nCell;
  54599. for(i=0; i<nCell; i++){
  54600. u8 *pCell = findCell(pPage, i);
  54601. if( eType==PTRMAP_OVERFLOW1 ){
  54602. CellInfo info;
  54603. pPage->xParseCell(pPage, pCell, &info);
  54604. if( info.nLocal<info.nPayload
  54605. && pCell+info.nSize-1<=pPage->aData+pPage->maskPage
  54606. && iFrom==get4byte(pCell+info.nSize-4)
  54607. ){
  54608. put4byte(pCell+info.nSize-4, iTo);
  54609. break;
  54610. }
  54611. }else{
  54612. if( get4byte(pCell)==iFrom ){
  54613. put4byte(pCell, iTo);
  54614. break;
  54615. }
  54616. }
  54617. }
  54618. if( i==nCell ){
  54619. if( eType!=PTRMAP_BTREE ||
  54620. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  54621. return SQLITE_CORRUPT_BKPT;
  54622. }
  54623. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  54624. }
  54625. pPage->isInit = isInitOrig;
  54626. }
  54627. return SQLITE_OK;
  54628. }
  54629. /*
  54630. ** Move the open database page pDbPage to location iFreePage in the
  54631. ** database. The pDbPage reference remains valid.
  54632. **
  54633. ** The isCommit flag indicates that there is no need to remember that
  54634. ** the journal needs to be sync()ed before database page pDbPage->pgno
  54635. ** can be written to. The caller has already promised not to write to that
  54636. ** page.
  54637. */
  54638. static int relocatePage(
  54639. BtShared *pBt, /* Btree */
  54640. MemPage *pDbPage, /* Open page to move */
  54641. u8 eType, /* Pointer map 'type' entry for pDbPage */
  54642. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  54643. Pgno iFreePage, /* The location to move pDbPage to */
  54644. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  54645. ){
  54646. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  54647. Pgno iDbPage = pDbPage->pgno;
  54648. Pager *pPager = pBt->pPager;
  54649. int rc;
  54650. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  54651. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  54652. assert( sqlite3_mutex_held(pBt->mutex) );
  54653. assert( pDbPage->pBt==pBt );
  54654. /* Move page iDbPage from its current location to page number iFreePage */
  54655. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  54656. iDbPage, iFreePage, iPtrPage, eType));
  54657. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  54658. if( rc!=SQLITE_OK ){
  54659. return rc;
  54660. }
  54661. pDbPage->pgno = iFreePage;
  54662. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  54663. ** that point to overflow pages. The pointer map entries for all these
  54664. ** pages need to be changed.
  54665. **
  54666. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  54667. ** pointer to a subsequent overflow page. If this is the case, then
  54668. ** the pointer map needs to be updated for the subsequent overflow page.
  54669. */
  54670. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  54671. rc = setChildPtrmaps(pDbPage);
  54672. if( rc!=SQLITE_OK ){
  54673. return rc;
  54674. }
  54675. }else{
  54676. Pgno nextOvfl = get4byte(pDbPage->aData);
  54677. if( nextOvfl!=0 ){
  54678. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  54679. if( rc!=SQLITE_OK ){
  54680. return rc;
  54681. }
  54682. }
  54683. }
  54684. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  54685. ** that it points at iFreePage. Also fix the pointer map entry for
  54686. ** iPtrPage.
  54687. */
  54688. if( eType!=PTRMAP_ROOTPAGE ){
  54689. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  54690. if( rc!=SQLITE_OK ){
  54691. return rc;
  54692. }
  54693. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  54694. if( rc!=SQLITE_OK ){
  54695. releasePage(pPtrPage);
  54696. return rc;
  54697. }
  54698. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  54699. releasePage(pPtrPage);
  54700. if( rc==SQLITE_OK ){
  54701. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  54702. }
  54703. }
  54704. return rc;
  54705. }
  54706. /* Forward declaration required by incrVacuumStep(). */
  54707. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  54708. /*
  54709. ** Perform a single step of an incremental-vacuum. If successful, return
  54710. ** SQLITE_OK. If there is no work to do (and therefore no point in
  54711. ** calling this function again), return SQLITE_DONE. Or, if an error
  54712. ** occurs, return some other error code.
  54713. **
  54714. ** More specifically, this function attempts to re-organize the database so
  54715. ** that the last page of the file currently in use is no longer in use.
  54716. **
  54717. ** Parameter nFin is the number of pages that this database would contain
  54718. ** were this function called until it returns SQLITE_DONE.
  54719. **
  54720. ** If the bCommit parameter is non-zero, this function assumes that the
  54721. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  54722. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  54723. ** operation, or false for an incremental vacuum.
  54724. */
  54725. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  54726. Pgno nFreeList; /* Number of pages still on the free-list */
  54727. int rc;
  54728. assert( sqlite3_mutex_held(pBt->mutex) );
  54729. assert( iLastPg>nFin );
  54730. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  54731. u8 eType;
  54732. Pgno iPtrPage;
  54733. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  54734. if( nFreeList==0 ){
  54735. return SQLITE_DONE;
  54736. }
  54737. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  54738. if( rc!=SQLITE_OK ){
  54739. return rc;
  54740. }
  54741. if( eType==PTRMAP_ROOTPAGE ){
  54742. return SQLITE_CORRUPT_BKPT;
  54743. }
  54744. if( eType==PTRMAP_FREEPAGE ){
  54745. if( bCommit==0 ){
  54746. /* Remove the page from the files free-list. This is not required
  54747. ** if bCommit is non-zero. In that case, the free-list will be
  54748. ** truncated to zero after this function returns, so it doesn't
  54749. ** matter if it still contains some garbage entries.
  54750. */
  54751. Pgno iFreePg;
  54752. MemPage *pFreePg;
  54753. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  54754. if( rc!=SQLITE_OK ){
  54755. return rc;
  54756. }
  54757. assert( iFreePg==iLastPg );
  54758. releasePage(pFreePg);
  54759. }
  54760. } else {
  54761. Pgno iFreePg; /* Index of free page to move pLastPg to */
  54762. MemPage *pLastPg;
  54763. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  54764. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  54765. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  54766. if( rc!=SQLITE_OK ){
  54767. return rc;
  54768. }
  54769. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  54770. ** is swapped with the first free page pulled off the free list.
  54771. **
  54772. ** On the other hand, if bCommit is greater than zero, then keep
  54773. ** looping until a free-page located within the first nFin pages
  54774. ** of the file is found.
  54775. */
  54776. if( bCommit==0 ){
  54777. eMode = BTALLOC_LE;
  54778. iNear = nFin;
  54779. }
  54780. do {
  54781. MemPage *pFreePg;
  54782. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  54783. if( rc!=SQLITE_OK ){
  54784. releasePage(pLastPg);
  54785. return rc;
  54786. }
  54787. releasePage(pFreePg);
  54788. }while( bCommit && iFreePg>nFin );
  54789. assert( iFreePg<iLastPg );
  54790. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  54791. releasePage(pLastPg);
  54792. if( rc!=SQLITE_OK ){
  54793. return rc;
  54794. }
  54795. }
  54796. }
  54797. if( bCommit==0 ){
  54798. do {
  54799. iLastPg--;
  54800. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  54801. pBt->bDoTruncate = 1;
  54802. pBt->nPage = iLastPg;
  54803. }
  54804. return SQLITE_OK;
  54805. }
  54806. /*
  54807. ** The database opened by the first argument is an auto-vacuum database
  54808. ** nOrig pages in size containing nFree free pages. Return the expected
  54809. ** size of the database in pages following an auto-vacuum operation.
  54810. */
  54811. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  54812. int nEntry; /* Number of entries on one ptrmap page */
  54813. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  54814. Pgno nFin; /* Return value */
  54815. nEntry = pBt->usableSize/5;
  54816. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  54817. nFin = nOrig - nFree - nPtrmap;
  54818. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  54819. nFin--;
  54820. }
  54821. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  54822. nFin--;
  54823. }
  54824. return nFin;
  54825. }
  54826. /*
  54827. ** A write-transaction must be opened before calling this function.
  54828. ** It performs a single unit of work towards an incremental vacuum.
  54829. **
  54830. ** If the incremental vacuum is finished after this function has run,
  54831. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  54832. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  54833. */
  54834. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  54835. int rc;
  54836. BtShared *pBt = p->pBt;
  54837. sqlite3BtreeEnter(p);
  54838. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  54839. if( !pBt->autoVacuum ){
  54840. rc = SQLITE_DONE;
  54841. }else{
  54842. Pgno nOrig = btreePagecount(pBt);
  54843. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  54844. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  54845. if( nOrig<nFin ){
  54846. rc = SQLITE_CORRUPT_BKPT;
  54847. }else if( nFree>0 ){
  54848. rc = saveAllCursors(pBt, 0, 0);
  54849. if( rc==SQLITE_OK ){
  54850. invalidateAllOverflowCache(pBt);
  54851. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  54852. }
  54853. if( rc==SQLITE_OK ){
  54854. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54855. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  54856. }
  54857. }else{
  54858. rc = SQLITE_DONE;
  54859. }
  54860. }
  54861. sqlite3BtreeLeave(p);
  54862. return rc;
  54863. }
  54864. /*
  54865. ** This routine is called prior to sqlite3PagerCommit when a transaction
  54866. ** is committed for an auto-vacuum database.
  54867. **
  54868. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  54869. ** the database file should be truncated to during the commit process.
  54870. ** i.e. the database has been reorganized so that only the first *pnTrunc
  54871. ** pages are in use.
  54872. */
  54873. static int autoVacuumCommit(BtShared *pBt){
  54874. int rc = SQLITE_OK;
  54875. Pager *pPager = pBt->pPager;
  54876. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  54877. assert( sqlite3_mutex_held(pBt->mutex) );
  54878. invalidateAllOverflowCache(pBt);
  54879. assert(pBt->autoVacuum);
  54880. if( !pBt->incrVacuum ){
  54881. Pgno nFin; /* Number of pages in database after autovacuuming */
  54882. Pgno nFree; /* Number of pages on the freelist initially */
  54883. Pgno iFree; /* The next page to be freed */
  54884. Pgno nOrig; /* Database size before freeing */
  54885. nOrig = btreePagecount(pBt);
  54886. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  54887. /* It is not possible to create a database for which the final page
  54888. ** is either a pointer-map page or the pending-byte page. If one
  54889. ** is encountered, this indicates corruption.
  54890. */
  54891. return SQLITE_CORRUPT_BKPT;
  54892. }
  54893. nFree = get4byte(&pBt->pPage1->aData[36]);
  54894. nFin = finalDbSize(pBt, nOrig, nFree);
  54895. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  54896. if( nFin<nOrig ){
  54897. rc = saveAllCursors(pBt, 0, 0);
  54898. }
  54899. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  54900. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  54901. }
  54902. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  54903. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54904. put4byte(&pBt->pPage1->aData[32], 0);
  54905. put4byte(&pBt->pPage1->aData[36], 0);
  54906. put4byte(&pBt->pPage1->aData[28], nFin);
  54907. pBt->bDoTruncate = 1;
  54908. pBt->nPage = nFin;
  54909. }
  54910. if( rc!=SQLITE_OK ){
  54911. sqlite3PagerRollback(pPager);
  54912. }
  54913. }
  54914. assert( nRef>=sqlite3PagerRefcount(pPager) );
  54915. return rc;
  54916. }
  54917. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  54918. # define setChildPtrmaps(x) SQLITE_OK
  54919. #endif
  54920. /*
  54921. ** This routine does the first phase of a two-phase commit. This routine
  54922. ** causes a rollback journal to be created (if it does not already exist)
  54923. ** and populated with enough information so that if a power loss occurs
  54924. ** the database can be restored to its original state by playing back
  54925. ** the journal. Then the contents of the journal are flushed out to
  54926. ** the disk. After the journal is safely on oxide, the changes to the
  54927. ** database are written into the database file and flushed to oxide.
  54928. ** At the end of this call, the rollback journal still exists on the
  54929. ** disk and we are still holding all locks, so the transaction has not
  54930. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  54931. ** commit process.
  54932. **
  54933. ** This call is a no-op if no write-transaction is currently active on pBt.
  54934. **
  54935. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  54936. ** the name of a master journal file that should be written into the
  54937. ** individual journal file, or is NULL, indicating no master journal file
  54938. ** (single database transaction).
  54939. **
  54940. ** When this is called, the master journal should already have been
  54941. ** created, populated with this journal pointer and synced to disk.
  54942. **
  54943. ** Once this is routine has returned, the only thing required to commit
  54944. ** the write-transaction for this database file is to delete the journal.
  54945. */
  54946. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  54947. int rc = SQLITE_OK;
  54948. if( p->inTrans==TRANS_WRITE ){
  54949. BtShared *pBt = p->pBt;
  54950. sqlite3BtreeEnter(p);
  54951. #ifndef SQLITE_OMIT_AUTOVACUUM
  54952. if( pBt->autoVacuum ){
  54953. rc = autoVacuumCommit(pBt);
  54954. if( rc!=SQLITE_OK ){
  54955. sqlite3BtreeLeave(p);
  54956. return rc;
  54957. }
  54958. }
  54959. if( pBt->bDoTruncate ){
  54960. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  54961. }
  54962. #endif
  54963. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  54964. sqlite3BtreeLeave(p);
  54965. }
  54966. return rc;
  54967. }
  54968. /*
  54969. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  54970. ** at the conclusion of a transaction.
  54971. */
  54972. static void btreeEndTransaction(Btree *p){
  54973. BtShared *pBt = p->pBt;
  54974. sqlite3 *db = p->db;
  54975. assert( sqlite3BtreeHoldsMutex(p) );
  54976. #ifndef SQLITE_OMIT_AUTOVACUUM
  54977. pBt->bDoTruncate = 0;
  54978. #endif
  54979. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  54980. /* If there are other active statements that belong to this database
  54981. ** handle, downgrade to a read-only transaction. The other statements
  54982. ** may still be reading from the database. */
  54983. downgradeAllSharedCacheTableLocks(p);
  54984. p->inTrans = TRANS_READ;
  54985. }else{
  54986. /* If the handle had any kind of transaction open, decrement the
  54987. ** transaction count of the shared btree. If the transaction count
  54988. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  54989. ** call below will unlock the pager. */
  54990. if( p->inTrans!=TRANS_NONE ){
  54991. clearAllSharedCacheTableLocks(p);
  54992. pBt->nTransaction--;
  54993. if( 0==pBt->nTransaction ){
  54994. pBt->inTransaction = TRANS_NONE;
  54995. }
  54996. }
  54997. /* Set the current transaction state to TRANS_NONE and unlock the
  54998. ** pager if this call closed the only read or write transaction. */
  54999. p->inTrans = TRANS_NONE;
  55000. unlockBtreeIfUnused(pBt);
  55001. }
  55002. btreeIntegrity(p);
  55003. }
  55004. /*
  55005. ** Commit the transaction currently in progress.
  55006. **
  55007. ** This routine implements the second phase of a 2-phase commit. The
  55008. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  55009. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  55010. ** routine did all the work of writing information out to disk and flushing the
  55011. ** contents so that they are written onto the disk platter. All this
  55012. ** routine has to do is delete or truncate or zero the header in the
  55013. ** the rollback journal (which causes the transaction to commit) and
  55014. ** drop locks.
  55015. **
  55016. ** Normally, if an error occurs while the pager layer is attempting to
  55017. ** finalize the underlying journal file, this function returns an error and
  55018. ** the upper layer will attempt a rollback. However, if the second argument
  55019. ** is non-zero then this b-tree transaction is part of a multi-file
  55020. ** transaction. In this case, the transaction has already been committed
  55021. ** (by deleting a master journal file) and the caller will ignore this
  55022. ** functions return code. So, even if an error occurs in the pager layer,
  55023. ** reset the b-tree objects internal state to indicate that the write
  55024. ** transaction has been closed. This is quite safe, as the pager will have
  55025. ** transitioned to the error state.
  55026. **
  55027. ** This will release the write lock on the database file. If there
  55028. ** are no active cursors, it also releases the read lock.
  55029. */
  55030. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  55031. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  55032. sqlite3BtreeEnter(p);
  55033. btreeIntegrity(p);
  55034. /* If the handle has a write-transaction open, commit the shared-btrees
  55035. ** transaction and set the shared state to TRANS_READ.
  55036. */
  55037. if( p->inTrans==TRANS_WRITE ){
  55038. int rc;
  55039. BtShared *pBt = p->pBt;
  55040. assert( pBt->inTransaction==TRANS_WRITE );
  55041. assert( pBt->nTransaction>0 );
  55042. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  55043. if( rc!=SQLITE_OK && bCleanup==0 ){
  55044. sqlite3BtreeLeave(p);
  55045. return rc;
  55046. }
  55047. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  55048. pBt->inTransaction = TRANS_READ;
  55049. btreeClearHasContent(pBt);
  55050. }
  55051. btreeEndTransaction(p);
  55052. sqlite3BtreeLeave(p);
  55053. return SQLITE_OK;
  55054. }
  55055. /*
  55056. ** Do both phases of a commit.
  55057. */
  55058. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  55059. int rc;
  55060. sqlite3BtreeEnter(p);
  55061. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  55062. if( rc==SQLITE_OK ){
  55063. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  55064. }
  55065. sqlite3BtreeLeave(p);
  55066. return rc;
  55067. }
  55068. /*
  55069. ** This routine sets the state to CURSOR_FAULT and the error
  55070. ** code to errCode for every cursor on any BtShared that pBtree
  55071. ** references. Or if the writeOnly flag is set to 1, then only
  55072. ** trip write cursors and leave read cursors unchanged.
  55073. **
  55074. ** Every cursor is a candidate to be tripped, including cursors
  55075. ** that belong to other database connections that happen to be
  55076. ** sharing the cache with pBtree.
  55077. **
  55078. ** This routine gets called when a rollback occurs. If the writeOnly
  55079. ** flag is true, then only write-cursors need be tripped - read-only
  55080. ** cursors save their current positions so that they may continue
  55081. ** following the rollback. Or, if writeOnly is false, all cursors are
  55082. ** tripped. In general, writeOnly is false if the transaction being
  55083. ** rolled back modified the database schema. In this case b-tree root
  55084. ** pages may be moved or deleted from the database altogether, making
  55085. ** it unsafe for read cursors to continue.
  55086. **
  55087. ** If the writeOnly flag is true and an error is encountered while
  55088. ** saving the current position of a read-only cursor, all cursors,
  55089. ** including all read-cursors are tripped.
  55090. **
  55091. ** SQLITE_OK is returned if successful, or if an error occurs while
  55092. ** saving a cursor position, an SQLite error code.
  55093. */
  55094. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  55095. BtCursor *p;
  55096. int rc = SQLITE_OK;
  55097. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  55098. if( pBtree ){
  55099. sqlite3BtreeEnter(pBtree);
  55100. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  55101. int i;
  55102. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  55103. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  55104. rc = saveCursorPosition(p);
  55105. if( rc!=SQLITE_OK ){
  55106. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  55107. break;
  55108. }
  55109. }
  55110. }else{
  55111. sqlite3BtreeClearCursor(p);
  55112. p->eState = CURSOR_FAULT;
  55113. p->skipNext = errCode;
  55114. }
  55115. for(i=0; i<=p->iPage; i++){
  55116. releasePage(p->apPage[i]);
  55117. p->apPage[i] = 0;
  55118. }
  55119. }
  55120. sqlite3BtreeLeave(pBtree);
  55121. }
  55122. return rc;
  55123. }
  55124. /*
  55125. ** Rollback the transaction in progress.
  55126. **
  55127. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  55128. ** Only write cursors are tripped if writeOnly is true but all cursors are
  55129. ** tripped if writeOnly is false. Any attempt to use
  55130. ** a tripped cursor will result in an error.
  55131. **
  55132. ** This will release the write lock on the database file. If there
  55133. ** are no active cursors, it also releases the read lock.
  55134. */
  55135. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  55136. int rc;
  55137. BtShared *pBt = p->pBt;
  55138. MemPage *pPage1;
  55139. assert( writeOnly==1 || writeOnly==0 );
  55140. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  55141. sqlite3BtreeEnter(p);
  55142. if( tripCode==SQLITE_OK ){
  55143. rc = tripCode = saveAllCursors(pBt, 0, 0);
  55144. if( rc ) writeOnly = 0;
  55145. }else{
  55146. rc = SQLITE_OK;
  55147. }
  55148. if( tripCode ){
  55149. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  55150. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  55151. if( rc2!=SQLITE_OK ) rc = rc2;
  55152. }
  55153. btreeIntegrity(p);
  55154. if( p->inTrans==TRANS_WRITE ){
  55155. int rc2;
  55156. assert( TRANS_WRITE==pBt->inTransaction );
  55157. rc2 = sqlite3PagerRollback(pBt->pPager);
  55158. if( rc2!=SQLITE_OK ){
  55159. rc = rc2;
  55160. }
  55161. /* The rollback may have destroyed the pPage1->aData value. So
  55162. ** call btreeGetPage() on page 1 again to make
  55163. ** sure pPage1->aData is set correctly. */
  55164. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  55165. int nPage = get4byte(28+(u8*)pPage1->aData);
  55166. testcase( nPage==0 );
  55167. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  55168. testcase( pBt->nPage!=nPage );
  55169. pBt->nPage = nPage;
  55170. releasePage(pPage1);
  55171. }
  55172. assert( countValidCursors(pBt, 1)==0 );
  55173. pBt->inTransaction = TRANS_READ;
  55174. btreeClearHasContent(pBt);
  55175. }
  55176. btreeEndTransaction(p);
  55177. sqlite3BtreeLeave(p);
  55178. return rc;
  55179. }
  55180. /*
  55181. ** Start a statement subtransaction. The subtransaction can be rolled
  55182. ** back independently of the main transaction. You must start a transaction
  55183. ** before starting a subtransaction. The subtransaction is ended automatically
  55184. ** if the main transaction commits or rolls back.
  55185. **
  55186. ** Statement subtransactions are used around individual SQL statements
  55187. ** that are contained within a BEGIN...COMMIT block. If a constraint
  55188. ** error occurs within the statement, the effect of that one statement
  55189. ** can be rolled back without having to rollback the entire transaction.
  55190. **
  55191. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  55192. ** value passed as the second parameter is the total number of savepoints,
  55193. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  55194. ** are no active savepoints and no other statement-transactions open,
  55195. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  55196. ** using the sqlite3BtreeSavepoint() function.
  55197. */
  55198. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  55199. int rc;
  55200. BtShared *pBt = p->pBt;
  55201. sqlite3BtreeEnter(p);
  55202. assert( p->inTrans==TRANS_WRITE );
  55203. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55204. assert( iStatement>0 );
  55205. assert( iStatement>p->db->nSavepoint );
  55206. assert( pBt->inTransaction==TRANS_WRITE );
  55207. /* At the pager level, a statement transaction is a savepoint with
  55208. ** an index greater than all savepoints created explicitly using
  55209. ** SQL statements. It is illegal to open, release or rollback any
  55210. ** such savepoints while the statement transaction savepoint is active.
  55211. */
  55212. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  55213. sqlite3BtreeLeave(p);
  55214. return rc;
  55215. }
  55216. /*
  55217. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  55218. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  55219. ** savepoint identified by parameter iSavepoint, depending on the value
  55220. ** of op.
  55221. **
  55222. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  55223. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  55224. ** contents of the entire transaction are rolled back. This is different
  55225. ** from a normal transaction rollback, as no locks are released and the
  55226. ** transaction remains open.
  55227. */
  55228. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  55229. int rc = SQLITE_OK;
  55230. if( p && p->inTrans==TRANS_WRITE ){
  55231. BtShared *pBt = p->pBt;
  55232. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  55233. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  55234. sqlite3BtreeEnter(p);
  55235. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  55236. if( rc==SQLITE_OK ){
  55237. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  55238. pBt->nPage = 0;
  55239. }
  55240. rc = newDatabase(pBt);
  55241. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  55242. /* The database size was written into the offset 28 of the header
  55243. ** when the transaction started, so we know that the value at offset
  55244. ** 28 is nonzero. */
  55245. assert( pBt->nPage>0 );
  55246. }
  55247. sqlite3BtreeLeave(p);
  55248. }
  55249. return rc;
  55250. }
  55251. /*
  55252. ** Create a new cursor for the BTree whose root is on the page
  55253. ** iTable. If a read-only cursor is requested, it is assumed that
  55254. ** the caller already has at least a read-only transaction open
  55255. ** on the database already. If a write-cursor is requested, then
  55256. ** the caller is assumed to have an open write transaction.
  55257. **
  55258. ** If wrFlag==0, then the cursor can only be used for reading.
  55259. ** If wrFlag==1, then the cursor can be used for reading or for
  55260. ** writing if other conditions for writing are also met. These
  55261. ** are the conditions that must be met in order for writing to
  55262. ** be allowed:
  55263. **
  55264. ** 1: The cursor must have been opened with wrFlag==1
  55265. **
  55266. ** 2: Other database connections that share the same pager cache
  55267. ** but which are not in the READ_UNCOMMITTED state may not have
  55268. ** cursors open with wrFlag==0 on the same table. Otherwise
  55269. ** the changes made by this write cursor would be visible to
  55270. ** the read cursors in the other database connection.
  55271. **
  55272. ** 3: The database must be writable (not on read-only media)
  55273. **
  55274. ** 4: There must be an active transaction.
  55275. **
  55276. ** No checking is done to make sure that page iTable really is the
  55277. ** root page of a b-tree. If it is not, then the cursor acquired
  55278. ** will not work correctly.
  55279. **
  55280. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  55281. ** on pCur to initialize the memory space prior to invoking this routine.
  55282. */
  55283. static int btreeCursor(
  55284. Btree *p, /* The btree */
  55285. int iTable, /* Root page of table to open */
  55286. int wrFlag, /* 1 to write. 0 read-only */
  55287. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  55288. BtCursor *pCur /* Space for new cursor */
  55289. ){
  55290. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  55291. BtCursor *pX; /* Looping over other all cursors */
  55292. assert( sqlite3BtreeHoldsMutex(p) );
  55293. assert( wrFlag==0
  55294. || wrFlag==BTREE_WRCSR
  55295. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  55296. );
  55297. /* The following assert statements verify that if this is a sharable
  55298. ** b-tree database, the connection is holding the required table locks,
  55299. ** and that no other connection has any open cursor that conflicts with
  55300. ** this lock. */
  55301. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  55302. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  55303. /* Assert that the caller has opened the required transaction. */
  55304. assert( p->inTrans>TRANS_NONE );
  55305. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  55306. assert( pBt->pPage1 && pBt->pPage1->aData );
  55307. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55308. if( wrFlag ){
  55309. allocateTempSpace(pBt);
  55310. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
  55311. }
  55312. if( iTable==1 && btreePagecount(pBt)==0 ){
  55313. assert( wrFlag==0 );
  55314. iTable = 0;
  55315. }
  55316. /* Now that no other errors can occur, finish filling in the BtCursor
  55317. ** variables and link the cursor into the BtShared list. */
  55318. pCur->pgnoRoot = (Pgno)iTable;
  55319. pCur->iPage = -1;
  55320. pCur->pKeyInfo = pKeyInfo;
  55321. pCur->pBtree = p;
  55322. pCur->pBt = pBt;
  55323. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  55324. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  55325. /* If there are two or more cursors on the same btree, then all such
  55326. ** cursors *must* have the BTCF_Multiple flag set. */
  55327. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  55328. if( pX->pgnoRoot==(Pgno)iTable ){
  55329. pX->curFlags |= BTCF_Multiple;
  55330. pCur->curFlags |= BTCF_Multiple;
  55331. }
  55332. }
  55333. pCur->pNext = pBt->pCursor;
  55334. pBt->pCursor = pCur;
  55335. pCur->eState = CURSOR_INVALID;
  55336. return SQLITE_OK;
  55337. }
  55338. SQLITE_PRIVATE int sqlite3BtreeCursor(
  55339. Btree *p, /* The btree */
  55340. int iTable, /* Root page of table to open */
  55341. int wrFlag, /* 1 to write. 0 read-only */
  55342. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  55343. BtCursor *pCur /* Write new cursor here */
  55344. ){
  55345. int rc;
  55346. if( iTable<1 ){
  55347. rc = SQLITE_CORRUPT_BKPT;
  55348. }else{
  55349. sqlite3BtreeEnter(p);
  55350. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  55351. sqlite3BtreeLeave(p);
  55352. }
  55353. return rc;
  55354. }
  55355. /*
  55356. ** Return the size of a BtCursor object in bytes.
  55357. **
  55358. ** This interfaces is needed so that users of cursors can preallocate
  55359. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  55360. ** to users so they cannot do the sizeof() themselves - they must call
  55361. ** this routine.
  55362. */
  55363. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  55364. return ROUND8(sizeof(BtCursor));
  55365. }
  55366. /*
  55367. ** Initialize memory that will be converted into a BtCursor object.
  55368. **
  55369. ** The simple approach here would be to memset() the entire object
  55370. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  55371. ** do not need to be zeroed and they are large, so we can save a lot
  55372. ** of run-time by skipping the initialization of those elements.
  55373. */
  55374. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  55375. memset(p, 0, offsetof(BtCursor, iPage));
  55376. }
  55377. /*
  55378. ** Close a cursor. The read lock on the database file is released
  55379. ** when the last cursor is closed.
  55380. */
  55381. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  55382. Btree *pBtree = pCur->pBtree;
  55383. if( pBtree ){
  55384. int i;
  55385. BtShared *pBt = pCur->pBt;
  55386. sqlite3BtreeEnter(pBtree);
  55387. sqlite3BtreeClearCursor(pCur);
  55388. assert( pBt->pCursor!=0 );
  55389. if( pBt->pCursor==pCur ){
  55390. pBt->pCursor = pCur->pNext;
  55391. }else{
  55392. BtCursor *pPrev = pBt->pCursor;
  55393. do{
  55394. if( pPrev->pNext==pCur ){
  55395. pPrev->pNext = pCur->pNext;
  55396. break;
  55397. }
  55398. pPrev = pPrev->pNext;
  55399. }while( ALWAYS(pPrev) );
  55400. }
  55401. for(i=0; i<=pCur->iPage; i++){
  55402. releasePage(pCur->apPage[i]);
  55403. }
  55404. unlockBtreeIfUnused(pBt);
  55405. sqlite3_free(pCur->aOverflow);
  55406. /* sqlite3_free(pCur); */
  55407. sqlite3BtreeLeave(pBtree);
  55408. }
  55409. return SQLITE_OK;
  55410. }
  55411. /*
  55412. ** Make sure the BtCursor* given in the argument has a valid
  55413. ** BtCursor.info structure. If it is not already valid, call
  55414. ** btreeParseCell() to fill it in.
  55415. **
  55416. ** BtCursor.info is a cache of the information in the current cell.
  55417. ** Using this cache reduces the number of calls to btreeParseCell().
  55418. */
  55419. #ifndef NDEBUG
  55420. static void assertCellInfo(BtCursor *pCur){
  55421. CellInfo info;
  55422. int iPage = pCur->iPage;
  55423. memset(&info, 0, sizeof(info));
  55424. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  55425. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  55426. }
  55427. #else
  55428. #define assertCellInfo(x)
  55429. #endif
  55430. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  55431. if( pCur->info.nSize==0 ){
  55432. int iPage = pCur->iPage;
  55433. pCur->curFlags |= BTCF_ValidNKey;
  55434. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  55435. }else{
  55436. assertCellInfo(pCur);
  55437. }
  55438. }
  55439. #ifndef NDEBUG /* The next routine used only within assert() statements */
  55440. /*
  55441. ** Return true if the given BtCursor is valid. A valid cursor is one
  55442. ** that is currently pointing to a row in a (non-empty) table.
  55443. ** This is a verification routine is used only within assert() statements.
  55444. */
  55445. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  55446. return pCur && pCur->eState==CURSOR_VALID;
  55447. }
  55448. #endif /* NDEBUG */
  55449. /*
  55450. ** Set *pSize to the size of the buffer needed to hold the value of
  55451. ** the key for the current entry. If the cursor is not pointing
  55452. ** to a valid entry, *pSize is set to 0.
  55453. **
  55454. ** For a table with the INTKEY flag set, this routine returns the key
  55455. ** itself, not the number of bytes in the key.
  55456. **
  55457. ** The caller must position the cursor prior to invoking this routine.
  55458. **
  55459. ** This routine cannot fail. It always returns SQLITE_OK.
  55460. */
  55461. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  55462. assert( cursorHoldsMutex(pCur) );
  55463. assert( pCur->eState==CURSOR_VALID );
  55464. getCellInfo(pCur);
  55465. *pSize = pCur->info.nKey;
  55466. return SQLITE_OK;
  55467. }
  55468. /*
  55469. ** Set *pSize to the number of bytes of data in the entry the
  55470. ** cursor currently points to.
  55471. **
  55472. ** The caller must guarantee that the cursor is pointing to a non-NULL
  55473. ** valid entry. In other words, the calling procedure must guarantee
  55474. ** that the cursor has Cursor.eState==CURSOR_VALID.
  55475. **
  55476. ** Failure is not possible. This function always returns SQLITE_OK.
  55477. ** It might just as well be a procedure (returning void) but we continue
  55478. ** to return an integer result code for historical reasons.
  55479. */
  55480. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  55481. assert( cursorHoldsMutex(pCur) );
  55482. assert( pCur->eState==CURSOR_VALID );
  55483. assert( pCur->iPage>=0 );
  55484. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  55485. assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
  55486. getCellInfo(pCur);
  55487. *pSize = pCur->info.nPayload;
  55488. return SQLITE_OK;
  55489. }
  55490. /*
  55491. ** Given the page number of an overflow page in the database (parameter
  55492. ** ovfl), this function finds the page number of the next page in the
  55493. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  55494. ** pointer-map data instead of reading the content of page ovfl to do so.
  55495. **
  55496. ** If an error occurs an SQLite error code is returned. Otherwise:
  55497. **
  55498. ** The page number of the next overflow page in the linked list is
  55499. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  55500. ** list, *pPgnoNext is set to zero.
  55501. **
  55502. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  55503. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  55504. ** reference. It is the responsibility of the caller to call releasePage()
  55505. ** on *ppPage to free the reference. In no reference was obtained (because
  55506. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  55507. ** *ppPage is set to zero.
  55508. */
  55509. static int getOverflowPage(
  55510. BtShared *pBt, /* The database file */
  55511. Pgno ovfl, /* Current overflow page number */
  55512. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  55513. Pgno *pPgnoNext /* OUT: Next overflow page number */
  55514. ){
  55515. Pgno next = 0;
  55516. MemPage *pPage = 0;
  55517. int rc = SQLITE_OK;
  55518. assert( sqlite3_mutex_held(pBt->mutex) );
  55519. assert(pPgnoNext);
  55520. #ifndef SQLITE_OMIT_AUTOVACUUM
  55521. /* Try to find the next page in the overflow list using the
  55522. ** autovacuum pointer-map pages. Guess that the next page in
  55523. ** the overflow list is page number (ovfl+1). If that guess turns
  55524. ** out to be wrong, fall back to loading the data of page
  55525. ** number ovfl to determine the next page number.
  55526. */
  55527. if( pBt->autoVacuum ){
  55528. Pgno pgno;
  55529. Pgno iGuess = ovfl+1;
  55530. u8 eType;
  55531. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  55532. iGuess++;
  55533. }
  55534. if( iGuess<=btreePagecount(pBt) ){
  55535. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  55536. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  55537. next = iGuess;
  55538. rc = SQLITE_DONE;
  55539. }
  55540. }
  55541. }
  55542. #endif
  55543. assert( next==0 || rc==SQLITE_DONE );
  55544. if( rc==SQLITE_OK ){
  55545. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  55546. assert( rc==SQLITE_OK || pPage==0 );
  55547. if( rc==SQLITE_OK ){
  55548. next = get4byte(pPage->aData);
  55549. }
  55550. }
  55551. *pPgnoNext = next;
  55552. if( ppPage ){
  55553. *ppPage = pPage;
  55554. }else{
  55555. releasePage(pPage);
  55556. }
  55557. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  55558. }
  55559. /*
  55560. ** Copy data from a buffer to a page, or from a page to a buffer.
  55561. **
  55562. ** pPayload is a pointer to data stored on database page pDbPage.
  55563. ** If argument eOp is false, then nByte bytes of data are copied
  55564. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  55565. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  55566. ** of data are copied from the buffer pBuf to pPayload.
  55567. **
  55568. ** SQLITE_OK is returned on success, otherwise an error code.
  55569. */
  55570. static int copyPayload(
  55571. void *pPayload, /* Pointer to page data */
  55572. void *pBuf, /* Pointer to buffer */
  55573. int nByte, /* Number of bytes to copy */
  55574. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  55575. DbPage *pDbPage /* Page containing pPayload */
  55576. ){
  55577. if( eOp ){
  55578. /* Copy data from buffer to page (a write operation) */
  55579. int rc = sqlite3PagerWrite(pDbPage);
  55580. if( rc!=SQLITE_OK ){
  55581. return rc;
  55582. }
  55583. memcpy(pPayload, pBuf, nByte);
  55584. }else{
  55585. /* Copy data from page to buffer (a read operation) */
  55586. memcpy(pBuf, pPayload, nByte);
  55587. }
  55588. return SQLITE_OK;
  55589. }
  55590. /*
  55591. ** This function is used to read or overwrite payload information
  55592. ** for the entry that the pCur cursor is pointing to. The eOp
  55593. ** argument is interpreted as follows:
  55594. **
  55595. ** 0: The operation is a read. Populate the overflow cache.
  55596. ** 1: The operation is a write. Populate the overflow cache.
  55597. ** 2: The operation is a read. Do not populate the overflow cache.
  55598. **
  55599. ** A total of "amt" bytes are read or written beginning at "offset".
  55600. ** Data is read to or from the buffer pBuf.
  55601. **
  55602. ** The content being read or written might appear on the main page
  55603. ** or be scattered out on multiple overflow pages.
  55604. **
  55605. ** If the current cursor entry uses one or more overflow pages and the
  55606. ** eOp argument is not 2, this function may allocate space for and lazily
  55607. ** populates the overflow page-list cache array (BtCursor.aOverflow).
  55608. ** Subsequent calls use this cache to make seeking to the supplied offset
  55609. ** more efficient.
  55610. **
  55611. ** Once an overflow page-list cache has been allocated, it may be
  55612. ** invalidated if some other cursor writes to the same table, or if
  55613. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  55614. ** mode, the following events may invalidate an overflow page-list cache.
  55615. **
  55616. ** * An incremental vacuum,
  55617. ** * A commit in auto_vacuum="full" mode,
  55618. ** * Creating a table (may require moving an overflow page).
  55619. */
  55620. static int accessPayload(
  55621. BtCursor *pCur, /* Cursor pointing to entry to read from */
  55622. u32 offset, /* Begin reading this far into payload */
  55623. u32 amt, /* Read this many bytes */
  55624. unsigned char *pBuf, /* Write the bytes into this buffer */
  55625. int eOp /* zero to read. non-zero to write. */
  55626. ){
  55627. unsigned char *aPayload;
  55628. int rc = SQLITE_OK;
  55629. int iIdx = 0;
  55630. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  55631. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  55632. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  55633. unsigned char * const pBufStart = pBuf;
  55634. int bEnd; /* True if reading to end of data */
  55635. #endif
  55636. assert( pPage );
  55637. assert( pCur->eState==CURSOR_VALID );
  55638. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  55639. assert( cursorHoldsMutex(pCur) );
  55640. assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
  55641. getCellInfo(pCur);
  55642. aPayload = pCur->info.pPayload;
  55643. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  55644. bEnd = offset+amt==pCur->info.nPayload;
  55645. #endif
  55646. assert( offset+amt <= pCur->info.nPayload );
  55647. if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
  55648. /* Trying to read or write past the end of the data is an error */
  55649. return SQLITE_CORRUPT_BKPT;
  55650. }
  55651. /* Check if data must be read/written to/from the btree page itself. */
  55652. if( offset<pCur->info.nLocal ){
  55653. int a = amt;
  55654. if( a+offset>pCur->info.nLocal ){
  55655. a = pCur->info.nLocal - offset;
  55656. }
  55657. rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
  55658. offset = 0;
  55659. pBuf += a;
  55660. amt -= a;
  55661. }else{
  55662. offset -= pCur->info.nLocal;
  55663. }
  55664. if( rc==SQLITE_OK && amt>0 ){
  55665. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  55666. Pgno nextPage;
  55667. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  55668. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  55669. ** Except, do not allocate aOverflow[] for eOp==2.
  55670. **
  55671. ** The aOverflow[] array is sized at one entry for each overflow page
  55672. ** in the overflow chain. The page number of the first overflow page is
  55673. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  55674. ** means "not yet known" (the cache is lazily populated).
  55675. */
  55676. if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  55677. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  55678. if( nOvfl>pCur->nOvflAlloc ){
  55679. Pgno *aNew = (Pgno*)sqlite3Realloc(
  55680. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  55681. );
  55682. if( aNew==0 ){
  55683. rc = SQLITE_NOMEM;
  55684. }else{
  55685. pCur->nOvflAlloc = nOvfl*2;
  55686. pCur->aOverflow = aNew;
  55687. }
  55688. }
  55689. if( rc==SQLITE_OK ){
  55690. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  55691. pCur->curFlags |= BTCF_ValidOvfl;
  55692. }
  55693. }
  55694. /* If the overflow page-list cache has been allocated and the
  55695. ** entry for the first required overflow page is valid, skip
  55696. ** directly to it.
  55697. */
  55698. if( (pCur->curFlags & BTCF_ValidOvfl)!=0
  55699. && pCur->aOverflow[offset/ovflSize]
  55700. ){
  55701. iIdx = (offset/ovflSize);
  55702. nextPage = pCur->aOverflow[iIdx];
  55703. offset = (offset%ovflSize);
  55704. }
  55705. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  55706. /* If required, populate the overflow page-list cache. */
  55707. if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
  55708. assert( pCur->aOverflow[iIdx]==0
  55709. || pCur->aOverflow[iIdx]==nextPage
  55710. || CORRUPT_DB );
  55711. pCur->aOverflow[iIdx] = nextPage;
  55712. }
  55713. if( offset>=ovflSize ){
  55714. /* The only reason to read this page is to obtain the page
  55715. ** number for the next page in the overflow chain. The page
  55716. ** data is not required. So first try to lookup the overflow
  55717. ** page-list cache, if any, then fall back to the getOverflowPage()
  55718. ** function.
  55719. **
  55720. ** Note that the aOverflow[] array must be allocated because eOp!=2
  55721. ** here. If eOp==2, then offset==0 and this branch is never taken.
  55722. */
  55723. assert( eOp!=2 );
  55724. assert( pCur->curFlags & BTCF_ValidOvfl );
  55725. assert( pCur->pBtree->db==pBt->db );
  55726. if( pCur->aOverflow[iIdx+1] ){
  55727. nextPage = pCur->aOverflow[iIdx+1];
  55728. }else{
  55729. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  55730. }
  55731. offset -= ovflSize;
  55732. }else{
  55733. /* Need to read this page properly. It contains some of the
  55734. ** range of data that is being read (eOp==0) or written (eOp!=0).
  55735. */
  55736. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  55737. sqlite3_file *fd;
  55738. #endif
  55739. int a = amt;
  55740. if( a + offset > ovflSize ){
  55741. a = ovflSize - offset;
  55742. }
  55743. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  55744. /* If all the following are true:
  55745. **
  55746. ** 1) this is a read operation, and
  55747. ** 2) data is required from the start of this overflow page, and
  55748. ** 3) the database is file-backed, and
  55749. ** 4) there is no open write-transaction, and
  55750. ** 5) the database is not a WAL database,
  55751. ** 6) all data from the page is being read.
  55752. ** 7) at least 4 bytes have already been read into the output buffer
  55753. **
  55754. ** then data can be read directly from the database file into the
  55755. ** output buffer, bypassing the page-cache altogether. This speeds
  55756. ** up loading large records that span many overflow pages.
  55757. */
  55758. if( (eOp&0x01)==0 /* (1) */
  55759. && offset==0 /* (2) */
  55760. && (bEnd || a==ovflSize) /* (6) */
  55761. && pBt->inTransaction==TRANS_READ /* (4) */
  55762. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  55763. && pBt->pPage1->aData[19]==0x01 /* (5) */
  55764. && &pBuf[-4]>=pBufStart /* (7) */
  55765. ){
  55766. u8 aSave[4];
  55767. u8 *aWrite = &pBuf[-4];
  55768. assert( aWrite>=pBufStart ); /* hence (7) */
  55769. memcpy(aSave, aWrite, 4);
  55770. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  55771. nextPage = get4byte(aWrite);
  55772. memcpy(aWrite, aSave, 4);
  55773. }else
  55774. #endif
  55775. {
  55776. DbPage *pDbPage;
  55777. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  55778. ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
  55779. );
  55780. if( rc==SQLITE_OK ){
  55781. aPayload = sqlite3PagerGetData(pDbPage);
  55782. nextPage = get4byte(aPayload);
  55783. rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
  55784. sqlite3PagerUnref(pDbPage);
  55785. offset = 0;
  55786. }
  55787. }
  55788. amt -= a;
  55789. pBuf += a;
  55790. }
  55791. }
  55792. }
  55793. if( rc==SQLITE_OK && amt>0 ){
  55794. return SQLITE_CORRUPT_BKPT;
  55795. }
  55796. return rc;
  55797. }
  55798. /*
  55799. ** Read part of the key associated with cursor pCur. Exactly
  55800. ** "amt" bytes will be transferred into pBuf[]. The transfer
  55801. ** begins at "offset".
  55802. **
  55803. ** The caller must ensure that pCur is pointing to a valid row
  55804. ** in the table.
  55805. **
  55806. ** Return SQLITE_OK on success or an error code if anything goes
  55807. ** wrong. An error is returned if "offset+amt" is larger than
  55808. ** the available payload.
  55809. */
  55810. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  55811. assert( cursorHoldsMutex(pCur) );
  55812. assert( pCur->eState==CURSOR_VALID );
  55813. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  55814. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  55815. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  55816. }
  55817. /*
  55818. ** Read part of the data associated with cursor pCur. Exactly
  55819. ** "amt" bytes will be transfered into pBuf[]. The transfer
  55820. ** begins at "offset".
  55821. **
  55822. ** Return SQLITE_OK on success or an error code if anything goes
  55823. ** wrong. An error is returned if "offset+amt" is larger than
  55824. ** the available payload.
  55825. */
  55826. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  55827. int rc;
  55828. #ifndef SQLITE_OMIT_INCRBLOB
  55829. if ( pCur->eState==CURSOR_INVALID ){
  55830. return SQLITE_ABORT;
  55831. }
  55832. #endif
  55833. assert( cursorHoldsMutex(pCur) );
  55834. rc = restoreCursorPosition(pCur);
  55835. if( rc==SQLITE_OK ){
  55836. assert( pCur->eState==CURSOR_VALID );
  55837. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  55838. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  55839. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  55840. }
  55841. return rc;
  55842. }
  55843. /*
  55844. ** Return a pointer to payload information from the entry that the
  55845. ** pCur cursor is pointing to. The pointer is to the beginning of
  55846. ** the key if index btrees (pPage->intKey==0) and is the data for
  55847. ** table btrees (pPage->intKey==1). The number of bytes of available
  55848. ** key/data is written into *pAmt. If *pAmt==0, then the value
  55849. ** returned will not be a valid pointer.
  55850. **
  55851. ** This routine is an optimization. It is common for the entire key
  55852. ** and data to fit on the local page and for there to be no overflow
  55853. ** pages. When that is so, this routine can be used to access the
  55854. ** key and data without making a copy. If the key and/or data spills
  55855. ** onto overflow pages, then accessPayload() must be used to reassemble
  55856. ** the key/data and copy it into a preallocated buffer.
  55857. **
  55858. ** The pointer returned by this routine looks directly into the cached
  55859. ** page of the database. The data might change or move the next time
  55860. ** any btree routine is called.
  55861. */
  55862. static const void *fetchPayload(
  55863. BtCursor *pCur, /* Cursor pointing to entry to read from */
  55864. u32 *pAmt /* Write the number of available bytes here */
  55865. ){
  55866. u32 amt;
  55867. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  55868. assert( pCur->eState==CURSOR_VALID );
  55869. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  55870. assert( cursorHoldsMutex(pCur) );
  55871. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  55872. assert( pCur->info.nSize>0 );
  55873. assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
  55874. assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
  55875. amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
  55876. if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
  55877. *pAmt = amt;
  55878. return (void*)pCur->info.pPayload;
  55879. }
  55880. /*
  55881. ** For the entry that cursor pCur is point to, return as
  55882. ** many bytes of the key or data as are available on the local
  55883. ** b-tree page. Write the number of available bytes into *pAmt.
  55884. **
  55885. ** The pointer returned is ephemeral. The key/data may move
  55886. ** or be destroyed on the next call to any Btree routine,
  55887. ** including calls from other threads against the same cache.
  55888. ** Hence, a mutex on the BtShared should be held prior to calling
  55889. ** this routine.
  55890. **
  55891. ** These routines is used to get quick access to key and data
  55892. ** in the common case where no overflow pages are used.
  55893. */
  55894. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
  55895. return fetchPayload(pCur, pAmt);
  55896. }
  55897. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
  55898. return fetchPayload(pCur, pAmt);
  55899. }
  55900. /*
  55901. ** Move the cursor down to a new child page. The newPgno argument is the
  55902. ** page number of the child page to move to.
  55903. **
  55904. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  55905. ** the new child page does not match the flags field of the parent (i.e.
  55906. ** if an intkey page appears to be the parent of a non-intkey page, or
  55907. ** vice-versa).
  55908. */
  55909. static int moveToChild(BtCursor *pCur, u32 newPgno){
  55910. BtShared *pBt = pCur->pBt;
  55911. assert( cursorHoldsMutex(pCur) );
  55912. assert( pCur->eState==CURSOR_VALID );
  55913. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  55914. assert( pCur->iPage>=0 );
  55915. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  55916. return SQLITE_CORRUPT_BKPT;
  55917. }
  55918. pCur->info.nSize = 0;
  55919. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  55920. pCur->iPage++;
  55921. pCur->aiIdx[pCur->iPage] = 0;
  55922. return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
  55923. pCur, pCur->curPagerFlags);
  55924. }
  55925. #if SQLITE_DEBUG
  55926. /*
  55927. ** Page pParent is an internal (non-leaf) tree page. This function
  55928. ** asserts that page number iChild is the left-child if the iIdx'th
  55929. ** cell in page pParent. Or, if iIdx is equal to the total number of
  55930. ** cells in pParent, that page number iChild is the right-child of
  55931. ** the page.
  55932. */
  55933. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  55934. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  55935. ** in a corrupt database */
  55936. assert( iIdx<=pParent->nCell );
  55937. if( iIdx==pParent->nCell ){
  55938. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  55939. }else{
  55940. assert( get4byte(findCell(pParent, iIdx))==iChild );
  55941. }
  55942. }
  55943. #else
  55944. # define assertParentIndex(x,y,z)
  55945. #endif
  55946. /*
  55947. ** Move the cursor up to the parent page.
  55948. **
  55949. ** pCur->idx is set to the cell index that contains the pointer
  55950. ** to the page we are coming from. If we are coming from the
  55951. ** right-most child page then pCur->idx is set to one more than
  55952. ** the largest cell index.
  55953. */
  55954. static void moveToParent(BtCursor *pCur){
  55955. assert( cursorHoldsMutex(pCur) );
  55956. assert( pCur->eState==CURSOR_VALID );
  55957. assert( pCur->iPage>0 );
  55958. assert( pCur->apPage[pCur->iPage] );
  55959. assertParentIndex(
  55960. pCur->apPage[pCur->iPage-1],
  55961. pCur->aiIdx[pCur->iPage-1],
  55962. pCur->apPage[pCur->iPage]->pgno
  55963. );
  55964. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  55965. pCur->info.nSize = 0;
  55966. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  55967. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  55968. }
  55969. /*
  55970. ** Move the cursor to point to the root page of its b-tree structure.
  55971. **
  55972. ** If the table has a virtual root page, then the cursor is moved to point
  55973. ** to the virtual root page instead of the actual root page. A table has a
  55974. ** virtual root page when the actual root page contains no cells and a
  55975. ** single child page. This can only happen with the table rooted at page 1.
  55976. **
  55977. ** If the b-tree structure is empty, the cursor state is set to
  55978. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  55979. ** cell located on the root (or virtual root) page and the cursor state
  55980. ** is set to CURSOR_VALID.
  55981. **
  55982. ** If this function returns successfully, it may be assumed that the
  55983. ** page-header flags indicate that the [virtual] root-page is the expected
  55984. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  55985. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  55986. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  55987. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  55988. ** b-tree).
  55989. */
  55990. static int moveToRoot(BtCursor *pCur){
  55991. MemPage *pRoot;
  55992. int rc = SQLITE_OK;
  55993. assert( cursorHoldsMutex(pCur) );
  55994. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  55995. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  55996. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  55997. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  55998. if( pCur->eState==CURSOR_FAULT ){
  55999. assert( pCur->skipNext!=SQLITE_OK );
  56000. return pCur->skipNext;
  56001. }
  56002. sqlite3BtreeClearCursor(pCur);
  56003. }
  56004. if( pCur->iPage>=0 ){
  56005. while( pCur->iPage ){
  56006. assert( pCur->apPage[pCur->iPage]!=0 );
  56007. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  56008. }
  56009. }else if( pCur->pgnoRoot==0 ){
  56010. pCur->eState = CURSOR_INVALID;
  56011. return SQLITE_OK;
  56012. }else{
  56013. assert( pCur->iPage==(-1) );
  56014. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  56015. 0, pCur->curPagerFlags);
  56016. if( rc!=SQLITE_OK ){
  56017. pCur->eState = CURSOR_INVALID;
  56018. return rc;
  56019. }
  56020. pCur->iPage = 0;
  56021. pCur->curIntKey = pCur->apPage[0]->intKey;
  56022. }
  56023. pRoot = pCur->apPage[0];
  56024. assert( pRoot->pgno==pCur->pgnoRoot );
  56025. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  56026. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  56027. ** NULL, the caller expects a table b-tree. If this is not the case,
  56028. ** return an SQLITE_CORRUPT error.
  56029. **
  56030. ** Earlier versions of SQLite assumed that this test could not fail
  56031. ** if the root page was already loaded when this function was called (i.e.
  56032. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  56033. ** in such a way that page pRoot is linked into a second b-tree table
  56034. ** (or the freelist). */
  56035. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  56036. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  56037. return SQLITE_CORRUPT_BKPT;
  56038. }
  56039. pCur->aiIdx[0] = 0;
  56040. pCur->info.nSize = 0;
  56041. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  56042. if( pRoot->nCell>0 ){
  56043. pCur->eState = CURSOR_VALID;
  56044. }else if( !pRoot->leaf ){
  56045. Pgno subpage;
  56046. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  56047. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  56048. pCur->eState = CURSOR_VALID;
  56049. rc = moveToChild(pCur, subpage);
  56050. }else{
  56051. pCur->eState = CURSOR_INVALID;
  56052. }
  56053. return rc;
  56054. }
  56055. /*
  56056. ** Move the cursor down to the left-most leaf entry beneath the
  56057. ** entry to which it is currently pointing.
  56058. **
  56059. ** The left-most leaf is the one with the smallest key - the first
  56060. ** in ascending order.
  56061. */
  56062. static int moveToLeftmost(BtCursor *pCur){
  56063. Pgno pgno;
  56064. int rc = SQLITE_OK;
  56065. MemPage *pPage;
  56066. assert( cursorHoldsMutex(pCur) );
  56067. assert( pCur->eState==CURSOR_VALID );
  56068. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  56069. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  56070. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  56071. rc = moveToChild(pCur, pgno);
  56072. }
  56073. return rc;
  56074. }
  56075. /*
  56076. ** Move the cursor down to the right-most leaf entry beneath the
  56077. ** page to which it is currently pointing. Notice the difference
  56078. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  56079. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  56080. ** finds the right-most entry beneath the *page*.
  56081. **
  56082. ** The right-most entry is the one with the largest key - the last
  56083. ** key in ascending order.
  56084. */
  56085. static int moveToRightmost(BtCursor *pCur){
  56086. Pgno pgno;
  56087. int rc = SQLITE_OK;
  56088. MemPage *pPage = 0;
  56089. assert( cursorHoldsMutex(pCur) );
  56090. assert( pCur->eState==CURSOR_VALID );
  56091. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  56092. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  56093. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  56094. rc = moveToChild(pCur, pgno);
  56095. if( rc ) return rc;
  56096. }
  56097. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  56098. assert( pCur->info.nSize==0 );
  56099. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  56100. return SQLITE_OK;
  56101. }
  56102. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  56103. ** on success. Set *pRes to 0 if the cursor actually points to something
  56104. ** or set *pRes to 1 if the table is empty.
  56105. */
  56106. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  56107. int rc;
  56108. assert( cursorHoldsMutex(pCur) );
  56109. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  56110. rc = moveToRoot(pCur);
  56111. if( rc==SQLITE_OK ){
  56112. if( pCur->eState==CURSOR_INVALID ){
  56113. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  56114. *pRes = 1;
  56115. }else{
  56116. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  56117. *pRes = 0;
  56118. rc = moveToLeftmost(pCur);
  56119. }
  56120. }
  56121. return rc;
  56122. }
  56123. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  56124. ** on success. Set *pRes to 0 if the cursor actually points to something
  56125. ** or set *pRes to 1 if the table is empty.
  56126. */
  56127. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  56128. int rc;
  56129. assert( cursorHoldsMutex(pCur) );
  56130. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  56131. /* If the cursor already points to the last entry, this is a no-op. */
  56132. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  56133. #ifdef SQLITE_DEBUG
  56134. /* This block serves to assert() that the cursor really does point
  56135. ** to the last entry in the b-tree. */
  56136. int ii;
  56137. for(ii=0; ii<pCur->iPage; ii++){
  56138. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  56139. }
  56140. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  56141. assert( pCur->apPage[pCur->iPage]->leaf );
  56142. #endif
  56143. return SQLITE_OK;
  56144. }
  56145. rc = moveToRoot(pCur);
  56146. if( rc==SQLITE_OK ){
  56147. if( CURSOR_INVALID==pCur->eState ){
  56148. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  56149. *pRes = 1;
  56150. }else{
  56151. assert( pCur->eState==CURSOR_VALID );
  56152. *pRes = 0;
  56153. rc = moveToRightmost(pCur);
  56154. if( rc==SQLITE_OK ){
  56155. pCur->curFlags |= BTCF_AtLast;
  56156. }else{
  56157. pCur->curFlags &= ~BTCF_AtLast;
  56158. }
  56159. }
  56160. }
  56161. return rc;
  56162. }
  56163. /* Move the cursor so that it points to an entry near the key
  56164. ** specified by pIdxKey or intKey. Return a success code.
  56165. **
  56166. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  56167. ** must be NULL. For index tables, pIdxKey is used and intKey
  56168. ** is ignored.
  56169. **
  56170. ** If an exact match is not found, then the cursor is always
  56171. ** left pointing at a leaf page which would hold the entry if it
  56172. ** were present. The cursor might point to an entry that comes
  56173. ** before or after the key.
  56174. **
  56175. ** An integer is written into *pRes which is the result of
  56176. ** comparing the key with the entry to which the cursor is
  56177. ** pointing. The meaning of the integer written into
  56178. ** *pRes is as follows:
  56179. **
  56180. ** *pRes<0 The cursor is left pointing at an entry that
  56181. ** is smaller than intKey/pIdxKey or if the table is empty
  56182. ** and the cursor is therefore left point to nothing.
  56183. **
  56184. ** *pRes==0 The cursor is left pointing at an entry that
  56185. ** exactly matches intKey/pIdxKey.
  56186. **
  56187. ** *pRes>0 The cursor is left pointing at an entry that
  56188. ** is larger than intKey/pIdxKey.
  56189. **
  56190. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  56191. ** exists an entry in the table that exactly matches pIdxKey.
  56192. */
  56193. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  56194. BtCursor *pCur, /* The cursor to be moved */
  56195. UnpackedRecord *pIdxKey, /* Unpacked index key */
  56196. i64 intKey, /* The table key */
  56197. int biasRight, /* If true, bias the search to the high end */
  56198. int *pRes /* Write search results here */
  56199. ){
  56200. int rc;
  56201. RecordCompare xRecordCompare;
  56202. assert( cursorHoldsMutex(pCur) );
  56203. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  56204. assert( pRes );
  56205. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  56206. /* If the cursor is already positioned at the point we are trying
  56207. ** to move to, then just return without doing any work */
  56208. if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  56209. && pCur->curIntKey
  56210. ){
  56211. if( pCur->info.nKey==intKey ){
  56212. *pRes = 0;
  56213. return SQLITE_OK;
  56214. }
  56215. if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
  56216. *pRes = -1;
  56217. return SQLITE_OK;
  56218. }
  56219. }
  56220. if( pIdxKey ){
  56221. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  56222. pIdxKey->errCode = 0;
  56223. assert( pIdxKey->default_rc==1
  56224. || pIdxKey->default_rc==0
  56225. || pIdxKey->default_rc==-1
  56226. );
  56227. }else{
  56228. xRecordCompare = 0; /* All keys are integers */
  56229. }
  56230. rc = moveToRoot(pCur);
  56231. if( rc ){
  56232. return rc;
  56233. }
  56234. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  56235. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  56236. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  56237. if( pCur->eState==CURSOR_INVALID ){
  56238. *pRes = -1;
  56239. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  56240. return SQLITE_OK;
  56241. }
  56242. assert( pCur->apPage[0]->intKey==pCur->curIntKey );
  56243. assert( pCur->curIntKey || pIdxKey );
  56244. for(;;){
  56245. int lwr, upr, idx, c;
  56246. Pgno chldPg;
  56247. MemPage *pPage = pCur->apPage[pCur->iPage];
  56248. u8 *pCell; /* Pointer to current cell in pPage */
  56249. /* pPage->nCell must be greater than zero. If this is the root-page
  56250. ** the cursor would have been INVALID above and this for(;;) loop
  56251. ** not run. If this is not the root-page, then the moveToChild() routine
  56252. ** would have already detected db corruption. Similarly, pPage must
  56253. ** be the right kind (index or table) of b-tree page. Otherwise
  56254. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  56255. assert( pPage->nCell>0 );
  56256. assert( pPage->intKey==(pIdxKey==0) );
  56257. lwr = 0;
  56258. upr = pPage->nCell-1;
  56259. assert( biasRight==0 || biasRight==1 );
  56260. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  56261. pCur->aiIdx[pCur->iPage] = (u16)idx;
  56262. if( xRecordCompare==0 ){
  56263. for(;;){
  56264. i64 nCellKey;
  56265. pCell = findCellPastPtr(pPage, idx);
  56266. if( pPage->intKeyLeaf ){
  56267. while( 0x80 <= *(pCell++) ){
  56268. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  56269. }
  56270. }
  56271. getVarint(pCell, (u64*)&nCellKey);
  56272. if( nCellKey<intKey ){
  56273. lwr = idx+1;
  56274. if( lwr>upr ){ c = -1; break; }
  56275. }else if( nCellKey>intKey ){
  56276. upr = idx-1;
  56277. if( lwr>upr ){ c = +1; break; }
  56278. }else{
  56279. assert( nCellKey==intKey );
  56280. pCur->curFlags |= BTCF_ValidNKey;
  56281. pCur->info.nKey = nCellKey;
  56282. pCur->aiIdx[pCur->iPage] = (u16)idx;
  56283. if( !pPage->leaf ){
  56284. lwr = idx;
  56285. goto moveto_next_layer;
  56286. }else{
  56287. *pRes = 0;
  56288. rc = SQLITE_OK;
  56289. goto moveto_finish;
  56290. }
  56291. }
  56292. assert( lwr+upr>=0 );
  56293. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  56294. }
  56295. }else{
  56296. for(;;){
  56297. int nCell; /* Size of the pCell cell in bytes */
  56298. pCell = findCellPastPtr(pPage, idx);
  56299. /* The maximum supported page-size is 65536 bytes. This means that
  56300. ** the maximum number of record bytes stored on an index B-Tree
  56301. ** page is less than 16384 bytes and may be stored as a 2-byte
  56302. ** varint. This information is used to attempt to avoid parsing
  56303. ** the entire cell by checking for the cases where the record is
  56304. ** stored entirely within the b-tree page by inspecting the first
  56305. ** 2 bytes of the cell.
  56306. */
  56307. nCell = pCell[0];
  56308. if( nCell<=pPage->max1bytePayload ){
  56309. /* This branch runs if the record-size field of the cell is a
  56310. ** single byte varint and the record fits entirely on the main
  56311. ** b-tree page. */
  56312. testcase( pCell+nCell+1==pPage->aDataEnd );
  56313. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  56314. }else if( !(pCell[1] & 0x80)
  56315. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  56316. ){
  56317. /* The record-size field is a 2 byte varint and the record
  56318. ** fits entirely on the main b-tree page. */
  56319. testcase( pCell+nCell+2==pPage->aDataEnd );
  56320. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  56321. }else{
  56322. /* The record flows over onto one or more overflow pages. In
  56323. ** this case the whole cell needs to be parsed, a buffer allocated
  56324. ** and accessPayload() used to retrieve the record into the
  56325. ** buffer before VdbeRecordCompare() can be called.
  56326. **
  56327. ** If the record is corrupt, the xRecordCompare routine may read
  56328. ** up to two varints past the end of the buffer. An extra 18
  56329. ** bytes of padding is allocated at the end of the buffer in
  56330. ** case this happens. */
  56331. void *pCellKey;
  56332. u8 * const pCellBody = pCell - pPage->childPtrSize;
  56333. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  56334. nCell = (int)pCur->info.nKey;
  56335. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  56336. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  56337. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  56338. testcase( nCell==2 ); /* Minimum legal index key size */
  56339. if( nCell<2 ){
  56340. rc = SQLITE_CORRUPT_BKPT;
  56341. goto moveto_finish;
  56342. }
  56343. pCellKey = sqlite3Malloc( nCell+18 );
  56344. if( pCellKey==0 ){
  56345. rc = SQLITE_NOMEM;
  56346. goto moveto_finish;
  56347. }
  56348. pCur->aiIdx[pCur->iPage] = (u16)idx;
  56349. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
  56350. if( rc ){
  56351. sqlite3_free(pCellKey);
  56352. goto moveto_finish;
  56353. }
  56354. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  56355. sqlite3_free(pCellKey);
  56356. }
  56357. assert(
  56358. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  56359. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  56360. );
  56361. if( c<0 ){
  56362. lwr = idx+1;
  56363. }else if( c>0 ){
  56364. upr = idx-1;
  56365. }else{
  56366. assert( c==0 );
  56367. *pRes = 0;
  56368. rc = SQLITE_OK;
  56369. pCur->aiIdx[pCur->iPage] = (u16)idx;
  56370. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  56371. goto moveto_finish;
  56372. }
  56373. if( lwr>upr ) break;
  56374. assert( lwr+upr>=0 );
  56375. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  56376. }
  56377. }
  56378. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  56379. assert( pPage->isInit );
  56380. if( pPage->leaf ){
  56381. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  56382. pCur->aiIdx[pCur->iPage] = (u16)idx;
  56383. *pRes = c;
  56384. rc = SQLITE_OK;
  56385. goto moveto_finish;
  56386. }
  56387. moveto_next_layer:
  56388. if( lwr>=pPage->nCell ){
  56389. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  56390. }else{
  56391. chldPg = get4byte(findCell(pPage, lwr));
  56392. }
  56393. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  56394. rc = moveToChild(pCur, chldPg);
  56395. if( rc ) break;
  56396. }
  56397. moveto_finish:
  56398. pCur->info.nSize = 0;
  56399. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  56400. return rc;
  56401. }
  56402. /*
  56403. ** Return TRUE if the cursor is not pointing at an entry of the table.
  56404. **
  56405. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  56406. ** past the last entry in the table or sqlite3BtreePrev() moves past
  56407. ** the first entry. TRUE is also returned if the table is empty.
  56408. */
  56409. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  56410. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  56411. ** have been deleted? This API will need to change to return an error code
  56412. ** as well as the boolean result value.
  56413. */
  56414. return (CURSOR_VALID!=pCur->eState);
  56415. }
  56416. /*
  56417. ** Advance the cursor to the next entry in the database. If
  56418. ** successful then set *pRes=0. If the cursor
  56419. ** was already pointing to the last entry in the database before
  56420. ** this routine was called, then set *pRes=1.
  56421. **
  56422. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  56423. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  56424. ** to the next cell on the current page. The (slower) btreeNext() helper
  56425. ** routine is called when it is necessary to move to a different page or
  56426. ** to restore the cursor.
  56427. **
  56428. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  56429. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  56430. ** if this routine could have been skipped if that SQL index had been
  56431. ** a unique index. Otherwise the caller will have set *pRes to zero.
  56432. ** Zero is the common case. The btree implementation is free to use the
  56433. ** initial *pRes value as a hint to improve performance, but the current
  56434. ** SQLite btree implementation does not. (Note that the comdb2 btree
  56435. ** implementation does use this hint, however.)
  56436. */
  56437. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  56438. int rc;
  56439. int idx;
  56440. MemPage *pPage;
  56441. assert( cursorHoldsMutex(pCur) );
  56442. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  56443. assert( *pRes==0 );
  56444. if( pCur->eState!=CURSOR_VALID ){
  56445. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  56446. rc = restoreCursorPosition(pCur);
  56447. if( rc!=SQLITE_OK ){
  56448. return rc;
  56449. }
  56450. if( CURSOR_INVALID==pCur->eState ){
  56451. *pRes = 1;
  56452. return SQLITE_OK;
  56453. }
  56454. if( pCur->skipNext ){
  56455. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  56456. pCur->eState = CURSOR_VALID;
  56457. if( pCur->skipNext>0 ){
  56458. pCur->skipNext = 0;
  56459. return SQLITE_OK;
  56460. }
  56461. pCur->skipNext = 0;
  56462. }
  56463. }
  56464. pPage = pCur->apPage[pCur->iPage];
  56465. idx = ++pCur->aiIdx[pCur->iPage];
  56466. assert( pPage->isInit );
  56467. /* If the database file is corrupt, it is possible for the value of idx
  56468. ** to be invalid here. This can only occur if a second cursor modifies
  56469. ** the page while cursor pCur is holding a reference to it. Which can
  56470. ** only happen if the database is corrupt in such a way as to link the
  56471. ** page into more than one b-tree structure. */
  56472. testcase( idx>pPage->nCell );
  56473. if( idx>=pPage->nCell ){
  56474. if( !pPage->leaf ){
  56475. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  56476. if( rc ) return rc;
  56477. return moveToLeftmost(pCur);
  56478. }
  56479. do{
  56480. if( pCur->iPage==0 ){
  56481. *pRes = 1;
  56482. pCur->eState = CURSOR_INVALID;
  56483. return SQLITE_OK;
  56484. }
  56485. moveToParent(pCur);
  56486. pPage = pCur->apPage[pCur->iPage];
  56487. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  56488. if( pPage->intKey ){
  56489. return sqlite3BtreeNext(pCur, pRes);
  56490. }else{
  56491. return SQLITE_OK;
  56492. }
  56493. }
  56494. if( pPage->leaf ){
  56495. return SQLITE_OK;
  56496. }else{
  56497. return moveToLeftmost(pCur);
  56498. }
  56499. }
  56500. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  56501. MemPage *pPage;
  56502. assert( cursorHoldsMutex(pCur) );
  56503. assert( pRes!=0 );
  56504. assert( *pRes==0 || *pRes==1 );
  56505. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  56506. pCur->info.nSize = 0;
  56507. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  56508. *pRes = 0;
  56509. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  56510. pPage = pCur->apPage[pCur->iPage];
  56511. if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
  56512. pCur->aiIdx[pCur->iPage]--;
  56513. return btreeNext(pCur, pRes);
  56514. }
  56515. if( pPage->leaf ){
  56516. return SQLITE_OK;
  56517. }else{
  56518. return moveToLeftmost(pCur);
  56519. }
  56520. }
  56521. /*
  56522. ** Step the cursor to the back to the previous entry in the database. If
  56523. ** successful then set *pRes=0. If the cursor
  56524. ** was already pointing to the first entry in the database before
  56525. ** this routine was called, then set *pRes=1.
  56526. **
  56527. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  56528. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  56529. ** to the previous cell on the current page. The (slower) btreePrevious()
  56530. ** helper routine is called when it is necessary to move to a different page
  56531. ** or to restore the cursor.
  56532. **
  56533. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  56534. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  56535. ** if this routine could have been skipped if that SQL index had been
  56536. ** a unique index. Otherwise the caller will have set *pRes to zero.
  56537. ** Zero is the common case. The btree implementation is free to use the
  56538. ** initial *pRes value as a hint to improve performance, but the current
  56539. ** SQLite btree implementation does not. (Note that the comdb2 btree
  56540. ** implementation does use this hint, however.)
  56541. */
  56542. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  56543. int rc;
  56544. MemPage *pPage;
  56545. assert( cursorHoldsMutex(pCur) );
  56546. assert( pRes!=0 );
  56547. assert( *pRes==0 );
  56548. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  56549. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  56550. assert( pCur->info.nSize==0 );
  56551. if( pCur->eState!=CURSOR_VALID ){
  56552. rc = restoreCursorPosition(pCur);
  56553. if( rc!=SQLITE_OK ){
  56554. return rc;
  56555. }
  56556. if( CURSOR_INVALID==pCur->eState ){
  56557. *pRes = 1;
  56558. return SQLITE_OK;
  56559. }
  56560. if( pCur->skipNext ){
  56561. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  56562. pCur->eState = CURSOR_VALID;
  56563. if( pCur->skipNext<0 ){
  56564. pCur->skipNext = 0;
  56565. return SQLITE_OK;
  56566. }
  56567. pCur->skipNext = 0;
  56568. }
  56569. }
  56570. pPage = pCur->apPage[pCur->iPage];
  56571. assert( pPage->isInit );
  56572. if( !pPage->leaf ){
  56573. int idx = pCur->aiIdx[pCur->iPage];
  56574. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  56575. if( rc ) return rc;
  56576. rc = moveToRightmost(pCur);
  56577. }else{
  56578. while( pCur->aiIdx[pCur->iPage]==0 ){
  56579. if( pCur->iPage==0 ){
  56580. pCur->eState = CURSOR_INVALID;
  56581. *pRes = 1;
  56582. return SQLITE_OK;
  56583. }
  56584. moveToParent(pCur);
  56585. }
  56586. assert( pCur->info.nSize==0 );
  56587. assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
  56588. pCur->aiIdx[pCur->iPage]--;
  56589. pPage = pCur->apPage[pCur->iPage];
  56590. if( pPage->intKey && !pPage->leaf ){
  56591. rc = sqlite3BtreePrevious(pCur, pRes);
  56592. }else{
  56593. rc = SQLITE_OK;
  56594. }
  56595. }
  56596. return rc;
  56597. }
  56598. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  56599. assert( cursorHoldsMutex(pCur) );
  56600. assert( pRes!=0 );
  56601. assert( *pRes==0 || *pRes==1 );
  56602. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  56603. *pRes = 0;
  56604. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  56605. pCur->info.nSize = 0;
  56606. if( pCur->eState!=CURSOR_VALID
  56607. || pCur->aiIdx[pCur->iPage]==0
  56608. || pCur->apPage[pCur->iPage]->leaf==0
  56609. ){
  56610. return btreePrevious(pCur, pRes);
  56611. }
  56612. pCur->aiIdx[pCur->iPage]--;
  56613. return SQLITE_OK;
  56614. }
  56615. /*
  56616. ** Allocate a new page from the database file.
  56617. **
  56618. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  56619. ** has already been called on the new page.) The new page has also
  56620. ** been referenced and the calling routine is responsible for calling
  56621. ** sqlite3PagerUnref() on the new page when it is done.
  56622. **
  56623. ** SQLITE_OK is returned on success. Any other return value indicates
  56624. ** an error. *ppPage is set to NULL in the event of an error.
  56625. **
  56626. ** If the "nearby" parameter is not 0, then an effort is made to
  56627. ** locate a page close to the page number "nearby". This can be used in an
  56628. ** attempt to keep related pages close to each other in the database file,
  56629. ** which in turn can make database access faster.
  56630. **
  56631. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  56632. ** anywhere on the free-list, then it is guaranteed to be returned. If
  56633. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  56634. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  56635. ** are no restrictions on which page is returned.
  56636. */
  56637. static int allocateBtreePage(
  56638. BtShared *pBt, /* The btree */
  56639. MemPage **ppPage, /* Store pointer to the allocated page here */
  56640. Pgno *pPgno, /* Store the page number here */
  56641. Pgno nearby, /* Search for a page near this one */
  56642. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  56643. ){
  56644. MemPage *pPage1;
  56645. int rc;
  56646. u32 n; /* Number of pages on the freelist */
  56647. u32 k; /* Number of leaves on the trunk of the freelist */
  56648. MemPage *pTrunk = 0;
  56649. MemPage *pPrevTrunk = 0;
  56650. Pgno mxPage; /* Total size of the database file */
  56651. assert( sqlite3_mutex_held(pBt->mutex) );
  56652. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  56653. pPage1 = pBt->pPage1;
  56654. mxPage = btreePagecount(pBt);
  56655. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  56656. ** stores stores the total number of pages on the freelist. */
  56657. n = get4byte(&pPage1->aData[36]);
  56658. testcase( n==mxPage-1 );
  56659. if( n>=mxPage ){
  56660. return SQLITE_CORRUPT_BKPT;
  56661. }
  56662. if( n>0 ){
  56663. /* There are pages on the freelist. Reuse one of those pages. */
  56664. Pgno iTrunk;
  56665. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  56666. u32 nSearch = 0; /* Count of the number of search attempts */
  56667. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  56668. ** shows that the page 'nearby' is somewhere on the free-list, then
  56669. ** the entire-list will be searched for that page.
  56670. */
  56671. #ifndef SQLITE_OMIT_AUTOVACUUM
  56672. if( eMode==BTALLOC_EXACT ){
  56673. if( nearby<=mxPage ){
  56674. u8 eType;
  56675. assert( nearby>0 );
  56676. assert( pBt->autoVacuum );
  56677. rc = ptrmapGet(pBt, nearby, &eType, 0);
  56678. if( rc ) return rc;
  56679. if( eType==PTRMAP_FREEPAGE ){
  56680. searchList = 1;
  56681. }
  56682. }
  56683. }else if( eMode==BTALLOC_LE ){
  56684. searchList = 1;
  56685. }
  56686. #endif
  56687. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  56688. ** first free-list trunk page. iPrevTrunk is initially 1.
  56689. */
  56690. rc = sqlite3PagerWrite(pPage1->pDbPage);
  56691. if( rc ) return rc;
  56692. put4byte(&pPage1->aData[36], n-1);
  56693. /* The code within this loop is run only once if the 'searchList' variable
  56694. ** is not true. Otherwise, it runs once for each trunk-page on the
  56695. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  56696. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  56697. */
  56698. do {
  56699. pPrevTrunk = pTrunk;
  56700. if( pPrevTrunk ){
  56701. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  56702. ** is the page number of the next freelist trunk page in the list or
  56703. ** zero if this is the last freelist trunk page. */
  56704. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  56705. }else{
  56706. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  56707. ** stores the page number of the first page of the freelist, or zero if
  56708. ** the freelist is empty. */
  56709. iTrunk = get4byte(&pPage1->aData[32]);
  56710. }
  56711. testcase( iTrunk==mxPage );
  56712. if( iTrunk>mxPage || nSearch++ > n ){
  56713. rc = SQLITE_CORRUPT_BKPT;
  56714. }else{
  56715. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  56716. }
  56717. if( rc ){
  56718. pTrunk = 0;
  56719. goto end_allocate_page;
  56720. }
  56721. assert( pTrunk!=0 );
  56722. assert( pTrunk->aData!=0 );
  56723. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  56724. ** is the number of leaf page pointers to follow. */
  56725. k = get4byte(&pTrunk->aData[4]);
  56726. if( k==0 && !searchList ){
  56727. /* The trunk has no leaves and the list is not being searched.
  56728. ** So extract the trunk page itself and use it as the newly
  56729. ** allocated page */
  56730. assert( pPrevTrunk==0 );
  56731. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  56732. if( rc ){
  56733. goto end_allocate_page;
  56734. }
  56735. *pPgno = iTrunk;
  56736. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  56737. *ppPage = pTrunk;
  56738. pTrunk = 0;
  56739. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  56740. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  56741. /* Value of k is out of range. Database corruption */
  56742. rc = SQLITE_CORRUPT_BKPT;
  56743. goto end_allocate_page;
  56744. #ifndef SQLITE_OMIT_AUTOVACUUM
  56745. }else if( searchList
  56746. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  56747. ){
  56748. /* The list is being searched and this trunk page is the page
  56749. ** to allocate, regardless of whether it has leaves.
  56750. */
  56751. *pPgno = iTrunk;
  56752. *ppPage = pTrunk;
  56753. searchList = 0;
  56754. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  56755. if( rc ){
  56756. goto end_allocate_page;
  56757. }
  56758. if( k==0 ){
  56759. if( !pPrevTrunk ){
  56760. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  56761. }else{
  56762. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  56763. if( rc!=SQLITE_OK ){
  56764. goto end_allocate_page;
  56765. }
  56766. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  56767. }
  56768. }else{
  56769. /* The trunk page is required by the caller but it contains
  56770. ** pointers to free-list leaves. The first leaf becomes a trunk
  56771. ** page in this case.
  56772. */
  56773. MemPage *pNewTrunk;
  56774. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  56775. if( iNewTrunk>mxPage ){
  56776. rc = SQLITE_CORRUPT_BKPT;
  56777. goto end_allocate_page;
  56778. }
  56779. testcase( iNewTrunk==mxPage );
  56780. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  56781. if( rc!=SQLITE_OK ){
  56782. goto end_allocate_page;
  56783. }
  56784. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  56785. if( rc!=SQLITE_OK ){
  56786. releasePage(pNewTrunk);
  56787. goto end_allocate_page;
  56788. }
  56789. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  56790. put4byte(&pNewTrunk->aData[4], k-1);
  56791. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  56792. releasePage(pNewTrunk);
  56793. if( !pPrevTrunk ){
  56794. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  56795. put4byte(&pPage1->aData[32], iNewTrunk);
  56796. }else{
  56797. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  56798. if( rc ){
  56799. goto end_allocate_page;
  56800. }
  56801. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  56802. }
  56803. }
  56804. pTrunk = 0;
  56805. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  56806. #endif
  56807. }else if( k>0 ){
  56808. /* Extract a leaf from the trunk */
  56809. u32 closest;
  56810. Pgno iPage;
  56811. unsigned char *aData = pTrunk->aData;
  56812. if( nearby>0 ){
  56813. u32 i;
  56814. closest = 0;
  56815. if( eMode==BTALLOC_LE ){
  56816. for(i=0; i<k; i++){
  56817. iPage = get4byte(&aData[8+i*4]);
  56818. if( iPage<=nearby ){
  56819. closest = i;
  56820. break;
  56821. }
  56822. }
  56823. }else{
  56824. int dist;
  56825. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  56826. for(i=1; i<k; i++){
  56827. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  56828. if( d2<dist ){
  56829. closest = i;
  56830. dist = d2;
  56831. }
  56832. }
  56833. }
  56834. }else{
  56835. closest = 0;
  56836. }
  56837. iPage = get4byte(&aData[8+closest*4]);
  56838. testcase( iPage==mxPage );
  56839. if( iPage>mxPage ){
  56840. rc = SQLITE_CORRUPT_BKPT;
  56841. goto end_allocate_page;
  56842. }
  56843. testcase( iPage==mxPage );
  56844. if( !searchList
  56845. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  56846. ){
  56847. int noContent;
  56848. *pPgno = iPage;
  56849. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  56850. ": %d more free pages\n",
  56851. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  56852. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  56853. if( rc ) goto end_allocate_page;
  56854. if( closest<k-1 ){
  56855. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  56856. }
  56857. put4byte(&aData[4], k-1);
  56858. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  56859. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  56860. if( rc==SQLITE_OK ){
  56861. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  56862. if( rc!=SQLITE_OK ){
  56863. releasePage(*ppPage);
  56864. *ppPage = 0;
  56865. }
  56866. }
  56867. searchList = 0;
  56868. }
  56869. }
  56870. releasePage(pPrevTrunk);
  56871. pPrevTrunk = 0;
  56872. }while( searchList );
  56873. }else{
  56874. /* There are no pages on the freelist, so append a new page to the
  56875. ** database image.
  56876. **
  56877. ** Normally, new pages allocated by this block can be requested from the
  56878. ** pager layer with the 'no-content' flag set. This prevents the pager
  56879. ** from trying to read the pages content from disk. However, if the
  56880. ** current transaction has already run one or more incremental-vacuum
  56881. ** steps, then the page we are about to allocate may contain content
  56882. ** that is required in the event of a rollback. In this case, do
  56883. ** not set the no-content flag. This causes the pager to load and journal
  56884. ** the current page content before overwriting it.
  56885. **
  56886. ** Note that the pager will not actually attempt to load or journal
  56887. ** content for any page that really does lie past the end of the database
  56888. ** file on disk. So the effects of disabling the no-content optimization
  56889. ** here are confined to those pages that lie between the end of the
  56890. ** database image and the end of the database file.
  56891. */
  56892. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  56893. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  56894. if( rc ) return rc;
  56895. pBt->nPage++;
  56896. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  56897. #ifndef SQLITE_OMIT_AUTOVACUUM
  56898. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  56899. /* If *pPgno refers to a pointer-map page, allocate two new pages
  56900. ** at the end of the file instead of one. The first allocated page
  56901. ** becomes a new pointer-map page, the second is used by the caller.
  56902. */
  56903. MemPage *pPg = 0;
  56904. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  56905. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  56906. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  56907. if( rc==SQLITE_OK ){
  56908. rc = sqlite3PagerWrite(pPg->pDbPage);
  56909. releasePage(pPg);
  56910. }
  56911. if( rc ) return rc;
  56912. pBt->nPage++;
  56913. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  56914. }
  56915. #endif
  56916. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  56917. *pPgno = pBt->nPage;
  56918. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  56919. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  56920. if( rc ) return rc;
  56921. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  56922. if( rc!=SQLITE_OK ){
  56923. releasePage(*ppPage);
  56924. *ppPage = 0;
  56925. }
  56926. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  56927. }
  56928. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  56929. end_allocate_page:
  56930. releasePage(pTrunk);
  56931. releasePage(pPrevTrunk);
  56932. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  56933. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  56934. return rc;
  56935. }
  56936. /*
  56937. ** This function is used to add page iPage to the database file free-list.
  56938. ** It is assumed that the page is not already a part of the free-list.
  56939. **
  56940. ** The value passed as the second argument to this function is optional.
  56941. ** If the caller happens to have a pointer to the MemPage object
  56942. ** corresponding to page iPage handy, it may pass it as the second value.
  56943. ** Otherwise, it may pass NULL.
  56944. **
  56945. ** If a pointer to a MemPage object is passed as the second argument,
  56946. ** its reference count is not altered by this function.
  56947. */
  56948. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  56949. MemPage *pTrunk = 0; /* Free-list trunk page */
  56950. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  56951. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  56952. MemPage *pPage; /* Page being freed. May be NULL. */
  56953. int rc; /* Return Code */
  56954. int nFree; /* Initial number of pages on free-list */
  56955. assert( sqlite3_mutex_held(pBt->mutex) );
  56956. assert( CORRUPT_DB || iPage>1 );
  56957. assert( !pMemPage || pMemPage->pgno==iPage );
  56958. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  56959. if( pMemPage ){
  56960. pPage = pMemPage;
  56961. sqlite3PagerRef(pPage->pDbPage);
  56962. }else{
  56963. pPage = btreePageLookup(pBt, iPage);
  56964. }
  56965. /* Increment the free page count on pPage1 */
  56966. rc = sqlite3PagerWrite(pPage1->pDbPage);
  56967. if( rc ) goto freepage_out;
  56968. nFree = get4byte(&pPage1->aData[36]);
  56969. put4byte(&pPage1->aData[36], nFree+1);
  56970. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  56971. /* If the secure_delete option is enabled, then
  56972. ** always fully overwrite deleted information with zeros.
  56973. */
  56974. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  56975. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  56976. ){
  56977. goto freepage_out;
  56978. }
  56979. memset(pPage->aData, 0, pPage->pBt->pageSize);
  56980. }
  56981. /* If the database supports auto-vacuum, write an entry in the pointer-map
  56982. ** to indicate that the page is free.
  56983. */
  56984. if( ISAUTOVACUUM ){
  56985. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  56986. if( rc ) goto freepage_out;
  56987. }
  56988. /* Now manipulate the actual database free-list structure. There are two
  56989. ** possibilities. If the free-list is currently empty, or if the first
  56990. ** trunk page in the free-list is full, then this page will become a
  56991. ** new free-list trunk page. Otherwise, it will become a leaf of the
  56992. ** first trunk page in the current free-list. This block tests if it
  56993. ** is possible to add the page as a new free-list leaf.
  56994. */
  56995. if( nFree!=0 ){
  56996. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  56997. iTrunk = get4byte(&pPage1->aData[32]);
  56998. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  56999. if( rc!=SQLITE_OK ){
  57000. goto freepage_out;
  57001. }
  57002. nLeaf = get4byte(&pTrunk->aData[4]);
  57003. assert( pBt->usableSize>32 );
  57004. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  57005. rc = SQLITE_CORRUPT_BKPT;
  57006. goto freepage_out;
  57007. }
  57008. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  57009. /* In this case there is room on the trunk page to insert the page
  57010. ** being freed as a new leaf.
  57011. **
  57012. ** Note that the trunk page is not really full until it contains
  57013. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  57014. ** coded. But due to a coding error in versions of SQLite prior to
  57015. ** 3.6.0, databases with freelist trunk pages holding more than
  57016. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  57017. ** to maintain backwards compatibility with older versions of SQLite,
  57018. ** we will continue to restrict the number of entries to usableSize/4 - 8
  57019. ** for now. At some point in the future (once everyone has upgraded
  57020. ** to 3.6.0 or later) we should consider fixing the conditional above
  57021. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  57022. **
  57023. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  57024. ** avoid using the last six entries in the freelist trunk page array in
  57025. ** order that database files created by newer versions of SQLite can be
  57026. ** read by older versions of SQLite.
  57027. */
  57028. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  57029. if( rc==SQLITE_OK ){
  57030. put4byte(&pTrunk->aData[4], nLeaf+1);
  57031. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  57032. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  57033. sqlite3PagerDontWrite(pPage->pDbPage);
  57034. }
  57035. rc = btreeSetHasContent(pBt, iPage);
  57036. }
  57037. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  57038. goto freepage_out;
  57039. }
  57040. }
  57041. /* If control flows to this point, then it was not possible to add the
  57042. ** the page being freed as a leaf page of the first trunk in the free-list.
  57043. ** Possibly because the free-list is empty, or possibly because the
  57044. ** first trunk in the free-list is full. Either way, the page being freed
  57045. ** will become the new first trunk page in the free-list.
  57046. */
  57047. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  57048. goto freepage_out;
  57049. }
  57050. rc = sqlite3PagerWrite(pPage->pDbPage);
  57051. if( rc!=SQLITE_OK ){
  57052. goto freepage_out;
  57053. }
  57054. put4byte(pPage->aData, iTrunk);
  57055. put4byte(&pPage->aData[4], 0);
  57056. put4byte(&pPage1->aData[32], iPage);
  57057. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  57058. freepage_out:
  57059. if( pPage ){
  57060. pPage->isInit = 0;
  57061. }
  57062. releasePage(pPage);
  57063. releasePage(pTrunk);
  57064. return rc;
  57065. }
  57066. static void freePage(MemPage *pPage, int *pRC){
  57067. if( (*pRC)==SQLITE_OK ){
  57068. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  57069. }
  57070. }
  57071. /*
  57072. ** Free any overflow pages associated with the given Cell. Write the
  57073. ** local Cell size (the number of bytes on the original page, omitting
  57074. ** overflow) into *pnSize.
  57075. */
  57076. static int clearCell(
  57077. MemPage *pPage, /* The page that contains the Cell */
  57078. unsigned char *pCell, /* First byte of the Cell */
  57079. u16 *pnSize /* Write the size of the Cell here */
  57080. ){
  57081. BtShared *pBt = pPage->pBt;
  57082. CellInfo info;
  57083. Pgno ovflPgno;
  57084. int rc;
  57085. int nOvfl;
  57086. u32 ovflPageSize;
  57087. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57088. pPage->xParseCell(pPage, pCell, &info);
  57089. *pnSize = info.nSize;
  57090. if( info.nLocal==info.nPayload ){
  57091. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  57092. }
  57093. if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){
  57094. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  57095. }
  57096. ovflPgno = get4byte(pCell + info.nSize - 4);
  57097. assert( pBt->usableSize > 4 );
  57098. ovflPageSize = pBt->usableSize - 4;
  57099. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  57100. assert( nOvfl>0 ||
  57101. (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
  57102. );
  57103. while( nOvfl-- ){
  57104. Pgno iNext = 0;
  57105. MemPage *pOvfl = 0;
  57106. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  57107. /* 0 is not a legal page number and page 1 cannot be an
  57108. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  57109. ** file the database must be corrupt. */
  57110. return SQLITE_CORRUPT_BKPT;
  57111. }
  57112. if( nOvfl ){
  57113. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  57114. if( rc ) return rc;
  57115. }
  57116. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  57117. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  57118. ){
  57119. /* There is no reason any cursor should have an outstanding reference
  57120. ** to an overflow page belonging to a cell that is being deleted/updated.
  57121. ** So if there exists more than one reference to this page, then it
  57122. ** must not really be an overflow page and the database must be corrupt.
  57123. ** It is helpful to detect this before calling freePage2(), as
  57124. ** freePage2() may zero the page contents if secure-delete mode is
  57125. ** enabled. If this 'overflow' page happens to be a page that the
  57126. ** caller is iterating through or using in some other way, this
  57127. ** can be problematic.
  57128. */
  57129. rc = SQLITE_CORRUPT_BKPT;
  57130. }else{
  57131. rc = freePage2(pBt, pOvfl, ovflPgno);
  57132. }
  57133. if( pOvfl ){
  57134. sqlite3PagerUnref(pOvfl->pDbPage);
  57135. }
  57136. if( rc ) return rc;
  57137. ovflPgno = iNext;
  57138. }
  57139. return SQLITE_OK;
  57140. }
  57141. /*
  57142. ** Create the byte sequence used to represent a cell on page pPage
  57143. ** and write that byte sequence into pCell[]. Overflow pages are
  57144. ** allocated and filled in as necessary. The calling procedure
  57145. ** is responsible for making sure sufficient space has been allocated
  57146. ** for pCell[].
  57147. **
  57148. ** Note that pCell does not necessary need to point to the pPage->aData
  57149. ** area. pCell might point to some temporary storage. The cell will
  57150. ** be constructed in this temporary area then copied into pPage->aData
  57151. ** later.
  57152. */
  57153. static int fillInCell(
  57154. MemPage *pPage, /* The page that contains the cell */
  57155. unsigned char *pCell, /* Complete text of the cell */
  57156. const void *pKey, i64 nKey, /* The key */
  57157. const void *pData,int nData, /* The data */
  57158. int nZero, /* Extra zero bytes to append to pData */
  57159. int *pnSize /* Write cell size here */
  57160. ){
  57161. int nPayload;
  57162. const u8 *pSrc;
  57163. int nSrc, n, rc;
  57164. int spaceLeft;
  57165. MemPage *pOvfl = 0;
  57166. MemPage *pToRelease = 0;
  57167. unsigned char *pPrior;
  57168. unsigned char *pPayload;
  57169. BtShared *pBt = pPage->pBt;
  57170. Pgno pgnoOvfl = 0;
  57171. int nHeader;
  57172. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57173. /* pPage is not necessarily writeable since pCell might be auxiliary
  57174. ** buffer space that is separate from the pPage buffer area */
  57175. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  57176. || sqlite3PagerIswriteable(pPage->pDbPage) );
  57177. /* Fill in the header. */
  57178. nHeader = pPage->childPtrSize;
  57179. nPayload = nData + nZero;
  57180. if( pPage->intKeyLeaf ){
  57181. nHeader += putVarint32(&pCell[nHeader], nPayload);
  57182. }else{
  57183. assert( nData==0 );
  57184. assert( nZero==0 );
  57185. }
  57186. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  57187. /* Fill in the payload size */
  57188. if( pPage->intKey ){
  57189. pSrc = pData;
  57190. nSrc = nData;
  57191. nData = 0;
  57192. }else{
  57193. assert( nKey<=0x7fffffff && pKey!=0 );
  57194. nPayload = (int)nKey;
  57195. pSrc = pKey;
  57196. nSrc = (int)nKey;
  57197. }
  57198. if( nPayload<=pPage->maxLocal ){
  57199. n = nHeader + nPayload;
  57200. testcase( n==3 );
  57201. testcase( n==4 );
  57202. if( n<4 ) n = 4;
  57203. *pnSize = n;
  57204. spaceLeft = nPayload;
  57205. pPrior = pCell;
  57206. }else{
  57207. int mn = pPage->minLocal;
  57208. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  57209. testcase( n==pPage->maxLocal );
  57210. testcase( n==pPage->maxLocal+1 );
  57211. if( n > pPage->maxLocal ) n = mn;
  57212. spaceLeft = n;
  57213. *pnSize = n + nHeader + 4;
  57214. pPrior = &pCell[nHeader+n];
  57215. }
  57216. pPayload = &pCell[nHeader];
  57217. /* At this point variables should be set as follows:
  57218. **
  57219. ** nPayload Total payload size in bytes
  57220. ** pPayload Begin writing payload here
  57221. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  57222. ** that means content must spill into overflow pages.
  57223. ** *pnSize Size of the local cell (not counting overflow pages)
  57224. ** pPrior Where to write the pgno of the first overflow page
  57225. **
  57226. ** Use a call to btreeParseCellPtr() to verify that the values above
  57227. ** were computed correctly.
  57228. */
  57229. #if SQLITE_DEBUG
  57230. {
  57231. CellInfo info;
  57232. pPage->xParseCell(pPage, pCell, &info);
  57233. assert( nHeader=(int)(info.pPayload - pCell) );
  57234. assert( info.nKey==nKey );
  57235. assert( *pnSize == info.nSize );
  57236. assert( spaceLeft == info.nLocal );
  57237. }
  57238. #endif
  57239. /* Write the payload into the local Cell and any extra into overflow pages */
  57240. while( nPayload>0 ){
  57241. if( spaceLeft==0 ){
  57242. #ifndef SQLITE_OMIT_AUTOVACUUM
  57243. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  57244. if( pBt->autoVacuum ){
  57245. do{
  57246. pgnoOvfl++;
  57247. } while(
  57248. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  57249. );
  57250. }
  57251. #endif
  57252. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  57253. #ifndef SQLITE_OMIT_AUTOVACUUM
  57254. /* If the database supports auto-vacuum, and the second or subsequent
  57255. ** overflow page is being allocated, add an entry to the pointer-map
  57256. ** for that page now.
  57257. **
  57258. ** If this is the first overflow page, then write a partial entry
  57259. ** to the pointer-map. If we write nothing to this pointer-map slot,
  57260. ** then the optimistic overflow chain processing in clearCell()
  57261. ** may misinterpret the uninitialized values and delete the
  57262. ** wrong pages from the database.
  57263. */
  57264. if( pBt->autoVacuum && rc==SQLITE_OK ){
  57265. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  57266. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  57267. if( rc ){
  57268. releasePage(pOvfl);
  57269. }
  57270. }
  57271. #endif
  57272. if( rc ){
  57273. releasePage(pToRelease);
  57274. return rc;
  57275. }
  57276. /* If pToRelease is not zero than pPrior points into the data area
  57277. ** of pToRelease. Make sure pToRelease is still writeable. */
  57278. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  57279. /* If pPrior is part of the data area of pPage, then make sure pPage
  57280. ** is still writeable */
  57281. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  57282. || sqlite3PagerIswriteable(pPage->pDbPage) );
  57283. put4byte(pPrior, pgnoOvfl);
  57284. releasePage(pToRelease);
  57285. pToRelease = pOvfl;
  57286. pPrior = pOvfl->aData;
  57287. put4byte(pPrior, 0);
  57288. pPayload = &pOvfl->aData[4];
  57289. spaceLeft = pBt->usableSize - 4;
  57290. }
  57291. n = nPayload;
  57292. if( n>spaceLeft ) n = spaceLeft;
  57293. /* If pToRelease is not zero than pPayload points into the data area
  57294. ** of pToRelease. Make sure pToRelease is still writeable. */
  57295. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  57296. /* If pPayload is part of the data area of pPage, then make sure pPage
  57297. ** is still writeable */
  57298. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  57299. || sqlite3PagerIswriteable(pPage->pDbPage) );
  57300. if( nSrc>0 ){
  57301. if( n>nSrc ) n = nSrc;
  57302. assert( pSrc );
  57303. memcpy(pPayload, pSrc, n);
  57304. }else{
  57305. memset(pPayload, 0, n);
  57306. }
  57307. nPayload -= n;
  57308. pPayload += n;
  57309. pSrc += n;
  57310. nSrc -= n;
  57311. spaceLeft -= n;
  57312. if( nSrc==0 ){
  57313. nSrc = nData;
  57314. pSrc = pData;
  57315. }
  57316. }
  57317. releasePage(pToRelease);
  57318. return SQLITE_OK;
  57319. }
  57320. /*
  57321. ** Remove the i-th cell from pPage. This routine effects pPage only.
  57322. ** The cell content is not freed or deallocated. It is assumed that
  57323. ** the cell content has been copied someplace else. This routine just
  57324. ** removes the reference to the cell from pPage.
  57325. **
  57326. ** "sz" must be the number of bytes in the cell.
  57327. */
  57328. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  57329. u32 pc; /* Offset to cell content of cell being deleted */
  57330. u8 *data; /* pPage->aData */
  57331. u8 *ptr; /* Used to move bytes around within data[] */
  57332. int rc; /* The return code */
  57333. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  57334. if( *pRC ) return;
  57335. assert( idx>=0 && idx<pPage->nCell );
  57336. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  57337. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57338. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57339. data = pPage->aData;
  57340. ptr = &pPage->aCellIdx[2*idx];
  57341. pc = get2byte(ptr);
  57342. hdr = pPage->hdrOffset;
  57343. testcase( pc==get2byte(&data[hdr+5]) );
  57344. testcase( pc+sz==pPage->pBt->usableSize );
  57345. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  57346. *pRC = SQLITE_CORRUPT_BKPT;
  57347. return;
  57348. }
  57349. rc = freeSpace(pPage, pc, sz);
  57350. if( rc ){
  57351. *pRC = rc;
  57352. return;
  57353. }
  57354. pPage->nCell--;
  57355. if( pPage->nCell==0 ){
  57356. memset(&data[hdr+1], 0, 4);
  57357. data[hdr+7] = 0;
  57358. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  57359. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  57360. - pPage->childPtrSize - 8;
  57361. }else{
  57362. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  57363. put2byte(&data[hdr+3], pPage->nCell);
  57364. pPage->nFree += 2;
  57365. }
  57366. }
  57367. /*
  57368. ** Insert a new cell on pPage at cell index "i". pCell points to the
  57369. ** content of the cell.
  57370. **
  57371. ** If the cell content will fit on the page, then put it there. If it
  57372. ** will not fit, then make a copy of the cell content into pTemp if
  57373. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  57374. ** in pPage->apOvfl[] and make it point to the cell content (either
  57375. ** in pTemp or the original pCell) and also record its index.
  57376. ** Allocating a new entry in pPage->aCell[] implies that
  57377. ** pPage->nOverflow is incremented.
  57378. */
  57379. static void insertCell(
  57380. MemPage *pPage, /* Page into which we are copying */
  57381. int i, /* New cell becomes the i-th cell of the page */
  57382. u8 *pCell, /* Content of the new cell */
  57383. int sz, /* Bytes of content in pCell */
  57384. u8 *pTemp, /* Temp storage space for pCell, if needed */
  57385. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  57386. int *pRC /* Read and write return code from here */
  57387. ){
  57388. int idx = 0; /* Where to write new cell content in data[] */
  57389. int j; /* Loop counter */
  57390. u8 *data; /* The content of the whole page */
  57391. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  57392. if( *pRC ) return;
  57393. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  57394. assert( MX_CELL(pPage->pBt)<=10921 );
  57395. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  57396. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  57397. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  57398. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57399. /* The cell should normally be sized correctly. However, when moving a
  57400. ** malformed cell from a leaf page to an interior page, if the cell size
  57401. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  57402. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  57403. ** the term after the || in the following assert(). */
  57404. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  57405. if( pPage->nOverflow || sz+2>pPage->nFree ){
  57406. if( pTemp ){
  57407. memcpy(pTemp, pCell, sz);
  57408. pCell = pTemp;
  57409. }
  57410. if( iChild ){
  57411. put4byte(pCell, iChild);
  57412. }
  57413. j = pPage->nOverflow++;
  57414. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  57415. pPage->apOvfl[j] = pCell;
  57416. pPage->aiOvfl[j] = (u16)i;
  57417. /* When multiple overflows occur, they are always sequential and in
  57418. ** sorted order. This invariants arise because multiple overflows can
  57419. ** only occur when inserting divider cells into the parent page during
  57420. ** balancing, and the dividers are adjacent and sorted.
  57421. */
  57422. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  57423. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  57424. }else{
  57425. int rc = sqlite3PagerWrite(pPage->pDbPage);
  57426. if( rc!=SQLITE_OK ){
  57427. *pRC = rc;
  57428. return;
  57429. }
  57430. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57431. data = pPage->aData;
  57432. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  57433. rc = allocateSpace(pPage, sz, &idx);
  57434. if( rc ){ *pRC = rc; return; }
  57435. /* The allocateSpace() routine guarantees the following properties
  57436. ** if it returns successfully */
  57437. assert( idx >= 0 );
  57438. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  57439. assert( idx+sz <= (int)pPage->pBt->usableSize );
  57440. pPage->nFree -= (u16)(2 + sz);
  57441. memcpy(&data[idx], pCell, sz);
  57442. if( iChild ){
  57443. put4byte(&data[idx], iChild);
  57444. }
  57445. pIns = pPage->aCellIdx + i*2;
  57446. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  57447. put2byte(pIns, idx);
  57448. pPage->nCell++;
  57449. /* increment the cell count */
  57450. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  57451. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  57452. #ifndef SQLITE_OMIT_AUTOVACUUM
  57453. if( pPage->pBt->autoVacuum ){
  57454. /* The cell may contain a pointer to an overflow page. If so, write
  57455. ** the entry for the overflow page into the pointer map.
  57456. */
  57457. ptrmapPutOvflPtr(pPage, pCell, pRC);
  57458. }
  57459. #endif
  57460. }
  57461. }
  57462. /*
  57463. ** A CellArray object contains a cache of pointers and sizes for a
  57464. ** consecutive sequence of cells that might be held multiple pages.
  57465. */
  57466. typedef struct CellArray CellArray;
  57467. struct CellArray {
  57468. int nCell; /* Number of cells in apCell[] */
  57469. MemPage *pRef; /* Reference page */
  57470. u8 **apCell; /* All cells begin balanced */
  57471. u16 *szCell; /* Local size of all cells in apCell[] */
  57472. };
  57473. /*
  57474. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  57475. ** computed.
  57476. */
  57477. static void populateCellCache(CellArray *p, int idx, int N){
  57478. assert( idx>=0 && idx+N<=p->nCell );
  57479. while( N>0 ){
  57480. assert( p->apCell[idx]!=0 );
  57481. if( p->szCell[idx]==0 ){
  57482. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  57483. }else{
  57484. assert( CORRUPT_DB ||
  57485. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  57486. }
  57487. idx++;
  57488. N--;
  57489. }
  57490. }
  57491. /*
  57492. ** Return the size of the Nth element of the cell array
  57493. */
  57494. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  57495. assert( N>=0 && N<p->nCell );
  57496. assert( p->szCell[N]==0 );
  57497. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  57498. return p->szCell[N];
  57499. }
  57500. static u16 cachedCellSize(CellArray *p, int N){
  57501. assert( N>=0 && N<p->nCell );
  57502. if( p->szCell[N] ) return p->szCell[N];
  57503. return computeCellSize(p, N);
  57504. }
  57505. /*
  57506. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  57507. ** szCell[] array contains the size in bytes of each cell. This function
  57508. ** replaces the current contents of page pPg with the contents of the cell
  57509. ** array.
  57510. **
  57511. ** Some of the cells in apCell[] may currently be stored in pPg. This
  57512. ** function works around problems caused by this by making a copy of any
  57513. ** such cells before overwriting the page data.
  57514. **
  57515. ** The MemPage.nFree field is invalidated by this function. It is the
  57516. ** responsibility of the caller to set it correctly.
  57517. */
  57518. static int rebuildPage(
  57519. MemPage *pPg, /* Edit this page */
  57520. int nCell, /* Final number of cells on page */
  57521. u8 **apCell, /* Array of cells */
  57522. u16 *szCell /* Array of cell sizes */
  57523. ){
  57524. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  57525. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  57526. const int usableSize = pPg->pBt->usableSize;
  57527. u8 * const pEnd = &aData[usableSize];
  57528. int i;
  57529. u8 *pCellptr = pPg->aCellIdx;
  57530. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  57531. u8 *pData;
  57532. i = get2byte(&aData[hdr+5]);
  57533. memcpy(&pTmp[i], &aData[i], usableSize - i);
  57534. pData = pEnd;
  57535. for(i=0; i<nCell; i++){
  57536. u8 *pCell = apCell[i];
  57537. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  57538. pCell = &pTmp[pCell - aData];
  57539. }
  57540. pData -= szCell[i];
  57541. put2byte(pCellptr, (pData - aData));
  57542. pCellptr += 2;
  57543. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  57544. memcpy(pData, pCell, szCell[i]);
  57545. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  57546. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  57547. }
  57548. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  57549. pPg->nCell = nCell;
  57550. pPg->nOverflow = 0;
  57551. put2byte(&aData[hdr+1], 0);
  57552. put2byte(&aData[hdr+3], pPg->nCell);
  57553. put2byte(&aData[hdr+5], pData - aData);
  57554. aData[hdr+7] = 0x00;
  57555. return SQLITE_OK;
  57556. }
  57557. /*
  57558. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  57559. ** contains the size in bytes of each such cell. This function attempts to
  57560. ** add the cells stored in the array to page pPg. If it cannot (because
  57561. ** the page needs to be defragmented before the cells will fit), non-zero
  57562. ** is returned. Otherwise, if the cells are added successfully, zero is
  57563. ** returned.
  57564. **
  57565. ** Argument pCellptr points to the first entry in the cell-pointer array
  57566. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  57567. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  57568. ** cell in the array. It is the responsibility of the caller to ensure
  57569. ** that it is safe to overwrite this part of the cell-pointer array.
  57570. **
  57571. ** When this function is called, *ppData points to the start of the
  57572. ** content area on page pPg. If the size of the content area is extended,
  57573. ** *ppData is updated to point to the new start of the content area
  57574. ** before returning.
  57575. **
  57576. ** Finally, argument pBegin points to the byte immediately following the
  57577. ** end of the space required by this page for the cell-pointer area (for
  57578. ** all cells - not just those inserted by the current call). If the content
  57579. ** area must be extended to before this point in order to accomodate all
  57580. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  57581. */
  57582. static int pageInsertArray(
  57583. MemPage *pPg, /* Page to add cells to */
  57584. u8 *pBegin, /* End of cell-pointer array */
  57585. u8 **ppData, /* IN/OUT: Page content -area pointer */
  57586. u8 *pCellptr, /* Pointer to cell-pointer area */
  57587. int iFirst, /* Index of first cell to add */
  57588. int nCell, /* Number of cells to add to pPg */
  57589. CellArray *pCArray /* Array of cells */
  57590. ){
  57591. int i;
  57592. u8 *aData = pPg->aData;
  57593. u8 *pData = *ppData;
  57594. int iEnd = iFirst + nCell;
  57595. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  57596. for(i=iFirst; i<iEnd; i++){
  57597. int sz, rc;
  57598. u8 *pSlot;
  57599. sz = cachedCellSize(pCArray, i);
  57600. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  57601. pData -= sz;
  57602. if( pData<pBegin ) return 1;
  57603. pSlot = pData;
  57604. }
  57605. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  57606. ** database. But they might for a corrupt database. Hence use memmove()
  57607. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  57608. assert( (pSlot+sz)<=pCArray->apCell[i]
  57609. || pSlot>=(pCArray->apCell[i]+sz)
  57610. || CORRUPT_DB );
  57611. memmove(pSlot, pCArray->apCell[i], sz);
  57612. put2byte(pCellptr, (pSlot - aData));
  57613. pCellptr += 2;
  57614. }
  57615. *ppData = pData;
  57616. return 0;
  57617. }
  57618. /*
  57619. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  57620. ** contains the size in bytes of each such cell. This function adds the
  57621. ** space associated with each cell in the array that is currently stored
  57622. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  57623. ** fields of the page are not updated.
  57624. **
  57625. ** This function returns the total number of cells added to the free-list.
  57626. */
  57627. static int pageFreeArray(
  57628. MemPage *pPg, /* Page to edit */
  57629. int iFirst, /* First cell to delete */
  57630. int nCell, /* Cells to delete */
  57631. CellArray *pCArray /* Array of cells */
  57632. ){
  57633. u8 * const aData = pPg->aData;
  57634. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  57635. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  57636. int nRet = 0;
  57637. int i;
  57638. int iEnd = iFirst + nCell;
  57639. u8 *pFree = 0;
  57640. int szFree = 0;
  57641. for(i=iFirst; i<iEnd; i++){
  57642. u8 *pCell = pCArray->apCell[i];
  57643. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  57644. int sz;
  57645. /* No need to use cachedCellSize() here. The sizes of all cells that
  57646. ** are to be freed have already been computing while deciding which
  57647. ** cells need freeing */
  57648. sz = pCArray->szCell[i]; assert( sz>0 );
  57649. if( pFree!=(pCell + sz) ){
  57650. if( pFree ){
  57651. assert( pFree>aData && (pFree - aData)<65536 );
  57652. freeSpace(pPg, (u16)(pFree - aData), szFree);
  57653. }
  57654. pFree = pCell;
  57655. szFree = sz;
  57656. if( pFree+sz>pEnd ) return 0;
  57657. }else{
  57658. pFree = pCell;
  57659. szFree += sz;
  57660. }
  57661. nRet++;
  57662. }
  57663. }
  57664. if( pFree ){
  57665. assert( pFree>aData && (pFree - aData)<65536 );
  57666. freeSpace(pPg, (u16)(pFree - aData), szFree);
  57667. }
  57668. return nRet;
  57669. }
  57670. /*
  57671. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  57672. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  57673. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  57674. ** starting at apCell[iNew].
  57675. **
  57676. ** This routine makes the necessary adjustments to pPg so that it contains
  57677. ** the correct cells after being balanced.
  57678. **
  57679. ** The pPg->nFree field is invalid when this function returns. It is the
  57680. ** responsibility of the caller to set it correctly.
  57681. */
  57682. static int editPage(
  57683. MemPage *pPg, /* Edit this page */
  57684. int iOld, /* Index of first cell currently on page */
  57685. int iNew, /* Index of new first cell on page */
  57686. int nNew, /* Final number of cells on page */
  57687. CellArray *pCArray /* Array of cells and sizes */
  57688. ){
  57689. u8 * const aData = pPg->aData;
  57690. const int hdr = pPg->hdrOffset;
  57691. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  57692. int nCell = pPg->nCell; /* Cells stored on pPg */
  57693. u8 *pData;
  57694. u8 *pCellptr;
  57695. int i;
  57696. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  57697. int iNewEnd = iNew + nNew;
  57698. #ifdef SQLITE_DEBUG
  57699. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  57700. memcpy(pTmp, aData, pPg->pBt->usableSize);
  57701. #endif
  57702. /* Remove cells from the start and end of the page */
  57703. if( iOld<iNew ){
  57704. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  57705. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  57706. nCell -= nShift;
  57707. }
  57708. if( iNewEnd < iOldEnd ){
  57709. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  57710. }
  57711. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  57712. if( pData<pBegin ) goto editpage_fail;
  57713. /* Add cells to the start of the page */
  57714. if( iNew<iOld ){
  57715. int nAdd = MIN(nNew,iOld-iNew);
  57716. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  57717. pCellptr = pPg->aCellIdx;
  57718. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  57719. if( pageInsertArray(
  57720. pPg, pBegin, &pData, pCellptr,
  57721. iNew, nAdd, pCArray
  57722. ) ) goto editpage_fail;
  57723. nCell += nAdd;
  57724. }
  57725. /* Add any overflow cells */
  57726. for(i=0; i<pPg->nOverflow; i++){
  57727. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  57728. if( iCell>=0 && iCell<nNew ){
  57729. pCellptr = &pPg->aCellIdx[iCell * 2];
  57730. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  57731. nCell++;
  57732. if( pageInsertArray(
  57733. pPg, pBegin, &pData, pCellptr,
  57734. iCell+iNew, 1, pCArray
  57735. ) ) goto editpage_fail;
  57736. }
  57737. }
  57738. /* Append cells to the end of the page */
  57739. pCellptr = &pPg->aCellIdx[nCell*2];
  57740. if( pageInsertArray(
  57741. pPg, pBegin, &pData, pCellptr,
  57742. iNew+nCell, nNew-nCell, pCArray
  57743. ) ) goto editpage_fail;
  57744. pPg->nCell = nNew;
  57745. pPg->nOverflow = 0;
  57746. put2byte(&aData[hdr+3], pPg->nCell);
  57747. put2byte(&aData[hdr+5], pData - aData);
  57748. #ifdef SQLITE_DEBUG
  57749. for(i=0; i<nNew && !CORRUPT_DB; i++){
  57750. u8 *pCell = pCArray->apCell[i+iNew];
  57751. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  57752. if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
  57753. pCell = &pTmp[pCell - aData];
  57754. }
  57755. assert( 0==memcmp(pCell, &aData[iOff],
  57756. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  57757. }
  57758. #endif
  57759. return SQLITE_OK;
  57760. editpage_fail:
  57761. /* Unable to edit this page. Rebuild it from scratch instead. */
  57762. populateCellCache(pCArray, iNew, nNew);
  57763. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  57764. }
  57765. /*
  57766. ** The following parameters determine how many adjacent pages get involved
  57767. ** in a balancing operation. NN is the number of neighbors on either side
  57768. ** of the page that participate in the balancing operation. NB is the
  57769. ** total number of pages that participate, including the target page and
  57770. ** NN neighbors on either side.
  57771. **
  57772. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  57773. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  57774. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  57775. ** The value of NN appears to give the best results overall.
  57776. */
  57777. #define NN 1 /* Number of neighbors on either side of pPage */
  57778. #define NB (NN*2+1) /* Total pages involved in the balance */
  57779. #ifndef SQLITE_OMIT_QUICKBALANCE
  57780. /*
  57781. ** This version of balance() handles the common special case where
  57782. ** a new entry is being inserted on the extreme right-end of the
  57783. ** tree, in other words, when the new entry will become the largest
  57784. ** entry in the tree.
  57785. **
  57786. ** Instead of trying to balance the 3 right-most leaf pages, just add
  57787. ** a new page to the right-hand side and put the one new entry in
  57788. ** that page. This leaves the right side of the tree somewhat
  57789. ** unbalanced. But odds are that we will be inserting new entries
  57790. ** at the end soon afterwards so the nearly empty page will quickly
  57791. ** fill up. On average.
  57792. **
  57793. ** pPage is the leaf page which is the right-most page in the tree.
  57794. ** pParent is its parent. pPage must have a single overflow entry
  57795. ** which is also the right-most entry on the page.
  57796. **
  57797. ** The pSpace buffer is used to store a temporary copy of the divider
  57798. ** cell that will be inserted into pParent. Such a cell consists of a 4
  57799. ** byte page number followed by a variable length integer. In other
  57800. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  57801. ** least 13 bytes in size.
  57802. */
  57803. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  57804. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  57805. MemPage *pNew; /* Newly allocated page */
  57806. int rc; /* Return Code */
  57807. Pgno pgnoNew; /* Page number of pNew */
  57808. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57809. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  57810. assert( pPage->nOverflow==1 );
  57811. /* This error condition is now caught prior to reaching this function */
  57812. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  57813. /* Allocate a new page. This page will become the right-sibling of
  57814. ** pPage. Make the parent page writable, so that the new divider cell
  57815. ** may be inserted. If both these operations are successful, proceed.
  57816. */
  57817. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  57818. if( rc==SQLITE_OK ){
  57819. u8 *pOut = &pSpace[4];
  57820. u8 *pCell = pPage->apOvfl[0];
  57821. u16 szCell = pPage->xCellSize(pPage, pCell);
  57822. u8 *pStop;
  57823. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  57824. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  57825. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  57826. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  57827. if( NEVER(rc) ) return rc;
  57828. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  57829. /* If this is an auto-vacuum database, update the pointer map
  57830. ** with entries for the new page, and any pointer from the
  57831. ** cell on the page to an overflow page. If either of these
  57832. ** operations fails, the return code is set, but the contents
  57833. ** of the parent page are still manipulated by thh code below.
  57834. ** That is Ok, at this point the parent page is guaranteed to
  57835. ** be marked as dirty. Returning an error code will cause a
  57836. ** rollback, undoing any changes made to the parent page.
  57837. */
  57838. if( ISAUTOVACUUM ){
  57839. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  57840. if( szCell>pNew->minLocal ){
  57841. ptrmapPutOvflPtr(pNew, pCell, &rc);
  57842. }
  57843. }
  57844. /* Create a divider cell to insert into pParent. The divider cell
  57845. ** consists of a 4-byte page number (the page number of pPage) and
  57846. ** a variable length key value (which must be the same value as the
  57847. ** largest key on pPage).
  57848. **
  57849. ** To find the largest key value on pPage, first find the right-most
  57850. ** cell on pPage. The first two fields of this cell are the
  57851. ** record-length (a variable length integer at most 32-bits in size)
  57852. ** and the key value (a variable length integer, may have any value).
  57853. ** The first of the while(...) loops below skips over the record-length
  57854. ** field. The second while(...) loop copies the key value from the
  57855. ** cell on pPage into the pSpace buffer.
  57856. */
  57857. pCell = findCell(pPage, pPage->nCell-1);
  57858. pStop = &pCell[9];
  57859. while( (*(pCell++)&0x80) && pCell<pStop );
  57860. pStop = &pCell[9];
  57861. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  57862. /* Insert the new divider cell into pParent. */
  57863. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  57864. 0, pPage->pgno, &rc);
  57865. /* Set the right-child pointer of pParent to point to the new page. */
  57866. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  57867. /* Release the reference to the new page. */
  57868. releasePage(pNew);
  57869. }
  57870. return rc;
  57871. }
  57872. #endif /* SQLITE_OMIT_QUICKBALANCE */
  57873. #if 0
  57874. /*
  57875. ** This function does not contribute anything to the operation of SQLite.
  57876. ** it is sometimes activated temporarily while debugging code responsible
  57877. ** for setting pointer-map entries.
  57878. */
  57879. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  57880. int i, j;
  57881. for(i=0; i<nPage; i++){
  57882. Pgno n;
  57883. u8 e;
  57884. MemPage *pPage = apPage[i];
  57885. BtShared *pBt = pPage->pBt;
  57886. assert( pPage->isInit );
  57887. for(j=0; j<pPage->nCell; j++){
  57888. CellInfo info;
  57889. u8 *z;
  57890. z = findCell(pPage, j);
  57891. pPage->xParseCell(pPage, z, &info);
  57892. if( info.nLocal<info.nPayload ){
  57893. Pgno ovfl = get4byte(&z[info.nSize-4]);
  57894. ptrmapGet(pBt, ovfl, &e, &n);
  57895. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  57896. }
  57897. if( !pPage->leaf ){
  57898. Pgno child = get4byte(z);
  57899. ptrmapGet(pBt, child, &e, &n);
  57900. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  57901. }
  57902. }
  57903. if( !pPage->leaf ){
  57904. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  57905. ptrmapGet(pBt, child, &e, &n);
  57906. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  57907. }
  57908. }
  57909. return 1;
  57910. }
  57911. #endif
  57912. /*
  57913. ** This function is used to copy the contents of the b-tree node stored
  57914. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  57915. ** the pointer-map entries for each child page are updated so that the
  57916. ** parent page stored in the pointer map is page pTo. If pFrom contained
  57917. ** any cells with overflow page pointers, then the corresponding pointer
  57918. ** map entries are also updated so that the parent page is page pTo.
  57919. **
  57920. ** If pFrom is currently carrying any overflow cells (entries in the
  57921. ** MemPage.apOvfl[] array), they are not copied to pTo.
  57922. **
  57923. ** Before returning, page pTo is reinitialized using btreeInitPage().
  57924. **
  57925. ** The performance of this function is not critical. It is only used by
  57926. ** the balance_shallower() and balance_deeper() procedures, neither of
  57927. ** which are called often under normal circumstances.
  57928. */
  57929. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  57930. if( (*pRC)==SQLITE_OK ){
  57931. BtShared * const pBt = pFrom->pBt;
  57932. u8 * const aFrom = pFrom->aData;
  57933. u8 * const aTo = pTo->aData;
  57934. int const iFromHdr = pFrom->hdrOffset;
  57935. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  57936. int rc;
  57937. int iData;
  57938. assert( pFrom->isInit );
  57939. assert( pFrom->nFree>=iToHdr );
  57940. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  57941. /* Copy the b-tree node content from page pFrom to page pTo. */
  57942. iData = get2byte(&aFrom[iFromHdr+5]);
  57943. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  57944. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  57945. /* Reinitialize page pTo so that the contents of the MemPage structure
  57946. ** match the new data. The initialization of pTo can actually fail under
  57947. ** fairly obscure circumstances, even though it is a copy of initialized
  57948. ** page pFrom.
  57949. */
  57950. pTo->isInit = 0;
  57951. rc = btreeInitPage(pTo);
  57952. if( rc!=SQLITE_OK ){
  57953. *pRC = rc;
  57954. return;
  57955. }
  57956. /* If this is an auto-vacuum database, update the pointer-map entries
  57957. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  57958. */
  57959. if( ISAUTOVACUUM ){
  57960. *pRC = setChildPtrmaps(pTo);
  57961. }
  57962. }
  57963. }
  57964. /*
  57965. ** This routine redistributes cells on the iParentIdx'th child of pParent
  57966. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  57967. ** same amount of free space. Usually a single sibling on either side of the
  57968. ** page are used in the balancing, though both siblings might come from one
  57969. ** side if the page is the first or last child of its parent. If the page
  57970. ** has fewer than 2 siblings (something which can only happen if the page
  57971. ** is a root page or a child of a root page) then all available siblings
  57972. ** participate in the balancing.
  57973. **
  57974. ** The number of siblings of the page might be increased or decreased by
  57975. ** one or two in an effort to keep pages nearly full but not over full.
  57976. **
  57977. ** Note that when this routine is called, some of the cells on the page
  57978. ** might not actually be stored in MemPage.aData[]. This can happen
  57979. ** if the page is overfull. This routine ensures that all cells allocated
  57980. ** to the page and its siblings fit into MemPage.aData[] before returning.
  57981. **
  57982. ** In the course of balancing the page and its siblings, cells may be
  57983. ** inserted into or removed from the parent page (pParent). Doing so
  57984. ** may cause the parent page to become overfull or underfull. If this
  57985. ** happens, it is the responsibility of the caller to invoke the correct
  57986. ** balancing routine to fix this problem (see the balance() routine).
  57987. **
  57988. ** If this routine fails for any reason, it might leave the database
  57989. ** in a corrupted state. So if this routine fails, the database should
  57990. ** be rolled back.
  57991. **
  57992. ** The third argument to this function, aOvflSpace, is a pointer to a
  57993. ** buffer big enough to hold one page. If while inserting cells into the parent
  57994. ** page (pParent) the parent page becomes overfull, this buffer is
  57995. ** used to store the parent's overflow cells. Because this function inserts
  57996. ** a maximum of four divider cells into the parent page, and the maximum
  57997. ** size of a cell stored within an internal node is always less than 1/4
  57998. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  57999. ** enough for all overflow cells.
  58000. **
  58001. ** If aOvflSpace is set to a null pointer, this function returns
  58002. ** SQLITE_NOMEM.
  58003. */
  58004. static int balance_nonroot(
  58005. MemPage *pParent, /* Parent page of siblings being balanced */
  58006. int iParentIdx, /* Index of "the page" in pParent */
  58007. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  58008. int isRoot, /* True if pParent is a root-page */
  58009. int bBulk /* True if this call is part of a bulk load */
  58010. ){
  58011. BtShared *pBt; /* The whole database */
  58012. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  58013. int nNew = 0; /* Number of pages in apNew[] */
  58014. int nOld; /* Number of pages in apOld[] */
  58015. int i, j, k; /* Loop counters */
  58016. int nxDiv; /* Next divider slot in pParent->aCell[] */
  58017. int rc = SQLITE_OK; /* The return code */
  58018. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  58019. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  58020. int usableSpace; /* Bytes in pPage beyond the header */
  58021. int pageFlags; /* Value of pPage->aData[0] */
  58022. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  58023. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  58024. int szScratch; /* Size of scratch memory requested */
  58025. MemPage *apOld[NB]; /* pPage and up to two siblings */
  58026. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  58027. u8 *pRight; /* Location in parent of right-sibling pointer */
  58028. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  58029. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  58030. int cntOld[NB+2]; /* Old index in b.apCell[] */
  58031. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  58032. u8 *aSpace1; /* Space for copies of dividers cells */
  58033. Pgno pgno; /* Temp var to store a page number in */
  58034. u8 abDone[NB+2]; /* True after i'th new page is populated */
  58035. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  58036. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  58037. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  58038. CellArray b; /* Parsed information on cells being balanced */
  58039. memset(abDone, 0, sizeof(abDone));
  58040. b.nCell = 0;
  58041. b.apCell = 0;
  58042. pBt = pParent->pBt;
  58043. assert( sqlite3_mutex_held(pBt->mutex) );
  58044. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  58045. #if 0
  58046. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  58047. #endif
  58048. /* At this point pParent may have at most one overflow cell. And if
  58049. ** this overflow cell is present, it must be the cell with
  58050. ** index iParentIdx. This scenario comes about when this function
  58051. ** is called (indirectly) from sqlite3BtreeDelete().
  58052. */
  58053. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  58054. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  58055. if( !aOvflSpace ){
  58056. return SQLITE_NOMEM;
  58057. }
  58058. /* Find the sibling pages to balance. Also locate the cells in pParent
  58059. ** that divide the siblings. An attempt is made to find NN siblings on
  58060. ** either side of pPage. More siblings are taken from one side, however,
  58061. ** if there are fewer than NN siblings on the other side. If pParent
  58062. ** has NB or fewer children then all children of pParent are taken.
  58063. **
  58064. ** This loop also drops the divider cells from the parent page. This
  58065. ** way, the remainder of the function does not have to deal with any
  58066. ** overflow cells in the parent page, since if any existed they will
  58067. ** have already been removed.
  58068. */
  58069. i = pParent->nOverflow + pParent->nCell;
  58070. if( i<2 ){
  58071. nxDiv = 0;
  58072. }else{
  58073. assert( bBulk==0 || bBulk==1 );
  58074. if( iParentIdx==0 ){
  58075. nxDiv = 0;
  58076. }else if( iParentIdx==i ){
  58077. nxDiv = i-2+bBulk;
  58078. }else{
  58079. nxDiv = iParentIdx-1;
  58080. }
  58081. i = 2-bBulk;
  58082. }
  58083. nOld = i+1;
  58084. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  58085. pRight = &pParent->aData[pParent->hdrOffset+8];
  58086. }else{
  58087. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  58088. }
  58089. pgno = get4byte(pRight);
  58090. while( 1 ){
  58091. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  58092. if( rc ){
  58093. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  58094. goto balance_cleanup;
  58095. }
  58096. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  58097. if( (i--)==0 ) break;
  58098. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  58099. apDiv[i] = pParent->apOvfl[0];
  58100. pgno = get4byte(apDiv[i]);
  58101. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  58102. pParent->nOverflow = 0;
  58103. }else{
  58104. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  58105. pgno = get4byte(apDiv[i]);
  58106. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  58107. /* Drop the cell from the parent page. apDiv[i] still points to
  58108. ** the cell within the parent, even though it has been dropped.
  58109. ** This is safe because dropping a cell only overwrites the first
  58110. ** four bytes of it, and this function does not need the first
  58111. ** four bytes of the divider cell. So the pointer is safe to use
  58112. ** later on.
  58113. **
  58114. ** But not if we are in secure-delete mode. In secure-delete mode,
  58115. ** the dropCell() routine will overwrite the entire cell with zeroes.
  58116. ** In this case, temporarily copy the cell into the aOvflSpace[]
  58117. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  58118. ** is allocated. */
  58119. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  58120. int iOff;
  58121. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  58122. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  58123. rc = SQLITE_CORRUPT_BKPT;
  58124. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  58125. goto balance_cleanup;
  58126. }else{
  58127. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  58128. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  58129. }
  58130. }
  58131. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  58132. }
  58133. }
  58134. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  58135. ** alignment */
  58136. nMaxCells = (nMaxCells + 3)&~3;
  58137. /*
  58138. ** Allocate space for memory structures
  58139. */
  58140. szScratch =
  58141. nMaxCells*sizeof(u8*) /* b.apCell */
  58142. + nMaxCells*sizeof(u16) /* b.szCell */
  58143. + pBt->pageSize; /* aSpace1 */
  58144. /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
  58145. ** that is more than 6 times the database page size. */
  58146. assert( szScratch<=6*(int)pBt->pageSize );
  58147. b.apCell = sqlite3ScratchMalloc( szScratch );
  58148. if( b.apCell==0 ){
  58149. rc = SQLITE_NOMEM;
  58150. goto balance_cleanup;
  58151. }
  58152. b.szCell = (u16*)&b.apCell[nMaxCells];
  58153. aSpace1 = (u8*)&b.szCell[nMaxCells];
  58154. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  58155. /*
  58156. ** Load pointers to all cells on sibling pages and the divider cells
  58157. ** into the local b.apCell[] array. Make copies of the divider cells
  58158. ** into space obtained from aSpace1[]. The divider cells have already
  58159. ** been removed from pParent.
  58160. **
  58161. ** If the siblings are on leaf pages, then the child pointers of the
  58162. ** divider cells are stripped from the cells before they are copied
  58163. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  58164. ** child pointers. If siblings are not leaves, then all cell in
  58165. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  58166. ** are alike.
  58167. **
  58168. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  58169. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  58170. */
  58171. b.pRef = apOld[0];
  58172. leafCorrection = b.pRef->leaf*4;
  58173. leafData = b.pRef->intKeyLeaf;
  58174. for(i=0; i<nOld; i++){
  58175. MemPage *pOld = apOld[i];
  58176. int limit = pOld->nCell;
  58177. u8 *aData = pOld->aData;
  58178. u16 maskPage = pOld->maskPage;
  58179. u8 *piCell = aData + pOld->cellOffset;
  58180. u8 *piEnd;
  58181. /* Verify that all sibling pages are of the same "type" (table-leaf,
  58182. ** table-interior, index-leaf, or index-interior).
  58183. */
  58184. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  58185. rc = SQLITE_CORRUPT_BKPT;
  58186. goto balance_cleanup;
  58187. }
  58188. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  58189. ** constains overflow cells, include them in the b.apCell[] array
  58190. ** in the correct spot.
  58191. **
  58192. ** Note that when there are multiple overflow cells, it is always the
  58193. ** case that they are sequential and adjacent. This invariant arises
  58194. ** because multiple overflows can only occurs when inserting divider
  58195. ** cells into a parent on a prior balance, and divider cells are always
  58196. ** adjacent and are inserted in order. There is an assert() tagged
  58197. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  58198. ** invariant.
  58199. **
  58200. ** This must be done in advance. Once the balance starts, the cell
  58201. ** offset section of the btree page will be overwritten and we will no
  58202. ** long be able to find the cells if a pointer to each cell is not saved
  58203. ** first.
  58204. */
  58205. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*limit);
  58206. if( pOld->nOverflow>0 ){
  58207. memset(&b.szCell[b.nCell+limit], 0, sizeof(b.szCell[0])*pOld->nOverflow);
  58208. limit = pOld->aiOvfl[0];
  58209. for(j=0; j<limit; j++){
  58210. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  58211. piCell += 2;
  58212. b.nCell++;
  58213. }
  58214. for(k=0; k<pOld->nOverflow; k++){
  58215. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  58216. b.apCell[b.nCell] = pOld->apOvfl[k];
  58217. b.nCell++;
  58218. }
  58219. }
  58220. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  58221. while( piCell<piEnd ){
  58222. assert( b.nCell<nMaxCells );
  58223. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  58224. piCell += 2;
  58225. b.nCell++;
  58226. }
  58227. cntOld[i] = b.nCell;
  58228. if( i<nOld-1 && !leafData){
  58229. u16 sz = (u16)szNew[i];
  58230. u8 *pTemp;
  58231. assert( b.nCell<nMaxCells );
  58232. b.szCell[b.nCell] = sz;
  58233. pTemp = &aSpace1[iSpace1];
  58234. iSpace1 += sz;
  58235. assert( sz<=pBt->maxLocal+23 );
  58236. assert( iSpace1 <= (int)pBt->pageSize );
  58237. memcpy(pTemp, apDiv[i], sz);
  58238. b.apCell[b.nCell] = pTemp+leafCorrection;
  58239. assert( leafCorrection==0 || leafCorrection==4 );
  58240. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  58241. if( !pOld->leaf ){
  58242. assert( leafCorrection==0 );
  58243. assert( pOld->hdrOffset==0 );
  58244. /* The right pointer of the child page pOld becomes the left
  58245. ** pointer of the divider cell */
  58246. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  58247. }else{
  58248. assert( leafCorrection==4 );
  58249. while( b.szCell[b.nCell]<4 ){
  58250. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  58251. ** does exist, pad it with 0x00 bytes. */
  58252. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  58253. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  58254. aSpace1[iSpace1++] = 0x00;
  58255. b.szCell[b.nCell]++;
  58256. }
  58257. }
  58258. b.nCell++;
  58259. }
  58260. }
  58261. /*
  58262. ** Figure out the number of pages needed to hold all b.nCell cells.
  58263. ** Store this number in "k". Also compute szNew[] which is the total
  58264. ** size of all cells on the i-th page and cntNew[] which is the index
  58265. ** in b.apCell[] of the cell that divides page i from page i+1.
  58266. ** cntNew[k] should equal b.nCell.
  58267. **
  58268. ** Values computed by this block:
  58269. **
  58270. ** k: The total number of sibling pages
  58271. ** szNew[i]: Spaced used on the i-th sibling page.
  58272. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  58273. ** the right of the i-th sibling page.
  58274. ** usableSpace: Number of bytes of space available on each sibling.
  58275. **
  58276. */
  58277. usableSpace = pBt->usableSize - 12 + leafCorrection;
  58278. for(i=0; i<nOld; i++){
  58279. MemPage *p = apOld[i];
  58280. szNew[i] = usableSpace - p->nFree;
  58281. if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  58282. for(j=0; j<p->nOverflow; j++){
  58283. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  58284. }
  58285. cntNew[i] = cntOld[i];
  58286. }
  58287. k = nOld;
  58288. for(i=0; i<k; i++){
  58289. int sz;
  58290. while( szNew[i]>usableSpace ){
  58291. if( i+1>=k ){
  58292. k = i+2;
  58293. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  58294. szNew[k-1] = 0;
  58295. cntNew[k-1] = b.nCell;
  58296. }
  58297. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  58298. szNew[i] -= sz;
  58299. if( !leafData ){
  58300. if( cntNew[i]<b.nCell ){
  58301. sz = 2 + cachedCellSize(&b, cntNew[i]);
  58302. }else{
  58303. sz = 0;
  58304. }
  58305. }
  58306. szNew[i+1] += sz;
  58307. cntNew[i]--;
  58308. }
  58309. while( cntNew[i]<b.nCell ){
  58310. sz = 2 + cachedCellSize(&b, cntNew[i]);
  58311. if( szNew[i]+sz>usableSpace ) break;
  58312. szNew[i] += sz;
  58313. cntNew[i]++;
  58314. if( !leafData ){
  58315. if( cntNew[i]<b.nCell ){
  58316. sz = 2 + cachedCellSize(&b, cntNew[i]);
  58317. }else{
  58318. sz = 0;
  58319. }
  58320. }
  58321. szNew[i+1] -= sz;
  58322. }
  58323. if( cntNew[i]>=b.nCell ){
  58324. k = i+1;
  58325. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  58326. rc = SQLITE_CORRUPT_BKPT;
  58327. goto balance_cleanup;
  58328. }
  58329. }
  58330. /*
  58331. ** The packing computed by the previous block is biased toward the siblings
  58332. ** on the left side (siblings with smaller keys). The left siblings are
  58333. ** always nearly full, while the right-most sibling might be nearly empty.
  58334. ** The next block of code attempts to adjust the packing of siblings to
  58335. ** get a better balance.
  58336. **
  58337. ** This adjustment is more than an optimization. The packing above might
  58338. ** be so out of balance as to be illegal. For example, the right-most
  58339. ** sibling might be completely empty. This adjustment is not optional.
  58340. */
  58341. for(i=k-1; i>0; i--){
  58342. int szRight = szNew[i]; /* Size of sibling on the right */
  58343. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  58344. int r; /* Index of right-most cell in left sibling */
  58345. int d; /* Index of first cell to the left of right sibling */
  58346. r = cntNew[i-1] - 1;
  58347. d = r + 1 - leafData;
  58348. (void)cachedCellSize(&b, d);
  58349. do{
  58350. assert( d<nMaxCells );
  58351. assert( r<nMaxCells );
  58352. (void)cachedCellSize(&b, r);
  58353. if( szRight!=0
  58354. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+2)) ){
  58355. break;
  58356. }
  58357. szRight += b.szCell[d] + 2;
  58358. szLeft -= b.szCell[r] + 2;
  58359. cntNew[i-1] = r;
  58360. r--;
  58361. d--;
  58362. }while( r>=0 );
  58363. szNew[i] = szRight;
  58364. szNew[i-1] = szLeft;
  58365. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  58366. rc = SQLITE_CORRUPT_BKPT;
  58367. goto balance_cleanup;
  58368. }
  58369. }
  58370. /* Sanity check: For a non-corrupt database file one of the follwing
  58371. ** must be true:
  58372. ** (1) We found one or more cells (cntNew[0])>0), or
  58373. ** (2) pPage is a virtual root page. A virtual root page is when
  58374. ** the real root page is page 1 and we are the only child of
  58375. ** that page.
  58376. */
  58377. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  58378. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  58379. apOld[0]->pgno, apOld[0]->nCell,
  58380. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  58381. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  58382. ));
  58383. /*
  58384. ** Allocate k new pages. Reuse old pages where possible.
  58385. */
  58386. pageFlags = apOld[0]->aData[0];
  58387. for(i=0; i<k; i++){
  58388. MemPage *pNew;
  58389. if( i<nOld ){
  58390. pNew = apNew[i] = apOld[i];
  58391. apOld[i] = 0;
  58392. rc = sqlite3PagerWrite(pNew->pDbPage);
  58393. nNew++;
  58394. if( rc ) goto balance_cleanup;
  58395. }else{
  58396. assert( i>0 );
  58397. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  58398. if( rc ) goto balance_cleanup;
  58399. zeroPage(pNew, pageFlags);
  58400. apNew[i] = pNew;
  58401. nNew++;
  58402. cntOld[i] = b.nCell;
  58403. /* Set the pointer-map entry for the new sibling page. */
  58404. if( ISAUTOVACUUM ){
  58405. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  58406. if( rc!=SQLITE_OK ){
  58407. goto balance_cleanup;
  58408. }
  58409. }
  58410. }
  58411. }
  58412. /*
  58413. ** Reassign page numbers so that the new pages are in ascending order.
  58414. ** This helps to keep entries in the disk file in order so that a scan
  58415. ** of the table is closer to a linear scan through the file. That in turn
  58416. ** helps the operating system to deliver pages from the disk more rapidly.
  58417. **
  58418. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  58419. ** than (NB+2) (a small constant), that should not be a problem.
  58420. **
  58421. ** When NB==3, this one optimization makes the database about 25% faster
  58422. ** for large insertions and deletions.
  58423. */
  58424. for(i=0; i<nNew; i++){
  58425. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  58426. aPgFlags[i] = apNew[i]->pDbPage->flags;
  58427. for(j=0; j<i; j++){
  58428. if( aPgno[j]==aPgno[i] ){
  58429. /* This branch is taken if the set of sibling pages somehow contains
  58430. ** duplicate entries. This can happen if the database is corrupt.
  58431. ** It would be simpler to detect this as part of the loop below, but
  58432. ** we do the detection here in order to avoid populating the pager
  58433. ** cache with two separate objects associated with the same
  58434. ** page number. */
  58435. assert( CORRUPT_DB );
  58436. rc = SQLITE_CORRUPT_BKPT;
  58437. goto balance_cleanup;
  58438. }
  58439. }
  58440. }
  58441. for(i=0; i<nNew; i++){
  58442. int iBest = 0; /* aPgno[] index of page number to use */
  58443. for(j=1; j<nNew; j++){
  58444. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  58445. }
  58446. pgno = aPgOrder[iBest];
  58447. aPgOrder[iBest] = 0xffffffff;
  58448. if( iBest!=i ){
  58449. if( iBest>i ){
  58450. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  58451. }
  58452. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  58453. apNew[i]->pgno = pgno;
  58454. }
  58455. }
  58456. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  58457. "%d(%d nc=%d) %d(%d nc=%d)\n",
  58458. apNew[0]->pgno, szNew[0], cntNew[0],
  58459. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  58460. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  58461. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  58462. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  58463. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  58464. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  58465. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  58466. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  58467. ));
  58468. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  58469. put4byte(pRight, apNew[nNew-1]->pgno);
  58470. /* If the sibling pages are not leaves, ensure that the right-child pointer
  58471. ** of the right-most new sibling page is set to the value that was
  58472. ** originally in the same field of the right-most old sibling page. */
  58473. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  58474. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  58475. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  58476. }
  58477. /* Make any required updates to pointer map entries associated with
  58478. ** cells stored on sibling pages following the balance operation. Pointer
  58479. ** map entries associated with divider cells are set by the insertCell()
  58480. ** routine. The associated pointer map entries are:
  58481. **
  58482. ** a) if the cell contains a reference to an overflow chain, the
  58483. ** entry associated with the first page in the overflow chain, and
  58484. **
  58485. ** b) if the sibling pages are not leaves, the child page associated
  58486. ** with the cell.
  58487. **
  58488. ** If the sibling pages are not leaves, then the pointer map entry
  58489. ** associated with the right-child of each sibling may also need to be
  58490. ** updated. This happens below, after the sibling pages have been
  58491. ** populated, not here.
  58492. */
  58493. if( ISAUTOVACUUM ){
  58494. MemPage *pNew = apNew[0];
  58495. u8 *aOld = pNew->aData;
  58496. int cntOldNext = pNew->nCell + pNew->nOverflow;
  58497. int usableSize = pBt->usableSize;
  58498. int iNew = 0;
  58499. int iOld = 0;
  58500. for(i=0; i<b.nCell; i++){
  58501. u8 *pCell = b.apCell[i];
  58502. if( i==cntOldNext ){
  58503. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  58504. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  58505. aOld = pOld->aData;
  58506. }
  58507. if( i==cntNew[iNew] ){
  58508. pNew = apNew[++iNew];
  58509. if( !leafData ) continue;
  58510. }
  58511. /* Cell pCell is destined for new sibling page pNew. Originally, it
  58512. ** was either part of sibling page iOld (possibly an overflow cell),
  58513. ** or else the divider cell to the left of sibling page iOld. So,
  58514. ** if sibling page iOld had the same page number as pNew, and if
  58515. ** pCell really was a part of sibling page iOld (not a divider or
  58516. ** overflow cell), we can skip updating the pointer map entries. */
  58517. if( iOld>=nNew
  58518. || pNew->pgno!=aPgno[iOld]
  58519. || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
  58520. ){
  58521. if( !leafCorrection ){
  58522. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  58523. }
  58524. if( cachedCellSize(&b,i)>pNew->minLocal ){
  58525. ptrmapPutOvflPtr(pNew, pCell, &rc);
  58526. }
  58527. if( rc ) goto balance_cleanup;
  58528. }
  58529. }
  58530. }
  58531. /* Insert new divider cells into pParent. */
  58532. for(i=0; i<nNew-1; i++){
  58533. u8 *pCell;
  58534. u8 *pTemp;
  58535. int sz;
  58536. MemPage *pNew = apNew[i];
  58537. j = cntNew[i];
  58538. assert( j<nMaxCells );
  58539. assert( b.apCell[j]!=0 );
  58540. pCell = b.apCell[j];
  58541. sz = b.szCell[j] + leafCorrection;
  58542. pTemp = &aOvflSpace[iOvflSpace];
  58543. if( !pNew->leaf ){
  58544. memcpy(&pNew->aData[8], pCell, 4);
  58545. }else if( leafData ){
  58546. /* If the tree is a leaf-data tree, and the siblings are leaves,
  58547. ** then there is no divider cell in b.apCell[]. Instead, the divider
  58548. ** cell consists of the integer key for the right-most cell of
  58549. ** the sibling-page assembled above only.
  58550. */
  58551. CellInfo info;
  58552. j--;
  58553. pNew->xParseCell(pNew, b.apCell[j], &info);
  58554. pCell = pTemp;
  58555. sz = 4 + putVarint(&pCell[4], info.nKey);
  58556. pTemp = 0;
  58557. }else{
  58558. pCell -= 4;
  58559. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  58560. ** previously stored on a leaf node, and its reported size was 4
  58561. ** bytes, then it may actually be smaller than this
  58562. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  58563. ** any cell). But it is important to pass the correct size to
  58564. ** insertCell(), so reparse the cell now.
  58565. **
  58566. ** Note that this can never happen in an SQLite data file, as all
  58567. ** cells are at least 4 bytes. It only happens in b-trees used
  58568. ** to evaluate "IN (SELECT ...)" and similar clauses.
  58569. */
  58570. if( b.szCell[j]==4 ){
  58571. assert(leafCorrection==4);
  58572. sz = pParent->xCellSize(pParent, pCell);
  58573. }
  58574. }
  58575. iOvflSpace += sz;
  58576. assert( sz<=pBt->maxLocal+23 );
  58577. assert( iOvflSpace <= (int)pBt->pageSize );
  58578. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  58579. if( rc!=SQLITE_OK ) goto balance_cleanup;
  58580. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  58581. }
  58582. /* Now update the actual sibling pages. The order in which they are updated
  58583. ** is important, as this code needs to avoid disrupting any page from which
  58584. ** cells may still to be read. In practice, this means:
  58585. **
  58586. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  58587. ** then it is not safe to update page apNew[iPg] until after
  58588. ** the left-hand sibling apNew[iPg-1] has been updated.
  58589. **
  58590. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  58591. ** then it is not safe to update page apNew[iPg] until after
  58592. ** the right-hand sibling apNew[iPg+1] has been updated.
  58593. **
  58594. ** If neither of the above apply, the page is safe to update.
  58595. **
  58596. ** The iPg value in the following loop starts at nNew-1 goes down
  58597. ** to 0, then back up to nNew-1 again, thus making two passes over
  58598. ** the pages. On the initial downward pass, only condition (1) above
  58599. ** needs to be tested because (2) will always be true from the previous
  58600. ** step. On the upward pass, both conditions are always true, so the
  58601. ** upwards pass simply processes pages that were missed on the downward
  58602. ** pass.
  58603. */
  58604. for(i=1-nNew; i<nNew; i++){
  58605. int iPg = i<0 ? -i : i;
  58606. assert( iPg>=0 && iPg<nNew );
  58607. if( abDone[iPg] ) continue; /* Skip pages already processed */
  58608. if( i>=0 /* On the upwards pass, or... */
  58609. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  58610. ){
  58611. int iNew;
  58612. int iOld;
  58613. int nNewCell;
  58614. /* Verify condition (1): If cells are moving left, update iPg
  58615. ** only after iPg-1 has already been updated. */
  58616. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  58617. /* Verify condition (2): If cells are moving right, update iPg
  58618. ** only after iPg+1 has already been updated. */
  58619. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  58620. if( iPg==0 ){
  58621. iNew = iOld = 0;
  58622. nNewCell = cntNew[0];
  58623. }else{
  58624. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  58625. iNew = cntNew[iPg-1] + !leafData;
  58626. nNewCell = cntNew[iPg] - iNew;
  58627. }
  58628. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  58629. if( rc ) goto balance_cleanup;
  58630. abDone[iPg]++;
  58631. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  58632. assert( apNew[iPg]->nOverflow==0 );
  58633. assert( apNew[iPg]->nCell==nNewCell );
  58634. }
  58635. }
  58636. /* All pages have been processed exactly once */
  58637. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  58638. assert( nOld>0 );
  58639. assert( nNew>0 );
  58640. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  58641. /* The root page of the b-tree now contains no cells. The only sibling
  58642. ** page is the right-child of the parent. Copy the contents of the
  58643. ** child page into the parent, decreasing the overall height of the
  58644. ** b-tree structure by one. This is described as the "balance-shallower"
  58645. ** sub-algorithm in some documentation.
  58646. **
  58647. ** If this is an auto-vacuum database, the call to copyNodeContent()
  58648. ** sets all pointer-map entries corresponding to database image pages
  58649. ** for which the pointer is stored within the content being copied.
  58650. **
  58651. ** It is critical that the child page be defragmented before being
  58652. ** copied into the parent, because if the parent is page 1 then it will
  58653. ** by smaller than the child due to the database header, and so all the
  58654. ** free space needs to be up front.
  58655. */
  58656. assert( nNew==1 || CORRUPT_DB );
  58657. rc = defragmentPage(apNew[0]);
  58658. testcase( rc!=SQLITE_OK );
  58659. assert( apNew[0]->nFree ==
  58660. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  58661. || rc!=SQLITE_OK
  58662. );
  58663. copyNodeContent(apNew[0], pParent, &rc);
  58664. freePage(apNew[0], &rc);
  58665. }else if( ISAUTOVACUUM && !leafCorrection ){
  58666. /* Fix the pointer map entries associated with the right-child of each
  58667. ** sibling page. All other pointer map entries have already been taken
  58668. ** care of. */
  58669. for(i=0; i<nNew; i++){
  58670. u32 key = get4byte(&apNew[i]->aData[8]);
  58671. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  58672. }
  58673. }
  58674. assert( pParent->isInit );
  58675. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  58676. nOld, nNew, b.nCell));
  58677. /* Free any old pages that were not reused as new pages.
  58678. */
  58679. for(i=nNew; i<nOld; i++){
  58680. freePage(apOld[i], &rc);
  58681. }
  58682. #if 0
  58683. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  58684. /* The ptrmapCheckPages() contains assert() statements that verify that
  58685. ** all pointer map pages are set correctly. This is helpful while
  58686. ** debugging. This is usually disabled because a corrupt database may
  58687. ** cause an assert() statement to fail. */
  58688. ptrmapCheckPages(apNew, nNew);
  58689. ptrmapCheckPages(&pParent, 1);
  58690. }
  58691. #endif
  58692. /*
  58693. ** Cleanup before returning.
  58694. */
  58695. balance_cleanup:
  58696. sqlite3ScratchFree(b.apCell);
  58697. for(i=0; i<nOld; i++){
  58698. releasePage(apOld[i]);
  58699. }
  58700. for(i=0; i<nNew; i++){
  58701. releasePage(apNew[i]);
  58702. }
  58703. return rc;
  58704. }
  58705. /*
  58706. ** This function is called when the root page of a b-tree structure is
  58707. ** overfull (has one or more overflow pages).
  58708. **
  58709. ** A new child page is allocated and the contents of the current root
  58710. ** page, including overflow cells, are copied into the child. The root
  58711. ** page is then overwritten to make it an empty page with the right-child
  58712. ** pointer pointing to the new page.
  58713. **
  58714. ** Before returning, all pointer-map entries corresponding to pages
  58715. ** that the new child-page now contains pointers to are updated. The
  58716. ** entry corresponding to the new right-child pointer of the root
  58717. ** page is also updated.
  58718. **
  58719. ** If successful, *ppChild is set to contain a reference to the child
  58720. ** page and SQLITE_OK is returned. In this case the caller is required
  58721. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  58722. ** an error code is returned and *ppChild is set to 0.
  58723. */
  58724. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  58725. int rc; /* Return value from subprocedures */
  58726. MemPage *pChild = 0; /* Pointer to a new child page */
  58727. Pgno pgnoChild = 0; /* Page number of the new child page */
  58728. BtShared *pBt = pRoot->pBt; /* The BTree */
  58729. assert( pRoot->nOverflow>0 );
  58730. assert( sqlite3_mutex_held(pBt->mutex) );
  58731. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  58732. ** page that will become the new right-child of pPage. Copy the contents
  58733. ** of the node stored on pRoot into the new child page.
  58734. */
  58735. rc = sqlite3PagerWrite(pRoot->pDbPage);
  58736. if( rc==SQLITE_OK ){
  58737. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  58738. copyNodeContent(pRoot, pChild, &rc);
  58739. if( ISAUTOVACUUM ){
  58740. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  58741. }
  58742. }
  58743. if( rc ){
  58744. *ppChild = 0;
  58745. releasePage(pChild);
  58746. return rc;
  58747. }
  58748. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  58749. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  58750. assert( pChild->nCell==pRoot->nCell );
  58751. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  58752. /* Copy the overflow cells from pRoot to pChild */
  58753. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  58754. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  58755. memcpy(pChild->apOvfl, pRoot->apOvfl,
  58756. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  58757. pChild->nOverflow = pRoot->nOverflow;
  58758. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  58759. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  58760. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  58761. *ppChild = pChild;
  58762. return SQLITE_OK;
  58763. }
  58764. /*
  58765. ** The page that pCur currently points to has just been modified in
  58766. ** some way. This function figures out if this modification means the
  58767. ** tree needs to be balanced, and if so calls the appropriate balancing
  58768. ** routine. Balancing routines are:
  58769. **
  58770. ** balance_quick()
  58771. ** balance_deeper()
  58772. ** balance_nonroot()
  58773. */
  58774. static int balance(BtCursor *pCur){
  58775. int rc = SQLITE_OK;
  58776. const int nMin = pCur->pBt->usableSize * 2 / 3;
  58777. u8 aBalanceQuickSpace[13];
  58778. u8 *pFree = 0;
  58779. TESTONLY( int balance_quick_called = 0 );
  58780. TESTONLY( int balance_deeper_called = 0 );
  58781. do {
  58782. int iPage = pCur->iPage;
  58783. MemPage *pPage = pCur->apPage[iPage];
  58784. if( iPage==0 ){
  58785. if( pPage->nOverflow ){
  58786. /* The root page of the b-tree is overfull. In this case call the
  58787. ** balance_deeper() function to create a new child for the root-page
  58788. ** and copy the current contents of the root-page to it. The
  58789. ** next iteration of the do-loop will balance the child page.
  58790. */
  58791. assert( (balance_deeper_called++)==0 );
  58792. rc = balance_deeper(pPage, &pCur->apPage[1]);
  58793. if( rc==SQLITE_OK ){
  58794. pCur->iPage = 1;
  58795. pCur->aiIdx[0] = 0;
  58796. pCur->aiIdx[1] = 0;
  58797. assert( pCur->apPage[1]->nOverflow );
  58798. }
  58799. }else{
  58800. break;
  58801. }
  58802. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  58803. break;
  58804. }else{
  58805. MemPage * const pParent = pCur->apPage[iPage-1];
  58806. int const iIdx = pCur->aiIdx[iPage-1];
  58807. rc = sqlite3PagerWrite(pParent->pDbPage);
  58808. if( rc==SQLITE_OK ){
  58809. #ifndef SQLITE_OMIT_QUICKBALANCE
  58810. if( pPage->intKeyLeaf
  58811. && pPage->nOverflow==1
  58812. && pPage->aiOvfl[0]==pPage->nCell
  58813. && pParent->pgno!=1
  58814. && pParent->nCell==iIdx
  58815. ){
  58816. /* Call balance_quick() to create a new sibling of pPage on which
  58817. ** to store the overflow cell. balance_quick() inserts a new cell
  58818. ** into pParent, which may cause pParent overflow. If this
  58819. ** happens, the next iteration of the do-loop will balance pParent
  58820. ** use either balance_nonroot() or balance_deeper(). Until this
  58821. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  58822. ** buffer.
  58823. **
  58824. ** The purpose of the following assert() is to check that only a
  58825. ** single call to balance_quick() is made for each call to this
  58826. ** function. If this were not verified, a subtle bug involving reuse
  58827. ** of the aBalanceQuickSpace[] might sneak in.
  58828. */
  58829. assert( (balance_quick_called++)==0 );
  58830. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  58831. }else
  58832. #endif
  58833. {
  58834. /* In this case, call balance_nonroot() to redistribute cells
  58835. ** between pPage and up to 2 of its sibling pages. This involves
  58836. ** modifying the contents of pParent, which may cause pParent to
  58837. ** become overfull or underfull. The next iteration of the do-loop
  58838. ** will balance the parent page to correct this.
  58839. **
  58840. ** If the parent page becomes overfull, the overflow cell or cells
  58841. ** are stored in the pSpace buffer allocated immediately below.
  58842. ** A subsequent iteration of the do-loop will deal with this by
  58843. ** calling balance_nonroot() (balance_deeper() may be called first,
  58844. ** but it doesn't deal with overflow cells - just moves them to a
  58845. ** different page). Once this subsequent call to balance_nonroot()
  58846. ** has completed, it is safe to release the pSpace buffer used by
  58847. ** the previous call, as the overflow cell data will have been
  58848. ** copied either into the body of a database page or into the new
  58849. ** pSpace buffer passed to the latter call to balance_nonroot().
  58850. */
  58851. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  58852. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  58853. pCur->hints&BTREE_BULKLOAD);
  58854. if( pFree ){
  58855. /* If pFree is not NULL, it points to the pSpace buffer used
  58856. ** by a previous call to balance_nonroot(). Its contents are
  58857. ** now stored either on real database pages or within the
  58858. ** new pSpace buffer, so it may be safely freed here. */
  58859. sqlite3PageFree(pFree);
  58860. }
  58861. /* The pSpace buffer will be freed after the next call to
  58862. ** balance_nonroot(), or just before this function returns, whichever
  58863. ** comes first. */
  58864. pFree = pSpace;
  58865. }
  58866. }
  58867. pPage->nOverflow = 0;
  58868. /* The next iteration of the do-loop balances the parent page. */
  58869. releasePage(pPage);
  58870. pCur->iPage--;
  58871. assert( pCur->iPage>=0 );
  58872. }
  58873. }while( rc==SQLITE_OK );
  58874. if( pFree ){
  58875. sqlite3PageFree(pFree);
  58876. }
  58877. return rc;
  58878. }
  58879. /*
  58880. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  58881. ** and the data is given by (pData,nData). The cursor is used only to
  58882. ** define what table the record should be inserted into. The cursor
  58883. ** is left pointing at a random location.
  58884. **
  58885. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  58886. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  58887. **
  58888. ** If the seekResult parameter is non-zero, then a successful call to
  58889. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  58890. ** been performed. seekResult is the search result returned (a negative
  58891. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  58892. ** a positive value if pCur points at an entry that is larger than
  58893. ** (pKey, nKey)).
  58894. **
  58895. ** If the seekResult parameter is non-zero, then the caller guarantees that
  58896. ** cursor pCur is pointing at the existing copy of a row that is to be
  58897. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  58898. ** point to any entry or to no entry at all and so this function has to seek
  58899. ** the cursor before the new key can be inserted.
  58900. */
  58901. SQLITE_PRIVATE int sqlite3BtreeInsert(
  58902. BtCursor *pCur, /* Insert data into the table of this cursor */
  58903. const void *pKey, i64 nKey, /* The key of the new record */
  58904. const void *pData, int nData, /* The data of the new record */
  58905. int nZero, /* Number of extra 0 bytes to append to data */
  58906. int appendBias, /* True if this is likely an append */
  58907. int seekResult /* Result of prior MovetoUnpacked() call */
  58908. ){
  58909. int rc;
  58910. int loc = seekResult; /* -1: before desired location +1: after */
  58911. int szNew = 0;
  58912. int idx;
  58913. MemPage *pPage;
  58914. Btree *p = pCur->pBtree;
  58915. BtShared *pBt = p->pBt;
  58916. unsigned char *oldCell;
  58917. unsigned char *newCell = 0;
  58918. if( pCur->eState==CURSOR_FAULT ){
  58919. assert( pCur->skipNext!=SQLITE_OK );
  58920. return pCur->skipNext;
  58921. }
  58922. assert( cursorHoldsMutex(pCur) );
  58923. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  58924. && pBt->inTransaction==TRANS_WRITE
  58925. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  58926. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  58927. /* Assert that the caller has been consistent. If this cursor was opened
  58928. ** expecting an index b-tree, then the caller should be inserting blob
  58929. ** keys with no associated data. If the cursor was opened expecting an
  58930. ** intkey table, the caller should be inserting integer keys with a
  58931. ** blob of associated data. */
  58932. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  58933. /* Save the positions of any other cursors open on this table.
  58934. **
  58935. ** In some cases, the call to btreeMoveto() below is a no-op. For
  58936. ** example, when inserting data into a table with auto-generated integer
  58937. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  58938. ** integer key to use. It then calls this function to actually insert the
  58939. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  58940. ** that the cursor is already where it needs to be and returns without
  58941. ** doing any work. To avoid thwarting these optimizations, it is important
  58942. ** not to clear the cursor here.
  58943. */
  58944. if( pCur->curFlags & BTCF_Multiple ){
  58945. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  58946. if( rc ) return rc;
  58947. }
  58948. if( pCur->pKeyInfo==0 ){
  58949. assert( pKey==0 );
  58950. /* If this is an insert into a table b-tree, invalidate any incrblob
  58951. ** cursors open on the row being replaced */
  58952. invalidateIncrblobCursors(p, nKey, 0);
  58953. /* If the cursor is currently on the last row and we are appending a
  58954. ** new row onto the end, set the "loc" to avoid an unnecessary
  58955. ** btreeMoveto() call */
  58956. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
  58957. && pCur->info.nKey==nKey-1 ){
  58958. loc = -1;
  58959. }else if( loc==0 ){
  58960. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, nKey, appendBias, &loc);
  58961. if( rc ) return rc;
  58962. }
  58963. }else if( loc==0 ){
  58964. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  58965. if( rc ) return rc;
  58966. }
  58967. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  58968. pPage = pCur->apPage[pCur->iPage];
  58969. assert( pPage->intKey || nKey>=0 );
  58970. assert( pPage->leaf || !pPage->intKey );
  58971. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  58972. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  58973. loc==0 ? "overwrite" : "new entry"));
  58974. assert( pPage->isInit );
  58975. newCell = pBt->pTmpSpace;
  58976. assert( newCell!=0 );
  58977. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  58978. if( rc ) goto end_insert;
  58979. assert( szNew==pPage->xCellSize(pPage, newCell) );
  58980. assert( szNew <= MX_CELL_SIZE(pBt) );
  58981. idx = pCur->aiIdx[pCur->iPage];
  58982. if( loc==0 ){
  58983. u16 szOld;
  58984. assert( idx<pPage->nCell );
  58985. rc = sqlite3PagerWrite(pPage->pDbPage);
  58986. if( rc ){
  58987. goto end_insert;
  58988. }
  58989. oldCell = findCell(pPage, idx);
  58990. if( !pPage->leaf ){
  58991. memcpy(newCell, oldCell, 4);
  58992. }
  58993. rc = clearCell(pPage, oldCell, &szOld);
  58994. dropCell(pPage, idx, szOld, &rc);
  58995. if( rc ) goto end_insert;
  58996. }else if( loc<0 && pPage->nCell>0 ){
  58997. assert( pPage->leaf );
  58998. idx = ++pCur->aiIdx[pCur->iPage];
  58999. }else{
  59000. assert( pPage->leaf );
  59001. }
  59002. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  59003. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  59004. /* If no error has occurred and pPage has an overflow cell, call balance()
  59005. ** to redistribute the cells within the tree. Since balance() may move
  59006. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  59007. ** variables.
  59008. **
  59009. ** Previous versions of SQLite called moveToRoot() to move the cursor
  59010. ** back to the root page as balance() used to invalidate the contents
  59011. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  59012. ** set the cursor state to "invalid". This makes common insert operations
  59013. ** slightly faster.
  59014. **
  59015. ** There is a subtle but important optimization here too. When inserting
  59016. ** multiple records into an intkey b-tree using a single cursor (as can
  59017. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  59018. ** is advantageous to leave the cursor pointing to the last entry in
  59019. ** the b-tree if possible. If the cursor is left pointing to the last
  59020. ** entry in the table, and the next row inserted has an integer key
  59021. ** larger than the largest existing key, it is possible to insert the
  59022. ** row without seeking the cursor. This can be a big performance boost.
  59023. */
  59024. pCur->info.nSize = 0;
  59025. if( rc==SQLITE_OK && pPage->nOverflow ){
  59026. pCur->curFlags &= ~(BTCF_ValidNKey);
  59027. rc = balance(pCur);
  59028. /* Must make sure nOverflow is reset to zero even if the balance()
  59029. ** fails. Internal data structure corruption will result otherwise.
  59030. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  59031. ** from trying to save the current position of the cursor. */
  59032. pCur->apPage[pCur->iPage]->nOverflow = 0;
  59033. pCur->eState = CURSOR_INVALID;
  59034. }
  59035. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  59036. end_insert:
  59037. return rc;
  59038. }
  59039. /*
  59040. ** Delete the entry that the cursor is pointing to.
  59041. **
  59042. ** If the second parameter is zero, then the cursor is left pointing at an
  59043. ** arbitrary location after the delete. If it is non-zero, then the cursor
  59044. ** is left in a state such that the next call to BtreeNext() or BtreePrev()
  59045. ** moves it to the same row as it would if the call to BtreeDelete() had
  59046. ** been omitted.
  59047. */
  59048. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, int bPreserve){
  59049. Btree *p = pCur->pBtree;
  59050. BtShared *pBt = p->pBt;
  59051. int rc; /* Return code */
  59052. MemPage *pPage; /* Page to delete cell from */
  59053. unsigned char *pCell; /* Pointer to cell to delete */
  59054. int iCellIdx; /* Index of cell to delete */
  59055. int iCellDepth; /* Depth of node containing pCell */
  59056. u16 szCell; /* Size of the cell being deleted */
  59057. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  59058. assert( cursorHoldsMutex(pCur) );
  59059. assert( pBt->inTransaction==TRANS_WRITE );
  59060. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59061. assert( pCur->curFlags & BTCF_WriteFlag );
  59062. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  59063. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  59064. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  59065. assert( pCur->eState==CURSOR_VALID );
  59066. iCellDepth = pCur->iPage;
  59067. iCellIdx = pCur->aiIdx[iCellDepth];
  59068. pPage = pCur->apPage[iCellDepth];
  59069. pCell = findCell(pPage, iCellIdx);
  59070. /* If the page containing the entry to delete is not a leaf page, move
  59071. ** the cursor to the largest entry in the tree that is smaller than
  59072. ** the entry being deleted. This cell will replace the cell being deleted
  59073. ** from the internal node. The 'previous' entry is used for this instead
  59074. ** of the 'next' entry, as the previous entry is always a part of the
  59075. ** sub-tree headed by the child page of the cell being deleted. This makes
  59076. ** balancing the tree following the delete operation easier. */
  59077. if( !pPage->leaf ){
  59078. int notUsed = 0;
  59079. rc = sqlite3BtreePrevious(pCur, &notUsed);
  59080. if( rc ) return rc;
  59081. }
  59082. /* Save the positions of any other cursors open on this table before
  59083. ** making any modifications. */
  59084. if( pCur->curFlags & BTCF_Multiple ){
  59085. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  59086. if( rc ) return rc;
  59087. }
  59088. /* If this is a delete operation to remove a row from a table b-tree,
  59089. ** invalidate any incrblob cursors open on the row being deleted. */
  59090. if( pCur->pKeyInfo==0 ){
  59091. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  59092. }
  59093. /* If the bPreserve flag is set to true, then the cursor position must
  59094. ** be preserved following this delete operation. If the current delete
  59095. ** will cause a b-tree rebalance, then this is done by saving the cursor
  59096. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  59097. ** returning.
  59098. **
  59099. ** Or, if the current delete will not cause a rebalance, then the cursor
  59100. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  59101. ** before or after the deleted entry. In this case set bSkipnext to true. */
  59102. if( bPreserve ){
  59103. if( !pPage->leaf
  59104. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  59105. ){
  59106. /* A b-tree rebalance will be required after deleting this entry.
  59107. ** Save the cursor key. */
  59108. rc = saveCursorKey(pCur);
  59109. if( rc ) return rc;
  59110. }else{
  59111. bSkipnext = 1;
  59112. }
  59113. }
  59114. /* Make the page containing the entry to be deleted writable. Then free any
  59115. ** overflow pages associated with the entry and finally remove the cell
  59116. ** itself from within the page. */
  59117. rc = sqlite3PagerWrite(pPage->pDbPage);
  59118. if( rc ) return rc;
  59119. rc = clearCell(pPage, pCell, &szCell);
  59120. dropCell(pPage, iCellIdx, szCell, &rc);
  59121. if( rc ) return rc;
  59122. /* If the cell deleted was not located on a leaf page, then the cursor
  59123. ** is currently pointing to the largest entry in the sub-tree headed
  59124. ** by the child-page of the cell that was just deleted from an internal
  59125. ** node. The cell from the leaf node needs to be moved to the internal
  59126. ** node to replace the deleted cell. */
  59127. if( !pPage->leaf ){
  59128. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  59129. int nCell;
  59130. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  59131. unsigned char *pTmp;
  59132. pCell = findCell(pLeaf, pLeaf->nCell-1);
  59133. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  59134. nCell = pLeaf->xCellSize(pLeaf, pCell);
  59135. assert( MX_CELL_SIZE(pBt) >= nCell );
  59136. pTmp = pBt->pTmpSpace;
  59137. assert( pTmp!=0 );
  59138. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  59139. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  59140. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  59141. if( rc ) return rc;
  59142. }
  59143. /* Balance the tree. If the entry deleted was located on a leaf page,
  59144. ** then the cursor still points to that page. In this case the first
  59145. ** call to balance() repairs the tree, and the if(...) condition is
  59146. ** never true.
  59147. **
  59148. ** Otherwise, if the entry deleted was on an internal node page, then
  59149. ** pCur is pointing to the leaf page from which a cell was removed to
  59150. ** replace the cell deleted from the internal node. This is slightly
  59151. ** tricky as the leaf node may be underfull, and the internal node may
  59152. ** be either under or overfull. In this case run the balancing algorithm
  59153. ** on the leaf node first. If the balance proceeds far enough up the
  59154. ** tree that we can be sure that any problem in the internal node has
  59155. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  59156. ** walk the cursor up the tree to the internal node and balance it as
  59157. ** well. */
  59158. rc = balance(pCur);
  59159. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  59160. while( pCur->iPage>iCellDepth ){
  59161. releasePage(pCur->apPage[pCur->iPage--]);
  59162. }
  59163. rc = balance(pCur);
  59164. }
  59165. if( rc==SQLITE_OK ){
  59166. if( bSkipnext ){
  59167. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  59168. assert( pPage==pCur->apPage[pCur->iPage] );
  59169. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  59170. pCur->eState = CURSOR_SKIPNEXT;
  59171. if( iCellIdx>=pPage->nCell ){
  59172. pCur->skipNext = -1;
  59173. pCur->aiIdx[iCellDepth] = pPage->nCell-1;
  59174. }else{
  59175. pCur->skipNext = 1;
  59176. }
  59177. }else{
  59178. rc = moveToRoot(pCur);
  59179. if( bPreserve ){
  59180. pCur->eState = CURSOR_REQUIRESEEK;
  59181. }
  59182. }
  59183. }
  59184. return rc;
  59185. }
  59186. /*
  59187. ** Create a new BTree table. Write into *piTable the page
  59188. ** number for the root page of the new table.
  59189. **
  59190. ** The type of type is determined by the flags parameter. Only the
  59191. ** following values of flags are currently in use. Other values for
  59192. ** flags might not work:
  59193. **
  59194. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  59195. ** BTREE_ZERODATA Used for SQL indices
  59196. */
  59197. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  59198. BtShared *pBt = p->pBt;
  59199. MemPage *pRoot;
  59200. Pgno pgnoRoot;
  59201. int rc;
  59202. int ptfFlags; /* Page-type flage for the root page of new table */
  59203. assert( sqlite3BtreeHoldsMutex(p) );
  59204. assert( pBt->inTransaction==TRANS_WRITE );
  59205. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59206. #ifdef SQLITE_OMIT_AUTOVACUUM
  59207. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  59208. if( rc ){
  59209. return rc;
  59210. }
  59211. #else
  59212. if( pBt->autoVacuum ){
  59213. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  59214. MemPage *pPageMove; /* The page to move to. */
  59215. /* Creating a new table may probably require moving an existing database
  59216. ** to make room for the new tables root page. In case this page turns
  59217. ** out to be an overflow page, delete all overflow page-map caches
  59218. ** held by open cursors.
  59219. */
  59220. invalidateAllOverflowCache(pBt);
  59221. /* Read the value of meta[3] from the database to determine where the
  59222. ** root page of the new table should go. meta[3] is the largest root-page
  59223. ** created so far, so the new root-page is (meta[3]+1).
  59224. */
  59225. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  59226. pgnoRoot++;
  59227. /* The new root-page may not be allocated on a pointer-map page, or the
  59228. ** PENDING_BYTE page.
  59229. */
  59230. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  59231. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  59232. pgnoRoot++;
  59233. }
  59234. assert( pgnoRoot>=3 || CORRUPT_DB );
  59235. testcase( pgnoRoot<3 );
  59236. /* Allocate a page. The page that currently resides at pgnoRoot will
  59237. ** be moved to the allocated page (unless the allocated page happens
  59238. ** to reside at pgnoRoot).
  59239. */
  59240. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  59241. if( rc!=SQLITE_OK ){
  59242. return rc;
  59243. }
  59244. if( pgnoMove!=pgnoRoot ){
  59245. /* pgnoRoot is the page that will be used for the root-page of
  59246. ** the new table (assuming an error did not occur). But we were
  59247. ** allocated pgnoMove. If required (i.e. if it was not allocated
  59248. ** by extending the file), the current page at position pgnoMove
  59249. ** is already journaled.
  59250. */
  59251. u8 eType = 0;
  59252. Pgno iPtrPage = 0;
  59253. /* Save the positions of any open cursors. This is required in
  59254. ** case they are holding a reference to an xFetch reference
  59255. ** corresponding to page pgnoRoot. */
  59256. rc = saveAllCursors(pBt, 0, 0);
  59257. releasePage(pPageMove);
  59258. if( rc!=SQLITE_OK ){
  59259. return rc;
  59260. }
  59261. /* Move the page currently at pgnoRoot to pgnoMove. */
  59262. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  59263. if( rc!=SQLITE_OK ){
  59264. return rc;
  59265. }
  59266. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  59267. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  59268. rc = SQLITE_CORRUPT_BKPT;
  59269. }
  59270. if( rc!=SQLITE_OK ){
  59271. releasePage(pRoot);
  59272. return rc;
  59273. }
  59274. assert( eType!=PTRMAP_ROOTPAGE );
  59275. assert( eType!=PTRMAP_FREEPAGE );
  59276. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  59277. releasePage(pRoot);
  59278. /* Obtain the page at pgnoRoot */
  59279. if( rc!=SQLITE_OK ){
  59280. return rc;
  59281. }
  59282. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  59283. if( rc!=SQLITE_OK ){
  59284. return rc;
  59285. }
  59286. rc = sqlite3PagerWrite(pRoot->pDbPage);
  59287. if( rc!=SQLITE_OK ){
  59288. releasePage(pRoot);
  59289. return rc;
  59290. }
  59291. }else{
  59292. pRoot = pPageMove;
  59293. }
  59294. /* Update the pointer-map and meta-data with the new root-page number. */
  59295. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  59296. if( rc ){
  59297. releasePage(pRoot);
  59298. return rc;
  59299. }
  59300. /* When the new root page was allocated, page 1 was made writable in
  59301. ** order either to increase the database filesize, or to decrement the
  59302. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  59303. */
  59304. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  59305. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  59306. if( NEVER(rc) ){
  59307. releasePage(pRoot);
  59308. return rc;
  59309. }
  59310. }else{
  59311. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  59312. if( rc ) return rc;
  59313. }
  59314. #endif
  59315. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  59316. if( createTabFlags & BTREE_INTKEY ){
  59317. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  59318. }else{
  59319. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  59320. }
  59321. zeroPage(pRoot, ptfFlags);
  59322. sqlite3PagerUnref(pRoot->pDbPage);
  59323. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  59324. *piTable = (int)pgnoRoot;
  59325. return SQLITE_OK;
  59326. }
  59327. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  59328. int rc;
  59329. sqlite3BtreeEnter(p);
  59330. rc = btreeCreateTable(p, piTable, flags);
  59331. sqlite3BtreeLeave(p);
  59332. return rc;
  59333. }
  59334. /*
  59335. ** Erase the given database page and all its children. Return
  59336. ** the page to the freelist.
  59337. */
  59338. static int clearDatabasePage(
  59339. BtShared *pBt, /* The BTree that contains the table */
  59340. Pgno pgno, /* Page number to clear */
  59341. int freePageFlag, /* Deallocate page if true */
  59342. int *pnChange /* Add number of Cells freed to this counter */
  59343. ){
  59344. MemPage *pPage;
  59345. int rc;
  59346. unsigned char *pCell;
  59347. int i;
  59348. int hdr;
  59349. u16 szCell;
  59350. assert( sqlite3_mutex_held(pBt->mutex) );
  59351. if( pgno>btreePagecount(pBt) ){
  59352. return SQLITE_CORRUPT_BKPT;
  59353. }
  59354. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  59355. if( rc ) return rc;
  59356. if( pPage->bBusy ){
  59357. rc = SQLITE_CORRUPT_BKPT;
  59358. goto cleardatabasepage_out;
  59359. }
  59360. pPage->bBusy = 1;
  59361. hdr = pPage->hdrOffset;
  59362. for(i=0; i<pPage->nCell; i++){
  59363. pCell = findCell(pPage, i);
  59364. if( !pPage->leaf ){
  59365. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  59366. if( rc ) goto cleardatabasepage_out;
  59367. }
  59368. rc = clearCell(pPage, pCell, &szCell);
  59369. if( rc ) goto cleardatabasepage_out;
  59370. }
  59371. if( !pPage->leaf ){
  59372. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  59373. if( rc ) goto cleardatabasepage_out;
  59374. }else if( pnChange ){
  59375. assert( pPage->intKey || CORRUPT_DB );
  59376. testcase( !pPage->intKey );
  59377. *pnChange += pPage->nCell;
  59378. }
  59379. if( freePageFlag ){
  59380. freePage(pPage, &rc);
  59381. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  59382. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  59383. }
  59384. cleardatabasepage_out:
  59385. pPage->bBusy = 0;
  59386. releasePage(pPage);
  59387. return rc;
  59388. }
  59389. /*
  59390. ** Delete all information from a single table in the database. iTable is
  59391. ** the page number of the root of the table. After this routine returns,
  59392. ** the root page is empty, but still exists.
  59393. **
  59394. ** This routine will fail with SQLITE_LOCKED if there are any open
  59395. ** read cursors on the table. Open write cursors are moved to the
  59396. ** root of the table.
  59397. **
  59398. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  59399. ** integer value pointed to by pnChange is incremented by the number of
  59400. ** entries in the table.
  59401. */
  59402. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  59403. int rc;
  59404. BtShared *pBt = p->pBt;
  59405. sqlite3BtreeEnter(p);
  59406. assert( p->inTrans==TRANS_WRITE );
  59407. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  59408. if( SQLITE_OK==rc ){
  59409. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  59410. ** is the root of a table b-tree - if it is not, the following call is
  59411. ** a no-op). */
  59412. invalidateIncrblobCursors(p, 0, 1);
  59413. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  59414. }
  59415. sqlite3BtreeLeave(p);
  59416. return rc;
  59417. }
  59418. /*
  59419. ** Delete all information from the single table that pCur is open on.
  59420. **
  59421. ** This routine only work for pCur on an ephemeral table.
  59422. */
  59423. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  59424. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  59425. }
  59426. /*
  59427. ** Erase all information in a table and add the root of the table to
  59428. ** the freelist. Except, the root of the principle table (the one on
  59429. ** page 1) is never added to the freelist.
  59430. **
  59431. ** This routine will fail with SQLITE_LOCKED if there are any open
  59432. ** cursors on the table.
  59433. **
  59434. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  59435. ** root page in the database file, then the last root page
  59436. ** in the database file is moved into the slot formerly occupied by
  59437. ** iTable and that last slot formerly occupied by the last root page
  59438. ** is added to the freelist instead of iTable. In this say, all
  59439. ** root pages are kept at the beginning of the database file, which
  59440. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  59441. ** page number that used to be the last root page in the file before
  59442. ** the move. If no page gets moved, *piMoved is set to 0.
  59443. ** The last root page is recorded in meta[3] and the value of
  59444. ** meta[3] is updated by this procedure.
  59445. */
  59446. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  59447. int rc;
  59448. MemPage *pPage = 0;
  59449. BtShared *pBt = p->pBt;
  59450. assert( sqlite3BtreeHoldsMutex(p) );
  59451. assert( p->inTrans==TRANS_WRITE );
  59452. /* It is illegal to drop a table if any cursors are open on the
  59453. ** database. This is because in auto-vacuum mode the backend may
  59454. ** need to move another root-page to fill a gap left by the deleted
  59455. ** root page. If an open cursor was using this page a problem would
  59456. ** occur.
  59457. **
  59458. ** This error is caught long before control reaches this point.
  59459. */
  59460. if( NEVER(pBt->pCursor) ){
  59461. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  59462. return SQLITE_LOCKED_SHAREDCACHE;
  59463. }
  59464. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  59465. if( rc ) return rc;
  59466. rc = sqlite3BtreeClearTable(p, iTable, 0);
  59467. if( rc ){
  59468. releasePage(pPage);
  59469. return rc;
  59470. }
  59471. *piMoved = 0;
  59472. if( iTable>1 ){
  59473. #ifdef SQLITE_OMIT_AUTOVACUUM
  59474. freePage(pPage, &rc);
  59475. releasePage(pPage);
  59476. #else
  59477. if( pBt->autoVacuum ){
  59478. Pgno maxRootPgno;
  59479. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  59480. if( iTable==maxRootPgno ){
  59481. /* If the table being dropped is the table with the largest root-page
  59482. ** number in the database, put the root page on the free list.
  59483. */
  59484. freePage(pPage, &rc);
  59485. releasePage(pPage);
  59486. if( rc!=SQLITE_OK ){
  59487. return rc;
  59488. }
  59489. }else{
  59490. /* The table being dropped does not have the largest root-page
  59491. ** number in the database. So move the page that does into the
  59492. ** gap left by the deleted root-page.
  59493. */
  59494. MemPage *pMove;
  59495. releasePage(pPage);
  59496. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  59497. if( rc!=SQLITE_OK ){
  59498. return rc;
  59499. }
  59500. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  59501. releasePage(pMove);
  59502. if( rc!=SQLITE_OK ){
  59503. return rc;
  59504. }
  59505. pMove = 0;
  59506. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  59507. freePage(pMove, &rc);
  59508. releasePage(pMove);
  59509. if( rc!=SQLITE_OK ){
  59510. return rc;
  59511. }
  59512. *piMoved = maxRootPgno;
  59513. }
  59514. /* Set the new 'max-root-page' value in the database header. This
  59515. ** is the old value less one, less one more if that happens to
  59516. ** be a root-page number, less one again if that is the
  59517. ** PENDING_BYTE_PAGE.
  59518. */
  59519. maxRootPgno--;
  59520. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  59521. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  59522. maxRootPgno--;
  59523. }
  59524. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  59525. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  59526. }else{
  59527. freePage(pPage, &rc);
  59528. releasePage(pPage);
  59529. }
  59530. #endif
  59531. }else{
  59532. /* If sqlite3BtreeDropTable was called on page 1.
  59533. ** This really never should happen except in a corrupt
  59534. ** database.
  59535. */
  59536. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  59537. releasePage(pPage);
  59538. }
  59539. return rc;
  59540. }
  59541. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  59542. int rc;
  59543. sqlite3BtreeEnter(p);
  59544. rc = btreeDropTable(p, iTable, piMoved);
  59545. sqlite3BtreeLeave(p);
  59546. return rc;
  59547. }
  59548. /*
  59549. ** This function may only be called if the b-tree connection already
  59550. ** has a read or write transaction open on the database.
  59551. **
  59552. ** Read the meta-information out of a database file. Meta[0]
  59553. ** is the number of free pages currently in the database. Meta[1]
  59554. ** through meta[15] are available for use by higher layers. Meta[0]
  59555. ** is read-only, the others are read/write.
  59556. **
  59557. ** The schema layer numbers meta values differently. At the schema
  59558. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  59559. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  59560. **
  59561. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  59562. ** of reading the value out of the header, it instead loads the "DataVersion"
  59563. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  59564. ** database file. It is a number computed by the pager. But its access
  59565. ** pattern is the same as header meta values, and so it is convenient to
  59566. ** read it from this routine.
  59567. */
  59568. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  59569. BtShared *pBt = p->pBt;
  59570. sqlite3BtreeEnter(p);
  59571. assert( p->inTrans>TRANS_NONE );
  59572. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  59573. assert( pBt->pPage1 );
  59574. assert( idx>=0 && idx<=15 );
  59575. if( idx==BTREE_DATA_VERSION ){
  59576. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  59577. }else{
  59578. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  59579. }
  59580. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  59581. ** database, mark the database as read-only. */
  59582. #ifdef SQLITE_OMIT_AUTOVACUUM
  59583. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  59584. pBt->btsFlags |= BTS_READ_ONLY;
  59585. }
  59586. #endif
  59587. sqlite3BtreeLeave(p);
  59588. }
  59589. /*
  59590. ** Write meta-information back into the database. Meta[0] is
  59591. ** read-only and may not be written.
  59592. */
  59593. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  59594. BtShared *pBt = p->pBt;
  59595. unsigned char *pP1;
  59596. int rc;
  59597. assert( idx>=1 && idx<=15 );
  59598. sqlite3BtreeEnter(p);
  59599. assert( p->inTrans==TRANS_WRITE );
  59600. assert( pBt->pPage1!=0 );
  59601. pP1 = pBt->pPage1->aData;
  59602. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  59603. if( rc==SQLITE_OK ){
  59604. put4byte(&pP1[36 + idx*4], iMeta);
  59605. #ifndef SQLITE_OMIT_AUTOVACUUM
  59606. if( idx==BTREE_INCR_VACUUM ){
  59607. assert( pBt->autoVacuum || iMeta==0 );
  59608. assert( iMeta==0 || iMeta==1 );
  59609. pBt->incrVacuum = (u8)iMeta;
  59610. }
  59611. #endif
  59612. }
  59613. sqlite3BtreeLeave(p);
  59614. return rc;
  59615. }
  59616. #ifndef SQLITE_OMIT_BTREECOUNT
  59617. /*
  59618. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  59619. ** number of entries in the b-tree and write the result to *pnEntry.
  59620. **
  59621. ** SQLITE_OK is returned if the operation is successfully executed.
  59622. ** Otherwise, if an error is encountered (i.e. an IO error or database
  59623. ** corruption) an SQLite error code is returned.
  59624. */
  59625. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  59626. i64 nEntry = 0; /* Value to return in *pnEntry */
  59627. int rc; /* Return code */
  59628. if( pCur->pgnoRoot==0 ){
  59629. *pnEntry = 0;
  59630. return SQLITE_OK;
  59631. }
  59632. rc = moveToRoot(pCur);
  59633. /* Unless an error occurs, the following loop runs one iteration for each
  59634. ** page in the B-Tree structure (not including overflow pages).
  59635. */
  59636. while( rc==SQLITE_OK ){
  59637. int iIdx; /* Index of child node in parent */
  59638. MemPage *pPage; /* Current page of the b-tree */
  59639. /* If this is a leaf page or the tree is not an int-key tree, then
  59640. ** this page contains countable entries. Increment the entry counter
  59641. ** accordingly.
  59642. */
  59643. pPage = pCur->apPage[pCur->iPage];
  59644. if( pPage->leaf || !pPage->intKey ){
  59645. nEntry += pPage->nCell;
  59646. }
  59647. /* pPage is a leaf node. This loop navigates the cursor so that it
  59648. ** points to the first interior cell that it points to the parent of
  59649. ** the next page in the tree that has not yet been visited. The
  59650. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  59651. ** of the page, or to the number of cells in the page if the next page
  59652. ** to visit is the right-child of its parent.
  59653. **
  59654. ** If all pages in the tree have been visited, return SQLITE_OK to the
  59655. ** caller.
  59656. */
  59657. if( pPage->leaf ){
  59658. do {
  59659. if( pCur->iPage==0 ){
  59660. /* All pages of the b-tree have been visited. Return successfully. */
  59661. *pnEntry = nEntry;
  59662. return moveToRoot(pCur);
  59663. }
  59664. moveToParent(pCur);
  59665. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  59666. pCur->aiIdx[pCur->iPage]++;
  59667. pPage = pCur->apPage[pCur->iPage];
  59668. }
  59669. /* Descend to the child node of the cell that the cursor currently
  59670. ** points at. This is the right-child if (iIdx==pPage->nCell).
  59671. */
  59672. iIdx = pCur->aiIdx[pCur->iPage];
  59673. if( iIdx==pPage->nCell ){
  59674. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  59675. }else{
  59676. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  59677. }
  59678. }
  59679. /* An error has occurred. Return an error code. */
  59680. return rc;
  59681. }
  59682. #endif
  59683. /*
  59684. ** Return the pager associated with a BTree. This routine is used for
  59685. ** testing and debugging only.
  59686. */
  59687. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  59688. return p->pBt->pPager;
  59689. }
  59690. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  59691. /*
  59692. ** Append a message to the error message string.
  59693. */
  59694. static void checkAppendMsg(
  59695. IntegrityCk *pCheck,
  59696. const char *zFormat,
  59697. ...
  59698. ){
  59699. va_list ap;
  59700. if( !pCheck->mxErr ) return;
  59701. pCheck->mxErr--;
  59702. pCheck->nErr++;
  59703. va_start(ap, zFormat);
  59704. if( pCheck->errMsg.nChar ){
  59705. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  59706. }
  59707. if( pCheck->zPfx ){
  59708. sqlite3XPrintf(&pCheck->errMsg, 0, pCheck->zPfx, pCheck->v1, pCheck->v2);
  59709. }
  59710. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  59711. va_end(ap);
  59712. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  59713. pCheck->mallocFailed = 1;
  59714. }
  59715. }
  59716. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  59717. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  59718. /*
  59719. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  59720. ** corresponds to page iPg is already set.
  59721. */
  59722. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  59723. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  59724. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  59725. }
  59726. /*
  59727. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  59728. */
  59729. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  59730. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  59731. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  59732. }
  59733. /*
  59734. ** Add 1 to the reference count for page iPage. If this is the second
  59735. ** reference to the page, add an error message to pCheck->zErrMsg.
  59736. ** Return 1 if there are 2 or more references to the page and 0 if
  59737. ** if this is the first reference to the page.
  59738. **
  59739. ** Also check that the page number is in bounds.
  59740. */
  59741. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  59742. if( iPage==0 ) return 1;
  59743. if( iPage>pCheck->nPage ){
  59744. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  59745. return 1;
  59746. }
  59747. if( getPageReferenced(pCheck, iPage) ){
  59748. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  59749. return 1;
  59750. }
  59751. setPageReferenced(pCheck, iPage);
  59752. return 0;
  59753. }
  59754. #ifndef SQLITE_OMIT_AUTOVACUUM
  59755. /*
  59756. ** Check that the entry in the pointer-map for page iChild maps to
  59757. ** page iParent, pointer type ptrType. If not, append an error message
  59758. ** to pCheck.
  59759. */
  59760. static void checkPtrmap(
  59761. IntegrityCk *pCheck, /* Integrity check context */
  59762. Pgno iChild, /* Child page number */
  59763. u8 eType, /* Expected pointer map type */
  59764. Pgno iParent /* Expected pointer map parent page number */
  59765. ){
  59766. int rc;
  59767. u8 ePtrmapType;
  59768. Pgno iPtrmapParent;
  59769. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  59770. if( rc!=SQLITE_OK ){
  59771. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  59772. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  59773. return;
  59774. }
  59775. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  59776. checkAppendMsg(pCheck,
  59777. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  59778. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  59779. }
  59780. }
  59781. #endif
  59782. /*
  59783. ** Check the integrity of the freelist or of an overflow page list.
  59784. ** Verify that the number of pages on the list is N.
  59785. */
  59786. static void checkList(
  59787. IntegrityCk *pCheck, /* Integrity checking context */
  59788. int isFreeList, /* True for a freelist. False for overflow page list */
  59789. int iPage, /* Page number for first page in the list */
  59790. int N /* Expected number of pages in the list */
  59791. ){
  59792. int i;
  59793. int expected = N;
  59794. int iFirst = iPage;
  59795. while( N-- > 0 && pCheck->mxErr ){
  59796. DbPage *pOvflPage;
  59797. unsigned char *pOvflData;
  59798. if( iPage<1 ){
  59799. checkAppendMsg(pCheck,
  59800. "%d of %d pages missing from overflow list starting at %d",
  59801. N+1, expected, iFirst);
  59802. break;
  59803. }
  59804. if( checkRef(pCheck, iPage) ) break;
  59805. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  59806. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  59807. break;
  59808. }
  59809. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  59810. if( isFreeList ){
  59811. int n = get4byte(&pOvflData[4]);
  59812. #ifndef SQLITE_OMIT_AUTOVACUUM
  59813. if( pCheck->pBt->autoVacuum ){
  59814. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  59815. }
  59816. #endif
  59817. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  59818. checkAppendMsg(pCheck,
  59819. "freelist leaf count too big on page %d", iPage);
  59820. N--;
  59821. }else{
  59822. for(i=0; i<n; i++){
  59823. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  59824. #ifndef SQLITE_OMIT_AUTOVACUUM
  59825. if( pCheck->pBt->autoVacuum ){
  59826. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  59827. }
  59828. #endif
  59829. checkRef(pCheck, iFreePage);
  59830. }
  59831. N -= n;
  59832. }
  59833. }
  59834. #ifndef SQLITE_OMIT_AUTOVACUUM
  59835. else{
  59836. /* If this database supports auto-vacuum and iPage is not the last
  59837. ** page in this overflow list, check that the pointer-map entry for
  59838. ** the following page matches iPage.
  59839. */
  59840. if( pCheck->pBt->autoVacuum && N>0 ){
  59841. i = get4byte(pOvflData);
  59842. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  59843. }
  59844. }
  59845. #endif
  59846. iPage = get4byte(pOvflData);
  59847. sqlite3PagerUnref(pOvflPage);
  59848. if( isFreeList && N<(iPage!=0) ){
  59849. checkAppendMsg(pCheck, "free-page count in header is too small");
  59850. }
  59851. }
  59852. }
  59853. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  59854. /*
  59855. ** An implementation of a min-heap.
  59856. **
  59857. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  59858. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  59859. ** and aHeap[N*2+1].
  59860. **
  59861. ** The heap property is this: Every node is less than or equal to both
  59862. ** of its daughter nodes. A consequence of the heap property is that the
  59863. ** root node aHeap[1] is always the minimum value currently in the heap.
  59864. **
  59865. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  59866. ** the heap, preserving the heap property. The btreeHeapPull() routine
  59867. ** removes the root element from the heap (the minimum value in the heap)
  59868. ** and then moves other nodes around as necessary to preserve the heap
  59869. ** property.
  59870. **
  59871. ** This heap is used for cell overlap and coverage testing. Each u32
  59872. ** entry represents the span of a cell or freeblock on a btree page.
  59873. ** The upper 16 bits are the index of the first byte of a range and the
  59874. ** lower 16 bits are the index of the last byte of that range.
  59875. */
  59876. static void btreeHeapInsert(u32 *aHeap, u32 x){
  59877. u32 j, i = ++aHeap[0];
  59878. aHeap[i] = x;
  59879. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  59880. x = aHeap[j];
  59881. aHeap[j] = aHeap[i];
  59882. aHeap[i] = x;
  59883. i = j;
  59884. }
  59885. }
  59886. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  59887. u32 j, i, x;
  59888. if( (x = aHeap[0])==0 ) return 0;
  59889. *pOut = aHeap[1];
  59890. aHeap[1] = aHeap[x];
  59891. aHeap[x] = 0xffffffff;
  59892. aHeap[0]--;
  59893. i = 1;
  59894. while( (j = i*2)<=aHeap[0] ){
  59895. if( aHeap[j]>aHeap[j+1] ) j++;
  59896. if( aHeap[i]<aHeap[j] ) break;
  59897. x = aHeap[i];
  59898. aHeap[i] = aHeap[j];
  59899. aHeap[j] = x;
  59900. i = j;
  59901. }
  59902. return 1;
  59903. }
  59904. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  59905. /*
  59906. ** Do various sanity checks on a single page of a tree. Return
  59907. ** the tree depth. Root pages return 0. Parents of root pages
  59908. ** return 1, and so forth.
  59909. **
  59910. ** These checks are done:
  59911. **
  59912. ** 1. Make sure that cells and freeblocks do not overlap
  59913. ** but combine to completely cover the page.
  59914. ** 2. Make sure integer cell keys are in order.
  59915. ** 3. Check the integrity of overflow pages.
  59916. ** 4. Recursively call checkTreePage on all children.
  59917. ** 5. Verify that the depth of all children is the same.
  59918. */
  59919. static int checkTreePage(
  59920. IntegrityCk *pCheck, /* Context for the sanity check */
  59921. int iPage, /* Page number of the page to check */
  59922. i64 *piMinKey, /* Write minimum integer primary key here */
  59923. i64 maxKey /* Error if integer primary key greater than this */
  59924. ){
  59925. MemPage *pPage = 0; /* The page being analyzed */
  59926. int i; /* Loop counter */
  59927. int rc; /* Result code from subroutine call */
  59928. int depth = -1, d2; /* Depth of a subtree */
  59929. int pgno; /* Page number */
  59930. int nFrag; /* Number of fragmented bytes on the page */
  59931. int hdr; /* Offset to the page header */
  59932. int cellStart; /* Offset to the start of the cell pointer array */
  59933. int nCell; /* Number of cells */
  59934. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  59935. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  59936. ** False if IPK must be strictly less than maxKey */
  59937. u8 *data; /* Page content */
  59938. u8 *pCell; /* Cell content */
  59939. u8 *pCellIdx; /* Next element of the cell pointer array */
  59940. BtShared *pBt; /* The BtShared object that owns pPage */
  59941. u32 pc; /* Address of a cell */
  59942. u32 usableSize; /* Usable size of the page */
  59943. u32 contentOffset; /* Offset to the start of the cell content area */
  59944. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  59945. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  59946. const char *saved_zPfx = pCheck->zPfx;
  59947. int saved_v1 = pCheck->v1;
  59948. int saved_v2 = pCheck->v2;
  59949. u8 savedIsInit = 0;
  59950. /* Check that the page exists
  59951. */
  59952. pBt = pCheck->pBt;
  59953. usableSize = pBt->usableSize;
  59954. if( iPage==0 ) return 0;
  59955. if( checkRef(pCheck, iPage) ) return 0;
  59956. pCheck->zPfx = "Page %d: ";
  59957. pCheck->v1 = iPage;
  59958. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  59959. checkAppendMsg(pCheck,
  59960. "unable to get the page. error code=%d", rc);
  59961. goto end_of_check;
  59962. }
  59963. /* Clear MemPage.isInit to make sure the corruption detection code in
  59964. ** btreeInitPage() is executed. */
  59965. savedIsInit = pPage->isInit;
  59966. pPage->isInit = 0;
  59967. if( (rc = btreeInitPage(pPage))!=0 ){
  59968. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  59969. checkAppendMsg(pCheck,
  59970. "btreeInitPage() returns error code %d", rc);
  59971. goto end_of_check;
  59972. }
  59973. data = pPage->aData;
  59974. hdr = pPage->hdrOffset;
  59975. /* Set up for cell analysis */
  59976. pCheck->zPfx = "On tree page %d cell %d: ";
  59977. contentOffset = get2byteNotZero(&data[hdr+5]);
  59978. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  59979. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  59980. ** number of cells on the page. */
  59981. nCell = get2byte(&data[hdr+3]);
  59982. assert( pPage->nCell==nCell );
  59983. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  59984. ** immediately follows the b-tree page header. */
  59985. cellStart = hdr + 12 - 4*pPage->leaf;
  59986. assert( pPage->aCellIdx==&data[cellStart] );
  59987. pCellIdx = &data[cellStart + 2*(nCell-1)];
  59988. if( !pPage->leaf ){
  59989. /* Analyze the right-child page of internal pages */
  59990. pgno = get4byte(&data[hdr+8]);
  59991. #ifndef SQLITE_OMIT_AUTOVACUUM
  59992. if( pBt->autoVacuum ){
  59993. pCheck->zPfx = "On page %d at right child: ";
  59994. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  59995. }
  59996. #endif
  59997. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  59998. keyCanBeEqual = 0;
  59999. }else{
  60000. /* For leaf pages, the coverage check will occur in the same loop
  60001. ** as the other cell checks, so initialize the heap. */
  60002. heap = pCheck->heap;
  60003. heap[0] = 0;
  60004. }
  60005. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  60006. ** integer offsets to the cell contents. */
  60007. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  60008. CellInfo info;
  60009. /* Check cell size */
  60010. pCheck->v2 = i;
  60011. assert( pCellIdx==&data[cellStart + i*2] );
  60012. pc = get2byteAligned(pCellIdx);
  60013. pCellIdx -= 2;
  60014. if( pc<contentOffset || pc>usableSize-4 ){
  60015. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  60016. pc, contentOffset, usableSize-4);
  60017. doCoverageCheck = 0;
  60018. continue;
  60019. }
  60020. pCell = &data[pc];
  60021. pPage->xParseCell(pPage, pCell, &info);
  60022. if( pc+info.nSize>usableSize ){
  60023. checkAppendMsg(pCheck, "Extends off end of page");
  60024. doCoverageCheck = 0;
  60025. continue;
  60026. }
  60027. /* Check for integer primary key out of range */
  60028. if( pPage->intKey ){
  60029. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  60030. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  60031. }
  60032. maxKey = info.nKey;
  60033. }
  60034. /* Check the content overflow list */
  60035. if( info.nPayload>info.nLocal ){
  60036. int nPage; /* Number of pages on the overflow chain */
  60037. Pgno pgnoOvfl; /* First page of the overflow chain */
  60038. assert( pc + info.nSize - 4 <= usableSize );
  60039. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  60040. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  60041. #ifndef SQLITE_OMIT_AUTOVACUUM
  60042. if( pBt->autoVacuum ){
  60043. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  60044. }
  60045. #endif
  60046. checkList(pCheck, 0, pgnoOvfl, nPage);
  60047. }
  60048. if( !pPage->leaf ){
  60049. /* Check sanity of left child page for internal pages */
  60050. pgno = get4byte(pCell);
  60051. #ifndef SQLITE_OMIT_AUTOVACUUM
  60052. if( pBt->autoVacuum ){
  60053. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  60054. }
  60055. #endif
  60056. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  60057. keyCanBeEqual = 0;
  60058. if( d2!=depth ){
  60059. checkAppendMsg(pCheck, "Child page depth differs");
  60060. depth = d2;
  60061. }
  60062. }else{
  60063. /* Populate the coverage-checking heap for leaf pages */
  60064. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  60065. }
  60066. }
  60067. *piMinKey = maxKey;
  60068. /* Check for complete coverage of the page
  60069. */
  60070. pCheck->zPfx = 0;
  60071. if( doCoverageCheck && pCheck->mxErr>0 ){
  60072. /* For leaf pages, the min-heap has already been initialized and the
  60073. ** cells have already been inserted. But for internal pages, that has
  60074. ** not yet been done, so do it now */
  60075. if( !pPage->leaf ){
  60076. heap = pCheck->heap;
  60077. heap[0] = 0;
  60078. for(i=nCell-1; i>=0; i--){
  60079. u32 size;
  60080. pc = get2byteAligned(&data[cellStart+i*2]);
  60081. size = pPage->xCellSize(pPage, &data[pc]);
  60082. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  60083. }
  60084. }
  60085. /* Add the freeblocks to the min-heap
  60086. **
  60087. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  60088. ** is the offset of the first freeblock, or zero if there are no
  60089. ** freeblocks on the page.
  60090. */
  60091. i = get2byte(&data[hdr+1]);
  60092. while( i>0 ){
  60093. int size, j;
  60094. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  60095. size = get2byte(&data[i+2]);
  60096. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  60097. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  60098. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  60099. ** big-endian integer which is the offset in the b-tree page of the next
  60100. ** freeblock in the chain, or zero if the freeblock is the last on the
  60101. ** chain. */
  60102. j = get2byte(&data[i]);
  60103. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  60104. ** increasing offset. */
  60105. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  60106. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  60107. i = j;
  60108. }
  60109. /* Analyze the min-heap looking for overlap between cells and/or
  60110. ** freeblocks, and counting the number of untracked bytes in nFrag.
  60111. **
  60112. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  60113. ** There is an implied first entry the covers the page header, the cell
  60114. ** pointer index, and the gap between the cell pointer index and the start
  60115. ** of cell content.
  60116. **
  60117. ** The loop below pulls entries from the min-heap in order and compares
  60118. ** the start_address against the previous end_address. If there is an
  60119. ** overlap, that means bytes are used multiple times. If there is a gap,
  60120. ** that gap is added to the fragmentation count.
  60121. */
  60122. nFrag = 0;
  60123. prev = contentOffset - 1; /* Implied first min-heap entry */
  60124. while( btreeHeapPull(heap,&x) ){
  60125. if( (prev&0xffff)>=(x>>16) ){
  60126. checkAppendMsg(pCheck,
  60127. "Multiple uses for byte %u of page %d", x>>16, iPage);
  60128. break;
  60129. }else{
  60130. nFrag += (x>>16) - (prev&0xffff) - 1;
  60131. prev = x;
  60132. }
  60133. }
  60134. nFrag += usableSize - (prev&0xffff) - 1;
  60135. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  60136. ** is stored in the fifth field of the b-tree page header.
  60137. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  60138. ** number of fragmented free bytes within the cell content area.
  60139. */
  60140. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  60141. checkAppendMsg(pCheck,
  60142. "Fragmentation of %d bytes reported as %d on page %d",
  60143. nFrag, data[hdr+7], iPage);
  60144. }
  60145. }
  60146. end_of_check:
  60147. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  60148. releasePage(pPage);
  60149. pCheck->zPfx = saved_zPfx;
  60150. pCheck->v1 = saved_v1;
  60151. pCheck->v2 = saved_v2;
  60152. return depth+1;
  60153. }
  60154. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  60155. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  60156. /*
  60157. ** This routine does a complete check of the given BTree file. aRoot[] is
  60158. ** an array of pages numbers were each page number is the root page of
  60159. ** a table. nRoot is the number of entries in aRoot.
  60160. **
  60161. ** A read-only or read-write transaction must be opened before calling
  60162. ** this function.
  60163. **
  60164. ** Write the number of error seen in *pnErr. Except for some memory
  60165. ** allocation errors, an error message held in memory obtained from
  60166. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  60167. ** returned. If a memory allocation error occurs, NULL is returned.
  60168. */
  60169. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  60170. Btree *p, /* The btree to be checked */
  60171. int *aRoot, /* An array of root pages numbers for individual trees */
  60172. int nRoot, /* Number of entries in aRoot[] */
  60173. int mxErr, /* Stop reporting errors after this many */
  60174. int *pnErr /* Write number of errors seen to this variable */
  60175. ){
  60176. Pgno i;
  60177. IntegrityCk sCheck;
  60178. BtShared *pBt = p->pBt;
  60179. int savedDbFlags = pBt->db->flags;
  60180. char zErr[100];
  60181. VVA_ONLY( int nRef );
  60182. sqlite3BtreeEnter(p);
  60183. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  60184. assert( (nRef = sqlite3PagerRefcount(pBt->pPager))>=0 );
  60185. sCheck.pBt = pBt;
  60186. sCheck.pPager = pBt->pPager;
  60187. sCheck.nPage = btreePagecount(sCheck.pBt);
  60188. sCheck.mxErr = mxErr;
  60189. sCheck.nErr = 0;
  60190. sCheck.mallocFailed = 0;
  60191. sCheck.zPfx = 0;
  60192. sCheck.v1 = 0;
  60193. sCheck.v2 = 0;
  60194. sCheck.aPgRef = 0;
  60195. sCheck.heap = 0;
  60196. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  60197. if( sCheck.nPage==0 ){
  60198. goto integrity_ck_cleanup;
  60199. }
  60200. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  60201. if( !sCheck.aPgRef ){
  60202. sCheck.mallocFailed = 1;
  60203. goto integrity_ck_cleanup;
  60204. }
  60205. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  60206. if( sCheck.heap==0 ){
  60207. sCheck.mallocFailed = 1;
  60208. goto integrity_ck_cleanup;
  60209. }
  60210. i = PENDING_BYTE_PAGE(pBt);
  60211. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  60212. /* Check the integrity of the freelist
  60213. */
  60214. sCheck.zPfx = "Main freelist: ";
  60215. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  60216. get4byte(&pBt->pPage1->aData[36]));
  60217. sCheck.zPfx = 0;
  60218. /* Check all the tables.
  60219. */
  60220. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  60221. pBt->db->flags &= ~SQLITE_CellSizeCk;
  60222. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  60223. i64 notUsed;
  60224. if( aRoot[i]==0 ) continue;
  60225. #ifndef SQLITE_OMIT_AUTOVACUUM
  60226. if( pBt->autoVacuum && aRoot[i]>1 ){
  60227. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  60228. }
  60229. #endif
  60230. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  60231. }
  60232. pBt->db->flags = savedDbFlags;
  60233. /* Make sure every page in the file is referenced
  60234. */
  60235. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  60236. #ifdef SQLITE_OMIT_AUTOVACUUM
  60237. if( getPageReferenced(&sCheck, i)==0 ){
  60238. checkAppendMsg(&sCheck, "Page %d is never used", i);
  60239. }
  60240. #else
  60241. /* If the database supports auto-vacuum, make sure no tables contain
  60242. ** references to pointer-map pages.
  60243. */
  60244. if( getPageReferenced(&sCheck, i)==0 &&
  60245. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  60246. checkAppendMsg(&sCheck, "Page %d is never used", i);
  60247. }
  60248. if( getPageReferenced(&sCheck, i)!=0 &&
  60249. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  60250. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  60251. }
  60252. #endif
  60253. }
  60254. /* Clean up and report errors.
  60255. */
  60256. integrity_ck_cleanup:
  60257. sqlite3PageFree(sCheck.heap);
  60258. sqlite3_free(sCheck.aPgRef);
  60259. if( sCheck.mallocFailed ){
  60260. sqlite3StrAccumReset(&sCheck.errMsg);
  60261. sCheck.nErr++;
  60262. }
  60263. *pnErr = sCheck.nErr;
  60264. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  60265. /* Make sure this analysis did not leave any unref() pages. */
  60266. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  60267. sqlite3BtreeLeave(p);
  60268. return sqlite3StrAccumFinish(&sCheck.errMsg);
  60269. }
  60270. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  60271. /*
  60272. ** Return the full pathname of the underlying database file. Return
  60273. ** an empty string if the database is in-memory or a TEMP database.
  60274. **
  60275. ** The pager filename is invariant as long as the pager is
  60276. ** open so it is safe to access without the BtShared mutex.
  60277. */
  60278. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  60279. assert( p->pBt->pPager!=0 );
  60280. return sqlite3PagerFilename(p->pBt->pPager, 1);
  60281. }
  60282. /*
  60283. ** Return the pathname of the journal file for this database. The return
  60284. ** value of this routine is the same regardless of whether the journal file
  60285. ** has been created or not.
  60286. **
  60287. ** The pager journal filename is invariant as long as the pager is
  60288. ** open so it is safe to access without the BtShared mutex.
  60289. */
  60290. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  60291. assert( p->pBt->pPager!=0 );
  60292. return sqlite3PagerJournalname(p->pBt->pPager);
  60293. }
  60294. /*
  60295. ** Return non-zero if a transaction is active.
  60296. */
  60297. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  60298. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  60299. return (p && (p->inTrans==TRANS_WRITE));
  60300. }
  60301. #ifndef SQLITE_OMIT_WAL
  60302. /*
  60303. ** Run a checkpoint on the Btree passed as the first argument.
  60304. **
  60305. ** Return SQLITE_LOCKED if this or any other connection has an open
  60306. ** transaction on the shared-cache the argument Btree is connected to.
  60307. **
  60308. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  60309. */
  60310. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  60311. int rc = SQLITE_OK;
  60312. if( p ){
  60313. BtShared *pBt = p->pBt;
  60314. sqlite3BtreeEnter(p);
  60315. if( pBt->inTransaction!=TRANS_NONE ){
  60316. rc = SQLITE_LOCKED;
  60317. }else{
  60318. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  60319. }
  60320. sqlite3BtreeLeave(p);
  60321. }
  60322. return rc;
  60323. }
  60324. #endif
  60325. /*
  60326. ** Return non-zero if a read (or write) transaction is active.
  60327. */
  60328. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  60329. assert( p );
  60330. assert( sqlite3_mutex_held(p->db->mutex) );
  60331. return p->inTrans!=TRANS_NONE;
  60332. }
  60333. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  60334. assert( p );
  60335. assert( sqlite3_mutex_held(p->db->mutex) );
  60336. return p->nBackup!=0;
  60337. }
  60338. /*
  60339. ** This function returns a pointer to a blob of memory associated with
  60340. ** a single shared-btree. The memory is used by client code for its own
  60341. ** purposes (for example, to store a high-level schema associated with
  60342. ** the shared-btree). The btree layer manages reference counting issues.
  60343. **
  60344. ** The first time this is called on a shared-btree, nBytes bytes of memory
  60345. ** are allocated, zeroed, and returned to the caller. For each subsequent
  60346. ** call the nBytes parameter is ignored and a pointer to the same blob
  60347. ** of memory returned.
  60348. **
  60349. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  60350. ** allocated, a null pointer is returned. If the blob has already been
  60351. ** allocated, it is returned as normal.
  60352. **
  60353. ** Just before the shared-btree is closed, the function passed as the
  60354. ** xFree argument when the memory allocation was made is invoked on the
  60355. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  60356. ** on the memory, the btree layer does that.
  60357. */
  60358. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  60359. BtShared *pBt = p->pBt;
  60360. sqlite3BtreeEnter(p);
  60361. if( !pBt->pSchema && nBytes ){
  60362. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  60363. pBt->xFreeSchema = xFree;
  60364. }
  60365. sqlite3BtreeLeave(p);
  60366. return pBt->pSchema;
  60367. }
  60368. /*
  60369. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  60370. ** btree as the argument handle holds an exclusive lock on the
  60371. ** sqlite_master table. Otherwise SQLITE_OK.
  60372. */
  60373. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  60374. int rc;
  60375. assert( sqlite3_mutex_held(p->db->mutex) );
  60376. sqlite3BtreeEnter(p);
  60377. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  60378. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  60379. sqlite3BtreeLeave(p);
  60380. return rc;
  60381. }
  60382. #ifndef SQLITE_OMIT_SHARED_CACHE
  60383. /*
  60384. ** Obtain a lock on the table whose root page is iTab. The
  60385. ** lock is a write lock if isWritelock is true or a read lock
  60386. ** if it is false.
  60387. */
  60388. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  60389. int rc = SQLITE_OK;
  60390. assert( p->inTrans!=TRANS_NONE );
  60391. if( p->sharable ){
  60392. u8 lockType = READ_LOCK + isWriteLock;
  60393. assert( READ_LOCK+1==WRITE_LOCK );
  60394. assert( isWriteLock==0 || isWriteLock==1 );
  60395. sqlite3BtreeEnter(p);
  60396. rc = querySharedCacheTableLock(p, iTab, lockType);
  60397. if( rc==SQLITE_OK ){
  60398. rc = setSharedCacheTableLock(p, iTab, lockType);
  60399. }
  60400. sqlite3BtreeLeave(p);
  60401. }
  60402. return rc;
  60403. }
  60404. #endif
  60405. #ifndef SQLITE_OMIT_INCRBLOB
  60406. /*
  60407. ** Argument pCsr must be a cursor opened for writing on an
  60408. ** INTKEY table currently pointing at a valid table entry.
  60409. ** This function modifies the data stored as part of that entry.
  60410. **
  60411. ** Only the data content may only be modified, it is not possible to
  60412. ** change the length of the data stored. If this function is called with
  60413. ** parameters that attempt to write past the end of the existing data,
  60414. ** no modifications are made and SQLITE_CORRUPT is returned.
  60415. */
  60416. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  60417. int rc;
  60418. assert( cursorHoldsMutex(pCsr) );
  60419. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  60420. assert( pCsr->curFlags & BTCF_Incrblob );
  60421. rc = restoreCursorPosition(pCsr);
  60422. if( rc!=SQLITE_OK ){
  60423. return rc;
  60424. }
  60425. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  60426. if( pCsr->eState!=CURSOR_VALID ){
  60427. return SQLITE_ABORT;
  60428. }
  60429. /* Save the positions of all other cursors open on this table. This is
  60430. ** required in case any of them are holding references to an xFetch
  60431. ** version of the b-tree page modified by the accessPayload call below.
  60432. **
  60433. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  60434. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  60435. ** saveAllCursors can only return SQLITE_OK.
  60436. */
  60437. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  60438. assert( rc==SQLITE_OK );
  60439. /* Check some assumptions:
  60440. ** (a) the cursor is open for writing,
  60441. ** (b) there is a read/write transaction open,
  60442. ** (c) the connection holds a write-lock on the table (if required),
  60443. ** (d) there are no conflicting read-locks, and
  60444. ** (e) the cursor points at a valid row of an intKey table.
  60445. */
  60446. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  60447. return SQLITE_READONLY;
  60448. }
  60449. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  60450. && pCsr->pBt->inTransaction==TRANS_WRITE );
  60451. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  60452. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  60453. assert( pCsr->apPage[pCsr->iPage]->intKey );
  60454. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  60455. }
  60456. /*
  60457. ** Mark this cursor as an incremental blob cursor.
  60458. */
  60459. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  60460. pCur->curFlags |= BTCF_Incrblob;
  60461. pCur->pBtree->hasIncrblobCur = 1;
  60462. }
  60463. #endif
  60464. /*
  60465. ** Set both the "read version" (single byte at byte offset 18) and
  60466. ** "write version" (single byte at byte offset 19) fields in the database
  60467. ** header to iVersion.
  60468. */
  60469. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  60470. BtShared *pBt = pBtree->pBt;
  60471. int rc; /* Return code */
  60472. assert( iVersion==1 || iVersion==2 );
  60473. /* If setting the version fields to 1, do not automatically open the
  60474. ** WAL connection, even if the version fields are currently set to 2.
  60475. */
  60476. pBt->btsFlags &= ~BTS_NO_WAL;
  60477. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  60478. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  60479. if( rc==SQLITE_OK ){
  60480. u8 *aData = pBt->pPage1->aData;
  60481. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  60482. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  60483. if( rc==SQLITE_OK ){
  60484. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  60485. if( rc==SQLITE_OK ){
  60486. aData[18] = (u8)iVersion;
  60487. aData[19] = (u8)iVersion;
  60488. }
  60489. }
  60490. }
  60491. }
  60492. pBt->btsFlags &= ~BTS_NO_WAL;
  60493. return rc;
  60494. }
  60495. /*
  60496. ** Return true if the cursor has a hint specified. This routine is
  60497. ** only used from within assert() statements
  60498. */
  60499. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  60500. return (pCsr->hints & mask)!=0;
  60501. }
  60502. /*
  60503. ** Return true if the given Btree is read-only.
  60504. */
  60505. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  60506. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  60507. }
  60508. /*
  60509. ** Return the size of the header added to each page by this module.
  60510. */
  60511. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  60512. /************** End of btree.c ***********************************************/
  60513. /************** Begin file backup.c ******************************************/
  60514. /*
  60515. ** 2009 January 28
  60516. **
  60517. ** The author disclaims copyright to this source code. In place of
  60518. ** a legal notice, here is a blessing:
  60519. **
  60520. ** May you do good and not evil.
  60521. ** May you find forgiveness for yourself and forgive others.
  60522. ** May you share freely, never taking more than you give.
  60523. **
  60524. *************************************************************************
  60525. ** This file contains the implementation of the sqlite3_backup_XXX()
  60526. ** API functions and the related features.
  60527. */
  60528. /* #include "sqliteInt.h" */
  60529. /* #include "btreeInt.h" */
  60530. /*
  60531. ** Structure allocated for each backup operation.
  60532. */
  60533. struct sqlite3_backup {
  60534. sqlite3* pDestDb; /* Destination database handle */
  60535. Btree *pDest; /* Destination b-tree file */
  60536. u32 iDestSchema; /* Original schema cookie in destination */
  60537. int bDestLocked; /* True once a write-transaction is open on pDest */
  60538. Pgno iNext; /* Page number of the next source page to copy */
  60539. sqlite3* pSrcDb; /* Source database handle */
  60540. Btree *pSrc; /* Source b-tree file */
  60541. int rc; /* Backup process error code */
  60542. /* These two variables are set by every call to backup_step(). They are
  60543. ** read by calls to backup_remaining() and backup_pagecount().
  60544. */
  60545. Pgno nRemaining; /* Number of pages left to copy */
  60546. Pgno nPagecount; /* Total number of pages to copy */
  60547. int isAttached; /* True once backup has been registered with pager */
  60548. sqlite3_backup *pNext; /* Next backup associated with source pager */
  60549. };
  60550. /*
  60551. ** THREAD SAFETY NOTES:
  60552. **
  60553. ** Once it has been created using backup_init(), a single sqlite3_backup
  60554. ** structure may be accessed via two groups of thread-safe entry points:
  60555. **
  60556. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  60557. ** backup_finish(). Both these functions obtain the source database
  60558. ** handle mutex and the mutex associated with the source BtShared
  60559. ** structure, in that order.
  60560. **
  60561. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  60562. ** invoked by the pager layer to report various state changes in
  60563. ** the page cache associated with the source database. The mutex
  60564. ** associated with the source database BtShared structure will always
  60565. ** be held when either of these functions are invoked.
  60566. **
  60567. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  60568. ** backup_pagecount() are not thread-safe functions. If they are called
  60569. ** while some other thread is calling backup_step() or backup_finish(),
  60570. ** the values returned may be invalid. There is no way for a call to
  60571. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  60572. ** or backup_pagecount().
  60573. **
  60574. ** Depending on the SQLite configuration, the database handles and/or
  60575. ** the Btree objects may have their own mutexes that require locking.
  60576. ** Non-sharable Btrees (in-memory databases for example), do not have
  60577. ** associated mutexes.
  60578. */
  60579. /*
  60580. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  60581. ** in connection handle pDb. If such a database cannot be found, return
  60582. ** a NULL pointer and write an error message to pErrorDb.
  60583. **
  60584. ** If the "temp" database is requested, it may need to be opened by this
  60585. ** function. If an error occurs while doing so, return 0 and write an
  60586. ** error message to pErrorDb.
  60587. */
  60588. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  60589. int i = sqlite3FindDbName(pDb, zDb);
  60590. if( i==1 ){
  60591. Parse *pParse;
  60592. int rc = 0;
  60593. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  60594. if( pParse==0 ){
  60595. sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
  60596. rc = SQLITE_NOMEM;
  60597. }else{
  60598. pParse->db = pDb;
  60599. if( sqlite3OpenTempDatabase(pParse) ){
  60600. sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  60601. rc = SQLITE_ERROR;
  60602. }
  60603. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  60604. sqlite3ParserReset(pParse);
  60605. sqlite3StackFree(pErrorDb, pParse);
  60606. }
  60607. if( rc ){
  60608. return 0;
  60609. }
  60610. }
  60611. if( i<0 ){
  60612. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  60613. return 0;
  60614. }
  60615. return pDb->aDb[i].pBt;
  60616. }
  60617. /*
  60618. ** Attempt to set the page size of the destination to match the page size
  60619. ** of the source.
  60620. */
  60621. static int setDestPgsz(sqlite3_backup *p){
  60622. int rc;
  60623. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  60624. return rc;
  60625. }
  60626. /*
  60627. ** Check that there is no open read-transaction on the b-tree passed as the
  60628. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  60629. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  60630. ** message in database handle db.
  60631. */
  60632. static int checkReadTransaction(sqlite3 *db, Btree *p){
  60633. if( sqlite3BtreeIsInReadTrans(p) ){
  60634. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  60635. return SQLITE_ERROR;
  60636. }
  60637. return SQLITE_OK;
  60638. }
  60639. /*
  60640. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  60641. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  60642. ** a pointer to the new sqlite3_backup object.
  60643. **
  60644. ** If an error occurs, NULL is returned and an error code and error message
  60645. ** stored in database handle pDestDb.
  60646. */
  60647. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  60648. sqlite3* pDestDb, /* Database to write to */
  60649. const char *zDestDb, /* Name of database within pDestDb */
  60650. sqlite3* pSrcDb, /* Database connection to read from */
  60651. const char *zSrcDb /* Name of database within pSrcDb */
  60652. ){
  60653. sqlite3_backup *p; /* Value to return */
  60654. #ifdef SQLITE_ENABLE_API_ARMOR
  60655. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  60656. (void)SQLITE_MISUSE_BKPT;
  60657. return 0;
  60658. }
  60659. #endif
  60660. /* Lock the source database handle. The destination database
  60661. ** handle is not locked in this routine, but it is locked in
  60662. ** sqlite3_backup_step(). The user is required to ensure that no
  60663. ** other thread accesses the destination handle for the duration
  60664. ** of the backup operation. Any attempt to use the destination
  60665. ** database connection while a backup is in progress may cause
  60666. ** a malfunction or a deadlock.
  60667. */
  60668. sqlite3_mutex_enter(pSrcDb->mutex);
  60669. sqlite3_mutex_enter(pDestDb->mutex);
  60670. if( pSrcDb==pDestDb ){
  60671. sqlite3ErrorWithMsg(
  60672. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  60673. );
  60674. p = 0;
  60675. }else {
  60676. /* Allocate space for a new sqlite3_backup object...
  60677. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  60678. ** call to sqlite3_backup_init() and is destroyed by a call to
  60679. ** sqlite3_backup_finish(). */
  60680. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  60681. if( !p ){
  60682. sqlite3Error(pDestDb, SQLITE_NOMEM);
  60683. }
  60684. }
  60685. /* If the allocation succeeded, populate the new object. */
  60686. if( p ){
  60687. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  60688. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  60689. p->pDestDb = pDestDb;
  60690. p->pSrcDb = pSrcDb;
  60691. p->iNext = 1;
  60692. p->isAttached = 0;
  60693. if( 0==p->pSrc || 0==p->pDest
  60694. || setDestPgsz(p)==SQLITE_NOMEM
  60695. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  60696. ){
  60697. /* One (or both) of the named databases did not exist or an OOM
  60698. ** error was hit. Or there is a transaction open on the destination
  60699. ** database. The error has already been written into the pDestDb
  60700. ** handle. All that is left to do here is free the sqlite3_backup
  60701. ** structure. */
  60702. sqlite3_free(p);
  60703. p = 0;
  60704. }
  60705. }
  60706. if( p ){
  60707. p->pSrc->nBackup++;
  60708. }
  60709. sqlite3_mutex_leave(pDestDb->mutex);
  60710. sqlite3_mutex_leave(pSrcDb->mutex);
  60711. return p;
  60712. }
  60713. /*
  60714. ** Argument rc is an SQLite error code. Return true if this error is
  60715. ** considered fatal if encountered during a backup operation. All errors
  60716. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  60717. */
  60718. static int isFatalError(int rc){
  60719. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  60720. }
  60721. /*
  60722. ** Parameter zSrcData points to a buffer containing the data for
  60723. ** page iSrcPg from the source database. Copy this data into the
  60724. ** destination database.
  60725. */
  60726. static int backupOnePage(
  60727. sqlite3_backup *p, /* Backup handle */
  60728. Pgno iSrcPg, /* Source database page to backup */
  60729. const u8 *zSrcData, /* Source database page data */
  60730. int bUpdate /* True for an update, false otherwise */
  60731. ){
  60732. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  60733. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  60734. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  60735. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  60736. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  60737. #ifdef SQLITE_HAS_CODEC
  60738. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  60739. ** guaranteed that the shared-mutex is held by this thread, handle
  60740. ** p->pSrc may not actually be the owner. */
  60741. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  60742. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  60743. #endif
  60744. int rc = SQLITE_OK;
  60745. i64 iOff;
  60746. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  60747. assert( p->bDestLocked );
  60748. assert( !isFatalError(p->rc) );
  60749. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  60750. assert( zSrcData );
  60751. /* Catch the case where the destination is an in-memory database and the
  60752. ** page sizes of the source and destination differ.
  60753. */
  60754. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  60755. rc = SQLITE_READONLY;
  60756. }
  60757. #ifdef SQLITE_HAS_CODEC
  60758. /* Backup is not possible if the page size of the destination is changing
  60759. ** and a codec is in use.
  60760. */
  60761. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  60762. rc = SQLITE_READONLY;
  60763. }
  60764. /* Backup is not possible if the number of bytes of reserve space differ
  60765. ** between source and destination. If there is a difference, try to
  60766. ** fix the destination to agree with the source. If that is not possible,
  60767. ** then the backup cannot proceed.
  60768. */
  60769. if( nSrcReserve!=nDestReserve ){
  60770. u32 newPgsz = nSrcPgsz;
  60771. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  60772. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  60773. }
  60774. #endif
  60775. /* This loop runs once for each destination page spanned by the source
  60776. ** page. For each iteration, variable iOff is set to the byte offset
  60777. ** of the destination page.
  60778. */
  60779. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  60780. DbPage *pDestPg = 0;
  60781. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  60782. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  60783. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  60784. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  60785. ){
  60786. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  60787. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  60788. u8 *zOut = &zDestData[iOff%nDestPgsz];
  60789. /* Copy the data from the source page into the destination page.
  60790. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  60791. ** and the pager code use this trick (clearing the first byte
  60792. ** of the page 'extra' space to invalidate the Btree layers
  60793. ** cached parse of the page). MemPage.isInit is marked
  60794. ** "MUST BE FIRST" for this purpose.
  60795. */
  60796. memcpy(zOut, zIn, nCopy);
  60797. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  60798. if( iOff==0 && bUpdate==0 ){
  60799. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  60800. }
  60801. }
  60802. sqlite3PagerUnref(pDestPg);
  60803. }
  60804. return rc;
  60805. }
  60806. /*
  60807. ** If pFile is currently larger than iSize bytes, then truncate it to
  60808. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  60809. ** this function is a no-op.
  60810. **
  60811. ** Return SQLITE_OK if everything is successful, or an SQLite error
  60812. ** code if an error occurs.
  60813. */
  60814. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  60815. i64 iCurrent;
  60816. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  60817. if( rc==SQLITE_OK && iCurrent>iSize ){
  60818. rc = sqlite3OsTruncate(pFile, iSize);
  60819. }
  60820. return rc;
  60821. }
  60822. /*
  60823. ** Register this backup object with the associated source pager for
  60824. ** callbacks when pages are changed or the cache invalidated.
  60825. */
  60826. static void attachBackupObject(sqlite3_backup *p){
  60827. sqlite3_backup **pp;
  60828. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  60829. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  60830. p->pNext = *pp;
  60831. *pp = p;
  60832. p->isAttached = 1;
  60833. }
  60834. /*
  60835. ** Copy nPage pages from the source b-tree to the destination.
  60836. */
  60837. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
  60838. int rc;
  60839. int destMode; /* Destination journal mode */
  60840. int pgszSrc = 0; /* Source page size */
  60841. int pgszDest = 0; /* Destination page size */
  60842. #ifdef SQLITE_ENABLE_API_ARMOR
  60843. if( p==0 ) return SQLITE_MISUSE_BKPT;
  60844. #endif
  60845. sqlite3_mutex_enter(p->pSrcDb->mutex);
  60846. sqlite3BtreeEnter(p->pSrc);
  60847. if( p->pDestDb ){
  60848. sqlite3_mutex_enter(p->pDestDb->mutex);
  60849. }
  60850. rc = p->rc;
  60851. if( !isFatalError(rc) ){
  60852. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  60853. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  60854. int ii; /* Iterator variable */
  60855. int nSrcPage = -1; /* Size of source db in pages */
  60856. int bCloseTrans = 0; /* True if src db requires unlocking */
  60857. /* If the source pager is currently in a write-transaction, return
  60858. ** SQLITE_BUSY immediately.
  60859. */
  60860. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  60861. rc = SQLITE_BUSY;
  60862. }else{
  60863. rc = SQLITE_OK;
  60864. }
  60865. /* Lock the destination database, if it is not locked already. */
  60866. if( SQLITE_OK==rc && p->bDestLocked==0
  60867. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  60868. ){
  60869. p->bDestLocked = 1;
  60870. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  60871. }
  60872. /* If there is no open read-transaction on the source database, open
  60873. ** one now. If a transaction is opened here, then it will be closed
  60874. ** before this function exits.
  60875. */
  60876. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  60877. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  60878. bCloseTrans = 1;
  60879. }
  60880. /* Do not allow backup if the destination database is in WAL mode
  60881. ** and the page sizes are different between source and destination */
  60882. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  60883. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  60884. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  60885. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  60886. rc = SQLITE_READONLY;
  60887. }
  60888. /* Now that there is a read-lock on the source database, query the
  60889. ** source pager for the number of pages in the database.
  60890. */
  60891. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  60892. assert( nSrcPage>=0 );
  60893. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  60894. const Pgno iSrcPg = p->iNext; /* Source page number */
  60895. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  60896. DbPage *pSrcPg; /* Source page object */
  60897. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  60898. if( rc==SQLITE_OK ){
  60899. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  60900. sqlite3PagerUnref(pSrcPg);
  60901. }
  60902. }
  60903. p->iNext++;
  60904. }
  60905. if( rc==SQLITE_OK ){
  60906. p->nPagecount = nSrcPage;
  60907. p->nRemaining = nSrcPage+1-p->iNext;
  60908. if( p->iNext>(Pgno)nSrcPage ){
  60909. rc = SQLITE_DONE;
  60910. }else if( !p->isAttached ){
  60911. attachBackupObject(p);
  60912. }
  60913. }
  60914. /* Update the schema version field in the destination database. This
  60915. ** is to make sure that the schema-version really does change in
  60916. ** the case where the source and destination databases have the
  60917. ** same schema version.
  60918. */
  60919. if( rc==SQLITE_DONE ){
  60920. if( nSrcPage==0 ){
  60921. rc = sqlite3BtreeNewDb(p->pDest);
  60922. nSrcPage = 1;
  60923. }
  60924. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  60925. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  60926. }
  60927. if( rc==SQLITE_OK ){
  60928. if( p->pDestDb ){
  60929. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  60930. }
  60931. if( destMode==PAGER_JOURNALMODE_WAL ){
  60932. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  60933. }
  60934. }
  60935. if( rc==SQLITE_OK ){
  60936. int nDestTruncate;
  60937. /* Set nDestTruncate to the final number of pages in the destination
  60938. ** database. The complication here is that the destination page
  60939. ** size may be different to the source page size.
  60940. **
  60941. ** If the source page size is smaller than the destination page size,
  60942. ** round up. In this case the call to sqlite3OsTruncate() below will
  60943. ** fix the size of the file. However it is important to call
  60944. ** sqlite3PagerTruncateImage() here so that any pages in the
  60945. ** destination file that lie beyond the nDestTruncate page mark are
  60946. ** journalled by PagerCommitPhaseOne() before they are destroyed
  60947. ** by the file truncation.
  60948. */
  60949. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  60950. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  60951. if( pgszSrc<pgszDest ){
  60952. int ratio = pgszDest/pgszSrc;
  60953. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  60954. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  60955. nDestTruncate--;
  60956. }
  60957. }else{
  60958. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  60959. }
  60960. assert( nDestTruncate>0 );
  60961. if( pgszSrc<pgszDest ){
  60962. /* If the source page-size is smaller than the destination page-size,
  60963. ** two extra things may need to happen:
  60964. **
  60965. ** * The destination may need to be truncated, and
  60966. **
  60967. ** * Data stored on the pages immediately following the
  60968. ** pending-byte page in the source database may need to be
  60969. ** copied into the destination database.
  60970. */
  60971. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  60972. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  60973. Pgno iPg;
  60974. int nDstPage;
  60975. i64 iOff;
  60976. i64 iEnd;
  60977. assert( pFile );
  60978. assert( nDestTruncate==0
  60979. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  60980. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  60981. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  60982. ));
  60983. /* This block ensures that all data required to recreate the original
  60984. ** database has been stored in the journal for pDestPager and the
  60985. ** journal synced to disk. So at this point we may safely modify
  60986. ** the database file in any way, knowing that if a power failure
  60987. ** occurs, the original database will be reconstructed from the
  60988. ** journal file. */
  60989. sqlite3PagerPagecount(pDestPager, &nDstPage);
  60990. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  60991. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  60992. DbPage *pPg;
  60993. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  60994. if( rc==SQLITE_OK ){
  60995. rc = sqlite3PagerWrite(pPg);
  60996. sqlite3PagerUnref(pPg);
  60997. }
  60998. }
  60999. }
  61000. if( rc==SQLITE_OK ){
  61001. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  61002. }
  61003. /* Write the extra pages and truncate the database file as required */
  61004. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  61005. for(
  61006. iOff=PENDING_BYTE+pgszSrc;
  61007. rc==SQLITE_OK && iOff<iEnd;
  61008. iOff+=pgszSrc
  61009. ){
  61010. PgHdr *pSrcPg = 0;
  61011. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  61012. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  61013. if( rc==SQLITE_OK ){
  61014. u8 *zData = sqlite3PagerGetData(pSrcPg);
  61015. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  61016. }
  61017. sqlite3PagerUnref(pSrcPg);
  61018. }
  61019. if( rc==SQLITE_OK ){
  61020. rc = backupTruncateFile(pFile, iSize);
  61021. }
  61022. /* Sync the database file to disk. */
  61023. if( rc==SQLITE_OK ){
  61024. rc = sqlite3PagerSync(pDestPager, 0);
  61025. }
  61026. }else{
  61027. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  61028. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  61029. }
  61030. /* Finish committing the transaction to the destination database. */
  61031. if( SQLITE_OK==rc
  61032. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  61033. ){
  61034. rc = SQLITE_DONE;
  61035. }
  61036. }
  61037. }
  61038. /* If bCloseTrans is true, then this function opened a read transaction
  61039. ** on the source database. Close the read transaction here. There is
  61040. ** no need to check the return values of the btree methods here, as
  61041. ** "committing" a read-only transaction cannot fail.
  61042. */
  61043. if( bCloseTrans ){
  61044. TESTONLY( int rc2 );
  61045. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  61046. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  61047. assert( rc2==SQLITE_OK );
  61048. }
  61049. if( rc==SQLITE_IOERR_NOMEM ){
  61050. rc = SQLITE_NOMEM;
  61051. }
  61052. p->rc = rc;
  61053. }
  61054. if( p->pDestDb ){
  61055. sqlite3_mutex_leave(p->pDestDb->mutex);
  61056. }
  61057. sqlite3BtreeLeave(p->pSrc);
  61058. sqlite3_mutex_leave(p->pSrcDb->mutex);
  61059. return rc;
  61060. }
  61061. /*
  61062. ** Release all resources associated with an sqlite3_backup* handle.
  61063. */
  61064. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
  61065. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  61066. sqlite3 *pSrcDb; /* Source database connection */
  61067. int rc; /* Value to return */
  61068. /* Enter the mutexes */
  61069. if( p==0 ) return SQLITE_OK;
  61070. pSrcDb = p->pSrcDb;
  61071. sqlite3_mutex_enter(pSrcDb->mutex);
  61072. sqlite3BtreeEnter(p->pSrc);
  61073. if( p->pDestDb ){
  61074. sqlite3_mutex_enter(p->pDestDb->mutex);
  61075. }
  61076. /* Detach this backup from the source pager. */
  61077. if( p->pDestDb ){
  61078. p->pSrc->nBackup--;
  61079. }
  61080. if( p->isAttached ){
  61081. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  61082. while( *pp!=p ){
  61083. pp = &(*pp)->pNext;
  61084. }
  61085. *pp = p->pNext;
  61086. }
  61087. /* If a transaction is still open on the Btree, roll it back. */
  61088. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  61089. /* Set the error code of the destination database handle. */
  61090. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  61091. if( p->pDestDb ){
  61092. sqlite3Error(p->pDestDb, rc);
  61093. /* Exit the mutexes and free the backup context structure. */
  61094. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  61095. }
  61096. sqlite3BtreeLeave(p->pSrc);
  61097. if( p->pDestDb ){
  61098. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  61099. ** call to sqlite3_backup_init() and is destroyed by a call to
  61100. ** sqlite3_backup_finish(). */
  61101. sqlite3_free(p);
  61102. }
  61103. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  61104. return rc;
  61105. }
  61106. /*
  61107. ** Return the number of pages still to be backed up as of the most recent
  61108. ** call to sqlite3_backup_step().
  61109. */
  61110. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
  61111. #ifdef SQLITE_ENABLE_API_ARMOR
  61112. if( p==0 ){
  61113. (void)SQLITE_MISUSE_BKPT;
  61114. return 0;
  61115. }
  61116. #endif
  61117. return p->nRemaining;
  61118. }
  61119. /*
  61120. ** Return the total number of pages in the source database as of the most
  61121. ** recent call to sqlite3_backup_step().
  61122. */
  61123. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
  61124. #ifdef SQLITE_ENABLE_API_ARMOR
  61125. if( p==0 ){
  61126. (void)SQLITE_MISUSE_BKPT;
  61127. return 0;
  61128. }
  61129. #endif
  61130. return p->nPagecount;
  61131. }
  61132. /*
  61133. ** This function is called after the contents of page iPage of the
  61134. ** source database have been modified. If page iPage has already been
  61135. ** copied into the destination database, then the data written to the
  61136. ** destination is now invalidated. The destination copy of iPage needs
  61137. ** to be updated with the new data before the backup operation is
  61138. ** complete.
  61139. **
  61140. ** It is assumed that the mutex associated with the BtShared object
  61141. ** corresponding to the source database is held when this function is
  61142. ** called.
  61143. */
  61144. static SQLITE_NOINLINE void backupUpdate(
  61145. sqlite3_backup *p,
  61146. Pgno iPage,
  61147. const u8 *aData
  61148. ){
  61149. assert( p!=0 );
  61150. do{
  61151. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  61152. if( !isFatalError(p->rc) && iPage<p->iNext ){
  61153. /* The backup process p has already copied page iPage. But now it
  61154. ** has been modified by a transaction on the source pager. Copy
  61155. ** the new data into the backup.
  61156. */
  61157. int rc;
  61158. assert( p->pDestDb );
  61159. sqlite3_mutex_enter(p->pDestDb->mutex);
  61160. rc = backupOnePage(p, iPage, aData, 1);
  61161. sqlite3_mutex_leave(p->pDestDb->mutex);
  61162. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  61163. if( rc!=SQLITE_OK ){
  61164. p->rc = rc;
  61165. }
  61166. }
  61167. }while( (p = p->pNext)!=0 );
  61168. }
  61169. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  61170. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  61171. }
  61172. /*
  61173. ** Restart the backup process. This is called when the pager layer
  61174. ** detects that the database has been modified by an external database
  61175. ** connection. In this case there is no way of knowing which of the
  61176. ** pages that have been copied into the destination database are still
  61177. ** valid and which are not, so the entire process needs to be restarted.
  61178. **
  61179. ** It is assumed that the mutex associated with the BtShared object
  61180. ** corresponding to the source database is held when this function is
  61181. ** called.
  61182. */
  61183. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  61184. sqlite3_backup *p; /* Iterator variable */
  61185. for(p=pBackup; p; p=p->pNext){
  61186. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  61187. p->iNext = 1;
  61188. }
  61189. }
  61190. #ifndef SQLITE_OMIT_VACUUM
  61191. /*
  61192. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  61193. ** must be active for both files.
  61194. **
  61195. ** The size of file pTo may be reduced by this operation. If anything
  61196. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  61197. ** transaction is committed before returning.
  61198. */
  61199. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  61200. int rc;
  61201. sqlite3_file *pFd; /* File descriptor for database pTo */
  61202. sqlite3_backup b;
  61203. sqlite3BtreeEnter(pTo);
  61204. sqlite3BtreeEnter(pFrom);
  61205. assert( sqlite3BtreeIsInTrans(pTo) );
  61206. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  61207. if( pFd->pMethods ){
  61208. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  61209. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  61210. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  61211. if( rc ) goto copy_finished;
  61212. }
  61213. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  61214. ** to 0. This is used by the implementations of sqlite3_backup_step()
  61215. ** and sqlite3_backup_finish() to detect that they are being called
  61216. ** from this function, not directly by the user.
  61217. */
  61218. memset(&b, 0, sizeof(b));
  61219. b.pSrcDb = pFrom->db;
  61220. b.pSrc = pFrom;
  61221. b.pDest = pTo;
  61222. b.iNext = 1;
  61223. #ifdef SQLITE_HAS_CODEC
  61224. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  61225. #endif
  61226. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  61227. ** file. By passing this as the number of pages to copy to
  61228. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  61229. ** within a single call (unless an error occurs). The assert() statement
  61230. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  61231. ** or an error code.
  61232. */
  61233. sqlite3_backup_step(&b, 0x7FFFFFFF);
  61234. assert( b.rc!=SQLITE_OK );
  61235. rc = sqlite3_backup_finish(&b);
  61236. if( rc==SQLITE_OK ){
  61237. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  61238. }else{
  61239. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  61240. }
  61241. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  61242. copy_finished:
  61243. sqlite3BtreeLeave(pFrom);
  61244. sqlite3BtreeLeave(pTo);
  61245. return rc;
  61246. }
  61247. #endif /* SQLITE_OMIT_VACUUM */
  61248. /************** End of backup.c **********************************************/
  61249. /************** Begin file vdbemem.c *****************************************/
  61250. /*
  61251. ** 2004 May 26
  61252. **
  61253. ** The author disclaims copyright to this source code. In place of
  61254. ** a legal notice, here is a blessing:
  61255. **
  61256. ** May you do good and not evil.
  61257. ** May you find forgiveness for yourself and forgive others.
  61258. ** May you share freely, never taking more than you give.
  61259. **
  61260. *************************************************************************
  61261. **
  61262. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  61263. ** stores a single value in the VDBE. Mem is an opaque structure visible
  61264. ** only within the VDBE. Interface routines refer to a Mem using the
  61265. ** name sqlite_value
  61266. */
  61267. /* #include "sqliteInt.h" */
  61268. /* #include "vdbeInt.h" */
  61269. #ifdef SQLITE_DEBUG
  61270. /*
  61271. ** Check invariants on a Mem object.
  61272. **
  61273. ** This routine is intended for use inside of assert() statements, like
  61274. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  61275. */
  61276. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  61277. /* If MEM_Dyn is set then Mem.xDel!=0.
  61278. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  61279. */
  61280. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  61281. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  61282. ** ensure that if Mem.szMalloc>0 then it is safe to do
  61283. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  61284. ** That saves a few cycles in inner loops. */
  61285. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  61286. /* Cannot be both MEM_Int and MEM_Real at the same time */
  61287. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  61288. /* The szMalloc field holds the correct memory allocation size */
  61289. assert( p->szMalloc==0
  61290. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  61291. /* If p holds a string or blob, the Mem.z must point to exactly
  61292. ** one of the following:
  61293. **
  61294. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  61295. ** (2) Memory to be freed using Mem.xDel
  61296. ** (3) An ephemeral string or blob
  61297. ** (4) A static string or blob
  61298. */
  61299. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  61300. assert(
  61301. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  61302. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  61303. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  61304. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  61305. );
  61306. }
  61307. return 1;
  61308. }
  61309. #endif
  61310. /*
  61311. ** If pMem is an object with a valid string representation, this routine
  61312. ** ensures the internal encoding for the string representation is
  61313. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  61314. **
  61315. ** If pMem is not a string object, or the encoding of the string
  61316. ** representation is already stored using the requested encoding, then this
  61317. ** routine is a no-op.
  61318. **
  61319. ** SQLITE_OK is returned if the conversion is successful (or not required).
  61320. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  61321. ** between formats.
  61322. */
  61323. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  61324. #ifndef SQLITE_OMIT_UTF16
  61325. int rc;
  61326. #endif
  61327. assert( (pMem->flags&MEM_RowSet)==0 );
  61328. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  61329. || desiredEnc==SQLITE_UTF16BE );
  61330. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  61331. return SQLITE_OK;
  61332. }
  61333. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61334. #ifdef SQLITE_OMIT_UTF16
  61335. return SQLITE_ERROR;
  61336. #else
  61337. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  61338. ** then the encoding of the value may not have changed.
  61339. */
  61340. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  61341. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  61342. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  61343. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  61344. return rc;
  61345. #endif
  61346. }
  61347. /*
  61348. ** Make sure pMem->z points to a writable allocation of at least
  61349. ** min(n,32) bytes.
  61350. **
  61351. ** If the bPreserve argument is true, then copy of the content of
  61352. ** pMem->z into the new allocation. pMem must be either a string or
  61353. ** blob if bPreserve is true. If bPreserve is false, any prior content
  61354. ** in pMem->z is discarded.
  61355. */
  61356. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  61357. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  61358. assert( (pMem->flags&MEM_RowSet)==0 );
  61359. /* If the bPreserve flag is set to true, then the memory cell must already
  61360. ** contain a valid string or blob value. */
  61361. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  61362. testcase( bPreserve && pMem->z==0 );
  61363. assert( pMem->szMalloc==0
  61364. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  61365. if( pMem->szMalloc<n ){
  61366. if( n<32 ) n = 32;
  61367. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  61368. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  61369. bPreserve = 0;
  61370. }else{
  61371. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  61372. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  61373. }
  61374. if( pMem->zMalloc==0 ){
  61375. sqlite3VdbeMemSetNull(pMem);
  61376. pMem->z = 0;
  61377. pMem->szMalloc = 0;
  61378. return SQLITE_NOMEM;
  61379. }else{
  61380. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  61381. }
  61382. }
  61383. if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
  61384. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  61385. }
  61386. if( (pMem->flags&MEM_Dyn)!=0 ){
  61387. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  61388. pMem->xDel((void *)(pMem->z));
  61389. }
  61390. pMem->z = pMem->zMalloc;
  61391. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  61392. return SQLITE_OK;
  61393. }
  61394. /*
  61395. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  61396. ** If pMem->zMalloc already meets or exceeds the requested size, this
  61397. ** routine is a no-op.
  61398. **
  61399. ** Any prior string or blob content in the pMem object may be discarded.
  61400. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  61401. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  61402. ** values are preserved.
  61403. **
  61404. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  61405. ** if unable to complete the resizing.
  61406. */
  61407. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  61408. assert( szNew>0 );
  61409. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  61410. if( pMem->szMalloc<szNew ){
  61411. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  61412. }
  61413. assert( (pMem->flags & MEM_Dyn)==0 );
  61414. pMem->z = pMem->zMalloc;
  61415. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  61416. return SQLITE_OK;
  61417. }
  61418. /*
  61419. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  61420. ** MEM.zMalloc, where it can be safely written.
  61421. **
  61422. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  61423. */
  61424. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  61425. int f;
  61426. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61427. assert( (pMem->flags&MEM_RowSet)==0 );
  61428. ExpandBlob(pMem);
  61429. f = pMem->flags;
  61430. if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
  61431. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  61432. return SQLITE_NOMEM;
  61433. }
  61434. pMem->z[pMem->n] = 0;
  61435. pMem->z[pMem->n+1] = 0;
  61436. pMem->flags |= MEM_Term;
  61437. }
  61438. pMem->flags &= ~MEM_Ephem;
  61439. #ifdef SQLITE_DEBUG
  61440. pMem->pScopyFrom = 0;
  61441. #endif
  61442. return SQLITE_OK;
  61443. }
  61444. /*
  61445. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  61446. ** blob stored in dynamically allocated space.
  61447. */
  61448. #ifndef SQLITE_OMIT_INCRBLOB
  61449. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  61450. if( pMem->flags & MEM_Zero ){
  61451. int nByte;
  61452. assert( pMem->flags&MEM_Blob );
  61453. assert( (pMem->flags&MEM_RowSet)==0 );
  61454. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61455. /* Set nByte to the number of bytes required to store the expanded blob. */
  61456. nByte = pMem->n + pMem->u.nZero;
  61457. if( nByte<=0 ){
  61458. nByte = 1;
  61459. }
  61460. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  61461. return SQLITE_NOMEM;
  61462. }
  61463. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  61464. pMem->n += pMem->u.nZero;
  61465. pMem->flags &= ~(MEM_Zero|MEM_Term);
  61466. }
  61467. return SQLITE_OK;
  61468. }
  61469. #endif
  61470. /*
  61471. ** It is already known that pMem contains an unterminated string.
  61472. ** Add the zero terminator.
  61473. */
  61474. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  61475. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  61476. return SQLITE_NOMEM;
  61477. }
  61478. pMem->z[pMem->n] = 0;
  61479. pMem->z[pMem->n+1] = 0;
  61480. pMem->flags |= MEM_Term;
  61481. return SQLITE_OK;
  61482. }
  61483. /*
  61484. ** Make sure the given Mem is \u0000 terminated.
  61485. */
  61486. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  61487. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61488. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  61489. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  61490. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  61491. return SQLITE_OK; /* Nothing to do */
  61492. }else{
  61493. return vdbeMemAddTerminator(pMem);
  61494. }
  61495. }
  61496. /*
  61497. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  61498. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  61499. ** is a no-op.
  61500. **
  61501. ** Existing representations MEM_Int and MEM_Real are invalidated if
  61502. ** bForce is true but are retained if bForce is false.
  61503. **
  61504. ** A MEM_Null value will never be passed to this function. This function is
  61505. ** used for converting values to text for returning to the user (i.e. via
  61506. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  61507. ** keys are strings. In the former case a NULL pointer is returned the
  61508. ** user and the latter is an internal programming error.
  61509. */
  61510. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  61511. int fg = pMem->flags;
  61512. const int nByte = 32;
  61513. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61514. assert( !(fg&MEM_Zero) );
  61515. assert( !(fg&(MEM_Str|MEM_Blob)) );
  61516. assert( fg&(MEM_Int|MEM_Real) );
  61517. assert( (pMem->flags&MEM_RowSet)==0 );
  61518. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61519. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  61520. return SQLITE_NOMEM;
  61521. }
  61522. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  61523. ** string representation of the value. Then, if the required encoding
  61524. ** is UTF-16le or UTF-16be do a translation.
  61525. **
  61526. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  61527. */
  61528. if( fg & MEM_Int ){
  61529. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  61530. }else{
  61531. assert( fg & MEM_Real );
  61532. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  61533. }
  61534. pMem->n = sqlite3Strlen30(pMem->z);
  61535. pMem->enc = SQLITE_UTF8;
  61536. pMem->flags |= MEM_Str|MEM_Term;
  61537. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  61538. sqlite3VdbeChangeEncoding(pMem, enc);
  61539. return SQLITE_OK;
  61540. }
  61541. /*
  61542. ** Memory cell pMem contains the context of an aggregate function.
  61543. ** This routine calls the finalize method for that function. The
  61544. ** result of the aggregate is stored back into pMem.
  61545. **
  61546. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  61547. ** otherwise.
  61548. */
  61549. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  61550. int rc = SQLITE_OK;
  61551. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  61552. sqlite3_context ctx;
  61553. Mem t;
  61554. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  61555. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61556. memset(&ctx, 0, sizeof(ctx));
  61557. memset(&t, 0, sizeof(t));
  61558. t.flags = MEM_Null;
  61559. t.db = pMem->db;
  61560. ctx.pOut = &t;
  61561. ctx.pMem = pMem;
  61562. ctx.pFunc = pFunc;
  61563. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  61564. assert( (pMem->flags & MEM_Dyn)==0 );
  61565. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  61566. memcpy(pMem, &t, sizeof(t));
  61567. rc = ctx.isError;
  61568. }
  61569. return rc;
  61570. }
  61571. /*
  61572. ** If the memory cell contains a value that must be freed by
  61573. ** invoking the external callback in Mem.xDel, then this routine
  61574. ** will free that value. It also sets Mem.flags to MEM_Null.
  61575. **
  61576. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  61577. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  61578. ** entry point for releasing Mem resources.
  61579. */
  61580. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  61581. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  61582. assert( VdbeMemDynamic(p) );
  61583. if( p->flags&MEM_Agg ){
  61584. sqlite3VdbeMemFinalize(p, p->u.pDef);
  61585. assert( (p->flags & MEM_Agg)==0 );
  61586. testcase( p->flags & MEM_Dyn );
  61587. }
  61588. if( p->flags&MEM_Dyn ){
  61589. assert( (p->flags&MEM_RowSet)==0 );
  61590. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  61591. p->xDel((void *)p->z);
  61592. }else if( p->flags&MEM_RowSet ){
  61593. sqlite3RowSetClear(p->u.pRowSet);
  61594. }else if( p->flags&MEM_Frame ){
  61595. VdbeFrame *pFrame = p->u.pFrame;
  61596. pFrame->pParent = pFrame->v->pDelFrame;
  61597. pFrame->v->pDelFrame = pFrame;
  61598. }
  61599. p->flags = MEM_Null;
  61600. }
  61601. /*
  61602. ** Release memory held by the Mem p, both external memory cleared
  61603. ** by p->xDel and memory in p->zMalloc.
  61604. **
  61605. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  61606. ** the unusual case where there really is memory in p that needs
  61607. ** to be freed.
  61608. */
  61609. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  61610. if( VdbeMemDynamic(p) ){
  61611. vdbeMemClearExternAndSetNull(p);
  61612. }
  61613. if( p->szMalloc ){
  61614. sqlite3DbFree(p->db, p->zMalloc);
  61615. p->szMalloc = 0;
  61616. }
  61617. p->z = 0;
  61618. }
  61619. /*
  61620. ** Release any memory resources held by the Mem. Both the memory that is
  61621. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  61622. **
  61623. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  61624. ** reset a Mem back to its minimum memory utilization.
  61625. **
  61626. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  61627. ** prior to inserting new content into the Mem.
  61628. */
  61629. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  61630. assert( sqlite3VdbeCheckMemInvariants(p) );
  61631. if( VdbeMemDynamic(p) || p->szMalloc ){
  61632. vdbeMemClear(p);
  61633. }
  61634. }
  61635. /*
  61636. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  61637. ** If the double is out of range of a 64-bit signed integer then
  61638. ** return the closest available 64-bit signed integer.
  61639. */
  61640. static i64 doubleToInt64(double r){
  61641. #ifdef SQLITE_OMIT_FLOATING_POINT
  61642. /* When floating-point is omitted, double and int64 are the same thing */
  61643. return r;
  61644. #else
  61645. /*
  61646. ** Many compilers we encounter do not define constants for the
  61647. ** minimum and maximum 64-bit integers, or they define them
  61648. ** inconsistently. And many do not understand the "LL" notation.
  61649. ** So we define our own static constants here using nothing
  61650. ** larger than a 32-bit integer constant.
  61651. */
  61652. static const i64 maxInt = LARGEST_INT64;
  61653. static const i64 minInt = SMALLEST_INT64;
  61654. if( r<=(double)minInt ){
  61655. return minInt;
  61656. }else if( r>=(double)maxInt ){
  61657. return maxInt;
  61658. }else{
  61659. return (i64)r;
  61660. }
  61661. #endif
  61662. }
  61663. /*
  61664. ** Return some kind of integer value which is the best we can do
  61665. ** at representing the value that *pMem describes as an integer.
  61666. ** If pMem is an integer, then the value is exact. If pMem is
  61667. ** a floating-point then the value returned is the integer part.
  61668. ** If pMem is a string or blob, then we make an attempt to convert
  61669. ** it into an integer and return that. If pMem represents an
  61670. ** an SQL-NULL value, return 0.
  61671. **
  61672. ** If pMem represents a string value, its encoding might be changed.
  61673. */
  61674. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  61675. int flags;
  61676. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61677. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61678. flags = pMem->flags;
  61679. if( flags & MEM_Int ){
  61680. return pMem->u.i;
  61681. }else if( flags & MEM_Real ){
  61682. return doubleToInt64(pMem->u.r);
  61683. }else if( flags & (MEM_Str|MEM_Blob) ){
  61684. i64 value = 0;
  61685. assert( pMem->z || pMem->n==0 );
  61686. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  61687. return value;
  61688. }else{
  61689. return 0;
  61690. }
  61691. }
  61692. /*
  61693. ** Return the best representation of pMem that we can get into a
  61694. ** double. If pMem is already a double or an integer, return its
  61695. ** value. If it is a string or blob, try to convert it to a double.
  61696. ** If it is a NULL, return 0.0.
  61697. */
  61698. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  61699. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61700. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61701. if( pMem->flags & MEM_Real ){
  61702. return pMem->u.r;
  61703. }else if( pMem->flags & MEM_Int ){
  61704. return (double)pMem->u.i;
  61705. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  61706. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  61707. double val = (double)0;
  61708. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  61709. return val;
  61710. }else{
  61711. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  61712. return (double)0;
  61713. }
  61714. }
  61715. /*
  61716. ** The MEM structure is already a MEM_Real. Try to also make it a
  61717. ** MEM_Int if we can.
  61718. */
  61719. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  61720. i64 ix;
  61721. assert( pMem->flags & MEM_Real );
  61722. assert( (pMem->flags & MEM_RowSet)==0 );
  61723. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61724. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61725. ix = doubleToInt64(pMem->u.r);
  61726. /* Only mark the value as an integer if
  61727. **
  61728. ** (1) the round-trip conversion real->int->real is a no-op, and
  61729. ** (2) The integer is neither the largest nor the smallest
  61730. ** possible integer (ticket #3922)
  61731. **
  61732. ** The second and third terms in the following conditional enforces
  61733. ** the second condition under the assumption that addition overflow causes
  61734. ** values to wrap around.
  61735. */
  61736. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  61737. pMem->u.i = ix;
  61738. MemSetTypeFlag(pMem, MEM_Int);
  61739. }
  61740. }
  61741. /*
  61742. ** Convert pMem to type integer. Invalidate any prior representations.
  61743. */
  61744. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  61745. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61746. assert( (pMem->flags & MEM_RowSet)==0 );
  61747. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61748. pMem->u.i = sqlite3VdbeIntValue(pMem);
  61749. MemSetTypeFlag(pMem, MEM_Int);
  61750. return SQLITE_OK;
  61751. }
  61752. /*
  61753. ** Convert pMem so that it is of type MEM_Real.
  61754. ** Invalidate any prior representations.
  61755. */
  61756. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  61757. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61758. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61759. pMem->u.r = sqlite3VdbeRealValue(pMem);
  61760. MemSetTypeFlag(pMem, MEM_Real);
  61761. return SQLITE_OK;
  61762. }
  61763. /*
  61764. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  61765. ** Invalidate any prior representations.
  61766. **
  61767. ** Every effort is made to force the conversion, even if the input
  61768. ** is a string that does not look completely like a number. Convert
  61769. ** as much of the string as we can and ignore the rest.
  61770. */
  61771. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  61772. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  61773. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  61774. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  61775. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  61776. MemSetTypeFlag(pMem, MEM_Int);
  61777. }else{
  61778. pMem->u.r = sqlite3VdbeRealValue(pMem);
  61779. MemSetTypeFlag(pMem, MEM_Real);
  61780. sqlite3VdbeIntegerAffinity(pMem);
  61781. }
  61782. }
  61783. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  61784. pMem->flags &= ~(MEM_Str|MEM_Blob);
  61785. return SQLITE_OK;
  61786. }
  61787. /*
  61788. ** Cast the datatype of the value in pMem according to the affinity
  61789. ** "aff". Casting is different from applying affinity in that a cast
  61790. ** is forced. In other words, the value is converted into the desired
  61791. ** affinity even if that results in loss of data. This routine is
  61792. ** used (for example) to implement the SQL "cast()" operator.
  61793. */
  61794. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  61795. if( pMem->flags & MEM_Null ) return;
  61796. switch( aff ){
  61797. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  61798. if( (pMem->flags & MEM_Blob)==0 ){
  61799. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  61800. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  61801. MemSetTypeFlag(pMem, MEM_Blob);
  61802. }else{
  61803. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  61804. }
  61805. break;
  61806. }
  61807. case SQLITE_AFF_NUMERIC: {
  61808. sqlite3VdbeMemNumerify(pMem);
  61809. break;
  61810. }
  61811. case SQLITE_AFF_INTEGER: {
  61812. sqlite3VdbeMemIntegerify(pMem);
  61813. break;
  61814. }
  61815. case SQLITE_AFF_REAL: {
  61816. sqlite3VdbeMemRealify(pMem);
  61817. break;
  61818. }
  61819. default: {
  61820. assert( aff==SQLITE_AFF_TEXT );
  61821. assert( MEM_Str==(MEM_Blob>>3) );
  61822. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  61823. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  61824. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  61825. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  61826. break;
  61827. }
  61828. }
  61829. }
  61830. /*
  61831. ** Initialize bulk memory to be a consistent Mem object.
  61832. **
  61833. ** The minimum amount of initialization feasible is performed.
  61834. */
  61835. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  61836. assert( (flags & ~MEM_TypeMask)==0 );
  61837. pMem->flags = flags;
  61838. pMem->db = db;
  61839. pMem->szMalloc = 0;
  61840. }
  61841. /*
  61842. ** Delete any previous value and set the value stored in *pMem to NULL.
  61843. **
  61844. ** This routine calls the Mem.xDel destructor to dispose of values that
  61845. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  61846. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  61847. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  61848. **
  61849. ** Use this routine to reset the Mem prior to insert a new value.
  61850. **
  61851. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  61852. */
  61853. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  61854. if( VdbeMemDynamic(pMem) ){
  61855. vdbeMemClearExternAndSetNull(pMem);
  61856. }else{
  61857. pMem->flags = MEM_Null;
  61858. }
  61859. }
  61860. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  61861. sqlite3VdbeMemSetNull((Mem*)p);
  61862. }
  61863. /*
  61864. ** Delete any previous value and set the value to be a BLOB of length
  61865. ** n containing all zeros.
  61866. */
  61867. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  61868. sqlite3VdbeMemRelease(pMem);
  61869. pMem->flags = MEM_Blob|MEM_Zero;
  61870. pMem->n = 0;
  61871. if( n<0 ) n = 0;
  61872. pMem->u.nZero = n;
  61873. pMem->enc = SQLITE_UTF8;
  61874. pMem->z = 0;
  61875. }
  61876. /*
  61877. ** The pMem is known to contain content that needs to be destroyed prior
  61878. ** to a value change. So invoke the destructor, then set the value to
  61879. ** a 64-bit integer.
  61880. */
  61881. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  61882. sqlite3VdbeMemSetNull(pMem);
  61883. pMem->u.i = val;
  61884. pMem->flags = MEM_Int;
  61885. }
  61886. /*
  61887. ** Delete any previous value and set the value stored in *pMem to val,
  61888. ** manifest type INTEGER.
  61889. */
  61890. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  61891. if( VdbeMemDynamic(pMem) ){
  61892. vdbeReleaseAndSetInt64(pMem, val);
  61893. }else{
  61894. pMem->u.i = val;
  61895. pMem->flags = MEM_Int;
  61896. }
  61897. }
  61898. #ifndef SQLITE_OMIT_FLOATING_POINT
  61899. /*
  61900. ** Delete any previous value and set the value stored in *pMem to val,
  61901. ** manifest type REAL.
  61902. */
  61903. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  61904. sqlite3VdbeMemSetNull(pMem);
  61905. if( !sqlite3IsNaN(val) ){
  61906. pMem->u.r = val;
  61907. pMem->flags = MEM_Real;
  61908. }
  61909. }
  61910. #endif
  61911. /*
  61912. ** Delete any previous value and set the value of pMem to be an
  61913. ** empty boolean index.
  61914. */
  61915. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  61916. sqlite3 *db = pMem->db;
  61917. assert( db!=0 );
  61918. assert( (pMem->flags & MEM_RowSet)==0 );
  61919. sqlite3VdbeMemRelease(pMem);
  61920. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  61921. if( db->mallocFailed ){
  61922. pMem->flags = MEM_Null;
  61923. pMem->szMalloc = 0;
  61924. }else{
  61925. assert( pMem->zMalloc );
  61926. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  61927. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  61928. assert( pMem->u.pRowSet!=0 );
  61929. pMem->flags = MEM_RowSet;
  61930. }
  61931. }
  61932. /*
  61933. ** Return true if the Mem object contains a TEXT or BLOB that is
  61934. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  61935. */
  61936. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  61937. assert( p->db!=0 );
  61938. if( p->flags & (MEM_Str|MEM_Blob) ){
  61939. int n = p->n;
  61940. if( p->flags & MEM_Zero ){
  61941. n += p->u.nZero;
  61942. }
  61943. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  61944. }
  61945. return 0;
  61946. }
  61947. #ifdef SQLITE_DEBUG
  61948. /*
  61949. ** This routine prepares a memory cell for modification by breaking
  61950. ** its link to a shallow copy and by marking any current shallow
  61951. ** copies of this cell as invalid.
  61952. **
  61953. ** This is used for testing and debugging only - to make sure shallow
  61954. ** copies are not misused.
  61955. */
  61956. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  61957. int i;
  61958. Mem *pX;
  61959. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  61960. if( pX->pScopyFrom==pMem ){
  61961. pX->flags |= MEM_Undefined;
  61962. pX->pScopyFrom = 0;
  61963. }
  61964. }
  61965. pMem->pScopyFrom = 0;
  61966. }
  61967. #endif /* SQLITE_DEBUG */
  61968. /*
  61969. ** Make an shallow copy of pFrom into pTo. Prior contents of
  61970. ** pTo are freed. The pFrom->z field is not duplicated. If
  61971. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  61972. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  61973. */
  61974. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  61975. vdbeMemClearExternAndSetNull(pTo);
  61976. assert( !VdbeMemDynamic(pTo) );
  61977. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  61978. }
  61979. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  61980. assert( (pFrom->flags & MEM_RowSet)==0 );
  61981. assert( pTo->db==pFrom->db );
  61982. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  61983. memcpy(pTo, pFrom, MEMCELLSIZE);
  61984. if( (pFrom->flags&MEM_Static)==0 ){
  61985. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  61986. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  61987. pTo->flags |= srcType;
  61988. }
  61989. }
  61990. /*
  61991. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  61992. ** freed before the copy is made.
  61993. */
  61994. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  61995. int rc = SQLITE_OK;
  61996. /* The pFrom==0 case in the following assert() is when an sqlite3_value
  61997. ** from sqlite3_value_dup() is used as the argument
  61998. ** to sqlite3_result_value(). */
  61999. assert( pTo->db==pFrom->db || pFrom->db==0 );
  62000. assert( (pFrom->flags & MEM_RowSet)==0 );
  62001. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  62002. memcpy(pTo, pFrom, MEMCELLSIZE);
  62003. pTo->flags &= ~MEM_Dyn;
  62004. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  62005. if( 0==(pFrom->flags&MEM_Static) ){
  62006. pTo->flags |= MEM_Ephem;
  62007. rc = sqlite3VdbeMemMakeWriteable(pTo);
  62008. }
  62009. }
  62010. return rc;
  62011. }
  62012. /*
  62013. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  62014. ** freed. If pFrom contains ephemeral data, a copy is made.
  62015. **
  62016. ** pFrom contains an SQL NULL when this routine returns.
  62017. */
  62018. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  62019. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  62020. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  62021. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  62022. sqlite3VdbeMemRelease(pTo);
  62023. memcpy(pTo, pFrom, sizeof(Mem));
  62024. pFrom->flags = MEM_Null;
  62025. pFrom->szMalloc = 0;
  62026. }
  62027. /*
  62028. ** Change the value of a Mem to be a string or a BLOB.
  62029. **
  62030. ** The memory management strategy depends on the value of the xDel
  62031. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  62032. ** string is copied into a (possibly existing) buffer managed by the
  62033. ** Mem structure. Otherwise, any existing buffer is freed and the
  62034. ** pointer copied.
  62035. **
  62036. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  62037. ** size limit) then no memory allocation occurs. If the string can be
  62038. ** stored without allocating memory, then it is. If a memory allocation
  62039. ** is required to store the string, then value of pMem is unchanged. In
  62040. ** either case, SQLITE_TOOBIG is returned.
  62041. */
  62042. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  62043. Mem *pMem, /* Memory cell to set to string value */
  62044. const char *z, /* String pointer */
  62045. int n, /* Bytes in string, or negative */
  62046. u8 enc, /* Encoding of z. 0 for BLOBs */
  62047. void (*xDel)(void*) /* Destructor function */
  62048. ){
  62049. int nByte = n; /* New value for pMem->n */
  62050. int iLimit; /* Maximum allowed string or blob size */
  62051. u16 flags = 0; /* New value for pMem->flags */
  62052. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  62053. assert( (pMem->flags & MEM_RowSet)==0 );
  62054. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  62055. if( !z ){
  62056. sqlite3VdbeMemSetNull(pMem);
  62057. return SQLITE_OK;
  62058. }
  62059. if( pMem->db ){
  62060. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  62061. }else{
  62062. iLimit = SQLITE_MAX_LENGTH;
  62063. }
  62064. flags = (enc==0?MEM_Blob:MEM_Str);
  62065. if( nByte<0 ){
  62066. assert( enc!=0 );
  62067. if( enc==SQLITE_UTF8 ){
  62068. nByte = sqlite3Strlen30(z);
  62069. if( nByte>iLimit ) nByte = iLimit+1;
  62070. }else{
  62071. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  62072. }
  62073. flags |= MEM_Term;
  62074. }
  62075. /* The following block sets the new values of Mem.z and Mem.xDel. It
  62076. ** also sets a flag in local variable "flags" to indicate the memory
  62077. ** management (one of MEM_Dyn or MEM_Static).
  62078. */
  62079. if( xDel==SQLITE_TRANSIENT ){
  62080. int nAlloc = nByte;
  62081. if( flags&MEM_Term ){
  62082. nAlloc += (enc==SQLITE_UTF8?1:2);
  62083. }
  62084. if( nByte>iLimit ){
  62085. return SQLITE_TOOBIG;
  62086. }
  62087. testcase( nAlloc==0 );
  62088. testcase( nAlloc==31 );
  62089. testcase( nAlloc==32 );
  62090. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  62091. return SQLITE_NOMEM;
  62092. }
  62093. memcpy(pMem->z, z, nAlloc);
  62094. }else if( xDel==SQLITE_DYNAMIC ){
  62095. sqlite3VdbeMemRelease(pMem);
  62096. pMem->zMalloc = pMem->z = (char *)z;
  62097. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  62098. }else{
  62099. sqlite3VdbeMemRelease(pMem);
  62100. pMem->z = (char *)z;
  62101. pMem->xDel = xDel;
  62102. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  62103. }
  62104. pMem->n = nByte;
  62105. pMem->flags = flags;
  62106. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  62107. #ifndef SQLITE_OMIT_UTF16
  62108. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  62109. return SQLITE_NOMEM;
  62110. }
  62111. #endif
  62112. if( nByte>iLimit ){
  62113. return SQLITE_TOOBIG;
  62114. }
  62115. return SQLITE_OK;
  62116. }
  62117. /*
  62118. ** Move data out of a btree key or data field and into a Mem structure.
  62119. ** The data or key is taken from the entry that pCur is currently pointing
  62120. ** to. offset and amt determine what portion of the data or key to retrieve.
  62121. ** key is true to get the key or false to get data. The result is written
  62122. ** into the pMem element.
  62123. **
  62124. ** The pMem object must have been initialized. This routine will use
  62125. ** pMem->zMalloc to hold the content from the btree, if possible. New
  62126. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  62127. ** is responsible for making sure that the pMem object is eventually
  62128. ** destroyed.
  62129. **
  62130. ** If this routine fails for any reason (malloc returns NULL or unable
  62131. ** to read from the disk) then the pMem is left in an inconsistent state.
  62132. */
  62133. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  62134. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  62135. u32 offset, /* Offset from the start of data to return bytes from. */
  62136. u32 amt, /* Number of bytes to return. */
  62137. int key, /* If true, retrieve from the btree key, not data. */
  62138. Mem *pMem /* OUT: Return data in this Mem structure. */
  62139. ){
  62140. int rc;
  62141. pMem->flags = MEM_Null;
  62142. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  62143. if( key ){
  62144. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  62145. }else{
  62146. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  62147. }
  62148. if( rc==SQLITE_OK ){
  62149. pMem->z[amt] = 0;
  62150. pMem->z[amt+1] = 0;
  62151. pMem->flags = MEM_Blob|MEM_Term;
  62152. pMem->n = (int)amt;
  62153. }else{
  62154. sqlite3VdbeMemRelease(pMem);
  62155. }
  62156. }
  62157. return rc;
  62158. }
  62159. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  62160. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  62161. u32 offset, /* Offset from the start of data to return bytes from. */
  62162. u32 amt, /* Number of bytes to return. */
  62163. int key, /* If true, retrieve from the btree key, not data. */
  62164. Mem *pMem /* OUT: Return data in this Mem structure. */
  62165. ){
  62166. char *zData; /* Data from the btree layer */
  62167. u32 available = 0; /* Number of bytes available on the local btree page */
  62168. int rc = SQLITE_OK; /* Return code */
  62169. assert( sqlite3BtreeCursorIsValid(pCur) );
  62170. assert( !VdbeMemDynamic(pMem) );
  62171. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  62172. ** that both the BtShared and database handle mutexes are held. */
  62173. assert( (pMem->flags & MEM_RowSet)==0 );
  62174. if( key ){
  62175. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  62176. }else{
  62177. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  62178. }
  62179. assert( zData!=0 );
  62180. if( offset+amt<=available ){
  62181. pMem->z = &zData[offset];
  62182. pMem->flags = MEM_Blob|MEM_Ephem;
  62183. pMem->n = (int)amt;
  62184. }else{
  62185. rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
  62186. }
  62187. return rc;
  62188. }
  62189. /*
  62190. ** The pVal argument is known to be a value other than NULL.
  62191. ** Convert it into a string with encoding enc and return a pointer
  62192. ** to a zero-terminated version of that string.
  62193. */
  62194. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  62195. assert( pVal!=0 );
  62196. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  62197. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  62198. assert( (pVal->flags & MEM_RowSet)==0 );
  62199. assert( (pVal->flags & (MEM_Null))==0 );
  62200. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  62201. pVal->flags |= MEM_Str;
  62202. if( pVal->flags & MEM_Zero ){
  62203. sqlite3VdbeMemExpandBlob(pVal);
  62204. }
  62205. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  62206. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  62207. }
  62208. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  62209. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  62210. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  62211. return 0;
  62212. }
  62213. }
  62214. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  62215. }else{
  62216. sqlite3VdbeMemStringify(pVal, enc, 0);
  62217. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  62218. }
  62219. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  62220. || pVal->db->mallocFailed );
  62221. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  62222. return pVal->z;
  62223. }else{
  62224. return 0;
  62225. }
  62226. }
  62227. /* This function is only available internally, it is not part of the
  62228. ** external API. It works in a similar way to sqlite3_value_text(),
  62229. ** except the data returned is in the encoding specified by the second
  62230. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  62231. ** SQLITE_UTF8.
  62232. **
  62233. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  62234. ** If that is the case, then the result must be aligned on an even byte
  62235. ** boundary.
  62236. */
  62237. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  62238. if( !pVal ) return 0;
  62239. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  62240. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  62241. assert( (pVal->flags & MEM_RowSet)==0 );
  62242. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  62243. return pVal->z;
  62244. }
  62245. if( pVal->flags&MEM_Null ){
  62246. return 0;
  62247. }
  62248. return valueToText(pVal, enc);
  62249. }
  62250. /*
  62251. ** Create a new sqlite3_value object.
  62252. */
  62253. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  62254. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  62255. if( p ){
  62256. p->flags = MEM_Null;
  62257. p->db = db;
  62258. }
  62259. return p;
  62260. }
  62261. /*
  62262. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  62263. ** valueNew(). See comments above valueNew() for details.
  62264. */
  62265. struct ValueNewStat4Ctx {
  62266. Parse *pParse;
  62267. Index *pIdx;
  62268. UnpackedRecord **ppRec;
  62269. int iVal;
  62270. };
  62271. /*
  62272. ** Allocate and return a pointer to a new sqlite3_value object. If
  62273. ** the second argument to this function is NULL, the object is allocated
  62274. ** by calling sqlite3ValueNew().
  62275. **
  62276. ** Otherwise, if the second argument is non-zero, then this function is
  62277. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  62278. ** already been allocated, allocate the UnpackedRecord structure that
  62279. ** that function will return to its caller here. Then return a pointer to
  62280. ** an sqlite3_value within the UnpackedRecord.a[] array.
  62281. */
  62282. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  62283. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  62284. if( p ){
  62285. UnpackedRecord *pRec = p->ppRec[0];
  62286. if( pRec==0 ){
  62287. Index *pIdx = p->pIdx; /* Index being probed */
  62288. int nByte; /* Bytes of space to allocate */
  62289. int i; /* Counter variable */
  62290. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  62291. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  62292. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  62293. if( pRec ){
  62294. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  62295. if( pRec->pKeyInfo ){
  62296. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  62297. assert( pRec->pKeyInfo->enc==ENC(db) );
  62298. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  62299. for(i=0; i<nCol; i++){
  62300. pRec->aMem[i].flags = MEM_Null;
  62301. pRec->aMem[i].db = db;
  62302. }
  62303. }else{
  62304. sqlite3DbFree(db, pRec);
  62305. pRec = 0;
  62306. }
  62307. }
  62308. if( pRec==0 ) return 0;
  62309. p->ppRec[0] = pRec;
  62310. }
  62311. pRec->nField = p->iVal+1;
  62312. return &pRec->aMem[p->iVal];
  62313. }
  62314. #else
  62315. UNUSED_PARAMETER(p);
  62316. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  62317. return sqlite3ValueNew(db);
  62318. }
  62319. /*
  62320. ** The expression object indicated by the second argument is guaranteed
  62321. ** to be a scalar SQL function. If
  62322. **
  62323. ** * all function arguments are SQL literals,
  62324. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  62325. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  62326. **
  62327. ** then this routine attempts to invoke the SQL function. Assuming no
  62328. ** error occurs, output parameter (*ppVal) is set to point to a value
  62329. ** object containing the result before returning SQLITE_OK.
  62330. **
  62331. ** Affinity aff is applied to the result of the function before returning.
  62332. ** If the result is a text value, the sqlite3_value object uses encoding
  62333. ** enc.
  62334. **
  62335. ** If the conditions above are not met, this function returns SQLITE_OK
  62336. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  62337. ** NULL and an SQLite error code returned.
  62338. */
  62339. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  62340. static int valueFromFunction(
  62341. sqlite3 *db, /* The database connection */
  62342. Expr *p, /* The expression to evaluate */
  62343. u8 enc, /* Encoding to use */
  62344. u8 aff, /* Affinity to use */
  62345. sqlite3_value **ppVal, /* Write the new value here */
  62346. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  62347. ){
  62348. sqlite3_context ctx; /* Context object for function invocation */
  62349. sqlite3_value **apVal = 0; /* Function arguments */
  62350. int nVal = 0; /* Size of apVal[] array */
  62351. FuncDef *pFunc = 0; /* Function definition */
  62352. sqlite3_value *pVal = 0; /* New value */
  62353. int rc = SQLITE_OK; /* Return code */
  62354. int nName; /* Size of function name in bytes */
  62355. ExprList *pList = 0; /* Function arguments */
  62356. int i; /* Iterator variable */
  62357. assert( pCtx!=0 );
  62358. assert( (p->flags & EP_TokenOnly)==0 );
  62359. pList = p->x.pList;
  62360. if( pList ) nVal = pList->nExpr;
  62361. nName = sqlite3Strlen30(p->u.zToken);
  62362. pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
  62363. assert( pFunc );
  62364. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  62365. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  62366. ){
  62367. return SQLITE_OK;
  62368. }
  62369. if( pList ){
  62370. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  62371. if( apVal==0 ){
  62372. rc = SQLITE_NOMEM;
  62373. goto value_from_function_out;
  62374. }
  62375. for(i=0; i<nVal; i++){
  62376. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  62377. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  62378. }
  62379. }
  62380. pVal = valueNew(db, pCtx);
  62381. if( pVal==0 ){
  62382. rc = SQLITE_NOMEM;
  62383. goto value_from_function_out;
  62384. }
  62385. assert( pCtx->pParse->rc==SQLITE_OK );
  62386. memset(&ctx, 0, sizeof(ctx));
  62387. ctx.pOut = pVal;
  62388. ctx.pFunc = pFunc;
  62389. pFunc->xFunc(&ctx, nVal, apVal);
  62390. if( ctx.isError ){
  62391. rc = ctx.isError;
  62392. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  62393. }else{
  62394. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  62395. assert( rc==SQLITE_OK );
  62396. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  62397. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  62398. rc = SQLITE_TOOBIG;
  62399. pCtx->pParse->nErr++;
  62400. }
  62401. }
  62402. pCtx->pParse->rc = rc;
  62403. value_from_function_out:
  62404. if( rc!=SQLITE_OK ){
  62405. pVal = 0;
  62406. }
  62407. if( apVal ){
  62408. for(i=0; i<nVal; i++){
  62409. sqlite3ValueFree(apVal[i]);
  62410. }
  62411. sqlite3DbFree(db, apVal);
  62412. }
  62413. *ppVal = pVal;
  62414. return rc;
  62415. }
  62416. #else
  62417. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  62418. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  62419. /*
  62420. ** Extract a value from the supplied expression in the manner described
  62421. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  62422. ** using valueNew().
  62423. **
  62424. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  62425. ** has been allocated, it is freed before returning. Or, if pCtx is not
  62426. ** NULL, it is assumed that the caller will free any allocated object
  62427. ** in all cases.
  62428. */
  62429. static int valueFromExpr(
  62430. sqlite3 *db, /* The database connection */
  62431. Expr *pExpr, /* The expression to evaluate */
  62432. u8 enc, /* Encoding to use */
  62433. u8 affinity, /* Affinity to use */
  62434. sqlite3_value **ppVal, /* Write the new value here */
  62435. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  62436. ){
  62437. int op;
  62438. char *zVal = 0;
  62439. sqlite3_value *pVal = 0;
  62440. int negInt = 1;
  62441. const char *zNeg = "";
  62442. int rc = SQLITE_OK;
  62443. if( !pExpr ){
  62444. *ppVal = 0;
  62445. return SQLITE_OK;
  62446. }
  62447. while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
  62448. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  62449. /* Compressed expressions only appear when parsing the DEFAULT clause
  62450. ** on a table column definition, and hence only when pCtx==0. This
  62451. ** check ensures that an EP_TokenOnly expression is never passed down
  62452. ** into valueFromFunction(). */
  62453. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  62454. if( op==TK_CAST ){
  62455. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  62456. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  62457. testcase( rc!=SQLITE_OK );
  62458. if( *ppVal ){
  62459. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  62460. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  62461. }
  62462. return rc;
  62463. }
  62464. /* Handle negative integers in a single step. This is needed in the
  62465. ** case when the value is -9223372036854775808.
  62466. */
  62467. if( op==TK_UMINUS
  62468. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  62469. pExpr = pExpr->pLeft;
  62470. op = pExpr->op;
  62471. negInt = -1;
  62472. zNeg = "-";
  62473. }
  62474. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  62475. pVal = valueNew(db, pCtx);
  62476. if( pVal==0 ) goto no_mem;
  62477. if( ExprHasProperty(pExpr, EP_IntValue) ){
  62478. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  62479. }else{
  62480. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  62481. if( zVal==0 ) goto no_mem;
  62482. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  62483. }
  62484. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  62485. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  62486. }else{
  62487. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  62488. }
  62489. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  62490. if( enc!=SQLITE_UTF8 ){
  62491. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  62492. }
  62493. }else if( op==TK_UMINUS ) {
  62494. /* This branch happens for multiple negative signs. Ex: -(-5) */
  62495. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  62496. && pVal!=0
  62497. ){
  62498. sqlite3VdbeMemNumerify(pVal);
  62499. if( pVal->flags & MEM_Real ){
  62500. pVal->u.r = -pVal->u.r;
  62501. }else if( pVal->u.i==SMALLEST_INT64 ){
  62502. pVal->u.r = -(double)SMALLEST_INT64;
  62503. MemSetTypeFlag(pVal, MEM_Real);
  62504. }else{
  62505. pVal->u.i = -pVal->u.i;
  62506. }
  62507. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  62508. }
  62509. }else if( op==TK_NULL ){
  62510. pVal = valueNew(db, pCtx);
  62511. if( pVal==0 ) goto no_mem;
  62512. }
  62513. #ifndef SQLITE_OMIT_BLOB_LITERAL
  62514. else if( op==TK_BLOB ){
  62515. int nVal;
  62516. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  62517. assert( pExpr->u.zToken[1]=='\'' );
  62518. pVal = valueNew(db, pCtx);
  62519. if( !pVal ) goto no_mem;
  62520. zVal = &pExpr->u.zToken[2];
  62521. nVal = sqlite3Strlen30(zVal)-1;
  62522. assert( zVal[nVal]=='\'' );
  62523. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  62524. 0, SQLITE_DYNAMIC);
  62525. }
  62526. #endif
  62527. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  62528. else if( op==TK_FUNCTION && pCtx!=0 ){
  62529. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  62530. }
  62531. #endif
  62532. *ppVal = pVal;
  62533. return rc;
  62534. no_mem:
  62535. db->mallocFailed = 1;
  62536. sqlite3DbFree(db, zVal);
  62537. assert( *ppVal==0 );
  62538. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  62539. if( pCtx==0 ) sqlite3ValueFree(pVal);
  62540. #else
  62541. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  62542. #endif
  62543. return SQLITE_NOMEM;
  62544. }
  62545. /*
  62546. ** Create a new sqlite3_value object, containing the value of pExpr.
  62547. **
  62548. ** This only works for very simple expressions that consist of one constant
  62549. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  62550. ** be converted directly into a value, then the value is allocated and
  62551. ** a pointer written to *ppVal. The caller is responsible for deallocating
  62552. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  62553. ** cannot be converted to a value, then *ppVal is set to NULL.
  62554. */
  62555. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  62556. sqlite3 *db, /* The database connection */
  62557. Expr *pExpr, /* The expression to evaluate */
  62558. u8 enc, /* Encoding to use */
  62559. u8 affinity, /* Affinity to use */
  62560. sqlite3_value **ppVal /* Write the new value here */
  62561. ){
  62562. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  62563. }
  62564. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  62565. /*
  62566. ** The implementation of the sqlite_record() function. This function accepts
  62567. ** a single argument of any type. The return value is a formatted database
  62568. ** record (a blob) containing the argument value.
  62569. **
  62570. ** This is used to convert the value stored in the 'sample' column of the
  62571. ** sqlite_stat3 table to the record format SQLite uses internally.
  62572. */
  62573. static void recordFunc(
  62574. sqlite3_context *context,
  62575. int argc,
  62576. sqlite3_value **argv
  62577. ){
  62578. const int file_format = 1;
  62579. u32 iSerial; /* Serial type */
  62580. int nSerial; /* Bytes of space for iSerial as varint */
  62581. u32 nVal; /* Bytes of space required for argv[0] */
  62582. int nRet;
  62583. sqlite3 *db;
  62584. u8 *aRet;
  62585. UNUSED_PARAMETER( argc );
  62586. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  62587. nSerial = sqlite3VarintLen(iSerial);
  62588. db = sqlite3_context_db_handle(context);
  62589. nRet = 1 + nSerial + nVal;
  62590. aRet = sqlite3DbMallocRaw(db, nRet);
  62591. if( aRet==0 ){
  62592. sqlite3_result_error_nomem(context);
  62593. }else{
  62594. aRet[0] = nSerial+1;
  62595. putVarint32(&aRet[1], iSerial);
  62596. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  62597. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  62598. sqlite3DbFree(db, aRet);
  62599. }
  62600. }
  62601. /*
  62602. ** Register built-in functions used to help read ANALYZE data.
  62603. */
  62604. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  62605. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  62606. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  62607. };
  62608. int i;
  62609. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  62610. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  62611. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  62612. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  62613. }
  62614. }
  62615. /*
  62616. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  62617. **
  62618. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  62619. ** pAlloc if one does not exist and the new value is added to the
  62620. ** UnpackedRecord object.
  62621. **
  62622. ** A value is extracted in the following cases:
  62623. **
  62624. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  62625. **
  62626. ** * The expression is a bound variable, and this is a reprepare, or
  62627. **
  62628. ** * The expression is a literal value.
  62629. **
  62630. ** On success, *ppVal is made to point to the extracted value. The caller
  62631. ** is responsible for ensuring that the value is eventually freed.
  62632. */
  62633. static int stat4ValueFromExpr(
  62634. Parse *pParse, /* Parse context */
  62635. Expr *pExpr, /* The expression to extract a value from */
  62636. u8 affinity, /* Affinity to use */
  62637. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  62638. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  62639. ){
  62640. int rc = SQLITE_OK;
  62641. sqlite3_value *pVal = 0;
  62642. sqlite3 *db = pParse->db;
  62643. /* Skip over any TK_COLLATE nodes */
  62644. pExpr = sqlite3ExprSkipCollate(pExpr);
  62645. if( !pExpr ){
  62646. pVal = valueNew(db, pAlloc);
  62647. if( pVal ){
  62648. sqlite3VdbeMemSetNull((Mem*)pVal);
  62649. }
  62650. }else if( pExpr->op==TK_VARIABLE
  62651. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  62652. ){
  62653. Vdbe *v;
  62654. int iBindVar = pExpr->iColumn;
  62655. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  62656. if( (v = pParse->pReprepare)!=0 ){
  62657. pVal = valueNew(db, pAlloc);
  62658. if( pVal ){
  62659. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  62660. if( rc==SQLITE_OK ){
  62661. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  62662. }
  62663. pVal->db = pParse->db;
  62664. }
  62665. }
  62666. }else{
  62667. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  62668. }
  62669. assert( pVal==0 || pVal->db==db );
  62670. *ppVal = pVal;
  62671. return rc;
  62672. }
  62673. /*
  62674. ** This function is used to allocate and populate UnpackedRecord
  62675. ** structures intended to be compared against sample index keys stored
  62676. ** in the sqlite_stat4 table.
  62677. **
  62678. ** A single call to this function attempts to populates field iVal (leftmost
  62679. ** is 0 etc.) of the unpacked record with a value extracted from expression
  62680. ** pExpr. Extraction of values is possible if:
  62681. **
  62682. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  62683. **
  62684. ** * The expression is a bound variable, and this is a reprepare, or
  62685. **
  62686. ** * The sqlite3ValueFromExpr() function is able to extract a value
  62687. ** from the expression (i.e. the expression is a literal value).
  62688. **
  62689. ** If a value can be extracted, the affinity passed as the 5th argument
  62690. ** is applied to it before it is copied into the UnpackedRecord. Output
  62691. ** parameter *pbOk is set to true if a value is extracted, or false
  62692. ** otherwise.
  62693. **
  62694. ** When this function is called, *ppRec must either point to an object
  62695. ** allocated by an earlier call to this function, or must be NULL. If it
  62696. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  62697. ** is allocated (and *ppRec set to point to it) before returning.
  62698. **
  62699. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  62700. ** error if a value cannot be extracted from pExpr. If an error does
  62701. ** occur, an SQLite error code is returned.
  62702. */
  62703. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  62704. Parse *pParse, /* Parse context */
  62705. Index *pIdx, /* Index being probed */
  62706. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  62707. Expr *pExpr, /* The expression to extract a value from */
  62708. u8 affinity, /* Affinity to use */
  62709. int iVal, /* Array element to populate */
  62710. int *pbOk /* OUT: True if value was extracted */
  62711. ){
  62712. int rc;
  62713. sqlite3_value *pVal = 0;
  62714. struct ValueNewStat4Ctx alloc;
  62715. alloc.pParse = pParse;
  62716. alloc.pIdx = pIdx;
  62717. alloc.ppRec = ppRec;
  62718. alloc.iVal = iVal;
  62719. rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
  62720. assert( pVal==0 || pVal->db==pParse->db );
  62721. *pbOk = (pVal!=0);
  62722. return rc;
  62723. }
  62724. /*
  62725. ** Attempt to extract a value from expression pExpr using the methods
  62726. ** as described for sqlite3Stat4ProbeSetValue() above.
  62727. **
  62728. ** If successful, set *ppVal to point to a new value object and return
  62729. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  62730. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  62731. ** does occur, return an SQLite error code. The final value of *ppVal
  62732. ** is undefined in this case.
  62733. */
  62734. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  62735. Parse *pParse, /* Parse context */
  62736. Expr *pExpr, /* The expression to extract a value from */
  62737. u8 affinity, /* Affinity to use */
  62738. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  62739. ){
  62740. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  62741. }
  62742. /*
  62743. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  62744. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  62745. ** sqlite3_value object is allocated.
  62746. **
  62747. ** If *ppVal is initially NULL then the caller is responsible for
  62748. ** ensuring that the value written into *ppVal is eventually freed.
  62749. */
  62750. SQLITE_PRIVATE int sqlite3Stat4Column(
  62751. sqlite3 *db, /* Database handle */
  62752. const void *pRec, /* Pointer to buffer containing record */
  62753. int nRec, /* Size of buffer pRec in bytes */
  62754. int iCol, /* Column to extract */
  62755. sqlite3_value **ppVal /* OUT: Extracted value */
  62756. ){
  62757. u32 t; /* a column type code */
  62758. int nHdr; /* Size of the header in the record */
  62759. int iHdr; /* Next unread header byte */
  62760. int iField; /* Next unread data byte */
  62761. int szField; /* Size of the current data field */
  62762. int i; /* Column index */
  62763. u8 *a = (u8*)pRec; /* Typecast byte array */
  62764. Mem *pMem = *ppVal; /* Write result into this Mem object */
  62765. assert( iCol>0 );
  62766. iHdr = getVarint32(a, nHdr);
  62767. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  62768. iField = nHdr;
  62769. for(i=0; i<=iCol; i++){
  62770. iHdr += getVarint32(&a[iHdr], t);
  62771. testcase( iHdr==nHdr );
  62772. testcase( iHdr==nHdr+1 );
  62773. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  62774. szField = sqlite3VdbeSerialTypeLen(t);
  62775. iField += szField;
  62776. }
  62777. testcase( iField==nRec );
  62778. testcase( iField==nRec+1 );
  62779. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  62780. if( pMem==0 ){
  62781. pMem = *ppVal = sqlite3ValueNew(db);
  62782. if( pMem==0 ) return SQLITE_NOMEM;
  62783. }
  62784. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  62785. pMem->enc = ENC(db);
  62786. return SQLITE_OK;
  62787. }
  62788. /*
  62789. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  62790. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  62791. ** the object.
  62792. */
  62793. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  62794. if( pRec ){
  62795. int i;
  62796. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  62797. Mem *aMem = pRec->aMem;
  62798. sqlite3 *db = aMem[0].db;
  62799. for(i=0; i<nCol; i++){
  62800. sqlite3VdbeMemRelease(&aMem[i]);
  62801. }
  62802. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  62803. sqlite3DbFree(db, pRec);
  62804. }
  62805. }
  62806. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  62807. /*
  62808. ** Change the string value of an sqlite3_value object
  62809. */
  62810. SQLITE_PRIVATE void sqlite3ValueSetStr(
  62811. sqlite3_value *v, /* Value to be set */
  62812. int n, /* Length of string z */
  62813. const void *z, /* Text of the new string */
  62814. u8 enc, /* Encoding to use */
  62815. void (*xDel)(void*) /* Destructor for the string */
  62816. ){
  62817. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  62818. }
  62819. /*
  62820. ** Free an sqlite3_value object
  62821. */
  62822. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  62823. if( !v ) return;
  62824. sqlite3VdbeMemRelease((Mem *)v);
  62825. sqlite3DbFree(((Mem*)v)->db, v);
  62826. }
  62827. /*
  62828. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  62829. ** sqlite3_value object assuming that it uses the encoding "enc".
  62830. ** The valueBytes() routine is a helper function.
  62831. */
  62832. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  62833. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  62834. }
  62835. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  62836. Mem *p = (Mem*)pVal;
  62837. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  62838. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  62839. return p->n;
  62840. }
  62841. if( (p->flags & MEM_Blob)!=0 ){
  62842. if( p->flags & MEM_Zero ){
  62843. return p->n + p->u.nZero;
  62844. }else{
  62845. return p->n;
  62846. }
  62847. }
  62848. if( p->flags & MEM_Null ) return 0;
  62849. return valueBytes(pVal, enc);
  62850. }
  62851. /************** End of vdbemem.c *********************************************/
  62852. /************** Begin file vdbeaux.c *****************************************/
  62853. /*
  62854. ** 2003 September 6
  62855. **
  62856. ** The author disclaims copyright to this source code. In place of
  62857. ** a legal notice, here is a blessing:
  62858. **
  62859. ** May you do good and not evil.
  62860. ** May you find forgiveness for yourself and forgive others.
  62861. ** May you share freely, never taking more than you give.
  62862. **
  62863. *************************************************************************
  62864. ** This file contains code used for creating, destroying, and populating
  62865. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  62866. */
  62867. /* #include "sqliteInt.h" */
  62868. /* #include "vdbeInt.h" */
  62869. /*
  62870. ** Create a new virtual database engine.
  62871. */
  62872. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  62873. sqlite3 *db = pParse->db;
  62874. Vdbe *p;
  62875. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  62876. if( p==0 ) return 0;
  62877. p->db = db;
  62878. if( db->pVdbe ){
  62879. db->pVdbe->pPrev = p;
  62880. }
  62881. p->pNext = db->pVdbe;
  62882. p->pPrev = 0;
  62883. db->pVdbe = p;
  62884. p->magic = VDBE_MAGIC_INIT;
  62885. p->pParse = pParse;
  62886. assert( pParse->aLabel==0 );
  62887. assert( pParse->nLabel==0 );
  62888. assert( pParse->nOpAlloc==0 );
  62889. assert( pParse->szOpAlloc==0 );
  62890. return p;
  62891. }
  62892. /*
  62893. ** Change the error string stored in Vdbe.zErrMsg
  62894. */
  62895. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  62896. va_list ap;
  62897. sqlite3DbFree(p->db, p->zErrMsg);
  62898. va_start(ap, zFormat);
  62899. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  62900. va_end(ap);
  62901. }
  62902. /*
  62903. ** Remember the SQL string for a prepared statement.
  62904. */
  62905. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  62906. assert( isPrepareV2==1 || isPrepareV2==0 );
  62907. if( p==0 ) return;
  62908. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  62909. if( !isPrepareV2 ) return;
  62910. #endif
  62911. assert( p->zSql==0 );
  62912. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  62913. p->isPrepareV2 = (u8)isPrepareV2;
  62914. }
  62915. /*
  62916. ** Return the SQL associated with a prepared statement
  62917. */
  62918. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
  62919. Vdbe *p = (Vdbe *)pStmt;
  62920. return p ? p->zSql : 0;
  62921. }
  62922. /*
  62923. ** Swap all content between two VDBE structures.
  62924. */
  62925. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  62926. Vdbe tmp, *pTmp;
  62927. char *zTmp;
  62928. tmp = *pA;
  62929. *pA = *pB;
  62930. *pB = tmp;
  62931. pTmp = pA->pNext;
  62932. pA->pNext = pB->pNext;
  62933. pB->pNext = pTmp;
  62934. pTmp = pA->pPrev;
  62935. pA->pPrev = pB->pPrev;
  62936. pB->pPrev = pTmp;
  62937. zTmp = pA->zSql;
  62938. pA->zSql = pB->zSql;
  62939. pB->zSql = zTmp;
  62940. pB->isPrepareV2 = pA->isPrepareV2;
  62941. }
  62942. /*
  62943. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  62944. ** than its current size. nOp is guaranteed to be less than or equal
  62945. ** to 1024/sizeof(Op).
  62946. **
  62947. ** If an out-of-memory error occurs while resizing the array, return
  62948. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  62949. ** unchanged (this is so that any opcodes already allocated can be
  62950. ** correctly deallocated along with the rest of the Vdbe).
  62951. */
  62952. static int growOpArray(Vdbe *v, int nOp){
  62953. VdbeOp *pNew;
  62954. Parse *p = v->pParse;
  62955. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  62956. ** more frequent reallocs and hence provide more opportunities for
  62957. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  62958. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  62959. ** by the minimum* amount required until the size reaches 512. Normal
  62960. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  62961. ** size of the op array or add 1KB of space, whichever is smaller. */
  62962. #ifdef SQLITE_TEST_REALLOC_STRESS
  62963. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  62964. #else
  62965. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  62966. UNUSED_PARAMETER(nOp);
  62967. #endif
  62968. assert( nOp<=(1024/sizeof(Op)) );
  62969. assert( nNew>=(p->nOpAlloc+nOp) );
  62970. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  62971. if( pNew ){
  62972. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  62973. p->nOpAlloc = p->szOpAlloc/sizeof(Op);
  62974. v->aOp = pNew;
  62975. }
  62976. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  62977. }
  62978. #ifdef SQLITE_DEBUG
  62979. /* This routine is just a convenient place to set a breakpoint that will
  62980. ** fire after each opcode is inserted and displayed using
  62981. ** "PRAGMA vdbe_addoptrace=on".
  62982. */
  62983. static void test_addop_breakpoint(void){
  62984. static int n = 0;
  62985. n++;
  62986. }
  62987. #endif
  62988. /*
  62989. ** Add a new instruction to the list of instructions current in the
  62990. ** VDBE. Return the address of the new instruction.
  62991. **
  62992. ** Parameters:
  62993. **
  62994. ** p Pointer to the VDBE
  62995. **
  62996. ** op The opcode for this instruction
  62997. **
  62998. ** p1, p2, p3 Operands
  62999. **
  63000. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  63001. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  63002. ** operand.
  63003. */
  63004. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  63005. assert( p->pParse->nOpAlloc<=p->nOp );
  63006. if( growOpArray(p, 1) ) return 1;
  63007. assert( p->pParse->nOpAlloc>p->nOp );
  63008. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  63009. }
  63010. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  63011. int i;
  63012. VdbeOp *pOp;
  63013. i = p->nOp;
  63014. assert( p->magic==VDBE_MAGIC_INIT );
  63015. assert( op>0 && op<0xff );
  63016. if( p->pParse->nOpAlloc<=i ){
  63017. return growOp3(p, op, p1, p2, p3);
  63018. }
  63019. p->nOp++;
  63020. pOp = &p->aOp[i];
  63021. pOp->opcode = (u8)op;
  63022. pOp->p5 = 0;
  63023. pOp->p1 = p1;
  63024. pOp->p2 = p2;
  63025. pOp->p3 = p3;
  63026. pOp->p4.p = 0;
  63027. pOp->p4type = P4_NOTUSED;
  63028. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63029. pOp->zComment = 0;
  63030. #endif
  63031. #ifdef SQLITE_DEBUG
  63032. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  63033. int jj, kk;
  63034. Parse *pParse = p->pParse;
  63035. for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
  63036. struct yColCache *x = pParse->aColCache + jj;
  63037. if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
  63038. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  63039. kk++;
  63040. }
  63041. if( kk ) printf("\n");
  63042. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  63043. test_addop_breakpoint();
  63044. }
  63045. #endif
  63046. #ifdef VDBE_PROFILE
  63047. pOp->cycles = 0;
  63048. pOp->cnt = 0;
  63049. #endif
  63050. #ifdef SQLITE_VDBE_COVERAGE
  63051. pOp->iSrcLine = 0;
  63052. #endif
  63053. return i;
  63054. }
  63055. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  63056. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  63057. }
  63058. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  63059. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  63060. }
  63061. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  63062. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  63063. }
  63064. /* Generate code for an unconditional jump to instruction iDest
  63065. */
  63066. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  63067. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  63068. }
  63069. /* Generate code to cause the string zStr to be loaded into
  63070. ** register iDest
  63071. */
  63072. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  63073. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  63074. }
  63075. /*
  63076. ** Generate code that initializes multiple registers to string or integer
  63077. ** constants. The registers begin with iDest and increase consecutively.
  63078. ** One register is initialized for each characgter in zTypes[]. For each
  63079. ** "s" character in zTypes[], the register is a string if the argument is
  63080. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  63081. ** in zTypes[], the register is initialized to an integer.
  63082. */
  63083. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  63084. va_list ap;
  63085. int i;
  63086. char c;
  63087. va_start(ap, zTypes);
  63088. for(i=0; (c = zTypes[i])!=0; i++){
  63089. if( c=='s' ){
  63090. const char *z = va_arg(ap, const char*);
  63091. int addr = sqlite3VdbeAddOp2(p, z==0 ? OP_Null : OP_String8, 0, iDest++);
  63092. if( z ) sqlite3VdbeChangeP4(p, addr, z, 0);
  63093. }else{
  63094. assert( c=='i' );
  63095. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
  63096. }
  63097. }
  63098. va_end(ap);
  63099. }
  63100. /*
  63101. ** Add an opcode that includes the p4 value as a pointer.
  63102. */
  63103. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  63104. Vdbe *p, /* Add the opcode to this VM */
  63105. int op, /* The new opcode */
  63106. int p1, /* The P1 operand */
  63107. int p2, /* The P2 operand */
  63108. int p3, /* The P3 operand */
  63109. const char *zP4, /* The P4 operand */
  63110. int p4type /* P4 operand type */
  63111. ){
  63112. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  63113. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  63114. return addr;
  63115. }
  63116. /*
  63117. ** Add an opcode that includes the p4 value with a P4_INT64 or
  63118. ** P4_REAL type.
  63119. */
  63120. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  63121. Vdbe *p, /* Add the opcode to this VM */
  63122. int op, /* The new opcode */
  63123. int p1, /* The P1 operand */
  63124. int p2, /* The P2 operand */
  63125. int p3, /* The P3 operand */
  63126. const u8 *zP4, /* The P4 operand */
  63127. int p4type /* P4 operand type */
  63128. ){
  63129. char *p4copy = sqlite3DbMallocRaw(sqlite3VdbeDb(p), 8);
  63130. if( p4copy ) memcpy(p4copy, zP4, 8);
  63131. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  63132. }
  63133. /*
  63134. ** Add an OP_ParseSchema opcode. This routine is broken out from
  63135. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  63136. ** as having been used.
  63137. **
  63138. ** The zWhere string must have been obtained from sqlite3_malloc().
  63139. ** This routine will take ownership of the allocated memory.
  63140. */
  63141. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  63142. int j;
  63143. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  63144. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  63145. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  63146. }
  63147. /*
  63148. ** Add an opcode that includes the p4 value as an integer.
  63149. */
  63150. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  63151. Vdbe *p, /* Add the opcode to this VM */
  63152. int op, /* The new opcode */
  63153. int p1, /* The P1 operand */
  63154. int p2, /* The P2 operand */
  63155. int p3, /* The P3 operand */
  63156. int p4 /* The P4 operand as an integer */
  63157. ){
  63158. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  63159. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  63160. return addr;
  63161. }
  63162. /*
  63163. ** Create a new symbolic label for an instruction that has yet to be
  63164. ** coded. The symbolic label is really just a negative number. The
  63165. ** label can be used as the P2 value of an operation. Later, when
  63166. ** the label is resolved to a specific address, the VDBE will scan
  63167. ** through its operation list and change all values of P2 which match
  63168. ** the label into the resolved address.
  63169. **
  63170. ** The VDBE knows that a P2 value is a label because labels are
  63171. ** always negative and P2 values are suppose to be non-negative.
  63172. ** Hence, a negative P2 value is a label that has yet to be resolved.
  63173. **
  63174. ** Zero is returned if a malloc() fails.
  63175. */
  63176. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  63177. Parse *p = v->pParse;
  63178. int i = p->nLabel++;
  63179. assert( v->magic==VDBE_MAGIC_INIT );
  63180. if( (i & (i-1))==0 ){
  63181. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  63182. (i*2+1)*sizeof(p->aLabel[0]));
  63183. }
  63184. if( p->aLabel ){
  63185. p->aLabel[i] = -1;
  63186. }
  63187. return ADDR(i);
  63188. }
  63189. /*
  63190. ** Resolve label "x" to be the address of the next instruction to
  63191. ** be inserted. The parameter "x" must have been obtained from
  63192. ** a prior call to sqlite3VdbeMakeLabel().
  63193. */
  63194. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  63195. Parse *p = v->pParse;
  63196. int j = ADDR(x);
  63197. assert( v->magic==VDBE_MAGIC_INIT );
  63198. assert( j<p->nLabel );
  63199. assert( j>=0 );
  63200. if( p->aLabel ){
  63201. p->aLabel[j] = v->nOp;
  63202. }
  63203. p->iFixedOp = v->nOp - 1;
  63204. }
  63205. /*
  63206. ** Mark the VDBE as one that can only be run one time.
  63207. */
  63208. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  63209. p->runOnlyOnce = 1;
  63210. }
  63211. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  63212. /*
  63213. ** The following type and function are used to iterate through all opcodes
  63214. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  63215. ** invoke directly or indirectly. It should be used as follows:
  63216. **
  63217. ** Op *pOp;
  63218. ** VdbeOpIter sIter;
  63219. **
  63220. ** memset(&sIter, 0, sizeof(sIter));
  63221. ** sIter.v = v; // v is of type Vdbe*
  63222. ** while( (pOp = opIterNext(&sIter)) ){
  63223. ** // Do something with pOp
  63224. ** }
  63225. ** sqlite3DbFree(v->db, sIter.apSub);
  63226. **
  63227. */
  63228. typedef struct VdbeOpIter VdbeOpIter;
  63229. struct VdbeOpIter {
  63230. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  63231. SubProgram **apSub; /* Array of subprograms */
  63232. int nSub; /* Number of entries in apSub */
  63233. int iAddr; /* Address of next instruction to return */
  63234. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  63235. };
  63236. static Op *opIterNext(VdbeOpIter *p){
  63237. Vdbe *v = p->v;
  63238. Op *pRet = 0;
  63239. Op *aOp;
  63240. int nOp;
  63241. if( p->iSub<=p->nSub ){
  63242. if( p->iSub==0 ){
  63243. aOp = v->aOp;
  63244. nOp = v->nOp;
  63245. }else{
  63246. aOp = p->apSub[p->iSub-1]->aOp;
  63247. nOp = p->apSub[p->iSub-1]->nOp;
  63248. }
  63249. assert( p->iAddr<nOp );
  63250. pRet = &aOp[p->iAddr];
  63251. p->iAddr++;
  63252. if( p->iAddr==nOp ){
  63253. p->iSub++;
  63254. p->iAddr = 0;
  63255. }
  63256. if( pRet->p4type==P4_SUBPROGRAM ){
  63257. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  63258. int j;
  63259. for(j=0; j<p->nSub; j++){
  63260. if( p->apSub[j]==pRet->p4.pProgram ) break;
  63261. }
  63262. if( j==p->nSub ){
  63263. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  63264. if( !p->apSub ){
  63265. pRet = 0;
  63266. }else{
  63267. p->apSub[p->nSub++] = pRet->p4.pProgram;
  63268. }
  63269. }
  63270. }
  63271. }
  63272. return pRet;
  63273. }
  63274. /*
  63275. ** Check if the program stored in the VM associated with pParse may
  63276. ** throw an ABORT exception (causing the statement, but not entire transaction
  63277. ** to be rolled back). This condition is true if the main program or any
  63278. ** sub-programs contains any of the following:
  63279. **
  63280. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  63281. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  63282. ** * OP_Destroy
  63283. ** * OP_VUpdate
  63284. ** * OP_VRename
  63285. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  63286. ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
  63287. **
  63288. ** Then check that the value of Parse.mayAbort is true if an
  63289. ** ABORT may be thrown, or false otherwise. Return true if it does
  63290. ** match, or false otherwise. This function is intended to be used as
  63291. ** part of an assert statement in the compiler. Similar to:
  63292. **
  63293. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  63294. */
  63295. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  63296. int hasAbort = 0;
  63297. int hasFkCounter = 0;
  63298. int hasCreateTable = 0;
  63299. int hasInitCoroutine = 0;
  63300. Op *pOp;
  63301. VdbeOpIter sIter;
  63302. memset(&sIter, 0, sizeof(sIter));
  63303. sIter.v = v;
  63304. while( (pOp = opIterNext(&sIter))!=0 ){
  63305. int opcode = pOp->opcode;
  63306. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  63307. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  63308. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  63309. ){
  63310. hasAbort = 1;
  63311. break;
  63312. }
  63313. if( opcode==OP_CreateTable ) hasCreateTable = 1;
  63314. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  63315. #ifndef SQLITE_OMIT_FOREIGN_KEY
  63316. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  63317. hasFkCounter = 1;
  63318. }
  63319. #endif
  63320. }
  63321. sqlite3DbFree(v->db, sIter.apSub);
  63322. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  63323. ** If malloc failed, then the while() loop above may not have iterated
  63324. ** through all opcodes and hasAbort may be set incorrectly. Return
  63325. ** true for this case to prevent the assert() in the callers frame
  63326. ** from failing. */
  63327. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  63328. || (hasCreateTable && hasInitCoroutine) );
  63329. }
  63330. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  63331. /*
  63332. ** This routine is called after all opcodes have been inserted. It loops
  63333. ** through all the opcodes and fixes up some details.
  63334. **
  63335. ** (1) For each jump instruction with a negative P2 value (a label)
  63336. ** resolve the P2 value to an actual address.
  63337. **
  63338. ** (2) Compute the maximum number of arguments used by any SQL function
  63339. ** and store that value in *pMaxFuncArgs.
  63340. **
  63341. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  63342. ** indicate what the prepared statement actually does.
  63343. **
  63344. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  63345. **
  63346. ** (5) Reclaim the memory allocated for storing labels.
  63347. */
  63348. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  63349. int i;
  63350. int nMaxArgs = *pMaxFuncArgs;
  63351. Op *pOp;
  63352. Parse *pParse = p->pParse;
  63353. int *aLabel = pParse->aLabel;
  63354. p->readOnly = 1;
  63355. p->bIsReader = 0;
  63356. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  63357. u8 opcode = pOp->opcode;
  63358. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  63359. ** cases from this switch! */
  63360. switch( opcode ){
  63361. case OP_Transaction: {
  63362. if( pOp->p2!=0 ) p->readOnly = 0;
  63363. /* fall thru */
  63364. }
  63365. case OP_AutoCommit:
  63366. case OP_Savepoint: {
  63367. p->bIsReader = 1;
  63368. break;
  63369. }
  63370. #ifndef SQLITE_OMIT_WAL
  63371. case OP_Checkpoint:
  63372. #endif
  63373. case OP_Vacuum:
  63374. case OP_JournalMode: {
  63375. p->readOnly = 0;
  63376. p->bIsReader = 1;
  63377. break;
  63378. }
  63379. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63380. case OP_VUpdate: {
  63381. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  63382. break;
  63383. }
  63384. case OP_VFilter: {
  63385. int n;
  63386. assert( p->nOp - i >= 3 );
  63387. assert( pOp[-1].opcode==OP_Integer );
  63388. n = pOp[-1].p1;
  63389. if( n>nMaxArgs ) nMaxArgs = n;
  63390. break;
  63391. }
  63392. #endif
  63393. case OP_Next:
  63394. case OP_NextIfOpen:
  63395. case OP_SorterNext: {
  63396. pOp->p4.xAdvance = sqlite3BtreeNext;
  63397. pOp->p4type = P4_ADVANCE;
  63398. break;
  63399. }
  63400. case OP_Prev:
  63401. case OP_PrevIfOpen: {
  63402. pOp->p4.xAdvance = sqlite3BtreePrevious;
  63403. pOp->p4type = P4_ADVANCE;
  63404. break;
  63405. }
  63406. }
  63407. pOp->opflags = sqlite3OpcodeProperty[opcode];
  63408. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  63409. assert( ADDR(pOp->p2)<pParse->nLabel );
  63410. pOp->p2 = aLabel[ADDR(pOp->p2)];
  63411. }
  63412. }
  63413. sqlite3DbFree(p->db, pParse->aLabel);
  63414. pParse->aLabel = 0;
  63415. pParse->nLabel = 0;
  63416. *pMaxFuncArgs = nMaxArgs;
  63417. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  63418. }
  63419. /*
  63420. ** Return the address of the next instruction to be inserted.
  63421. */
  63422. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  63423. assert( p->magic==VDBE_MAGIC_INIT );
  63424. return p->nOp;
  63425. }
  63426. /*
  63427. ** This function returns a pointer to the array of opcodes associated with
  63428. ** the Vdbe passed as the first argument. It is the callers responsibility
  63429. ** to arrange for the returned array to be eventually freed using the
  63430. ** vdbeFreeOpArray() function.
  63431. **
  63432. ** Before returning, *pnOp is set to the number of entries in the returned
  63433. ** array. Also, *pnMaxArg is set to the larger of its current value and
  63434. ** the number of entries in the Vdbe.apArg[] array required to execute the
  63435. ** returned program.
  63436. */
  63437. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  63438. VdbeOp *aOp = p->aOp;
  63439. assert( aOp && !p->db->mallocFailed );
  63440. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  63441. assert( DbMaskAllZero(p->btreeMask) );
  63442. resolveP2Values(p, pnMaxArg);
  63443. *pnOp = p->nOp;
  63444. p->aOp = 0;
  63445. return aOp;
  63446. }
  63447. /*
  63448. ** Add a whole list of operations to the operation stack. Return the
  63449. ** address of the first operation added.
  63450. */
  63451. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
  63452. int addr, i;
  63453. VdbeOp *pOut;
  63454. assert( nOp>0 );
  63455. assert( p->magic==VDBE_MAGIC_INIT );
  63456. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  63457. return 0;
  63458. }
  63459. addr = p->nOp;
  63460. pOut = &p->aOp[addr];
  63461. for(i=0; i<nOp; i++, aOp++, pOut++){
  63462. pOut->opcode = aOp->opcode;
  63463. pOut->p1 = aOp->p1;
  63464. pOut->p2 = aOp->p2;
  63465. assert( aOp->p2>=0 );
  63466. pOut->p3 = aOp->p3;
  63467. pOut->p4type = P4_NOTUSED;
  63468. pOut->p4.p = 0;
  63469. pOut->p5 = 0;
  63470. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63471. pOut->zComment = 0;
  63472. #endif
  63473. #ifdef SQLITE_VDBE_COVERAGE
  63474. pOut->iSrcLine = iLineno+i;
  63475. #else
  63476. (void)iLineno;
  63477. #endif
  63478. #ifdef SQLITE_DEBUG
  63479. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  63480. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  63481. }
  63482. #endif
  63483. }
  63484. p->nOp += nOp;
  63485. return addr;
  63486. }
  63487. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  63488. /*
  63489. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  63490. */
  63491. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  63492. Vdbe *p, /* VM to add scanstatus() to */
  63493. int addrExplain, /* Address of OP_Explain (or 0) */
  63494. int addrLoop, /* Address of loop counter */
  63495. int addrVisit, /* Address of rows visited counter */
  63496. LogEst nEst, /* Estimated number of output rows */
  63497. const char *zName /* Name of table or index being scanned */
  63498. ){
  63499. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  63500. ScanStatus *aNew;
  63501. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  63502. if( aNew ){
  63503. ScanStatus *pNew = &aNew[p->nScan++];
  63504. pNew->addrExplain = addrExplain;
  63505. pNew->addrLoop = addrLoop;
  63506. pNew->addrVisit = addrVisit;
  63507. pNew->nEst = nEst;
  63508. pNew->zName = sqlite3DbStrDup(p->db, zName);
  63509. p->aScan = aNew;
  63510. }
  63511. }
  63512. #endif
  63513. /*
  63514. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  63515. ** for a specific instruction.
  63516. */
  63517. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  63518. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  63519. }
  63520. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  63521. sqlite3VdbeGetOp(p,addr)->p1 = val;
  63522. }
  63523. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  63524. sqlite3VdbeGetOp(p,addr)->p2 = val;
  63525. }
  63526. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  63527. sqlite3VdbeGetOp(p,addr)->p3 = val;
  63528. }
  63529. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
  63530. sqlite3VdbeGetOp(p,-1)->p5 = p5;
  63531. }
  63532. /*
  63533. ** Change the P2 operand of instruction addr so that it points to
  63534. ** the address of the next instruction to be coded.
  63535. */
  63536. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  63537. p->pParse->iFixedOp = p->nOp - 1;
  63538. sqlite3VdbeChangeP2(p, addr, p->nOp);
  63539. }
  63540. /*
  63541. ** If the input FuncDef structure is ephemeral, then free it. If
  63542. ** the FuncDef is not ephermal, then do nothing.
  63543. */
  63544. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  63545. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  63546. sqlite3DbFree(db, pDef);
  63547. }
  63548. }
  63549. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  63550. /*
  63551. ** Delete a P4 value if necessary.
  63552. */
  63553. static void freeP4(sqlite3 *db, int p4type, void *p4){
  63554. if( p4 ){
  63555. assert( db );
  63556. switch( p4type ){
  63557. case P4_FUNCCTX: {
  63558. freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
  63559. /* Fall through into the next case */
  63560. }
  63561. case P4_REAL:
  63562. case P4_INT64:
  63563. case P4_DYNAMIC:
  63564. case P4_INTARRAY: {
  63565. sqlite3DbFree(db, p4);
  63566. break;
  63567. }
  63568. case P4_KEYINFO: {
  63569. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  63570. break;
  63571. }
  63572. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  63573. case P4_EXPR: {
  63574. sqlite3ExprDelete(db, (Expr*)p4);
  63575. break;
  63576. }
  63577. #endif
  63578. case P4_MPRINTF: {
  63579. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  63580. break;
  63581. }
  63582. case P4_FUNCDEF: {
  63583. freeEphemeralFunction(db, (FuncDef*)p4);
  63584. break;
  63585. }
  63586. case P4_MEM: {
  63587. if( db->pnBytesFreed==0 ){
  63588. sqlite3ValueFree((sqlite3_value*)p4);
  63589. }else{
  63590. Mem *p = (Mem*)p4;
  63591. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  63592. sqlite3DbFree(db, p);
  63593. }
  63594. break;
  63595. }
  63596. case P4_VTAB : {
  63597. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  63598. break;
  63599. }
  63600. }
  63601. }
  63602. }
  63603. /*
  63604. ** Free the space allocated for aOp and any p4 values allocated for the
  63605. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  63606. ** nOp entries.
  63607. */
  63608. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  63609. if( aOp ){
  63610. Op *pOp;
  63611. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  63612. freeP4(db, pOp->p4type, pOp->p4.p);
  63613. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63614. sqlite3DbFree(db, pOp->zComment);
  63615. #endif
  63616. }
  63617. }
  63618. sqlite3DbFree(db, aOp);
  63619. }
  63620. /*
  63621. ** Link the SubProgram object passed as the second argument into the linked
  63622. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  63623. ** objects when the VM is no longer required.
  63624. */
  63625. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  63626. p->pNext = pVdbe->pProgram;
  63627. pVdbe->pProgram = p;
  63628. }
  63629. /*
  63630. ** Change the opcode at addr into OP_Noop
  63631. */
  63632. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  63633. if( addr<p->nOp ){
  63634. VdbeOp *pOp = &p->aOp[addr];
  63635. sqlite3 *db = p->db;
  63636. freeP4(db, pOp->p4type, pOp->p4.p);
  63637. memset(pOp, 0, sizeof(pOp[0]));
  63638. pOp->opcode = OP_Noop;
  63639. }
  63640. }
  63641. /*
  63642. ** If the last opcode is "op" and it is not a jump destination,
  63643. ** then remove it. Return true if and only if an opcode was removed.
  63644. */
  63645. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  63646. if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
  63647. sqlite3VdbeChangeToNoop(p, p->nOp-1);
  63648. return 1;
  63649. }else{
  63650. return 0;
  63651. }
  63652. }
  63653. /*
  63654. ** Change the value of the P4 operand for a specific instruction.
  63655. ** This routine is useful when a large program is loaded from a
  63656. ** static array using sqlite3VdbeAddOpList but we want to make a
  63657. ** few minor changes to the program.
  63658. **
  63659. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  63660. ** the string is made into memory obtained from sqlite3_malloc().
  63661. ** A value of n==0 means copy bytes of zP4 up to and including the
  63662. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  63663. **
  63664. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  63665. ** to a string or structure that is guaranteed to exist for the lifetime of
  63666. ** the Vdbe. In these cases we can just copy the pointer.
  63667. **
  63668. ** If addr<0 then change P4 on the most recently inserted instruction.
  63669. */
  63670. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  63671. Op *pOp;
  63672. sqlite3 *db;
  63673. assert( p!=0 );
  63674. db = p->db;
  63675. assert( p->magic==VDBE_MAGIC_INIT );
  63676. if( p->aOp==0 || db->mallocFailed ){
  63677. if( n!=P4_VTAB ){
  63678. freeP4(db, n, (void*)*(char**)&zP4);
  63679. }
  63680. return;
  63681. }
  63682. assert( p->nOp>0 );
  63683. assert( addr<p->nOp );
  63684. if( addr<0 ){
  63685. addr = p->nOp - 1;
  63686. }
  63687. pOp = &p->aOp[addr];
  63688. assert( pOp->p4type==P4_NOTUSED
  63689. || pOp->p4type==P4_INT32
  63690. || pOp->p4type==P4_KEYINFO );
  63691. freeP4(db, pOp->p4type, pOp->p4.p);
  63692. pOp->p4.p = 0;
  63693. if( n==P4_INT32 ){
  63694. /* Note: this cast is safe, because the origin data point was an int
  63695. ** that was cast to a (const char *). */
  63696. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  63697. pOp->p4type = P4_INT32;
  63698. }else if( zP4==0 ){
  63699. pOp->p4.p = 0;
  63700. pOp->p4type = P4_NOTUSED;
  63701. }else if( n==P4_KEYINFO ){
  63702. pOp->p4.p = (void*)zP4;
  63703. pOp->p4type = P4_KEYINFO;
  63704. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  63705. }else if( n==P4_EXPR ){
  63706. /* Responsibility for deleting the Expr tree is handed over to the
  63707. ** VDBE by this operation. The caller should have already invoked
  63708. ** sqlite3ExprDup() or whatever other routine is needed to make a
  63709. ** private copy of the tree. */
  63710. pOp->p4.pExpr = (Expr*)zP4;
  63711. pOp->p4type = P4_EXPR;
  63712. #endif
  63713. }else if( n==P4_VTAB ){
  63714. pOp->p4.p = (void*)zP4;
  63715. pOp->p4type = P4_VTAB;
  63716. sqlite3VtabLock((VTable *)zP4);
  63717. assert( ((VTable *)zP4)->db==p->db );
  63718. }else if( n<0 ){
  63719. pOp->p4.p = (void*)zP4;
  63720. pOp->p4type = (signed char)n;
  63721. }else{
  63722. if( n==0 ) n = sqlite3Strlen30(zP4);
  63723. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  63724. pOp->p4type = P4_DYNAMIC;
  63725. }
  63726. }
  63727. /*
  63728. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  63729. ** index given.
  63730. */
  63731. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  63732. Vdbe *v = pParse->pVdbe;
  63733. assert( v!=0 );
  63734. assert( pIdx!=0 );
  63735. sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
  63736. P4_KEYINFO);
  63737. }
  63738. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  63739. /*
  63740. ** Change the comment on the most recently coded instruction. Or
  63741. ** insert a No-op and add the comment to that new instruction. This
  63742. ** makes the code easier to read during debugging. None of this happens
  63743. ** in a production build.
  63744. */
  63745. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  63746. assert( p->nOp>0 || p->aOp==0 );
  63747. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  63748. if( p->nOp ){
  63749. assert( p->aOp );
  63750. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  63751. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  63752. }
  63753. }
  63754. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  63755. va_list ap;
  63756. if( p ){
  63757. va_start(ap, zFormat);
  63758. vdbeVComment(p, zFormat, ap);
  63759. va_end(ap);
  63760. }
  63761. }
  63762. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  63763. va_list ap;
  63764. if( p ){
  63765. sqlite3VdbeAddOp0(p, OP_Noop);
  63766. va_start(ap, zFormat);
  63767. vdbeVComment(p, zFormat, ap);
  63768. va_end(ap);
  63769. }
  63770. }
  63771. #endif /* NDEBUG */
  63772. #ifdef SQLITE_VDBE_COVERAGE
  63773. /*
  63774. ** Set the value if the iSrcLine field for the previously coded instruction.
  63775. */
  63776. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  63777. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  63778. }
  63779. #endif /* SQLITE_VDBE_COVERAGE */
  63780. /*
  63781. ** Return the opcode for a given address. If the address is -1, then
  63782. ** return the most recently inserted opcode.
  63783. **
  63784. ** If a memory allocation error has occurred prior to the calling of this
  63785. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  63786. ** is readable but not writable, though it is cast to a writable value.
  63787. ** The return of a dummy opcode allows the call to continue functioning
  63788. ** after an OOM fault without having to check to see if the return from
  63789. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  63790. ** dummy will never be written to. This is verified by code inspection and
  63791. ** by running with Valgrind.
  63792. */
  63793. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  63794. /* C89 specifies that the constant "dummy" will be initialized to all
  63795. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  63796. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  63797. assert( p->magic==VDBE_MAGIC_INIT );
  63798. if( addr<0 ){
  63799. addr = p->nOp - 1;
  63800. }
  63801. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  63802. if( p->db->mallocFailed ){
  63803. return (VdbeOp*)&dummy;
  63804. }else{
  63805. return &p->aOp[addr];
  63806. }
  63807. }
  63808. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  63809. /*
  63810. ** Return an integer value for one of the parameters to the opcode pOp
  63811. ** determined by character c.
  63812. */
  63813. static int translateP(char c, const Op *pOp){
  63814. if( c=='1' ) return pOp->p1;
  63815. if( c=='2' ) return pOp->p2;
  63816. if( c=='3' ) return pOp->p3;
  63817. if( c=='4' ) return pOp->p4.i;
  63818. return pOp->p5;
  63819. }
  63820. /*
  63821. ** Compute a string for the "comment" field of a VDBE opcode listing.
  63822. **
  63823. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  63824. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  63825. ** absence of other comments, this synopsis becomes the comment on the opcode.
  63826. ** Some translation occurs:
  63827. **
  63828. ** "PX" -> "r[X]"
  63829. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  63830. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  63831. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  63832. */
  63833. static int displayComment(
  63834. const Op *pOp, /* The opcode to be commented */
  63835. const char *zP4, /* Previously obtained value for P4 */
  63836. char *zTemp, /* Write result here */
  63837. int nTemp /* Space available in zTemp[] */
  63838. ){
  63839. const char *zOpName;
  63840. const char *zSynopsis;
  63841. int nOpName;
  63842. int ii, jj;
  63843. zOpName = sqlite3OpcodeName(pOp->opcode);
  63844. nOpName = sqlite3Strlen30(zOpName);
  63845. if( zOpName[nOpName+1] ){
  63846. int seenCom = 0;
  63847. char c;
  63848. zSynopsis = zOpName += nOpName + 1;
  63849. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  63850. if( c=='P' ){
  63851. c = zSynopsis[++ii];
  63852. if( c=='4' ){
  63853. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  63854. }else if( c=='X' ){
  63855. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  63856. seenCom = 1;
  63857. }else{
  63858. int v1 = translateP(c, pOp);
  63859. int v2;
  63860. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  63861. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  63862. ii += 3;
  63863. jj += sqlite3Strlen30(zTemp+jj);
  63864. v2 = translateP(zSynopsis[ii], pOp);
  63865. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  63866. ii += 2;
  63867. v2++;
  63868. }
  63869. if( v2>1 ){
  63870. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  63871. }
  63872. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  63873. ii += 4;
  63874. }
  63875. }
  63876. jj += sqlite3Strlen30(zTemp+jj);
  63877. }else{
  63878. zTemp[jj++] = c;
  63879. }
  63880. }
  63881. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  63882. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  63883. jj += sqlite3Strlen30(zTemp+jj);
  63884. }
  63885. if( jj<nTemp ) zTemp[jj] = 0;
  63886. }else if( pOp->zComment ){
  63887. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  63888. jj = sqlite3Strlen30(zTemp);
  63889. }else{
  63890. zTemp[0] = 0;
  63891. jj = 0;
  63892. }
  63893. return jj;
  63894. }
  63895. #endif /* SQLITE_DEBUG */
  63896. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  63897. /*
  63898. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  63899. ** that can be displayed in the P4 column of EXPLAIN output.
  63900. */
  63901. static int displayP4Expr(int nTemp, char *zTemp, Expr *pExpr){
  63902. const char *zOp = 0;
  63903. int n;
  63904. switch( pExpr->op ){
  63905. case TK_STRING:
  63906. sqlite3_snprintf(nTemp, zTemp, "%Q", pExpr->u.zToken);
  63907. break;
  63908. case TK_INTEGER:
  63909. sqlite3_snprintf(nTemp, zTemp, "%d", pExpr->u.iValue);
  63910. break;
  63911. case TK_NULL:
  63912. sqlite3_snprintf(nTemp, zTemp, "NULL");
  63913. break;
  63914. case TK_REGISTER: {
  63915. sqlite3_snprintf(nTemp, zTemp, "r[%d]", pExpr->iTable);
  63916. break;
  63917. }
  63918. case TK_COLUMN: {
  63919. if( pExpr->iColumn<0 ){
  63920. sqlite3_snprintf(nTemp, zTemp, "rowid");
  63921. }else{
  63922. sqlite3_snprintf(nTemp, zTemp, "c%d", (int)pExpr->iColumn);
  63923. }
  63924. break;
  63925. }
  63926. case TK_LT: zOp = "LT"; break;
  63927. case TK_LE: zOp = "LE"; break;
  63928. case TK_GT: zOp = "GT"; break;
  63929. case TK_GE: zOp = "GE"; break;
  63930. case TK_NE: zOp = "NE"; break;
  63931. case TK_EQ: zOp = "EQ"; break;
  63932. case TK_IS: zOp = "IS"; break;
  63933. case TK_ISNOT: zOp = "ISNOT"; break;
  63934. case TK_AND: zOp = "AND"; break;
  63935. case TK_OR: zOp = "OR"; break;
  63936. case TK_PLUS: zOp = "ADD"; break;
  63937. case TK_STAR: zOp = "MUL"; break;
  63938. case TK_MINUS: zOp = "SUB"; break;
  63939. case TK_REM: zOp = "REM"; break;
  63940. case TK_BITAND: zOp = "BITAND"; break;
  63941. case TK_BITOR: zOp = "BITOR"; break;
  63942. case TK_SLASH: zOp = "DIV"; break;
  63943. case TK_LSHIFT: zOp = "LSHIFT"; break;
  63944. case TK_RSHIFT: zOp = "RSHIFT"; break;
  63945. case TK_CONCAT: zOp = "CONCAT"; break;
  63946. case TK_UMINUS: zOp = "MINUS"; break;
  63947. case TK_UPLUS: zOp = "PLUS"; break;
  63948. case TK_BITNOT: zOp = "BITNOT"; break;
  63949. case TK_NOT: zOp = "NOT"; break;
  63950. case TK_ISNULL: zOp = "ISNULL"; break;
  63951. case TK_NOTNULL: zOp = "NOTNULL"; break;
  63952. default:
  63953. sqlite3_snprintf(nTemp, zTemp, "%s", "expr");
  63954. break;
  63955. }
  63956. if( zOp ){
  63957. sqlite3_snprintf(nTemp, zTemp, "%s(", zOp);
  63958. n = sqlite3Strlen30(zTemp);
  63959. n += displayP4Expr(nTemp-n, zTemp+n, pExpr->pLeft);
  63960. if( n<nTemp-1 && pExpr->pRight ){
  63961. zTemp[n++] = ',';
  63962. n += displayP4Expr(nTemp-n, zTemp+n, pExpr->pRight);
  63963. }
  63964. sqlite3_snprintf(nTemp-n, zTemp+n, ")");
  63965. }
  63966. return sqlite3Strlen30(zTemp);
  63967. }
  63968. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  63969. #if VDBE_DISPLAY_P4
  63970. /*
  63971. ** Compute a string that describes the P4 parameter for an opcode.
  63972. ** Use zTemp for any required temporary buffer space.
  63973. */
  63974. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  63975. char *zP4 = zTemp;
  63976. assert( nTemp>=20 );
  63977. switch( pOp->p4type ){
  63978. case P4_KEYINFO: {
  63979. int i, j;
  63980. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  63981. assert( pKeyInfo->aSortOrder!=0 );
  63982. sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
  63983. i = sqlite3Strlen30(zTemp);
  63984. for(j=0; j<pKeyInfo->nField; j++){
  63985. CollSeq *pColl = pKeyInfo->aColl[j];
  63986. const char *zColl = pColl ? pColl->zName : "nil";
  63987. int n = sqlite3Strlen30(zColl);
  63988. if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
  63989. zColl = "B";
  63990. n = 1;
  63991. }
  63992. if( i+n>nTemp-7 ){
  63993. memcpy(&zTemp[i],",...",4);
  63994. i += 4;
  63995. break;
  63996. }
  63997. zTemp[i++] = ',';
  63998. if( pKeyInfo->aSortOrder[j] ){
  63999. zTemp[i++] = '-';
  64000. }
  64001. memcpy(&zTemp[i], zColl, n+1);
  64002. i += n;
  64003. }
  64004. zTemp[i++] = ')';
  64005. zTemp[i] = 0;
  64006. assert( i<nTemp );
  64007. break;
  64008. }
  64009. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  64010. case P4_EXPR: {
  64011. displayP4Expr(nTemp, zTemp, pOp->p4.pExpr);
  64012. break;
  64013. }
  64014. #endif
  64015. case P4_COLLSEQ: {
  64016. CollSeq *pColl = pOp->p4.pColl;
  64017. sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
  64018. break;
  64019. }
  64020. case P4_FUNCDEF: {
  64021. FuncDef *pDef = pOp->p4.pFunc;
  64022. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  64023. break;
  64024. }
  64025. #ifdef SQLITE_DEBUG
  64026. case P4_FUNCCTX: {
  64027. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  64028. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  64029. break;
  64030. }
  64031. #endif
  64032. case P4_INT64: {
  64033. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  64034. break;
  64035. }
  64036. case P4_INT32: {
  64037. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  64038. break;
  64039. }
  64040. case P4_REAL: {
  64041. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  64042. break;
  64043. }
  64044. case P4_MEM: {
  64045. Mem *pMem = pOp->p4.pMem;
  64046. if( pMem->flags & MEM_Str ){
  64047. zP4 = pMem->z;
  64048. }else if( pMem->flags & MEM_Int ){
  64049. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  64050. }else if( pMem->flags & MEM_Real ){
  64051. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
  64052. }else if( pMem->flags & MEM_Null ){
  64053. sqlite3_snprintf(nTemp, zTemp, "NULL");
  64054. }else{
  64055. assert( pMem->flags & MEM_Blob );
  64056. zP4 = "(blob)";
  64057. }
  64058. break;
  64059. }
  64060. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64061. case P4_VTAB: {
  64062. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  64063. sqlite3_snprintf(nTemp, zTemp, "vtab:%p", pVtab);
  64064. break;
  64065. }
  64066. #endif
  64067. case P4_INTARRAY: {
  64068. sqlite3_snprintf(nTemp, zTemp, "intarray");
  64069. break;
  64070. }
  64071. case P4_SUBPROGRAM: {
  64072. sqlite3_snprintf(nTemp, zTemp, "program");
  64073. break;
  64074. }
  64075. case P4_ADVANCE: {
  64076. zTemp[0] = 0;
  64077. break;
  64078. }
  64079. default: {
  64080. zP4 = pOp->p4.z;
  64081. if( zP4==0 ){
  64082. zP4 = zTemp;
  64083. zTemp[0] = 0;
  64084. }
  64085. }
  64086. }
  64087. assert( zP4!=0 );
  64088. return zP4;
  64089. }
  64090. #endif /* VDBE_DISPLAY_P4 */
  64091. /*
  64092. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  64093. **
  64094. ** The prepared statements need to know in advance the complete set of
  64095. ** attached databases that will be use. A mask of these databases
  64096. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  64097. ** p->btreeMask of databases that will require a lock.
  64098. */
  64099. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  64100. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  64101. assert( i<(int)sizeof(p->btreeMask)*8 );
  64102. DbMaskSet(p->btreeMask, i);
  64103. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  64104. DbMaskSet(p->lockMask, i);
  64105. }
  64106. }
  64107. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  64108. /*
  64109. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  64110. ** this routine obtains the mutex associated with each BtShared structure
  64111. ** that may be accessed by the VM passed as an argument. In doing so it also
  64112. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  64113. ** that the correct busy-handler callback is invoked if required.
  64114. **
  64115. ** If SQLite is not threadsafe but does support shared-cache mode, then
  64116. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  64117. ** of all of BtShared structures accessible via the database handle
  64118. ** associated with the VM.
  64119. **
  64120. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  64121. ** function is a no-op.
  64122. **
  64123. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  64124. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  64125. ** corresponding to btrees that use shared cache. Then the runtime of
  64126. ** this routine is N*N. But as N is rarely more than 1, this should not
  64127. ** be a problem.
  64128. */
  64129. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  64130. int i;
  64131. sqlite3 *db;
  64132. Db *aDb;
  64133. int nDb;
  64134. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  64135. db = p->db;
  64136. aDb = db->aDb;
  64137. nDb = db->nDb;
  64138. for(i=0; i<nDb; i++){
  64139. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  64140. sqlite3BtreeEnter(aDb[i].pBt);
  64141. }
  64142. }
  64143. }
  64144. #endif
  64145. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  64146. /*
  64147. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  64148. */
  64149. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  64150. int i;
  64151. sqlite3 *db;
  64152. Db *aDb;
  64153. int nDb;
  64154. db = p->db;
  64155. aDb = db->aDb;
  64156. nDb = db->nDb;
  64157. for(i=0; i<nDb; i++){
  64158. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  64159. sqlite3BtreeLeave(aDb[i].pBt);
  64160. }
  64161. }
  64162. }
  64163. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  64164. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  64165. vdbeLeave(p);
  64166. }
  64167. #endif
  64168. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  64169. /*
  64170. ** Print a single opcode. This routine is used for debugging only.
  64171. */
  64172. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  64173. char *zP4;
  64174. char zPtr[50];
  64175. char zCom[100];
  64176. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  64177. if( pOut==0 ) pOut = stdout;
  64178. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  64179. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  64180. displayComment(pOp, zP4, zCom, sizeof(zCom));
  64181. #else
  64182. zCom[0] = 0;
  64183. #endif
  64184. /* NB: The sqlite3OpcodeName() function is implemented by code created
  64185. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  64186. ** information from the vdbe.c source text */
  64187. fprintf(pOut, zFormat1, pc,
  64188. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  64189. zCom
  64190. );
  64191. fflush(pOut);
  64192. }
  64193. #endif
  64194. /*
  64195. ** Release an array of N Mem elements
  64196. */
  64197. static void releaseMemArray(Mem *p, int N){
  64198. if( p && N ){
  64199. Mem *pEnd = &p[N];
  64200. sqlite3 *db = p->db;
  64201. u8 malloc_failed = db->mallocFailed;
  64202. if( db->pnBytesFreed ){
  64203. do{
  64204. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  64205. }while( (++p)<pEnd );
  64206. return;
  64207. }
  64208. do{
  64209. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  64210. assert( sqlite3VdbeCheckMemInvariants(p) );
  64211. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  64212. ** that takes advantage of the fact that the memory cell value is
  64213. ** being set to NULL after releasing any dynamic resources.
  64214. **
  64215. ** The justification for duplicating code is that according to
  64216. ** callgrind, this causes a certain test case to hit the CPU 4.7
  64217. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  64218. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  64219. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  64220. ** with no indexes using a single prepared INSERT statement, bind()
  64221. ** and reset(). Inserts are grouped into a transaction.
  64222. */
  64223. testcase( p->flags & MEM_Agg );
  64224. testcase( p->flags & MEM_Dyn );
  64225. testcase( p->flags & MEM_Frame );
  64226. testcase( p->flags & MEM_RowSet );
  64227. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  64228. sqlite3VdbeMemRelease(p);
  64229. }else if( p->szMalloc ){
  64230. sqlite3DbFree(db, p->zMalloc);
  64231. p->szMalloc = 0;
  64232. }
  64233. p->flags = MEM_Undefined;
  64234. }while( (++p)<pEnd );
  64235. db->mallocFailed = malloc_failed;
  64236. }
  64237. }
  64238. /*
  64239. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  64240. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  64241. */
  64242. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  64243. int i;
  64244. Mem *aMem = VdbeFrameMem(p);
  64245. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  64246. for(i=0; i<p->nChildCsr; i++){
  64247. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  64248. }
  64249. releaseMemArray(aMem, p->nChildMem);
  64250. sqlite3DbFree(p->v->db, p);
  64251. }
  64252. #ifndef SQLITE_OMIT_EXPLAIN
  64253. /*
  64254. ** Give a listing of the program in the virtual machine.
  64255. **
  64256. ** The interface is the same as sqlite3VdbeExec(). But instead of
  64257. ** running the code, it invokes the callback once for each instruction.
  64258. ** This feature is used to implement "EXPLAIN".
  64259. **
  64260. ** When p->explain==1, each instruction is listed. When
  64261. ** p->explain==2, only OP_Explain instructions are listed and these
  64262. ** are shown in a different format. p->explain==2 is used to implement
  64263. ** EXPLAIN QUERY PLAN.
  64264. **
  64265. ** When p->explain==1, first the main program is listed, then each of
  64266. ** the trigger subprograms are listed one by one.
  64267. */
  64268. SQLITE_PRIVATE int sqlite3VdbeList(
  64269. Vdbe *p /* The VDBE */
  64270. ){
  64271. int nRow; /* Stop when row count reaches this */
  64272. int nSub = 0; /* Number of sub-vdbes seen so far */
  64273. SubProgram **apSub = 0; /* Array of sub-vdbes */
  64274. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  64275. sqlite3 *db = p->db; /* The database connection */
  64276. int i; /* Loop counter */
  64277. int rc = SQLITE_OK; /* Return code */
  64278. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  64279. assert( p->explain );
  64280. assert( p->magic==VDBE_MAGIC_RUN );
  64281. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  64282. /* Even though this opcode does not use dynamic strings for
  64283. ** the result, result columns may become dynamic if the user calls
  64284. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  64285. */
  64286. releaseMemArray(pMem, 8);
  64287. p->pResultSet = 0;
  64288. if( p->rc==SQLITE_NOMEM ){
  64289. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  64290. ** sqlite3_column_text16() failed. */
  64291. db->mallocFailed = 1;
  64292. return SQLITE_ERROR;
  64293. }
  64294. /* When the number of output rows reaches nRow, that means the
  64295. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  64296. ** nRow is the sum of the number of rows in the main program, plus
  64297. ** the sum of the number of rows in all trigger subprograms encountered
  64298. ** so far. The nRow value will increase as new trigger subprograms are
  64299. ** encountered, but p->pc will eventually catch up to nRow.
  64300. */
  64301. nRow = p->nOp;
  64302. if( p->explain==1 ){
  64303. /* The first 8 memory cells are used for the result set. So we will
  64304. ** commandeer the 9th cell to use as storage for an array of pointers
  64305. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  64306. ** cells. */
  64307. assert( p->nMem>9 );
  64308. pSub = &p->aMem[9];
  64309. if( pSub->flags&MEM_Blob ){
  64310. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  64311. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  64312. nSub = pSub->n/sizeof(Vdbe*);
  64313. apSub = (SubProgram **)pSub->z;
  64314. }
  64315. for(i=0; i<nSub; i++){
  64316. nRow += apSub[i]->nOp;
  64317. }
  64318. }
  64319. do{
  64320. i = p->pc++;
  64321. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  64322. if( i>=nRow ){
  64323. p->rc = SQLITE_OK;
  64324. rc = SQLITE_DONE;
  64325. }else if( db->u1.isInterrupted ){
  64326. p->rc = SQLITE_INTERRUPT;
  64327. rc = SQLITE_ERROR;
  64328. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  64329. }else{
  64330. char *zP4;
  64331. Op *pOp;
  64332. if( i<p->nOp ){
  64333. /* The output line number is small enough that we are still in the
  64334. ** main program. */
  64335. pOp = &p->aOp[i];
  64336. }else{
  64337. /* We are currently listing subprograms. Figure out which one and
  64338. ** pick up the appropriate opcode. */
  64339. int j;
  64340. i -= p->nOp;
  64341. for(j=0; i>=apSub[j]->nOp; j++){
  64342. i -= apSub[j]->nOp;
  64343. }
  64344. pOp = &apSub[j]->aOp[i];
  64345. }
  64346. if( p->explain==1 ){
  64347. pMem->flags = MEM_Int;
  64348. pMem->u.i = i; /* Program counter */
  64349. pMem++;
  64350. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  64351. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  64352. assert( pMem->z!=0 );
  64353. pMem->n = sqlite3Strlen30(pMem->z);
  64354. pMem->enc = SQLITE_UTF8;
  64355. pMem++;
  64356. /* When an OP_Program opcode is encounter (the only opcode that has
  64357. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  64358. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  64359. ** has not already been seen.
  64360. */
  64361. if( pOp->p4type==P4_SUBPROGRAM ){
  64362. int nByte = (nSub+1)*sizeof(SubProgram*);
  64363. int j;
  64364. for(j=0; j<nSub; j++){
  64365. if( apSub[j]==pOp->p4.pProgram ) break;
  64366. }
  64367. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  64368. apSub = (SubProgram **)pSub->z;
  64369. apSub[nSub++] = pOp->p4.pProgram;
  64370. pSub->flags |= MEM_Blob;
  64371. pSub->n = nSub*sizeof(SubProgram*);
  64372. }
  64373. }
  64374. }
  64375. pMem->flags = MEM_Int;
  64376. pMem->u.i = pOp->p1; /* P1 */
  64377. pMem++;
  64378. pMem->flags = MEM_Int;
  64379. pMem->u.i = pOp->p2; /* P2 */
  64380. pMem++;
  64381. pMem->flags = MEM_Int;
  64382. pMem->u.i = pOp->p3; /* P3 */
  64383. pMem++;
  64384. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  64385. assert( p->db->mallocFailed );
  64386. return SQLITE_ERROR;
  64387. }
  64388. pMem->flags = MEM_Str|MEM_Term;
  64389. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  64390. if( zP4!=pMem->z ){
  64391. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  64392. }else{
  64393. assert( pMem->z!=0 );
  64394. pMem->n = sqlite3Strlen30(pMem->z);
  64395. pMem->enc = SQLITE_UTF8;
  64396. }
  64397. pMem++;
  64398. if( p->explain==1 ){
  64399. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  64400. assert( p->db->mallocFailed );
  64401. return SQLITE_ERROR;
  64402. }
  64403. pMem->flags = MEM_Str|MEM_Term;
  64404. pMem->n = 2;
  64405. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  64406. pMem->enc = SQLITE_UTF8;
  64407. pMem++;
  64408. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  64409. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  64410. assert( p->db->mallocFailed );
  64411. return SQLITE_ERROR;
  64412. }
  64413. pMem->flags = MEM_Str|MEM_Term;
  64414. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  64415. pMem->enc = SQLITE_UTF8;
  64416. #else
  64417. pMem->flags = MEM_Null; /* Comment */
  64418. #endif
  64419. }
  64420. p->nResColumn = 8 - 4*(p->explain-1);
  64421. p->pResultSet = &p->aMem[1];
  64422. p->rc = SQLITE_OK;
  64423. rc = SQLITE_ROW;
  64424. }
  64425. return rc;
  64426. }
  64427. #endif /* SQLITE_OMIT_EXPLAIN */
  64428. #ifdef SQLITE_DEBUG
  64429. /*
  64430. ** Print the SQL that was used to generate a VDBE program.
  64431. */
  64432. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  64433. const char *z = 0;
  64434. if( p->zSql ){
  64435. z = p->zSql;
  64436. }else if( p->nOp>=1 ){
  64437. const VdbeOp *pOp = &p->aOp[0];
  64438. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  64439. z = pOp->p4.z;
  64440. while( sqlite3Isspace(*z) ) z++;
  64441. }
  64442. }
  64443. if( z ) printf("SQL: [%s]\n", z);
  64444. }
  64445. #endif
  64446. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  64447. /*
  64448. ** Print an IOTRACE message showing SQL content.
  64449. */
  64450. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  64451. int nOp = p->nOp;
  64452. VdbeOp *pOp;
  64453. if( sqlite3IoTrace==0 ) return;
  64454. if( nOp<1 ) return;
  64455. pOp = &p->aOp[0];
  64456. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  64457. int i, j;
  64458. char z[1000];
  64459. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  64460. for(i=0; sqlite3Isspace(z[i]); i++){}
  64461. for(j=0; z[i]; i++){
  64462. if( sqlite3Isspace(z[i]) ){
  64463. if( z[i-1]!=' ' ){
  64464. z[j++] = ' ';
  64465. }
  64466. }else{
  64467. z[j++] = z[i];
  64468. }
  64469. }
  64470. z[j] = 0;
  64471. sqlite3IoTrace("SQL %s\n", z);
  64472. }
  64473. }
  64474. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  64475. /*
  64476. ** Allocate space from a fixed size buffer and return a pointer to
  64477. ** that space. If insufficient space is available, return NULL.
  64478. **
  64479. ** The pBuf parameter is the initial value of a pointer which will
  64480. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  64481. ** NULL, it means that memory space has already been allocated and that
  64482. ** this routine should not allocate any new memory. When pBuf is not
  64483. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  64484. ** is NULL.
  64485. **
  64486. ** nByte is the number of bytes of space needed.
  64487. **
  64488. ** pFrom points to *pnFrom bytes of available space. New space is allocated
  64489. ** from the end of the pFrom buffer and *pnFrom is decremented.
  64490. **
  64491. ** *pnNeeded is a counter of the number of bytes of space that have failed
  64492. ** to allocate. If there is insufficient space in pFrom to satisfy the
  64493. ** request, then increment *pnNeeded by the amount of the request.
  64494. */
  64495. static void *allocSpace(
  64496. void *pBuf, /* Where return pointer will be stored */
  64497. int nByte, /* Number of bytes to allocate */
  64498. u8 *pFrom, /* Memory available for allocation */
  64499. int *pnFrom, /* IN/OUT: Space available at pFrom */
  64500. int *pnNeeded /* If allocation cannot be made, increment *pnByte */
  64501. ){
  64502. assert( EIGHT_BYTE_ALIGNMENT(pFrom) );
  64503. if( pBuf==0 ){
  64504. nByte = ROUND8(nByte);
  64505. if( nByte <= *pnFrom ){
  64506. *pnFrom -= nByte;
  64507. pBuf = &pFrom[*pnFrom];
  64508. }else{
  64509. *pnNeeded += nByte;
  64510. }
  64511. }
  64512. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  64513. return pBuf;
  64514. }
  64515. /*
  64516. ** Rewind the VDBE back to the beginning in preparation for
  64517. ** running it.
  64518. */
  64519. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  64520. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  64521. int i;
  64522. #endif
  64523. assert( p!=0 );
  64524. assert( p->magic==VDBE_MAGIC_INIT );
  64525. /* There should be at least one opcode.
  64526. */
  64527. assert( p->nOp>0 );
  64528. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  64529. p->magic = VDBE_MAGIC_RUN;
  64530. #ifdef SQLITE_DEBUG
  64531. for(i=1; i<p->nMem; i++){
  64532. assert( p->aMem[i].db==p->db );
  64533. }
  64534. #endif
  64535. p->pc = -1;
  64536. p->rc = SQLITE_OK;
  64537. p->errorAction = OE_Abort;
  64538. p->magic = VDBE_MAGIC_RUN;
  64539. p->nChange = 0;
  64540. p->cacheCtr = 1;
  64541. p->minWriteFileFormat = 255;
  64542. p->iStatement = 0;
  64543. p->nFkConstraint = 0;
  64544. #ifdef VDBE_PROFILE
  64545. for(i=0; i<p->nOp; i++){
  64546. p->aOp[i].cnt = 0;
  64547. p->aOp[i].cycles = 0;
  64548. }
  64549. #endif
  64550. }
  64551. /*
  64552. ** Prepare a virtual machine for execution for the first time after
  64553. ** creating the virtual machine. This involves things such
  64554. ** as allocating registers and initializing the program counter.
  64555. ** After the VDBE has be prepped, it can be executed by one or more
  64556. ** calls to sqlite3VdbeExec().
  64557. **
  64558. ** This function may be called exactly once on each virtual machine.
  64559. ** After this routine is called the VM has been "packaged" and is ready
  64560. ** to run. After this routine is called, further calls to
  64561. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  64562. ** the Vdbe from the Parse object that helped generate it so that the
  64563. ** the Vdbe becomes an independent entity and the Parse object can be
  64564. ** destroyed.
  64565. **
  64566. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  64567. ** to its initial state after it has been run.
  64568. */
  64569. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  64570. Vdbe *p, /* The VDBE */
  64571. Parse *pParse /* Parsing context */
  64572. ){
  64573. sqlite3 *db; /* The database connection */
  64574. int nVar; /* Number of parameters */
  64575. int nMem; /* Number of VM memory registers */
  64576. int nCursor; /* Number of cursors required */
  64577. int nArg; /* Number of arguments in subprograms */
  64578. int nOnce; /* Number of OP_Once instructions */
  64579. int n; /* Loop counter */
  64580. int nFree; /* Available free space */
  64581. u8 *zCsr; /* Memory available for allocation */
  64582. int nByte; /* How much extra memory is needed */
  64583. assert( p!=0 );
  64584. assert( p->nOp>0 );
  64585. assert( pParse!=0 );
  64586. assert( p->magic==VDBE_MAGIC_INIT );
  64587. assert( pParse==p->pParse );
  64588. db = p->db;
  64589. assert( db->mallocFailed==0 );
  64590. nVar = pParse->nVar;
  64591. nMem = pParse->nMem;
  64592. nCursor = pParse->nTab;
  64593. nArg = pParse->nMaxArg;
  64594. nOnce = pParse->nOnce;
  64595. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  64596. /* For each cursor required, also allocate a memory cell. Memory
  64597. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  64598. ** the vdbe program. Instead they are used to allocate space for
  64599. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  64600. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  64601. ** stores the blob of memory associated with cursor 1, etc.
  64602. **
  64603. ** See also: allocateCursor().
  64604. */
  64605. nMem += nCursor;
  64606. /* zCsr will initially point to nFree bytes of unused space at the
  64607. ** end of the opcode array, p->aOp. The computation of nFree is
  64608. ** conservative - it might be smaller than the true number of free
  64609. ** bytes, but never larger. nFree must be a multiple of 8 - it is
  64610. ** rounded down if is not.
  64611. */
  64612. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode space used */
  64613. zCsr = &((u8*)p->aOp)[n]; /* Unused opcode space */
  64614. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  64615. nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused space */
  64616. assert( nFree>=0 );
  64617. if( nFree>0 ){
  64618. memset(zCsr, 0, nFree);
  64619. assert( EIGHT_BYTE_ALIGNMENT(&zCsr[nFree]) );
  64620. }
  64621. resolveP2Values(p, &nArg);
  64622. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  64623. if( pParse->explain && nMem<10 ){
  64624. nMem = 10;
  64625. }
  64626. p->expired = 0;
  64627. /* Memory for registers, parameters, cursor, etc, is allocated in two
  64628. ** passes. On the first pass, we try to reuse unused space at the
  64629. ** end of the opcode array. If we are unable to satisfy all memory
  64630. ** requirements by reusing the opcode array tail, then the second
  64631. ** pass will fill in the rest using a fresh allocation.
  64632. **
  64633. ** This two-pass approach that reuses as much memory as possible from
  64634. ** the leftover space at the end of the opcode array can significantly
  64635. ** reduce the amount of memory held by a prepared statement.
  64636. */
  64637. do {
  64638. nByte = 0;
  64639. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), zCsr, &nFree, &nByte);
  64640. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), zCsr, &nFree, &nByte);
  64641. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), zCsr, &nFree, &nByte);
  64642. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), zCsr, &nFree, &nByte);
  64643. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  64644. zCsr, &nFree, &nByte);
  64645. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, zCsr, &nFree, &nByte);
  64646. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  64647. p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), zCsr, &nFree, &nByte);
  64648. #endif
  64649. if( nByte ){
  64650. p->pFree = sqlite3DbMallocZero(db, nByte);
  64651. }
  64652. zCsr = p->pFree;
  64653. nFree = nByte;
  64654. }while( nByte && !db->mallocFailed );
  64655. p->nCursor = nCursor;
  64656. p->nOnceFlag = nOnce;
  64657. if( p->aVar ){
  64658. p->nVar = (ynVar)nVar;
  64659. for(n=0; n<nVar; n++){
  64660. p->aVar[n].flags = MEM_Null;
  64661. p->aVar[n].db = db;
  64662. }
  64663. }
  64664. if( p->azVar && pParse->nzVar>0 ){
  64665. p->nzVar = pParse->nzVar;
  64666. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  64667. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  64668. }
  64669. if( p->aMem ){
  64670. p->aMem--; /* aMem[] goes from 1..nMem */
  64671. p->nMem = nMem; /* not from 0..nMem-1 */
  64672. for(n=1; n<=nMem; n++){
  64673. p->aMem[n].flags = MEM_Undefined;
  64674. p->aMem[n].db = db;
  64675. }
  64676. }
  64677. p->explain = pParse->explain;
  64678. sqlite3VdbeRewind(p);
  64679. }
  64680. /*
  64681. ** Close a VDBE cursor and release all the resources that cursor
  64682. ** happens to hold.
  64683. */
  64684. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  64685. if( pCx==0 ){
  64686. return;
  64687. }
  64688. assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
  64689. switch( pCx->eCurType ){
  64690. case CURTYPE_SORTER: {
  64691. sqlite3VdbeSorterClose(p->db, pCx);
  64692. break;
  64693. }
  64694. case CURTYPE_BTREE: {
  64695. if( pCx->pBt ){
  64696. sqlite3BtreeClose(pCx->pBt);
  64697. /* The pCx->pCursor will be close automatically, if it exists, by
  64698. ** the call above. */
  64699. }else{
  64700. assert( pCx->uc.pCursor!=0 );
  64701. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  64702. }
  64703. break;
  64704. }
  64705. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64706. case CURTYPE_VTAB: {
  64707. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  64708. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  64709. assert( pVCur->pVtab->nRef>0 );
  64710. pVCur->pVtab->nRef--;
  64711. pModule->xClose(pVCur);
  64712. break;
  64713. }
  64714. #endif
  64715. }
  64716. }
  64717. /*
  64718. ** Close all cursors in the current frame.
  64719. */
  64720. static void closeCursorsInFrame(Vdbe *p){
  64721. if( p->apCsr ){
  64722. int i;
  64723. for(i=0; i<p->nCursor; i++){
  64724. VdbeCursor *pC = p->apCsr[i];
  64725. if( pC ){
  64726. sqlite3VdbeFreeCursor(p, pC);
  64727. p->apCsr[i] = 0;
  64728. }
  64729. }
  64730. }
  64731. }
  64732. /*
  64733. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  64734. ** is used, for example, when a trigger sub-program is halted to restore
  64735. ** control to the main program.
  64736. */
  64737. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  64738. Vdbe *v = pFrame->v;
  64739. closeCursorsInFrame(v);
  64740. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  64741. v->anExec = pFrame->anExec;
  64742. #endif
  64743. v->aOnceFlag = pFrame->aOnceFlag;
  64744. v->nOnceFlag = pFrame->nOnceFlag;
  64745. v->aOp = pFrame->aOp;
  64746. v->nOp = pFrame->nOp;
  64747. v->aMem = pFrame->aMem;
  64748. v->nMem = pFrame->nMem;
  64749. v->apCsr = pFrame->apCsr;
  64750. v->nCursor = pFrame->nCursor;
  64751. v->db->lastRowid = pFrame->lastRowid;
  64752. v->nChange = pFrame->nChange;
  64753. v->db->nChange = pFrame->nDbChange;
  64754. return pFrame->pc;
  64755. }
  64756. /*
  64757. ** Close all cursors.
  64758. **
  64759. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  64760. ** cell array. This is necessary as the memory cell array may contain
  64761. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  64762. ** open cursors.
  64763. */
  64764. static void closeAllCursors(Vdbe *p){
  64765. if( p->pFrame ){
  64766. VdbeFrame *pFrame;
  64767. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  64768. sqlite3VdbeFrameRestore(pFrame);
  64769. p->pFrame = 0;
  64770. p->nFrame = 0;
  64771. }
  64772. assert( p->nFrame==0 );
  64773. closeCursorsInFrame(p);
  64774. if( p->aMem ){
  64775. releaseMemArray(&p->aMem[1], p->nMem);
  64776. }
  64777. while( p->pDelFrame ){
  64778. VdbeFrame *pDel = p->pDelFrame;
  64779. p->pDelFrame = pDel->pParent;
  64780. sqlite3VdbeFrameDelete(pDel);
  64781. }
  64782. /* Delete any auxdata allocations made by the VM */
  64783. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
  64784. assert( p->pAuxData==0 );
  64785. }
  64786. /*
  64787. ** Clean up the VM after a single run.
  64788. */
  64789. static void Cleanup(Vdbe *p){
  64790. sqlite3 *db = p->db;
  64791. #ifdef SQLITE_DEBUG
  64792. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  64793. ** Vdbe.aMem[] arrays have already been cleaned up. */
  64794. int i;
  64795. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  64796. if( p->aMem ){
  64797. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  64798. }
  64799. #endif
  64800. sqlite3DbFree(db, p->zErrMsg);
  64801. p->zErrMsg = 0;
  64802. p->pResultSet = 0;
  64803. }
  64804. /*
  64805. ** Set the number of result columns that will be returned by this SQL
  64806. ** statement. This is now set at compile time, rather than during
  64807. ** execution of the vdbe program so that sqlite3_column_count() can
  64808. ** be called on an SQL statement before sqlite3_step().
  64809. */
  64810. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  64811. Mem *pColName;
  64812. int n;
  64813. sqlite3 *db = p->db;
  64814. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  64815. sqlite3DbFree(db, p->aColName);
  64816. n = nResColumn*COLNAME_N;
  64817. p->nResColumn = (u16)nResColumn;
  64818. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  64819. if( p->aColName==0 ) return;
  64820. while( n-- > 0 ){
  64821. pColName->flags = MEM_Null;
  64822. pColName->db = p->db;
  64823. pColName++;
  64824. }
  64825. }
  64826. /*
  64827. ** Set the name of the idx'th column to be returned by the SQL statement.
  64828. ** zName must be a pointer to a nul terminated string.
  64829. **
  64830. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  64831. **
  64832. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  64833. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  64834. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  64835. */
  64836. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  64837. Vdbe *p, /* Vdbe being configured */
  64838. int idx, /* Index of column zName applies to */
  64839. int var, /* One of the COLNAME_* constants */
  64840. const char *zName, /* Pointer to buffer containing name */
  64841. void (*xDel)(void*) /* Memory management strategy for zName */
  64842. ){
  64843. int rc;
  64844. Mem *pColName;
  64845. assert( idx<p->nResColumn );
  64846. assert( var<COLNAME_N );
  64847. if( p->db->mallocFailed ){
  64848. assert( !zName || xDel!=SQLITE_DYNAMIC );
  64849. return SQLITE_NOMEM;
  64850. }
  64851. assert( p->aColName!=0 );
  64852. pColName = &(p->aColName[idx+var*p->nResColumn]);
  64853. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  64854. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  64855. return rc;
  64856. }
  64857. /*
  64858. ** A read or write transaction may or may not be active on database handle
  64859. ** db. If a transaction is active, commit it. If there is a
  64860. ** write-transaction spanning more than one database file, this routine
  64861. ** takes care of the master journal trickery.
  64862. */
  64863. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  64864. int i;
  64865. int nTrans = 0; /* Number of databases with an active write-transaction */
  64866. int rc = SQLITE_OK;
  64867. int needXcommit = 0;
  64868. #ifdef SQLITE_OMIT_VIRTUALTABLE
  64869. /* With this option, sqlite3VtabSync() is defined to be simply
  64870. ** SQLITE_OK so p is not used.
  64871. */
  64872. UNUSED_PARAMETER(p);
  64873. #endif
  64874. /* Before doing anything else, call the xSync() callback for any
  64875. ** virtual module tables written in this transaction. This has to
  64876. ** be done before determining whether a master journal file is
  64877. ** required, as an xSync() callback may add an attached database
  64878. ** to the transaction.
  64879. */
  64880. rc = sqlite3VtabSync(db, p);
  64881. /* This loop determines (a) if the commit hook should be invoked and
  64882. ** (b) how many database files have open write transactions, not
  64883. ** including the temp database. (b) is important because if more than
  64884. ** one database file has an open write transaction, a master journal
  64885. ** file is required for an atomic commit.
  64886. */
  64887. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  64888. Btree *pBt = db->aDb[i].pBt;
  64889. if( sqlite3BtreeIsInTrans(pBt) ){
  64890. needXcommit = 1;
  64891. if( i!=1 ) nTrans++;
  64892. sqlite3BtreeEnter(pBt);
  64893. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  64894. sqlite3BtreeLeave(pBt);
  64895. }
  64896. }
  64897. if( rc!=SQLITE_OK ){
  64898. return rc;
  64899. }
  64900. /* If there are any write-transactions at all, invoke the commit hook */
  64901. if( needXcommit && db->xCommitCallback ){
  64902. rc = db->xCommitCallback(db->pCommitArg);
  64903. if( rc ){
  64904. return SQLITE_CONSTRAINT_COMMITHOOK;
  64905. }
  64906. }
  64907. /* The simple case - no more than one database file (not counting the
  64908. ** TEMP database) has a transaction active. There is no need for the
  64909. ** master-journal.
  64910. **
  64911. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  64912. ** string, it means the main database is :memory: or a temp file. In
  64913. ** that case we do not support atomic multi-file commits, so use the
  64914. ** simple case then too.
  64915. */
  64916. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  64917. || nTrans<=1
  64918. ){
  64919. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  64920. Btree *pBt = db->aDb[i].pBt;
  64921. if( pBt ){
  64922. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  64923. }
  64924. }
  64925. /* Do the commit only if all databases successfully complete phase 1.
  64926. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  64927. ** IO error while deleting or truncating a journal file. It is unlikely,
  64928. ** but could happen. In this case abandon processing and return the error.
  64929. */
  64930. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  64931. Btree *pBt = db->aDb[i].pBt;
  64932. if( pBt ){
  64933. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  64934. }
  64935. }
  64936. if( rc==SQLITE_OK ){
  64937. sqlite3VtabCommit(db);
  64938. }
  64939. }
  64940. /* The complex case - There is a multi-file write-transaction active.
  64941. ** This requires a master journal file to ensure the transaction is
  64942. ** committed atomically.
  64943. */
  64944. #ifndef SQLITE_OMIT_DISKIO
  64945. else{
  64946. sqlite3_vfs *pVfs = db->pVfs;
  64947. int needSync = 0;
  64948. char *zMaster = 0; /* File-name for the master journal */
  64949. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  64950. sqlite3_file *pMaster = 0;
  64951. i64 offset = 0;
  64952. int res;
  64953. int retryCount = 0;
  64954. int nMainFile;
  64955. /* Select a master journal file name */
  64956. nMainFile = sqlite3Strlen30(zMainFile);
  64957. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  64958. if( zMaster==0 ) return SQLITE_NOMEM;
  64959. do {
  64960. u32 iRandom;
  64961. if( retryCount ){
  64962. if( retryCount>100 ){
  64963. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  64964. sqlite3OsDelete(pVfs, zMaster, 0);
  64965. break;
  64966. }else if( retryCount==1 ){
  64967. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  64968. }
  64969. }
  64970. retryCount++;
  64971. sqlite3_randomness(sizeof(iRandom), &iRandom);
  64972. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  64973. (iRandom>>8)&0xffffff, iRandom&0xff);
  64974. /* The antipenultimate character of the master journal name must
  64975. ** be "9" to avoid name collisions when using 8+3 filenames. */
  64976. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  64977. sqlite3FileSuffix3(zMainFile, zMaster);
  64978. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  64979. }while( rc==SQLITE_OK && res );
  64980. if( rc==SQLITE_OK ){
  64981. /* Open the master journal. */
  64982. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  64983. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  64984. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  64985. );
  64986. }
  64987. if( rc!=SQLITE_OK ){
  64988. sqlite3DbFree(db, zMaster);
  64989. return rc;
  64990. }
  64991. /* Write the name of each database file in the transaction into the new
  64992. ** master journal file. If an error occurs at this point close
  64993. ** and delete the master journal file. All the individual journal files
  64994. ** still have 'null' as the master journal pointer, so they will roll
  64995. ** back independently if a failure occurs.
  64996. */
  64997. for(i=0; i<db->nDb; i++){
  64998. Btree *pBt = db->aDb[i].pBt;
  64999. if( sqlite3BtreeIsInTrans(pBt) ){
  65000. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  65001. if( zFile==0 ){
  65002. continue; /* Ignore TEMP and :memory: databases */
  65003. }
  65004. assert( zFile[0]!=0 );
  65005. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  65006. needSync = 1;
  65007. }
  65008. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  65009. offset += sqlite3Strlen30(zFile)+1;
  65010. if( rc!=SQLITE_OK ){
  65011. sqlite3OsCloseFree(pMaster);
  65012. sqlite3OsDelete(pVfs, zMaster, 0);
  65013. sqlite3DbFree(db, zMaster);
  65014. return rc;
  65015. }
  65016. }
  65017. }
  65018. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  65019. ** flag is set this is not required.
  65020. */
  65021. if( needSync
  65022. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  65023. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  65024. ){
  65025. sqlite3OsCloseFree(pMaster);
  65026. sqlite3OsDelete(pVfs, zMaster, 0);
  65027. sqlite3DbFree(db, zMaster);
  65028. return rc;
  65029. }
  65030. /* Sync all the db files involved in the transaction. The same call
  65031. ** sets the master journal pointer in each individual journal. If
  65032. ** an error occurs here, do not delete the master journal file.
  65033. **
  65034. ** If the error occurs during the first call to
  65035. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  65036. ** master journal file will be orphaned. But we cannot delete it,
  65037. ** in case the master journal file name was written into the journal
  65038. ** file before the failure occurred.
  65039. */
  65040. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  65041. Btree *pBt = db->aDb[i].pBt;
  65042. if( pBt ){
  65043. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  65044. }
  65045. }
  65046. sqlite3OsCloseFree(pMaster);
  65047. assert( rc!=SQLITE_BUSY );
  65048. if( rc!=SQLITE_OK ){
  65049. sqlite3DbFree(db, zMaster);
  65050. return rc;
  65051. }
  65052. /* Delete the master journal file. This commits the transaction. After
  65053. ** doing this the directory is synced again before any individual
  65054. ** transaction files are deleted.
  65055. */
  65056. rc = sqlite3OsDelete(pVfs, zMaster, needSync);
  65057. sqlite3DbFree(db, zMaster);
  65058. zMaster = 0;
  65059. if( rc ){
  65060. return rc;
  65061. }
  65062. /* All files and directories have already been synced, so the following
  65063. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  65064. ** deleting or truncating journals. If something goes wrong while
  65065. ** this is happening we don't really care. The integrity of the
  65066. ** transaction is already guaranteed, but some stray 'cold' journals
  65067. ** may be lying around. Returning an error code won't help matters.
  65068. */
  65069. disable_simulated_io_errors();
  65070. sqlite3BeginBenignMalloc();
  65071. for(i=0; i<db->nDb; i++){
  65072. Btree *pBt = db->aDb[i].pBt;
  65073. if( pBt ){
  65074. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  65075. }
  65076. }
  65077. sqlite3EndBenignMalloc();
  65078. enable_simulated_io_errors();
  65079. sqlite3VtabCommit(db);
  65080. }
  65081. #endif
  65082. return rc;
  65083. }
  65084. /*
  65085. ** This routine checks that the sqlite3.nVdbeActive count variable
  65086. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  65087. ** currently active. An assertion fails if the two counts do not match.
  65088. ** This is an internal self-check only - it is not an essential processing
  65089. ** step.
  65090. **
  65091. ** This is a no-op if NDEBUG is defined.
  65092. */
  65093. #ifndef NDEBUG
  65094. static void checkActiveVdbeCnt(sqlite3 *db){
  65095. Vdbe *p;
  65096. int cnt = 0;
  65097. int nWrite = 0;
  65098. int nRead = 0;
  65099. p = db->pVdbe;
  65100. while( p ){
  65101. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  65102. cnt++;
  65103. if( p->readOnly==0 ) nWrite++;
  65104. if( p->bIsReader ) nRead++;
  65105. }
  65106. p = p->pNext;
  65107. }
  65108. assert( cnt==db->nVdbeActive );
  65109. assert( nWrite==db->nVdbeWrite );
  65110. assert( nRead==db->nVdbeRead );
  65111. }
  65112. #else
  65113. #define checkActiveVdbeCnt(x)
  65114. #endif
  65115. /*
  65116. ** If the Vdbe passed as the first argument opened a statement-transaction,
  65117. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  65118. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  65119. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  65120. ** statement transaction is committed.
  65121. **
  65122. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  65123. ** Otherwise SQLITE_OK.
  65124. */
  65125. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  65126. sqlite3 *const db = p->db;
  65127. int rc = SQLITE_OK;
  65128. /* If p->iStatement is greater than zero, then this Vdbe opened a
  65129. ** statement transaction that should be closed here. The only exception
  65130. ** is that an IO error may have occurred, causing an emergency rollback.
  65131. ** In this case (db->nStatement==0), and there is nothing to do.
  65132. */
  65133. if( db->nStatement && p->iStatement ){
  65134. int i;
  65135. const int iSavepoint = p->iStatement-1;
  65136. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  65137. assert( db->nStatement>0 );
  65138. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  65139. for(i=0; i<db->nDb; i++){
  65140. int rc2 = SQLITE_OK;
  65141. Btree *pBt = db->aDb[i].pBt;
  65142. if( pBt ){
  65143. if( eOp==SAVEPOINT_ROLLBACK ){
  65144. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  65145. }
  65146. if( rc2==SQLITE_OK ){
  65147. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  65148. }
  65149. if( rc==SQLITE_OK ){
  65150. rc = rc2;
  65151. }
  65152. }
  65153. }
  65154. db->nStatement--;
  65155. p->iStatement = 0;
  65156. if( rc==SQLITE_OK ){
  65157. if( eOp==SAVEPOINT_ROLLBACK ){
  65158. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  65159. }
  65160. if( rc==SQLITE_OK ){
  65161. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  65162. }
  65163. }
  65164. /* If the statement transaction is being rolled back, also restore the
  65165. ** database handles deferred constraint counter to the value it had when
  65166. ** the statement transaction was opened. */
  65167. if( eOp==SAVEPOINT_ROLLBACK ){
  65168. db->nDeferredCons = p->nStmtDefCons;
  65169. db->nDeferredImmCons = p->nStmtDefImmCons;
  65170. }
  65171. }
  65172. return rc;
  65173. }
  65174. /*
  65175. ** This function is called when a transaction opened by the database
  65176. ** handle associated with the VM passed as an argument is about to be
  65177. ** committed. If there are outstanding deferred foreign key constraint
  65178. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  65179. **
  65180. ** If there are outstanding FK violations and this function returns
  65181. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  65182. ** and write an error message to it. Then return SQLITE_ERROR.
  65183. */
  65184. #ifndef SQLITE_OMIT_FOREIGN_KEY
  65185. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  65186. sqlite3 *db = p->db;
  65187. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  65188. || (!deferred && p->nFkConstraint>0)
  65189. ){
  65190. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  65191. p->errorAction = OE_Abort;
  65192. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  65193. return SQLITE_ERROR;
  65194. }
  65195. return SQLITE_OK;
  65196. }
  65197. #endif
  65198. /*
  65199. ** This routine is called the when a VDBE tries to halt. If the VDBE
  65200. ** has made changes and is in autocommit mode, then commit those
  65201. ** changes. If a rollback is needed, then do the rollback.
  65202. **
  65203. ** This routine is the only way to move the state of a VM from
  65204. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  65205. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  65206. **
  65207. ** Return an error code. If the commit could not complete because of
  65208. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  65209. ** means the close did not happen and needs to be repeated.
  65210. */
  65211. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  65212. int rc; /* Used to store transient return codes */
  65213. sqlite3 *db = p->db;
  65214. /* This function contains the logic that determines if a statement or
  65215. ** transaction will be committed or rolled back as a result of the
  65216. ** execution of this virtual machine.
  65217. **
  65218. ** If any of the following errors occur:
  65219. **
  65220. ** SQLITE_NOMEM
  65221. ** SQLITE_IOERR
  65222. ** SQLITE_FULL
  65223. ** SQLITE_INTERRUPT
  65224. **
  65225. ** Then the internal cache might have been left in an inconsistent
  65226. ** state. We need to rollback the statement transaction, if there is
  65227. ** one, or the complete transaction if there is no statement transaction.
  65228. */
  65229. if( p->db->mallocFailed ){
  65230. p->rc = SQLITE_NOMEM;
  65231. }
  65232. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  65233. closeAllCursors(p);
  65234. if( p->magic!=VDBE_MAGIC_RUN ){
  65235. return SQLITE_OK;
  65236. }
  65237. checkActiveVdbeCnt(db);
  65238. /* No commit or rollback needed if the program never started or if the
  65239. ** SQL statement does not read or write a database file. */
  65240. if( p->pc>=0 && p->bIsReader ){
  65241. int mrc; /* Primary error code from p->rc */
  65242. int eStatementOp = 0;
  65243. int isSpecialError; /* Set to true if a 'special' error */
  65244. /* Lock all btrees used by the statement */
  65245. sqlite3VdbeEnter(p);
  65246. /* Check for one of the special errors */
  65247. mrc = p->rc & 0xff;
  65248. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  65249. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  65250. if( isSpecialError ){
  65251. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  65252. ** no rollback is necessary. Otherwise, at least a savepoint
  65253. ** transaction must be rolled back to restore the database to a
  65254. ** consistent state.
  65255. **
  65256. ** Even if the statement is read-only, it is important to perform
  65257. ** a statement or transaction rollback operation. If the error
  65258. ** occurred while writing to the journal, sub-journal or database
  65259. ** file as part of an effort to free up cache space (see function
  65260. ** pagerStress() in pager.c), the rollback is required to restore
  65261. ** the pager to a consistent state.
  65262. */
  65263. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  65264. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  65265. eStatementOp = SAVEPOINT_ROLLBACK;
  65266. }else{
  65267. /* We are forced to roll back the active transaction. Before doing
  65268. ** so, abort any other statements this handle currently has active.
  65269. */
  65270. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  65271. sqlite3CloseSavepoints(db);
  65272. db->autoCommit = 1;
  65273. p->nChange = 0;
  65274. }
  65275. }
  65276. }
  65277. /* Check for immediate foreign key violations. */
  65278. if( p->rc==SQLITE_OK ){
  65279. sqlite3VdbeCheckFk(p, 0);
  65280. }
  65281. /* If the auto-commit flag is set and this is the only active writer
  65282. ** VM, then we do either a commit or rollback of the current transaction.
  65283. **
  65284. ** Note: This block also runs if one of the special errors handled
  65285. ** above has occurred.
  65286. */
  65287. if( !sqlite3VtabInSync(db)
  65288. && db->autoCommit
  65289. && db->nVdbeWrite==(p->readOnly==0)
  65290. ){
  65291. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  65292. rc = sqlite3VdbeCheckFk(p, 1);
  65293. if( rc!=SQLITE_OK ){
  65294. if( NEVER(p->readOnly) ){
  65295. sqlite3VdbeLeave(p);
  65296. return SQLITE_ERROR;
  65297. }
  65298. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  65299. }else{
  65300. /* The auto-commit flag is true, the vdbe program was successful
  65301. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  65302. ** key constraints to hold up the transaction. This means a commit
  65303. ** is required. */
  65304. rc = vdbeCommit(db, p);
  65305. }
  65306. if( rc==SQLITE_BUSY && p->readOnly ){
  65307. sqlite3VdbeLeave(p);
  65308. return SQLITE_BUSY;
  65309. }else if( rc!=SQLITE_OK ){
  65310. p->rc = rc;
  65311. sqlite3RollbackAll(db, SQLITE_OK);
  65312. p->nChange = 0;
  65313. }else{
  65314. db->nDeferredCons = 0;
  65315. db->nDeferredImmCons = 0;
  65316. db->flags &= ~SQLITE_DeferFKs;
  65317. sqlite3CommitInternalChanges(db);
  65318. }
  65319. }else{
  65320. sqlite3RollbackAll(db, SQLITE_OK);
  65321. p->nChange = 0;
  65322. }
  65323. db->nStatement = 0;
  65324. }else if( eStatementOp==0 ){
  65325. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  65326. eStatementOp = SAVEPOINT_RELEASE;
  65327. }else if( p->errorAction==OE_Abort ){
  65328. eStatementOp = SAVEPOINT_ROLLBACK;
  65329. }else{
  65330. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  65331. sqlite3CloseSavepoints(db);
  65332. db->autoCommit = 1;
  65333. p->nChange = 0;
  65334. }
  65335. }
  65336. /* If eStatementOp is non-zero, then a statement transaction needs to
  65337. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  65338. ** do so. If this operation returns an error, and the current statement
  65339. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  65340. ** current statement error code.
  65341. */
  65342. if( eStatementOp ){
  65343. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  65344. if( rc ){
  65345. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  65346. p->rc = rc;
  65347. sqlite3DbFree(db, p->zErrMsg);
  65348. p->zErrMsg = 0;
  65349. }
  65350. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  65351. sqlite3CloseSavepoints(db);
  65352. db->autoCommit = 1;
  65353. p->nChange = 0;
  65354. }
  65355. }
  65356. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  65357. ** has been rolled back, update the database connection change-counter.
  65358. */
  65359. if( p->changeCntOn ){
  65360. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  65361. sqlite3VdbeSetChanges(db, p->nChange);
  65362. }else{
  65363. sqlite3VdbeSetChanges(db, 0);
  65364. }
  65365. p->nChange = 0;
  65366. }
  65367. /* Release the locks */
  65368. sqlite3VdbeLeave(p);
  65369. }
  65370. /* We have successfully halted and closed the VM. Record this fact. */
  65371. if( p->pc>=0 ){
  65372. db->nVdbeActive--;
  65373. if( !p->readOnly ) db->nVdbeWrite--;
  65374. if( p->bIsReader ) db->nVdbeRead--;
  65375. assert( db->nVdbeActive>=db->nVdbeRead );
  65376. assert( db->nVdbeRead>=db->nVdbeWrite );
  65377. assert( db->nVdbeWrite>=0 );
  65378. }
  65379. p->magic = VDBE_MAGIC_HALT;
  65380. checkActiveVdbeCnt(db);
  65381. if( p->db->mallocFailed ){
  65382. p->rc = SQLITE_NOMEM;
  65383. }
  65384. /* If the auto-commit flag is set to true, then any locks that were held
  65385. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  65386. ** to invoke any required unlock-notify callbacks.
  65387. */
  65388. if( db->autoCommit ){
  65389. sqlite3ConnectionUnlocked(db);
  65390. }
  65391. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  65392. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  65393. }
  65394. /*
  65395. ** Each VDBE holds the result of the most recent sqlite3_step() call
  65396. ** in p->rc. This routine sets that result back to SQLITE_OK.
  65397. */
  65398. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  65399. p->rc = SQLITE_OK;
  65400. }
  65401. /*
  65402. ** Copy the error code and error message belonging to the VDBE passed
  65403. ** as the first argument to its database handle (so that they will be
  65404. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  65405. **
  65406. ** This function does not clear the VDBE error code or message, just
  65407. ** copies them to the database handle.
  65408. */
  65409. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  65410. sqlite3 *db = p->db;
  65411. int rc = p->rc;
  65412. if( p->zErrMsg ){
  65413. u8 mallocFailed = db->mallocFailed;
  65414. sqlite3BeginBenignMalloc();
  65415. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  65416. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  65417. sqlite3EndBenignMalloc();
  65418. db->mallocFailed = mallocFailed;
  65419. db->errCode = rc;
  65420. }else{
  65421. sqlite3Error(db, rc);
  65422. }
  65423. return rc;
  65424. }
  65425. #ifdef SQLITE_ENABLE_SQLLOG
  65426. /*
  65427. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  65428. ** invoke it.
  65429. */
  65430. static void vdbeInvokeSqllog(Vdbe *v){
  65431. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  65432. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  65433. assert( v->db->init.busy==0 );
  65434. if( zExpanded ){
  65435. sqlite3GlobalConfig.xSqllog(
  65436. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  65437. );
  65438. sqlite3DbFree(v->db, zExpanded);
  65439. }
  65440. }
  65441. }
  65442. #else
  65443. # define vdbeInvokeSqllog(x)
  65444. #endif
  65445. /*
  65446. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  65447. ** Write any error messages into *pzErrMsg. Return the result code.
  65448. **
  65449. ** After this routine is run, the VDBE should be ready to be executed
  65450. ** again.
  65451. **
  65452. ** To look at it another way, this routine resets the state of the
  65453. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  65454. ** VDBE_MAGIC_INIT.
  65455. */
  65456. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  65457. sqlite3 *db;
  65458. db = p->db;
  65459. /* If the VM did not run to completion or if it encountered an
  65460. ** error, then it might not have been halted properly. So halt
  65461. ** it now.
  65462. */
  65463. sqlite3VdbeHalt(p);
  65464. /* If the VDBE has be run even partially, then transfer the error code
  65465. ** and error message from the VDBE into the main database structure. But
  65466. ** if the VDBE has just been set to run but has not actually executed any
  65467. ** instructions yet, leave the main database error information unchanged.
  65468. */
  65469. if( p->pc>=0 ){
  65470. vdbeInvokeSqllog(p);
  65471. sqlite3VdbeTransferError(p);
  65472. sqlite3DbFree(db, p->zErrMsg);
  65473. p->zErrMsg = 0;
  65474. if( p->runOnlyOnce ) p->expired = 1;
  65475. }else if( p->rc && p->expired ){
  65476. /* The expired flag was set on the VDBE before the first call
  65477. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  65478. ** called), set the database error in this case as well.
  65479. */
  65480. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  65481. sqlite3DbFree(db, p->zErrMsg);
  65482. p->zErrMsg = 0;
  65483. }
  65484. /* Reclaim all memory used by the VDBE
  65485. */
  65486. Cleanup(p);
  65487. /* Save profiling information from this VDBE run.
  65488. */
  65489. #ifdef VDBE_PROFILE
  65490. {
  65491. FILE *out = fopen("vdbe_profile.out", "a");
  65492. if( out ){
  65493. int i;
  65494. fprintf(out, "---- ");
  65495. for(i=0; i<p->nOp; i++){
  65496. fprintf(out, "%02x", p->aOp[i].opcode);
  65497. }
  65498. fprintf(out, "\n");
  65499. if( p->zSql ){
  65500. char c, pc = 0;
  65501. fprintf(out, "-- ");
  65502. for(i=0; (c = p->zSql[i])!=0; i++){
  65503. if( pc=='\n' ) fprintf(out, "-- ");
  65504. putc(c, out);
  65505. pc = c;
  65506. }
  65507. if( pc!='\n' ) fprintf(out, "\n");
  65508. }
  65509. for(i=0; i<p->nOp; i++){
  65510. char zHdr[100];
  65511. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  65512. p->aOp[i].cnt,
  65513. p->aOp[i].cycles,
  65514. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  65515. );
  65516. fprintf(out, "%s", zHdr);
  65517. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  65518. }
  65519. fclose(out);
  65520. }
  65521. }
  65522. #endif
  65523. p->iCurrentTime = 0;
  65524. p->magic = VDBE_MAGIC_INIT;
  65525. return p->rc & db->errMask;
  65526. }
  65527. /*
  65528. ** Clean up and delete a VDBE after execution. Return an integer which is
  65529. ** the result code. Write any error message text into *pzErrMsg.
  65530. */
  65531. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  65532. int rc = SQLITE_OK;
  65533. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  65534. rc = sqlite3VdbeReset(p);
  65535. assert( (rc & p->db->errMask)==rc );
  65536. }
  65537. sqlite3VdbeDelete(p);
  65538. return rc;
  65539. }
  65540. /*
  65541. ** If parameter iOp is less than zero, then invoke the destructor for
  65542. ** all auxiliary data pointers currently cached by the VM passed as
  65543. ** the first argument.
  65544. **
  65545. ** Or, if iOp is greater than or equal to zero, then the destructor is
  65546. ** only invoked for those auxiliary data pointers created by the user
  65547. ** function invoked by the OP_Function opcode at instruction iOp of
  65548. ** VM pVdbe, and only then if:
  65549. **
  65550. ** * the associated function parameter is the 32nd or later (counting
  65551. ** from left to right), or
  65552. **
  65553. ** * the corresponding bit in argument mask is clear (where the first
  65554. ** function parameter corresponds to bit 0 etc.).
  65555. */
  65556. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  65557. AuxData **pp = &pVdbe->pAuxData;
  65558. while( *pp ){
  65559. AuxData *pAux = *pp;
  65560. if( (iOp<0)
  65561. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
  65562. ){
  65563. testcase( pAux->iArg==31 );
  65564. if( pAux->xDelete ){
  65565. pAux->xDelete(pAux->pAux);
  65566. }
  65567. *pp = pAux->pNext;
  65568. sqlite3DbFree(pVdbe->db, pAux);
  65569. }else{
  65570. pp= &pAux->pNext;
  65571. }
  65572. }
  65573. }
  65574. /*
  65575. ** Free all memory associated with the Vdbe passed as the second argument,
  65576. ** except for object itself, which is preserved.
  65577. **
  65578. ** The difference between this function and sqlite3VdbeDelete() is that
  65579. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  65580. ** the database connection and frees the object itself.
  65581. */
  65582. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  65583. SubProgram *pSub, *pNext;
  65584. int i;
  65585. assert( p->db==0 || p->db==db );
  65586. releaseMemArray(p->aVar, p->nVar);
  65587. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  65588. for(pSub=p->pProgram; pSub; pSub=pNext){
  65589. pNext = pSub->pNext;
  65590. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  65591. sqlite3DbFree(db, pSub);
  65592. }
  65593. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  65594. vdbeFreeOpArray(db, p->aOp, p->nOp);
  65595. sqlite3DbFree(db, p->aColName);
  65596. sqlite3DbFree(db, p->zSql);
  65597. sqlite3DbFree(db, p->pFree);
  65598. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  65599. for(i=0; i<p->nScan; i++){
  65600. sqlite3DbFree(db, p->aScan[i].zName);
  65601. }
  65602. sqlite3DbFree(db, p->aScan);
  65603. #endif
  65604. }
  65605. /*
  65606. ** Delete an entire VDBE.
  65607. */
  65608. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  65609. sqlite3 *db;
  65610. if( NEVER(p==0) ) return;
  65611. db = p->db;
  65612. assert( sqlite3_mutex_held(db->mutex) );
  65613. sqlite3VdbeClearObject(db, p);
  65614. if( p->pPrev ){
  65615. p->pPrev->pNext = p->pNext;
  65616. }else{
  65617. assert( db->pVdbe==p );
  65618. db->pVdbe = p->pNext;
  65619. }
  65620. if( p->pNext ){
  65621. p->pNext->pPrev = p->pPrev;
  65622. }
  65623. p->magic = VDBE_MAGIC_DEAD;
  65624. p->db = 0;
  65625. sqlite3DbFree(db, p);
  65626. }
  65627. /*
  65628. ** The cursor "p" has a pending seek operation that has not yet been
  65629. ** carried out. Seek the cursor now. If an error occurs, return
  65630. ** the appropriate error code.
  65631. */
  65632. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  65633. int res, rc;
  65634. #ifdef SQLITE_TEST
  65635. extern int sqlite3_search_count;
  65636. #endif
  65637. assert( p->deferredMoveto );
  65638. assert( p->isTable );
  65639. assert( p->eCurType==CURTYPE_BTREE );
  65640. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  65641. if( rc ) return rc;
  65642. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  65643. #ifdef SQLITE_TEST
  65644. sqlite3_search_count++;
  65645. #endif
  65646. p->deferredMoveto = 0;
  65647. p->cacheStatus = CACHE_STALE;
  65648. return SQLITE_OK;
  65649. }
  65650. /*
  65651. ** Something has moved cursor "p" out of place. Maybe the row it was
  65652. ** pointed to was deleted out from under it. Or maybe the btree was
  65653. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  65654. ** is supposed to be pointing. If the row was deleted out from under the
  65655. ** cursor, set the cursor to point to a NULL row.
  65656. */
  65657. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  65658. int isDifferentRow, rc;
  65659. assert( p->eCurType==CURTYPE_BTREE );
  65660. assert( p->uc.pCursor!=0 );
  65661. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  65662. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  65663. p->cacheStatus = CACHE_STALE;
  65664. if( isDifferentRow ) p->nullRow = 1;
  65665. return rc;
  65666. }
  65667. /*
  65668. ** Check to ensure that the cursor is valid. Restore the cursor
  65669. ** if need be. Return any I/O error from the restore operation.
  65670. */
  65671. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  65672. assert( p->eCurType==CURTYPE_BTREE );
  65673. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  65674. return handleMovedCursor(p);
  65675. }
  65676. return SQLITE_OK;
  65677. }
  65678. /*
  65679. ** Make sure the cursor p is ready to read or write the row to which it
  65680. ** was last positioned. Return an error code if an OOM fault or I/O error
  65681. ** prevents us from positioning the cursor to its correct position.
  65682. **
  65683. ** If a MoveTo operation is pending on the given cursor, then do that
  65684. ** MoveTo now. If no move is pending, check to see if the row has been
  65685. ** deleted out from under the cursor and if it has, mark the row as
  65686. ** a NULL row.
  65687. **
  65688. ** If the cursor is already pointing to the correct row and that row has
  65689. ** not been deleted out from under the cursor, then this routine is a no-op.
  65690. */
  65691. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  65692. if( p->eCurType==CURTYPE_BTREE ){
  65693. if( p->deferredMoveto ){
  65694. return handleDeferredMoveto(p);
  65695. }
  65696. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  65697. return handleMovedCursor(p);
  65698. }
  65699. }
  65700. return SQLITE_OK;
  65701. }
  65702. /*
  65703. ** The following functions:
  65704. **
  65705. ** sqlite3VdbeSerialType()
  65706. ** sqlite3VdbeSerialTypeLen()
  65707. ** sqlite3VdbeSerialLen()
  65708. ** sqlite3VdbeSerialPut()
  65709. ** sqlite3VdbeSerialGet()
  65710. **
  65711. ** encapsulate the code that serializes values for storage in SQLite
  65712. ** data and index records. Each serialized value consists of a
  65713. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  65714. ** integer, stored as a varint.
  65715. **
  65716. ** In an SQLite index record, the serial type is stored directly before
  65717. ** the blob of data that it corresponds to. In a table record, all serial
  65718. ** types are stored at the start of the record, and the blobs of data at
  65719. ** the end. Hence these functions allow the caller to handle the
  65720. ** serial-type and data blob separately.
  65721. **
  65722. ** The following table describes the various storage classes for data:
  65723. **
  65724. ** serial type bytes of data type
  65725. ** -------------- --------------- ---------------
  65726. ** 0 0 NULL
  65727. ** 1 1 signed integer
  65728. ** 2 2 signed integer
  65729. ** 3 3 signed integer
  65730. ** 4 4 signed integer
  65731. ** 5 6 signed integer
  65732. ** 6 8 signed integer
  65733. ** 7 8 IEEE float
  65734. ** 8 0 Integer constant 0
  65735. ** 9 0 Integer constant 1
  65736. ** 10,11 reserved for expansion
  65737. ** N>=12 and even (N-12)/2 BLOB
  65738. ** N>=13 and odd (N-13)/2 text
  65739. **
  65740. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  65741. ** of SQLite will not understand those serial types.
  65742. */
  65743. /*
  65744. ** Return the serial-type for the value stored in pMem.
  65745. */
  65746. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  65747. int flags = pMem->flags;
  65748. u32 n;
  65749. assert( pLen!=0 );
  65750. if( flags&MEM_Null ){
  65751. *pLen = 0;
  65752. return 0;
  65753. }
  65754. if( flags&MEM_Int ){
  65755. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  65756. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  65757. i64 i = pMem->u.i;
  65758. u64 u;
  65759. if( i<0 ){
  65760. u = ~i;
  65761. }else{
  65762. u = i;
  65763. }
  65764. if( u<=127 ){
  65765. if( (i&1)==i && file_format>=4 ){
  65766. *pLen = 0;
  65767. return 8+(u32)u;
  65768. }else{
  65769. *pLen = 1;
  65770. return 1;
  65771. }
  65772. }
  65773. if( u<=32767 ){ *pLen = 2; return 2; }
  65774. if( u<=8388607 ){ *pLen = 3; return 3; }
  65775. if( u<=2147483647 ){ *pLen = 4; return 4; }
  65776. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  65777. *pLen = 8;
  65778. return 6;
  65779. }
  65780. if( flags&MEM_Real ){
  65781. *pLen = 8;
  65782. return 7;
  65783. }
  65784. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  65785. assert( pMem->n>=0 );
  65786. n = (u32)pMem->n;
  65787. if( flags & MEM_Zero ){
  65788. n += pMem->u.nZero;
  65789. }
  65790. *pLen = n;
  65791. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  65792. }
  65793. /*
  65794. ** The sizes for serial types less than 128
  65795. */
  65796. static const u8 sqlite3SmallTypeSizes[] = {
  65797. /* 0 1 2 3 4 5 6 7 8 9 */
  65798. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  65799. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  65800. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  65801. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  65802. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  65803. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  65804. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  65805. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  65806. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  65807. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  65808. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  65809. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  65810. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  65811. };
  65812. /*
  65813. ** Return the length of the data corresponding to the supplied serial-type.
  65814. */
  65815. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  65816. if( serial_type>=128 ){
  65817. return (serial_type-12)/2;
  65818. }else{
  65819. assert( serial_type<12
  65820. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  65821. return sqlite3SmallTypeSizes[serial_type];
  65822. }
  65823. }
  65824. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  65825. assert( serial_type<128 );
  65826. return sqlite3SmallTypeSizes[serial_type];
  65827. }
  65828. /*
  65829. ** If we are on an architecture with mixed-endian floating
  65830. ** points (ex: ARM7) then swap the lower 4 bytes with the
  65831. ** upper 4 bytes. Return the result.
  65832. **
  65833. ** For most architectures, this is a no-op.
  65834. **
  65835. ** (later): It is reported to me that the mixed-endian problem
  65836. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  65837. ** that early versions of GCC stored the two words of a 64-bit
  65838. ** float in the wrong order. And that error has been propagated
  65839. ** ever since. The blame is not necessarily with GCC, though.
  65840. ** GCC might have just copying the problem from a prior compiler.
  65841. ** I am also told that newer versions of GCC that follow a different
  65842. ** ABI get the byte order right.
  65843. **
  65844. ** Developers using SQLite on an ARM7 should compile and run their
  65845. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  65846. ** enabled, some asserts below will ensure that the byte order of
  65847. ** floating point values is correct.
  65848. **
  65849. ** (2007-08-30) Frank van Vugt has studied this problem closely
  65850. ** and has send his findings to the SQLite developers. Frank
  65851. ** writes that some Linux kernels offer floating point hardware
  65852. ** emulation that uses only 32-bit mantissas instead of a full
  65853. ** 48-bits as required by the IEEE standard. (This is the
  65854. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  65855. ** byte swapping becomes very complicated. To avoid problems,
  65856. ** the necessary byte swapping is carried out using a 64-bit integer
  65857. ** rather than a 64-bit float. Frank assures us that the code here
  65858. ** works for him. We, the developers, have no way to independently
  65859. ** verify this, but Frank seems to know what he is talking about
  65860. ** so we trust him.
  65861. */
  65862. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  65863. static u64 floatSwap(u64 in){
  65864. union {
  65865. u64 r;
  65866. u32 i[2];
  65867. } u;
  65868. u32 t;
  65869. u.r = in;
  65870. t = u.i[0];
  65871. u.i[0] = u.i[1];
  65872. u.i[1] = t;
  65873. return u.r;
  65874. }
  65875. # define swapMixedEndianFloat(X) X = floatSwap(X)
  65876. #else
  65877. # define swapMixedEndianFloat(X)
  65878. #endif
  65879. /*
  65880. ** Write the serialized data blob for the value stored in pMem into
  65881. ** buf. It is assumed that the caller has allocated sufficient space.
  65882. ** Return the number of bytes written.
  65883. **
  65884. ** nBuf is the amount of space left in buf[]. The caller is responsible
  65885. ** for allocating enough space to buf[] to hold the entire field, exclusive
  65886. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  65887. **
  65888. ** Return the number of bytes actually written into buf[]. The number
  65889. ** of bytes in the zero-filled tail is included in the return value only
  65890. ** if those bytes were zeroed in buf[].
  65891. */
  65892. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  65893. u32 len;
  65894. /* Integer and Real */
  65895. if( serial_type<=7 && serial_type>0 ){
  65896. u64 v;
  65897. u32 i;
  65898. if( serial_type==7 ){
  65899. assert( sizeof(v)==sizeof(pMem->u.r) );
  65900. memcpy(&v, &pMem->u.r, sizeof(v));
  65901. swapMixedEndianFloat(v);
  65902. }else{
  65903. v = pMem->u.i;
  65904. }
  65905. len = i = sqlite3SmallTypeSizes[serial_type];
  65906. assert( i>0 );
  65907. do{
  65908. buf[--i] = (u8)(v&0xFF);
  65909. v >>= 8;
  65910. }while( i );
  65911. return len;
  65912. }
  65913. /* String or blob */
  65914. if( serial_type>=12 ){
  65915. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  65916. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  65917. len = pMem->n;
  65918. if( len>0 ) memcpy(buf, pMem->z, len);
  65919. return len;
  65920. }
  65921. /* NULL or constants 0 or 1 */
  65922. return 0;
  65923. }
  65924. /* Input "x" is a sequence of unsigned characters that represent a
  65925. ** big-endian integer. Return the equivalent native integer
  65926. */
  65927. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  65928. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  65929. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  65930. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  65931. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  65932. /*
  65933. ** Deserialize the data blob pointed to by buf as serial type serial_type
  65934. ** and store the result in pMem. Return the number of bytes read.
  65935. **
  65936. ** This function is implemented as two separate routines for performance.
  65937. ** The few cases that require local variables are broken out into a separate
  65938. ** routine so that in most cases the overhead of moving the stack pointer
  65939. ** is avoided.
  65940. */
  65941. static u32 SQLITE_NOINLINE serialGet(
  65942. const unsigned char *buf, /* Buffer to deserialize from */
  65943. u32 serial_type, /* Serial type to deserialize */
  65944. Mem *pMem /* Memory cell to write value into */
  65945. ){
  65946. u64 x = FOUR_BYTE_UINT(buf);
  65947. u32 y = FOUR_BYTE_UINT(buf+4);
  65948. x = (x<<32) + y;
  65949. if( serial_type==6 ){
  65950. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  65951. ** twos-complement integer. */
  65952. pMem->u.i = *(i64*)&x;
  65953. pMem->flags = MEM_Int;
  65954. testcase( pMem->u.i<0 );
  65955. }else{
  65956. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  65957. ** floating point number. */
  65958. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  65959. /* Verify that integers and floating point values use the same
  65960. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  65961. ** defined that 64-bit floating point values really are mixed
  65962. ** endian.
  65963. */
  65964. static const u64 t1 = ((u64)0x3ff00000)<<32;
  65965. static const double r1 = 1.0;
  65966. u64 t2 = t1;
  65967. swapMixedEndianFloat(t2);
  65968. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  65969. #endif
  65970. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  65971. swapMixedEndianFloat(x);
  65972. memcpy(&pMem->u.r, &x, sizeof(x));
  65973. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  65974. }
  65975. return 8;
  65976. }
  65977. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  65978. const unsigned char *buf, /* Buffer to deserialize from */
  65979. u32 serial_type, /* Serial type to deserialize */
  65980. Mem *pMem /* Memory cell to write value into */
  65981. ){
  65982. switch( serial_type ){
  65983. case 10: /* Reserved for future use */
  65984. case 11: /* Reserved for future use */
  65985. case 0: { /* Null */
  65986. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  65987. pMem->flags = MEM_Null;
  65988. break;
  65989. }
  65990. case 1: {
  65991. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  65992. ** integer. */
  65993. pMem->u.i = ONE_BYTE_INT(buf);
  65994. pMem->flags = MEM_Int;
  65995. testcase( pMem->u.i<0 );
  65996. return 1;
  65997. }
  65998. case 2: { /* 2-byte signed integer */
  65999. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  66000. ** twos-complement integer. */
  66001. pMem->u.i = TWO_BYTE_INT(buf);
  66002. pMem->flags = MEM_Int;
  66003. testcase( pMem->u.i<0 );
  66004. return 2;
  66005. }
  66006. case 3: { /* 3-byte signed integer */
  66007. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  66008. ** twos-complement integer. */
  66009. pMem->u.i = THREE_BYTE_INT(buf);
  66010. pMem->flags = MEM_Int;
  66011. testcase( pMem->u.i<0 );
  66012. return 3;
  66013. }
  66014. case 4: { /* 4-byte signed integer */
  66015. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  66016. ** twos-complement integer. */
  66017. pMem->u.i = FOUR_BYTE_INT(buf);
  66018. #ifdef __HP_cc
  66019. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  66020. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  66021. #endif
  66022. pMem->flags = MEM_Int;
  66023. testcase( pMem->u.i<0 );
  66024. return 4;
  66025. }
  66026. case 5: { /* 6-byte signed integer */
  66027. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  66028. ** twos-complement integer. */
  66029. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  66030. pMem->flags = MEM_Int;
  66031. testcase( pMem->u.i<0 );
  66032. return 6;
  66033. }
  66034. case 6: /* 8-byte signed integer */
  66035. case 7: { /* IEEE floating point */
  66036. /* These use local variables, so do them in a separate routine
  66037. ** to avoid having to move the frame pointer in the common case */
  66038. return serialGet(buf,serial_type,pMem);
  66039. }
  66040. case 8: /* Integer 0 */
  66041. case 9: { /* Integer 1 */
  66042. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  66043. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  66044. pMem->u.i = serial_type-8;
  66045. pMem->flags = MEM_Int;
  66046. return 0;
  66047. }
  66048. default: {
  66049. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  66050. ** length.
  66051. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  66052. ** (N-13)/2 bytes in length. */
  66053. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  66054. pMem->z = (char *)buf;
  66055. pMem->n = (serial_type-12)/2;
  66056. pMem->flags = aFlag[serial_type&1];
  66057. return pMem->n;
  66058. }
  66059. }
  66060. return 0;
  66061. }
  66062. /*
  66063. ** This routine is used to allocate sufficient space for an UnpackedRecord
  66064. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  66065. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  66066. **
  66067. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  66068. ** the unaligned buffer passed via the second and third arguments (presumably
  66069. ** stack space). If the former, then *ppFree is set to a pointer that should
  66070. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  66071. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  66072. ** before returning.
  66073. **
  66074. ** If an OOM error occurs, NULL is returned.
  66075. */
  66076. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  66077. KeyInfo *pKeyInfo, /* Description of the record */
  66078. char *pSpace, /* Unaligned space available */
  66079. int szSpace, /* Size of pSpace[] in bytes */
  66080. char **ppFree /* OUT: Caller should free this pointer */
  66081. ){
  66082. UnpackedRecord *p; /* Unpacked record to return */
  66083. int nOff; /* Increment pSpace by nOff to align it */
  66084. int nByte; /* Number of bytes required for *p */
  66085. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  66086. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  66087. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  66088. */
  66089. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  66090. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  66091. if( nByte>szSpace+nOff ){
  66092. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  66093. *ppFree = (char *)p;
  66094. if( !p ) return 0;
  66095. }else{
  66096. p = (UnpackedRecord*)&pSpace[nOff];
  66097. *ppFree = 0;
  66098. }
  66099. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  66100. assert( pKeyInfo->aSortOrder!=0 );
  66101. p->pKeyInfo = pKeyInfo;
  66102. p->nField = pKeyInfo->nField + 1;
  66103. return p;
  66104. }
  66105. /*
  66106. ** Given the nKey-byte encoding of a record in pKey[], populate the
  66107. ** UnpackedRecord structure indicated by the fourth argument with the
  66108. ** contents of the decoded record.
  66109. */
  66110. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  66111. KeyInfo *pKeyInfo, /* Information about the record format */
  66112. int nKey, /* Size of the binary record */
  66113. const void *pKey, /* The binary record */
  66114. UnpackedRecord *p /* Populate this structure before returning. */
  66115. ){
  66116. const unsigned char *aKey = (const unsigned char *)pKey;
  66117. int d;
  66118. u32 idx; /* Offset in aKey[] to read from */
  66119. u16 u; /* Unsigned loop counter */
  66120. u32 szHdr;
  66121. Mem *pMem = p->aMem;
  66122. p->default_rc = 0;
  66123. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  66124. idx = getVarint32(aKey, szHdr);
  66125. d = szHdr;
  66126. u = 0;
  66127. while( idx<szHdr && d<=nKey ){
  66128. u32 serial_type;
  66129. idx += getVarint32(&aKey[idx], serial_type);
  66130. pMem->enc = pKeyInfo->enc;
  66131. pMem->db = pKeyInfo->db;
  66132. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  66133. pMem->szMalloc = 0;
  66134. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  66135. pMem++;
  66136. if( (++u)>=p->nField ) break;
  66137. }
  66138. assert( u<=pKeyInfo->nField + 1 );
  66139. p->nField = u;
  66140. }
  66141. #if SQLITE_DEBUG
  66142. /*
  66143. ** This function compares two index or table record keys in the same way
  66144. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  66145. ** this function deserializes and compares values using the
  66146. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  66147. ** in assert() statements to ensure that the optimized code in
  66148. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  66149. **
  66150. ** Return true if the result of comparison is equivalent to desiredResult.
  66151. ** Return false if there is a disagreement.
  66152. */
  66153. static int vdbeRecordCompareDebug(
  66154. int nKey1, const void *pKey1, /* Left key */
  66155. const UnpackedRecord *pPKey2, /* Right key */
  66156. int desiredResult /* Correct answer */
  66157. ){
  66158. u32 d1; /* Offset into aKey[] of next data element */
  66159. u32 idx1; /* Offset into aKey[] of next header element */
  66160. u32 szHdr1; /* Number of bytes in header */
  66161. int i = 0;
  66162. int rc = 0;
  66163. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  66164. KeyInfo *pKeyInfo;
  66165. Mem mem1;
  66166. pKeyInfo = pPKey2->pKeyInfo;
  66167. if( pKeyInfo->db==0 ) return 1;
  66168. mem1.enc = pKeyInfo->enc;
  66169. mem1.db = pKeyInfo->db;
  66170. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  66171. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  66172. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  66173. ** We could initialize it, as shown here, to silence those complaints.
  66174. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  66175. ** the unnecessary initialization has a measurable negative performance
  66176. ** impact, since this routine is a very high runner. And so, we choose
  66177. ** to ignore the compiler warnings and leave this variable uninitialized.
  66178. */
  66179. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  66180. idx1 = getVarint32(aKey1, szHdr1);
  66181. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  66182. d1 = szHdr1;
  66183. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  66184. assert( pKeyInfo->aSortOrder!=0 );
  66185. assert( pKeyInfo->nField>0 );
  66186. assert( idx1<=szHdr1 || CORRUPT_DB );
  66187. do{
  66188. u32 serial_type1;
  66189. /* Read the serial types for the next element in each key. */
  66190. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  66191. /* Verify that there is enough key space remaining to avoid
  66192. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  66193. ** always be greater than or equal to the amount of required key space.
  66194. ** Use that approximation to avoid the more expensive call to
  66195. ** sqlite3VdbeSerialTypeLen() in the common case.
  66196. */
  66197. if( d1+serial_type1+2>(u32)nKey1
  66198. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  66199. ){
  66200. break;
  66201. }
  66202. /* Extract the values to be compared.
  66203. */
  66204. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  66205. /* Do the comparison
  66206. */
  66207. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  66208. if( rc!=0 ){
  66209. assert( mem1.szMalloc==0 ); /* See comment below */
  66210. if( pKeyInfo->aSortOrder[i] ){
  66211. rc = -rc; /* Invert the result for DESC sort order. */
  66212. }
  66213. goto debugCompareEnd;
  66214. }
  66215. i++;
  66216. }while( idx1<szHdr1 && i<pPKey2->nField );
  66217. /* No memory allocation is ever used on mem1. Prove this using
  66218. ** the following assert(). If the assert() fails, it indicates a
  66219. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  66220. */
  66221. assert( mem1.szMalloc==0 );
  66222. /* rc==0 here means that one of the keys ran out of fields and
  66223. ** all the fields up to that point were equal. Return the default_rc
  66224. ** value. */
  66225. rc = pPKey2->default_rc;
  66226. debugCompareEnd:
  66227. if( desiredResult==0 && rc==0 ) return 1;
  66228. if( desiredResult<0 && rc<0 ) return 1;
  66229. if( desiredResult>0 && rc>0 ) return 1;
  66230. if( CORRUPT_DB ) return 1;
  66231. if( pKeyInfo->db->mallocFailed ) return 1;
  66232. return 0;
  66233. }
  66234. #endif
  66235. #if SQLITE_DEBUG
  66236. /*
  66237. ** Count the number of fields (a.k.a. columns) in the record given by
  66238. ** pKey,nKey. The verify that this count is less than or equal to the
  66239. ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
  66240. **
  66241. ** If this constraint is not satisfied, it means that the high-speed
  66242. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  66243. ** not work correctly. If this assert() ever fires, it probably means
  66244. ** that the KeyInfo.nField or KeyInfo.nXField values were computed
  66245. ** incorrectly.
  66246. */
  66247. static void vdbeAssertFieldCountWithinLimits(
  66248. int nKey, const void *pKey, /* The record to verify */
  66249. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  66250. ){
  66251. int nField = 0;
  66252. u32 szHdr;
  66253. u32 idx;
  66254. u32 notUsed;
  66255. const unsigned char *aKey = (const unsigned char*)pKey;
  66256. if( CORRUPT_DB ) return;
  66257. idx = getVarint32(aKey, szHdr);
  66258. assert( nKey>=0 );
  66259. assert( szHdr<=(u32)nKey );
  66260. while( idx<szHdr ){
  66261. idx += getVarint32(aKey+idx, notUsed);
  66262. nField++;
  66263. }
  66264. assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
  66265. }
  66266. #else
  66267. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  66268. #endif
  66269. /*
  66270. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  66271. ** using the collation sequence pColl. As usual, return a negative , zero
  66272. ** or positive value if *pMem1 is less than, equal to or greater than
  66273. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  66274. */
  66275. static int vdbeCompareMemString(
  66276. const Mem *pMem1,
  66277. const Mem *pMem2,
  66278. const CollSeq *pColl,
  66279. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  66280. ){
  66281. if( pMem1->enc==pColl->enc ){
  66282. /* The strings are already in the correct encoding. Call the
  66283. ** comparison function directly */
  66284. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  66285. }else{
  66286. int rc;
  66287. const void *v1, *v2;
  66288. int n1, n2;
  66289. Mem c1;
  66290. Mem c2;
  66291. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  66292. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  66293. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  66294. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  66295. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  66296. n1 = v1==0 ? 0 : c1.n;
  66297. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  66298. n2 = v2==0 ? 0 : c2.n;
  66299. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  66300. sqlite3VdbeMemRelease(&c1);
  66301. sqlite3VdbeMemRelease(&c2);
  66302. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
  66303. return rc;
  66304. }
  66305. }
  66306. /*
  66307. ** Compare two blobs. Return negative, zero, or positive if the first
  66308. ** is less than, equal to, or greater than the second, respectively.
  66309. ** If one blob is a prefix of the other, then the shorter is the lessor.
  66310. */
  66311. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  66312. int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
  66313. if( c ) return c;
  66314. return pB1->n - pB2->n;
  66315. }
  66316. /*
  66317. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  66318. ** number. Return negative, zero, or positive if the first (i64) is less than,
  66319. ** equal to, or greater than the second (double).
  66320. */
  66321. static int sqlite3IntFloatCompare(i64 i, double r){
  66322. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  66323. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  66324. if( x<r ) return -1;
  66325. if( x>r ) return +1;
  66326. return 0;
  66327. }else{
  66328. i64 y;
  66329. double s;
  66330. if( r<-9223372036854775808.0 ) return +1;
  66331. if( r>9223372036854775807.0 ) return -1;
  66332. y = (i64)r;
  66333. if( i<y ) return -1;
  66334. if( i>y ){
  66335. if( y==SMALLEST_INT64 && r>0.0 ) return -1;
  66336. return +1;
  66337. }
  66338. s = (double)i;
  66339. if( s<r ) return -1;
  66340. if( s>r ) return +1;
  66341. return 0;
  66342. }
  66343. }
  66344. /*
  66345. ** Compare the values contained by the two memory cells, returning
  66346. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  66347. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  66348. ** and reals) sorted numerically, followed by text ordered by the collating
  66349. ** sequence pColl and finally blob's ordered by memcmp().
  66350. **
  66351. ** Two NULL values are considered equal by this function.
  66352. */
  66353. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  66354. int f1, f2;
  66355. int combined_flags;
  66356. f1 = pMem1->flags;
  66357. f2 = pMem2->flags;
  66358. combined_flags = f1|f2;
  66359. assert( (combined_flags & MEM_RowSet)==0 );
  66360. /* If one value is NULL, it is less than the other. If both values
  66361. ** are NULL, return 0.
  66362. */
  66363. if( combined_flags&MEM_Null ){
  66364. return (f2&MEM_Null) - (f1&MEM_Null);
  66365. }
  66366. /* At least one of the two values is a number
  66367. */
  66368. if( combined_flags&(MEM_Int|MEM_Real) ){
  66369. if( (f1 & f2 & MEM_Int)!=0 ){
  66370. if( pMem1->u.i < pMem2->u.i ) return -1;
  66371. if( pMem1->u.i > pMem2->u.i ) return +1;
  66372. return 0;
  66373. }
  66374. if( (f1 & f2 & MEM_Real)!=0 ){
  66375. if( pMem1->u.r < pMem2->u.r ) return -1;
  66376. if( pMem1->u.r > pMem2->u.r ) return +1;
  66377. return 0;
  66378. }
  66379. if( (f1&MEM_Int)!=0 ){
  66380. if( (f2&MEM_Real)!=0 ){
  66381. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  66382. }else{
  66383. return -1;
  66384. }
  66385. }
  66386. if( (f1&MEM_Real)!=0 ){
  66387. if( (f2&MEM_Int)!=0 ){
  66388. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  66389. }else{
  66390. return -1;
  66391. }
  66392. }
  66393. return +1;
  66394. }
  66395. /* If one value is a string and the other is a blob, the string is less.
  66396. ** If both are strings, compare using the collating functions.
  66397. */
  66398. if( combined_flags&MEM_Str ){
  66399. if( (f1 & MEM_Str)==0 ){
  66400. return 1;
  66401. }
  66402. if( (f2 & MEM_Str)==0 ){
  66403. return -1;
  66404. }
  66405. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  66406. assert( pMem1->enc==SQLITE_UTF8 ||
  66407. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  66408. /* The collation sequence must be defined at this point, even if
  66409. ** the user deletes the collation sequence after the vdbe program is
  66410. ** compiled (this was not always the case).
  66411. */
  66412. assert( !pColl || pColl->xCmp );
  66413. if( pColl ){
  66414. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  66415. }
  66416. /* If a NULL pointer was passed as the collate function, fall through
  66417. ** to the blob case and use memcmp(). */
  66418. }
  66419. /* Both values must be blobs. Compare using memcmp(). */
  66420. return sqlite3BlobCompare(pMem1, pMem2);
  66421. }
  66422. /*
  66423. ** The first argument passed to this function is a serial-type that
  66424. ** corresponds to an integer - all values between 1 and 9 inclusive
  66425. ** except 7. The second points to a buffer containing an integer value
  66426. ** serialized according to serial_type. This function deserializes
  66427. ** and returns the value.
  66428. */
  66429. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  66430. u32 y;
  66431. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  66432. switch( serial_type ){
  66433. case 0:
  66434. case 1:
  66435. testcase( aKey[0]&0x80 );
  66436. return ONE_BYTE_INT(aKey);
  66437. case 2:
  66438. testcase( aKey[0]&0x80 );
  66439. return TWO_BYTE_INT(aKey);
  66440. case 3:
  66441. testcase( aKey[0]&0x80 );
  66442. return THREE_BYTE_INT(aKey);
  66443. case 4: {
  66444. testcase( aKey[0]&0x80 );
  66445. y = FOUR_BYTE_UINT(aKey);
  66446. return (i64)*(int*)&y;
  66447. }
  66448. case 5: {
  66449. testcase( aKey[0]&0x80 );
  66450. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  66451. }
  66452. case 6: {
  66453. u64 x = FOUR_BYTE_UINT(aKey);
  66454. testcase( aKey[0]&0x80 );
  66455. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  66456. return (i64)*(i64*)&x;
  66457. }
  66458. }
  66459. return (serial_type - 8);
  66460. }
  66461. /*
  66462. ** This function compares the two table rows or index records
  66463. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  66464. ** or positive integer if key1 is less than, equal to or
  66465. ** greater than key2. The {nKey1, pKey1} key must be a blob
  66466. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  66467. ** key must be a parsed key such as obtained from
  66468. ** sqlite3VdbeParseRecord.
  66469. **
  66470. ** If argument bSkip is non-zero, it is assumed that the caller has already
  66471. ** determined that the first fields of the keys are equal.
  66472. **
  66473. ** Key1 and Key2 do not have to contain the same number of fields. If all
  66474. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  66475. ** returned.
  66476. **
  66477. ** If database corruption is discovered, set pPKey2->errCode to
  66478. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  66479. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  66480. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  66481. */
  66482. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  66483. int nKey1, const void *pKey1, /* Left key */
  66484. UnpackedRecord *pPKey2, /* Right key */
  66485. int bSkip /* If true, skip the first field */
  66486. ){
  66487. u32 d1; /* Offset into aKey[] of next data element */
  66488. int i; /* Index of next field to compare */
  66489. u32 szHdr1; /* Size of record header in bytes */
  66490. u32 idx1; /* Offset of first type in header */
  66491. int rc = 0; /* Return value */
  66492. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  66493. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  66494. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  66495. Mem mem1;
  66496. /* If bSkip is true, then the caller has already determined that the first
  66497. ** two elements in the keys are equal. Fix the various stack variables so
  66498. ** that this routine begins comparing at the second field. */
  66499. if( bSkip ){
  66500. u32 s1;
  66501. idx1 = 1 + getVarint32(&aKey1[1], s1);
  66502. szHdr1 = aKey1[0];
  66503. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  66504. i = 1;
  66505. pRhs++;
  66506. }else{
  66507. idx1 = getVarint32(aKey1, szHdr1);
  66508. d1 = szHdr1;
  66509. if( d1>(unsigned)nKey1 ){
  66510. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  66511. return 0; /* Corruption */
  66512. }
  66513. i = 0;
  66514. }
  66515. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  66516. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  66517. || CORRUPT_DB );
  66518. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  66519. assert( pPKey2->pKeyInfo->nField>0 );
  66520. assert( idx1<=szHdr1 || CORRUPT_DB );
  66521. do{
  66522. u32 serial_type;
  66523. /* RHS is an integer */
  66524. if( pRhs->flags & MEM_Int ){
  66525. serial_type = aKey1[idx1];
  66526. testcase( serial_type==12 );
  66527. if( serial_type>=10 ){
  66528. rc = +1;
  66529. }else if( serial_type==0 ){
  66530. rc = -1;
  66531. }else if( serial_type==7 ){
  66532. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  66533. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  66534. }else{
  66535. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  66536. i64 rhs = pRhs->u.i;
  66537. if( lhs<rhs ){
  66538. rc = -1;
  66539. }else if( lhs>rhs ){
  66540. rc = +1;
  66541. }
  66542. }
  66543. }
  66544. /* RHS is real */
  66545. else if( pRhs->flags & MEM_Real ){
  66546. serial_type = aKey1[idx1];
  66547. if( serial_type>=10 ){
  66548. /* Serial types 12 or greater are strings and blobs (greater than
  66549. ** numbers). Types 10 and 11 are currently "reserved for future
  66550. ** use", so it doesn't really matter what the results of comparing
  66551. ** them to numberic values are. */
  66552. rc = +1;
  66553. }else if( serial_type==0 ){
  66554. rc = -1;
  66555. }else{
  66556. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  66557. if( serial_type==7 ){
  66558. if( mem1.u.r<pRhs->u.r ){
  66559. rc = -1;
  66560. }else if( mem1.u.r>pRhs->u.r ){
  66561. rc = +1;
  66562. }
  66563. }else{
  66564. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  66565. }
  66566. }
  66567. }
  66568. /* RHS is a string */
  66569. else if( pRhs->flags & MEM_Str ){
  66570. getVarint32(&aKey1[idx1], serial_type);
  66571. testcase( serial_type==12 );
  66572. if( serial_type<12 ){
  66573. rc = -1;
  66574. }else if( !(serial_type & 0x01) ){
  66575. rc = +1;
  66576. }else{
  66577. mem1.n = (serial_type - 12) / 2;
  66578. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  66579. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  66580. if( (d1+mem1.n) > (unsigned)nKey1 ){
  66581. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  66582. return 0; /* Corruption */
  66583. }else if( pKeyInfo->aColl[i] ){
  66584. mem1.enc = pKeyInfo->enc;
  66585. mem1.db = pKeyInfo->db;
  66586. mem1.flags = MEM_Str;
  66587. mem1.z = (char*)&aKey1[d1];
  66588. rc = vdbeCompareMemString(
  66589. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  66590. );
  66591. }else{
  66592. int nCmp = MIN(mem1.n, pRhs->n);
  66593. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  66594. if( rc==0 ) rc = mem1.n - pRhs->n;
  66595. }
  66596. }
  66597. }
  66598. /* RHS is a blob */
  66599. else if( pRhs->flags & MEM_Blob ){
  66600. getVarint32(&aKey1[idx1], serial_type);
  66601. testcase( serial_type==12 );
  66602. if( serial_type<12 || (serial_type & 0x01) ){
  66603. rc = -1;
  66604. }else{
  66605. int nStr = (serial_type - 12) / 2;
  66606. testcase( (d1+nStr)==(unsigned)nKey1 );
  66607. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  66608. if( (d1+nStr) > (unsigned)nKey1 ){
  66609. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  66610. return 0; /* Corruption */
  66611. }else{
  66612. int nCmp = MIN(nStr, pRhs->n);
  66613. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  66614. if( rc==0 ) rc = nStr - pRhs->n;
  66615. }
  66616. }
  66617. }
  66618. /* RHS is null */
  66619. else{
  66620. serial_type = aKey1[idx1];
  66621. rc = (serial_type!=0);
  66622. }
  66623. if( rc!=0 ){
  66624. if( pKeyInfo->aSortOrder[i] ){
  66625. rc = -rc;
  66626. }
  66627. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  66628. assert( mem1.szMalloc==0 ); /* See comment below */
  66629. return rc;
  66630. }
  66631. i++;
  66632. pRhs++;
  66633. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  66634. idx1 += sqlite3VarintLen(serial_type);
  66635. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  66636. /* No memory allocation is ever used on mem1. Prove this using
  66637. ** the following assert(). If the assert() fails, it indicates a
  66638. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  66639. assert( mem1.szMalloc==0 );
  66640. /* rc==0 here means that one or both of the keys ran out of fields and
  66641. ** all the fields up to that point were equal. Return the default_rc
  66642. ** value. */
  66643. assert( CORRUPT_DB
  66644. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  66645. || pKeyInfo->db->mallocFailed
  66646. );
  66647. pPKey2->eqSeen = 1;
  66648. return pPKey2->default_rc;
  66649. }
  66650. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  66651. int nKey1, const void *pKey1, /* Left key */
  66652. UnpackedRecord *pPKey2 /* Right key */
  66653. ){
  66654. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  66655. }
  66656. /*
  66657. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  66658. ** that (a) the first field of pPKey2 is an integer, and (b) the
  66659. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  66660. ** byte (i.e. is less than 128).
  66661. **
  66662. ** To avoid concerns about buffer overreads, this routine is only used
  66663. ** on schemas where the maximum valid header size is 63 bytes or less.
  66664. */
  66665. static int vdbeRecordCompareInt(
  66666. int nKey1, const void *pKey1, /* Left key */
  66667. UnpackedRecord *pPKey2 /* Right key */
  66668. ){
  66669. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  66670. int serial_type = ((const u8*)pKey1)[1];
  66671. int res;
  66672. u32 y;
  66673. u64 x;
  66674. i64 v = pPKey2->aMem[0].u.i;
  66675. i64 lhs;
  66676. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  66677. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  66678. switch( serial_type ){
  66679. case 1: { /* 1-byte signed integer */
  66680. lhs = ONE_BYTE_INT(aKey);
  66681. testcase( lhs<0 );
  66682. break;
  66683. }
  66684. case 2: { /* 2-byte signed integer */
  66685. lhs = TWO_BYTE_INT(aKey);
  66686. testcase( lhs<0 );
  66687. break;
  66688. }
  66689. case 3: { /* 3-byte signed integer */
  66690. lhs = THREE_BYTE_INT(aKey);
  66691. testcase( lhs<0 );
  66692. break;
  66693. }
  66694. case 4: { /* 4-byte signed integer */
  66695. y = FOUR_BYTE_UINT(aKey);
  66696. lhs = (i64)*(int*)&y;
  66697. testcase( lhs<0 );
  66698. break;
  66699. }
  66700. case 5: { /* 6-byte signed integer */
  66701. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  66702. testcase( lhs<0 );
  66703. break;
  66704. }
  66705. case 6: { /* 8-byte signed integer */
  66706. x = FOUR_BYTE_UINT(aKey);
  66707. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  66708. lhs = *(i64*)&x;
  66709. testcase( lhs<0 );
  66710. break;
  66711. }
  66712. case 8:
  66713. lhs = 0;
  66714. break;
  66715. case 9:
  66716. lhs = 1;
  66717. break;
  66718. /* This case could be removed without changing the results of running
  66719. ** this code. Including it causes gcc to generate a faster switch
  66720. ** statement (since the range of switch targets now starts at zero and
  66721. ** is contiguous) but does not cause any duplicate code to be generated
  66722. ** (as gcc is clever enough to combine the two like cases). Other
  66723. ** compilers might be similar. */
  66724. case 0: case 7:
  66725. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  66726. default:
  66727. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  66728. }
  66729. if( v>lhs ){
  66730. res = pPKey2->r1;
  66731. }else if( v<lhs ){
  66732. res = pPKey2->r2;
  66733. }else if( pPKey2->nField>1 ){
  66734. /* The first fields of the two keys are equal. Compare the trailing
  66735. ** fields. */
  66736. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  66737. }else{
  66738. /* The first fields of the two keys are equal and there are no trailing
  66739. ** fields. Return pPKey2->default_rc in this case. */
  66740. res = pPKey2->default_rc;
  66741. pPKey2->eqSeen = 1;
  66742. }
  66743. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  66744. return res;
  66745. }
  66746. /*
  66747. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  66748. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  66749. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  66750. ** at the start of (pKey1/nKey1) fits in a single byte.
  66751. */
  66752. static int vdbeRecordCompareString(
  66753. int nKey1, const void *pKey1, /* Left key */
  66754. UnpackedRecord *pPKey2 /* Right key */
  66755. ){
  66756. const u8 *aKey1 = (const u8*)pKey1;
  66757. int serial_type;
  66758. int res;
  66759. assert( pPKey2->aMem[0].flags & MEM_Str );
  66760. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  66761. getVarint32(&aKey1[1], serial_type);
  66762. if( serial_type<12 ){
  66763. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  66764. }else if( !(serial_type & 0x01) ){
  66765. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  66766. }else{
  66767. int nCmp;
  66768. int nStr;
  66769. int szHdr = aKey1[0];
  66770. nStr = (serial_type-12) / 2;
  66771. if( (szHdr + nStr) > nKey1 ){
  66772. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  66773. return 0; /* Corruption */
  66774. }
  66775. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  66776. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  66777. if( res==0 ){
  66778. res = nStr - pPKey2->aMem[0].n;
  66779. if( res==0 ){
  66780. if( pPKey2->nField>1 ){
  66781. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  66782. }else{
  66783. res = pPKey2->default_rc;
  66784. pPKey2->eqSeen = 1;
  66785. }
  66786. }else if( res>0 ){
  66787. res = pPKey2->r2;
  66788. }else{
  66789. res = pPKey2->r1;
  66790. }
  66791. }else if( res>0 ){
  66792. res = pPKey2->r2;
  66793. }else{
  66794. res = pPKey2->r1;
  66795. }
  66796. }
  66797. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  66798. || CORRUPT_DB
  66799. || pPKey2->pKeyInfo->db->mallocFailed
  66800. );
  66801. return res;
  66802. }
  66803. /*
  66804. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  66805. ** suitable for comparing serialized records to the unpacked record passed
  66806. ** as the only argument.
  66807. */
  66808. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  66809. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  66810. ** that the size-of-header varint that occurs at the start of each record
  66811. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  66812. ** also assumes that it is safe to overread a buffer by at least the
  66813. ** maximum possible legal header size plus 8 bytes. Because there is
  66814. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  66815. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  66816. ** limit the size of the header to 64 bytes in cases where the first field
  66817. ** is an integer.
  66818. **
  66819. ** The easiest way to enforce this limit is to consider only records with
  66820. ** 13 fields or less. If the first field is an integer, the maximum legal
  66821. ** header size is (12*5 + 1 + 1) bytes. */
  66822. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  66823. int flags = p->aMem[0].flags;
  66824. if( p->pKeyInfo->aSortOrder[0] ){
  66825. p->r1 = 1;
  66826. p->r2 = -1;
  66827. }else{
  66828. p->r1 = -1;
  66829. p->r2 = 1;
  66830. }
  66831. if( (flags & MEM_Int) ){
  66832. return vdbeRecordCompareInt;
  66833. }
  66834. testcase( flags & MEM_Real );
  66835. testcase( flags & MEM_Null );
  66836. testcase( flags & MEM_Blob );
  66837. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  66838. assert( flags & MEM_Str );
  66839. return vdbeRecordCompareString;
  66840. }
  66841. }
  66842. return sqlite3VdbeRecordCompare;
  66843. }
  66844. /*
  66845. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  66846. ** Read the rowid (the last field in the record) and store it in *rowid.
  66847. ** Return SQLITE_OK if everything works, or an error code otherwise.
  66848. **
  66849. ** pCur might be pointing to text obtained from a corrupt database file.
  66850. ** So the content cannot be trusted. Do appropriate checks on the content.
  66851. */
  66852. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  66853. i64 nCellKey = 0;
  66854. int rc;
  66855. u32 szHdr; /* Size of the header */
  66856. u32 typeRowid; /* Serial type of the rowid */
  66857. u32 lenRowid; /* Size of the rowid */
  66858. Mem m, v;
  66859. /* Get the size of the index entry. Only indices entries of less
  66860. ** than 2GiB are support - anything large must be database corruption.
  66861. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  66862. ** this code can safely assume that nCellKey is 32-bits
  66863. */
  66864. assert( sqlite3BtreeCursorIsValid(pCur) );
  66865. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  66866. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  66867. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  66868. /* Read in the complete content of the index entry */
  66869. sqlite3VdbeMemInit(&m, db, 0);
  66870. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  66871. if( rc ){
  66872. return rc;
  66873. }
  66874. /* The index entry must begin with a header size */
  66875. (void)getVarint32((u8*)m.z, szHdr);
  66876. testcase( szHdr==3 );
  66877. testcase( szHdr==m.n );
  66878. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  66879. goto idx_rowid_corruption;
  66880. }
  66881. /* The last field of the index should be an integer - the ROWID.
  66882. ** Verify that the last entry really is an integer. */
  66883. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  66884. testcase( typeRowid==1 );
  66885. testcase( typeRowid==2 );
  66886. testcase( typeRowid==3 );
  66887. testcase( typeRowid==4 );
  66888. testcase( typeRowid==5 );
  66889. testcase( typeRowid==6 );
  66890. testcase( typeRowid==8 );
  66891. testcase( typeRowid==9 );
  66892. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  66893. goto idx_rowid_corruption;
  66894. }
  66895. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  66896. testcase( (u32)m.n==szHdr+lenRowid );
  66897. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  66898. goto idx_rowid_corruption;
  66899. }
  66900. /* Fetch the integer off the end of the index record */
  66901. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  66902. *rowid = v.u.i;
  66903. sqlite3VdbeMemRelease(&m);
  66904. return SQLITE_OK;
  66905. /* Jump here if database corruption is detected after m has been
  66906. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  66907. idx_rowid_corruption:
  66908. testcase( m.szMalloc!=0 );
  66909. sqlite3VdbeMemRelease(&m);
  66910. return SQLITE_CORRUPT_BKPT;
  66911. }
  66912. /*
  66913. ** Compare the key of the index entry that cursor pC is pointing to against
  66914. ** the key string in pUnpacked. Write into *pRes a number
  66915. ** that is negative, zero, or positive if pC is less than, equal to,
  66916. ** or greater than pUnpacked. Return SQLITE_OK on success.
  66917. **
  66918. ** pUnpacked is either created without a rowid or is truncated so that it
  66919. ** omits the rowid at the end. The rowid at the end of the index entry
  66920. ** is ignored as well. Hence, this routine only compares the prefixes
  66921. ** of the keys prior to the final rowid, not the entire key.
  66922. */
  66923. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  66924. sqlite3 *db, /* Database connection */
  66925. VdbeCursor *pC, /* The cursor to compare against */
  66926. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  66927. int *res /* Write the comparison result here */
  66928. ){
  66929. i64 nCellKey = 0;
  66930. int rc;
  66931. BtCursor *pCur;
  66932. Mem m;
  66933. assert( pC->eCurType==CURTYPE_BTREE );
  66934. pCur = pC->uc.pCursor;
  66935. assert( sqlite3BtreeCursorIsValid(pCur) );
  66936. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  66937. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  66938. /* nCellKey will always be between 0 and 0xffffffff because of the way
  66939. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  66940. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  66941. *res = 0;
  66942. return SQLITE_CORRUPT_BKPT;
  66943. }
  66944. sqlite3VdbeMemInit(&m, db, 0);
  66945. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  66946. if( rc ){
  66947. return rc;
  66948. }
  66949. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  66950. sqlite3VdbeMemRelease(&m);
  66951. return SQLITE_OK;
  66952. }
  66953. /*
  66954. ** This routine sets the value to be returned by subsequent calls to
  66955. ** sqlite3_changes() on the database handle 'db'.
  66956. */
  66957. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  66958. assert( sqlite3_mutex_held(db->mutex) );
  66959. db->nChange = nChange;
  66960. db->nTotalChange += nChange;
  66961. }
  66962. /*
  66963. ** Set a flag in the vdbe to update the change counter when it is finalised
  66964. ** or reset.
  66965. */
  66966. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  66967. v->changeCntOn = 1;
  66968. }
  66969. /*
  66970. ** Mark every prepared statement associated with a database connection
  66971. ** as expired.
  66972. **
  66973. ** An expired statement means that recompilation of the statement is
  66974. ** recommend. Statements expire when things happen that make their
  66975. ** programs obsolete. Removing user-defined functions or collating
  66976. ** sequences, or changing an authorization function are the types of
  66977. ** things that make prepared statements obsolete.
  66978. */
  66979. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  66980. Vdbe *p;
  66981. for(p = db->pVdbe; p; p=p->pNext){
  66982. p->expired = 1;
  66983. }
  66984. }
  66985. /*
  66986. ** Return the database associated with the Vdbe.
  66987. */
  66988. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  66989. return v->db;
  66990. }
  66991. /*
  66992. ** Return a pointer to an sqlite3_value structure containing the value bound
  66993. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  66994. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  66995. ** constants) to the value before returning it.
  66996. **
  66997. ** The returned value must be freed by the caller using sqlite3ValueFree().
  66998. */
  66999. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  67000. assert( iVar>0 );
  67001. if( v ){
  67002. Mem *pMem = &v->aVar[iVar-1];
  67003. if( 0==(pMem->flags & MEM_Null) ){
  67004. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  67005. if( pRet ){
  67006. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  67007. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  67008. }
  67009. return pRet;
  67010. }
  67011. }
  67012. return 0;
  67013. }
  67014. /*
  67015. ** Configure SQL variable iVar so that binding a new value to it signals
  67016. ** to sqlite3_reoptimize() that re-preparing the statement may result
  67017. ** in a better query plan.
  67018. */
  67019. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  67020. assert( iVar>0 );
  67021. if( iVar>32 ){
  67022. v->expmask = 0xffffffff;
  67023. }else{
  67024. v->expmask |= ((u32)1 << (iVar-1));
  67025. }
  67026. }
  67027. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67028. /*
  67029. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  67030. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  67031. ** in memory obtained from sqlite3DbMalloc).
  67032. */
  67033. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  67034. sqlite3 *db = p->db;
  67035. sqlite3DbFree(db, p->zErrMsg);
  67036. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  67037. sqlite3_free(pVtab->zErrMsg);
  67038. pVtab->zErrMsg = 0;
  67039. }
  67040. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  67041. /************** End of vdbeaux.c *********************************************/
  67042. /************** Begin file vdbeapi.c *****************************************/
  67043. /*
  67044. ** 2004 May 26
  67045. **
  67046. ** The author disclaims copyright to this source code. In place of
  67047. ** a legal notice, here is a blessing:
  67048. **
  67049. ** May you do good and not evil.
  67050. ** May you find forgiveness for yourself and forgive others.
  67051. ** May you share freely, never taking more than you give.
  67052. **
  67053. *************************************************************************
  67054. **
  67055. ** This file contains code use to implement APIs that are part of the
  67056. ** VDBE.
  67057. */
  67058. /* #include "sqliteInt.h" */
  67059. /* #include "vdbeInt.h" */
  67060. #ifndef SQLITE_OMIT_DEPRECATED
  67061. /*
  67062. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  67063. ** to be recompiled. A statement needs to be recompiled whenever the
  67064. ** execution environment changes in a way that would alter the program
  67065. ** that sqlite3_prepare() generates. For example, if new functions or
  67066. ** collating sequences are registered or if an authorizer function is
  67067. ** added or changed.
  67068. */
  67069. SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
  67070. Vdbe *p = (Vdbe*)pStmt;
  67071. return p==0 || p->expired;
  67072. }
  67073. #endif
  67074. /*
  67075. ** Check on a Vdbe to make sure it has not been finalized. Log
  67076. ** an error and return true if it has been finalized (or is otherwise
  67077. ** invalid). Return false if it is ok.
  67078. */
  67079. static int vdbeSafety(Vdbe *p){
  67080. if( p->db==0 ){
  67081. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  67082. return 1;
  67083. }else{
  67084. return 0;
  67085. }
  67086. }
  67087. static int vdbeSafetyNotNull(Vdbe *p){
  67088. if( p==0 ){
  67089. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  67090. return 1;
  67091. }else{
  67092. return vdbeSafety(p);
  67093. }
  67094. }
  67095. #ifndef SQLITE_OMIT_TRACE
  67096. /*
  67097. ** Invoke the profile callback. This routine is only called if we already
  67098. ** know that the profile callback is defined and needs to be invoked.
  67099. */
  67100. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  67101. sqlite3_int64 iNow;
  67102. assert( p->startTime>0 );
  67103. assert( db->xProfile!=0 );
  67104. assert( db->init.busy==0 );
  67105. assert( p->zSql!=0 );
  67106. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  67107. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  67108. p->startTime = 0;
  67109. }
  67110. /*
  67111. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  67112. ** is needed, and it invokes the callback if it is needed.
  67113. */
  67114. # define checkProfileCallback(DB,P) \
  67115. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  67116. #else
  67117. # define checkProfileCallback(DB,P) /*no-op*/
  67118. #endif
  67119. /*
  67120. ** The following routine destroys a virtual machine that is created by
  67121. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  67122. ** success/failure code that describes the result of executing the virtual
  67123. ** machine.
  67124. **
  67125. ** This routine sets the error code and string returned by
  67126. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  67127. */
  67128. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
  67129. int rc;
  67130. if( pStmt==0 ){
  67131. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  67132. ** pointer is a harmless no-op. */
  67133. rc = SQLITE_OK;
  67134. }else{
  67135. Vdbe *v = (Vdbe*)pStmt;
  67136. sqlite3 *db = v->db;
  67137. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  67138. sqlite3_mutex_enter(db->mutex);
  67139. checkProfileCallback(db, v);
  67140. rc = sqlite3VdbeFinalize(v);
  67141. rc = sqlite3ApiExit(db, rc);
  67142. sqlite3LeaveMutexAndCloseZombie(db);
  67143. }
  67144. return rc;
  67145. }
  67146. /*
  67147. ** Terminate the current execution of an SQL statement and reset it
  67148. ** back to its starting state so that it can be reused. A success code from
  67149. ** the prior execution is returned.
  67150. **
  67151. ** This routine sets the error code and string returned by
  67152. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  67153. */
  67154. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
  67155. int rc;
  67156. if( pStmt==0 ){
  67157. rc = SQLITE_OK;
  67158. }else{
  67159. Vdbe *v = (Vdbe*)pStmt;
  67160. sqlite3 *db = v->db;
  67161. sqlite3_mutex_enter(db->mutex);
  67162. checkProfileCallback(db, v);
  67163. rc = sqlite3VdbeReset(v);
  67164. sqlite3VdbeRewind(v);
  67165. assert( (rc & (db->errMask))==rc );
  67166. rc = sqlite3ApiExit(db, rc);
  67167. sqlite3_mutex_leave(db->mutex);
  67168. }
  67169. return rc;
  67170. }
  67171. /*
  67172. ** Set all the parameters in the compiled SQL statement to NULL.
  67173. */
  67174. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  67175. int i;
  67176. int rc = SQLITE_OK;
  67177. Vdbe *p = (Vdbe*)pStmt;
  67178. #if SQLITE_THREADSAFE
  67179. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  67180. #endif
  67181. sqlite3_mutex_enter(mutex);
  67182. for(i=0; i<p->nVar; i++){
  67183. sqlite3VdbeMemRelease(&p->aVar[i]);
  67184. p->aVar[i].flags = MEM_Null;
  67185. }
  67186. if( p->isPrepareV2 && p->expmask ){
  67187. p->expired = 1;
  67188. }
  67189. sqlite3_mutex_leave(mutex);
  67190. return rc;
  67191. }
  67192. /**************************** sqlite3_value_ *******************************
  67193. ** The following routines extract information from a Mem or sqlite3_value
  67194. ** structure.
  67195. */
  67196. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
  67197. Mem *p = (Mem*)pVal;
  67198. if( p->flags & (MEM_Blob|MEM_Str) ){
  67199. if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
  67200. assert( p->flags==MEM_Null && p->z==0 );
  67201. return 0;
  67202. }
  67203. p->flags |= MEM_Blob;
  67204. return p->n ? p->z : 0;
  67205. }else{
  67206. return sqlite3_value_text(pVal);
  67207. }
  67208. }
  67209. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
  67210. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  67211. }
  67212. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
  67213. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  67214. }
  67215. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
  67216. return sqlite3VdbeRealValue((Mem*)pVal);
  67217. }
  67218. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
  67219. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  67220. }
  67221. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
  67222. return sqlite3VdbeIntValue((Mem*)pVal);
  67223. }
  67224. SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value *pVal){
  67225. return ((Mem*)pVal)->eSubtype;
  67226. }
  67227. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
  67228. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  67229. }
  67230. #ifndef SQLITE_OMIT_UTF16
  67231. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
  67232. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  67233. }
  67234. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
  67235. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  67236. }
  67237. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
  67238. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  67239. }
  67240. #endif /* SQLITE_OMIT_UTF16 */
  67241. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  67242. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  67243. ** point number string BLOB NULL
  67244. */
  67245. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
  67246. static const u8 aType[] = {
  67247. SQLITE_BLOB, /* 0x00 */
  67248. SQLITE_NULL, /* 0x01 */
  67249. SQLITE_TEXT, /* 0x02 */
  67250. SQLITE_NULL, /* 0x03 */
  67251. SQLITE_INTEGER, /* 0x04 */
  67252. SQLITE_NULL, /* 0x05 */
  67253. SQLITE_INTEGER, /* 0x06 */
  67254. SQLITE_NULL, /* 0x07 */
  67255. SQLITE_FLOAT, /* 0x08 */
  67256. SQLITE_NULL, /* 0x09 */
  67257. SQLITE_FLOAT, /* 0x0a */
  67258. SQLITE_NULL, /* 0x0b */
  67259. SQLITE_INTEGER, /* 0x0c */
  67260. SQLITE_NULL, /* 0x0d */
  67261. SQLITE_INTEGER, /* 0x0e */
  67262. SQLITE_NULL, /* 0x0f */
  67263. SQLITE_BLOB, /* 0x10 */
  67264. SQLITE_NULL, /* 0x11 */
  67265. SQLITE_TEXT, /* 0x12 */
  67266. SQLITE_NULL, /* 0x13 */
  67267. SQLITE_INTEGER, /* 0x14 */
  67268. SQLITE_NULL, /* 0x15 */
  67269. SQLITE_INTEGER, /* 0x16 */
  67270. SQLITE_NULL, /* 0x17 */
  67271. SQLITE_FLOAT, /* 0x18 */
  67272. SQLITE_NULL, /* 0x19 */
  67273. SQLITE_FLOAT, /* 0x1a */
  67274. SQLITE_NULL, /* 0x1b */
  67275. SQLITE_INTEGER, /* 0x1c */
  67276. SQLITE_NULL, /* 0x1d */
  67277. SQLITE_INTEGER, /* 0x1e */
  67278. SQLITE_NULL, /* 0x1f */
  67279. };
  67280. return aType[pVal->flags&MEM_AffMask];
  67281. }
  67282. /* Make a copy of an sqlite3_value object
  67283. */
  67284. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *pOrig){
  67285. sqlite3_value *pNew;
  67286. if( pOrig==0 ) return 0;
  67287. pNew = sqlite3_malloc( sizeof(*pNew) );
  67288. if( pNew==0 ) return 0;
  67289. memset(pNew, 0, sizeof(*pNew));
  67290. memcpy(pNew, pOrig, MEMCELLSIZE);
  67291. pNew->flags &= ~MEM_Dyn;
  67292. pNew->db = 0;
  67293. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  67294. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  67295. pNew->flags |= MEM_Ephem;
  67296. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  67297. sqlite3ValueFree(pNew);
  67298. pNew = 0;
  67299. }
  67300. }
  67301. return pNew;
  67302. }
  67303. /* Destroy an sqlite3_value object previously obtained from
  67304. ** sqlite3_value_dup().
  67305. */
  67306. SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *pOld){
  67307. sqlite3ValueFree(pOld);
  67308. }
  67309. /**************************** sqlite3_result_ *******************************
  67310. ** The following routines are used by user-defined functions to specify
  67311. ** the function result.
  67312. **
  67313. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  67314. ** result as a string or blob but if the string or blob is too large, it
  67315. ** then sets the error code to SQLITE_TOOBIG
  67316. **
  67317. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  67318. ** on value P is not going to be used and need to be destroyed.
  67319. */
  67320. static void setResultStrOrError(
  67321. sqlite3_context *pCtx, /* Function context */
  67322. const char *z, /* String pointer */
  67323. int n, /* Bytes in string, or negative */
  67324. u8 enc, /* Encoding of z. 0 for BLOBs */
  67325. void (*xDel)(void*) /* Destructor function */
  67326. ){
  67327. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  67328. sqlite3_result_error_toobig(pCtx);
  67329. }
  67330. }
  67331. static int invokeValueDestructor(
  67332. const void *p, /* Value to destroy */
  67333. void (*xDel)(void*), /* The destructor */
  67334. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  67335. ){
  67336. assert( xDel!=SQLITE_DYNAMIC );
  67337. if( xDel==0 ){
  67338. /* noop */
  67339. }else if( xDel==SQLITE_TRANSIENT ){
  67340. /* noop */
  67341. }else{
  67342. xDel((void*)p);
  67343. }
  67344. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  67345. return SQLITE_TOOBIG;
  67346. }
  67347. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
  67348. sqlite3_context *pCtx,
  67349. const void *z,
  67350. int n,
  67351. void (*xDel)(void *)
  67352. ){
  67353. assert( n>=0 );
  67354. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67355. setResultStrOrError(pCtx, z, n, 0, xDel);
  67356. }
  67357. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
  67358. sqlite3_context *pCtx,
  67359. const void *z,
  67360. sqlite3_uint64 n,
  67361. void (*xDel)(void *)
  67362. ){
  67363. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67364. assert( xDel!=SQLITE_DYNAMIC );
  67365. if( n>0x7fffffff ){
  67366. (void)invokeValueDestructor(z, xDel, pCtx);
  67367. }else{
  67368. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  67369. }
  67370. }
  67371. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  67372. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67373. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  67374. }
  67375. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  67376. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67377. pCtx->isError = SQLITE_ERROR;
  67378. pCtx->fErrorOrAux = 1;
  67379. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  67380. }
  67381. #ifndef SQLITE_OMIT_UTF16
  67382. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  67383. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67384. pCtx->isError = SQLITE_ERROR;
  67385. pCtx->fErrorOrAux = 1;
  67386. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  67387. }
  67388. #endif
  67389. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  67390. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67391. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  67392. }
  67393. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  67394. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67395. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  67396. }
  67397. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
  67398. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67399. sqlite3VdbeMemSetNull(pCtx->pOut);
  67400. }
  67401. SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  67402. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67403. pCtx->pOut->eSubtype = eSubtype & 0xff;
  67404. }
  67405. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
  67406. sqlite3_context *pCtx,
  67407. const char *z,
  67408. int n,
  67409. void (*xDel)(void *)
  67410. ){
  67411. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67412. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  67413. }
  67414. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
  67415. sqlite3_context *pCtx,
  67416. const char *z,
  67417. sqlite3_uint64 n,
  67418. void (*xDel)(void *),
  67419. unsigned char enc
  67420. ){
  67421. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67422. assert( xDel!=SQLITE_DYNAMIC );
  67423. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  67424. if( n>0x7fffffff ){
  67425. (void)invokeValueDestructor(z, xDel, pCtx);
  67426. }else{
  67427. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  67428. }
  67429. }
  67430. #ifndef SQLITE_OMIT_UTF16
  67431. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
  67432. sqlite3_context *pCtx,
  67433. const void *z,
  67434. int n,
  67435. void (*xDel)(void *)
  67436. ){
  67437. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67438. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  67439. }
  67440. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
  67441. sqlite3_context *pCtx,
  67442. const void *z,
  67443. int n,
  67444. void (*xDel)(void *)
  67445. ){
  67446. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67447. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  67448. }
  67449. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
  67450. sqlite3_context *pCtx,
  67451. const void *z,
  67452. int n,
  67453. void (*xDel)(void *)
  67454. ){
  67455. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67456. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  67457. }
  67458. #endif /* SQLITE_OMIT_UTF16 */
  67459. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  67460. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67461. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  67462. }
  67463. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  67464. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67465. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  67466. }
  67467. SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  67468. Mem *pOut = pCtx->pOut;
  67469. assert( sqlite3_mutex_held(pOut->db->mutex) );
  67470. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  67471. return SQLITE_TOOBIG;
  67472. }
  67473. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  67474. return SQLITE_OK;
  67475. }
  67476. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  67477. pCtx->isError = errCode;
  67478. pCtx->fErrorOrAux = 1;
  67479. #ifdef SQLITE_DEBUG
  67480. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  67481. #endif
  67482. if( pCtx->pOut->flags & MEM_Null ){
  67483. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  67484. SQLITE_UTF8, SQLITE_STATIC);
  67485. }
  67486. }
  67487. /* Force an SQLITE_TOOBIG error. */
  67488. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
  67489. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67490. pCtx->isError = SQLITE_TOOBIG;
  67491. pCtx->fErrorOrAux = 1;
  67492. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  67493. SQLITE_UTF8, SQLITE_STATIC);
  67494. }
  67495. /* An SQLITE_NOMEM error. */
  67496. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
  67497. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67498. sqlite3VdbeMemSetNull(pCtx->pOut);
  67499. pCtx->isError = SQLITE_NOMEM;
  67500. pCtx->fErrorOrAux = 1;
  67501. pCtx->pOut->db->mallocFailed = 1;
  67502. }
  67503. /*
  67504. ** This function is called after a transaction has been committed. It
  67505. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  67506. */
  67507. static int doWalCallbacks(sqlite3 *db){
  67508. int rc = SQLITE_OK;
  67509. #ifndef SQLITE_OMIT_WAL
  67510. int i;
  67511. for(i=0; i<db->nDb; i++){
  67512. Btree *pBt = db->aDb[i].pBt;
  67513. if( pBt ){
  67514. int nEntry;
  67515. sqlite3BtreeEnter(pBt);
  67516. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  67517. sqlite3BtreeLeave(pBt);
  67518. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  67519. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  67520. }
  67521. }
  67522. }
  67523. #endif
  67524. return rc;
  67525. }
  67526. /*
  67527. ** Execute the statement pStmt, either until a row of data is ready, the
  67528. ** statement is completely executed or an error occurs.
  67529. **
  67530. ** This routine implements the bulk of the logic behind the sqlite_step()
  67531. ** API. The only thing omitted is the automatic recompile if a
  67532. ** schema change has occurred. That detail is handled by the
  67533. ** outer sqlite3_step() wrapper procedure.
  67534. */
  67535. static int sqlite3Step(Vdbe *p){
  67536. sqlite3 *db;
  67537. int rc;
  67538. assert(p);
  67539. if( p->magic!=VDBE_MAGIC_RUN ){
  67540. /* We used to require that sqlite3_reset() be called before retrying
  67541. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  67542. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  67543. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  67544. ** This "automatic-reset" change is not technically an incompatibility,
  67545. ** since any application that receives an SQLITE_MISUSE is broken by
  67546. ** definition.
  67547. **
  67548. ** Nevertheless, some published applications that were originally written
  67549. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  67550. ** returns, and those were broken by the automatic-reset change. As a
  67551. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  67552. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  67553. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  67554. ** or SQLITE_BUSY error.
  67555. */
  67556. #ifdef SQLITE_OMIT_AUTORESET
  67557. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  67558. sqlite3_reset((sqlite3_stmt*)p);
  67559. }else{
  67560. return SQLITE_MISUSE_BKPT;
  67561. }
  67562. #else
  67563. sqlite3_reset((sqlite3_stmt*)p);
  67564. #endif
  67565. }
  67566. /* Check that malloc() has not failed. If it has, return early. */
  67567. db = p->db;
  67568. if( db->mallocFailed ){
  67569. p->rc = SQLITE_NOMEM;
  67570. return SQLITE_NOMEM;
  67571. }
  67572. if( p->pc<=0 && p->expired ){
  67573. p->rc = SQLITE_SCHEMA;
  67574. rc = SQLITE_ERROR;
  67575. goto end_of_step;
  67576. }
  67577. if( p->pc<0 ){
  67578. /* If there are no other statements currently running, then
  67579. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  67580. ** from interrupting a statement that has not yet started.
  67581. */
  67582. if( db->nVdbeActive==0 ){
  67583. db->u1.isInterrupted = 0;
  67584. }
  67585. assert( db->nVdbeWrite>0 || db->autoCommit==0
  67586. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  67587. );
  67588. #ifndef SQLITE_OMIT_TRACE
  67589. if( db->xProfile && !db->init.busy && p->zSql ){
  67590. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  67591. }else{
  67592. assert( p->startTime==0 );
  67593. }
  67594. #endif
  67595. db->nVdbeActive++;
  67596. if( p->readOnly==0 ) db->nVdbeWrite++;
  67597. if( p->bIsReader ) db->nVdbeRead++;
  67598. p->pc = 0;
  67599. }
  67600. #ifdef SQLITE_DEBUG
  67601. p->rcApp = SQLITE_OK;
  67602. #endif
  67603. #ifndef SQLITE_OMIT_EXPLAIN
  67604. if( p->explain ){
  67605. rc = sqlite3VdbeList(p);
  67606. }else
  67607. #endif /* SQLITE_OMIT_EXPLAIN */
  67608. {
  67609. db->nVdbeExec++;
  67610. rc = sqlite3VdbeExec(p);
  67611. db->nVdbeExec--;
  67612. }
  67613. #ifndef SQLITE_OMIT_TRACE
  67614. /* If the statement completed successfully, invoke the profile callback */
  67615. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  67616. #endif
  67617. if( rc==SQLITE_DONE ){
  67618. assert( p->rc==SQLITE_OK );
  67619. p->rc = doWalCallbacks(db);
  67620. if( p->rc!=SQLITE_OK ){
  67621. rc = SQLITE_ERROR;
  67622. }
  67623. }
  67624. db->errCode = rc;
  67625. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  67626. p->rc = SQLITE_NOMEM;
  67627. }
  67628. end_of_step:
  67629. /* At this point local variable rc holds the value that should be
  67630. ** returned if this statement was compiled using the legacy
  67631. ** sqlite3_prepare() interface. According to the docs, this can only
  67632. ** be one of the values in the first assert() below. Variable p->rc
  67633. ** contains the value that would be returned if sqlite3_finalize()
  67634. ** were called on statement p.
  67635. */
  67636. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  67637. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  67638. );
  67639. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  67640. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  67641. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  67642. ** error has occurred, then return the error code in p->rc to the
  67643. ** caller. Set the error code in the database handle to the same value.
  67644. */
  67645. rc = sqlite3VdbeTransferError(p);
  67646. }
  67647. return (rc&db->errMask);
  67648. }
  67649. /*
  67650. ** This is the top-level implementation of sqlite3_step(). Call
  67651. ** sqlite3Step() to do most of the work. If a schema error occurs,
  67652. ** call sqlite3Reprepare() and try again.
  67653. */
  67654. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
  67655. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  67656. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  67657. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  67658. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  67659. sqlite3 *db; /* The database connection */
  67660. if( vdbeSafetyNotNull(v) ){
  67661. return SQLITE_MISUSE_BKPT;
  67662. }
  67663. db = v->db;
  67664. sqlite3_mutex_enter(db->mutex);
  67665. v->doingRerun = 0;
  67666. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  67667. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  67668. int savedPc = v->pc;
  67669. rc2 = rc = sqlite3Reprepare(v);
  67670. if( rc!=SQLITE_OK) break;
  67671. sqlite3_reset(pStmt);
  67672. if( savedPc>=0 ) v->doingRerun = 1;
  67673. assert( v->expired==0 );
  67674. }
  67675. if( rc2!=SQLITE_OK ){
  67676. /* This case occurs after failing to recompile an sql statement.
  67677. ** The error message from the SQL compiler has already been loaded
  67678. ** into the database handle. This block copies the error message
  67679. ** from the database handle into the statement and sets the statement
  67680. ** program counter to 0 to ensure that when the statement is
  67681. ** finalized or reset the parser error message is available via
  67682. ** sqlite3_errmsg() and sqlite3_errcode().
  67683. */
  67684. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  67685. sqlite3DbFree(db, v->zErrMsg);
  67686. if( !db->mallocFailed ){
  67687. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  67688. v->rc = rc2;
  67689. } else {
  67690. v->zErrMsg = 0;
  67691. v->rc = rc = SQLITE_NOMEM;
  67692. }
  67693. }
  67694. rc = sqlite3ApiExit(db, rc);
  67695. sqlite3_mutex_leave(db->mutex);
  67696. return rc;
  67697. }
  67698. /*
  67699. ** Extract the user data from a sqlite3_context structure and return a
  67700. ** pointer to it.
  67701. */
  67702. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
  67703. assert( p && p->pFunc );
  67704. return p->pFunc->pUserData;
  67705. }
  67706. /*
  67707. ** Extract the user data from a sqlite3_context structure and return a
  67708. ** pointer to it.
  67709. **
  67710. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  67711. ** returns a copy of the pointer to the database connection (the 1st
  67712. ** parameter) of the sqlite3_create_function() and
  67713. ** sqlite3_create_function16() routines that originally registered the
  67714. ** application defined function.
  67715. */
  67716. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
  67717. assert( p && p->pOut );
  67718. return p->pOut->db;
  67719. }
  67720. /*
  67721. ** Return the current time for a statement. If the current time
  67722. ** is requested more than once within the same run of a single prepared
  67723. ** statement, the exact same time is returned for each invocation regardless
  67724. ** of the amount of time that elapses between invocations. In other words,
  67725. ** the time returned is always the time of the first call.
  67726. */
  67727. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  67728. int rc;
  67729. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  67730. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  67731. assert( p->pVdbe!=0 );
  67732. #else
  67733. sqlite3_int64 iTime = 0;
  67734. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  67735. #endif
  67736. if( *piTime==0 ){
  67737. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  67738. if( rc ) *piTime = 0;
  67739. }
  67740. return *piTime;
  67741. }
  67742. /*
  67743. ** The following is the implementation of an SQL function that always
  67744. ** fails with an error message stating that the function is used in the
  67745. ** wrong context. The sqlite3_overload_function() API might construct
  67746. ** SQL function that use this routine so that the functions will exist
  67747. ** for name resolution but are actually overloaded by the xFindFunction
  67748. ** method of virtual tables.
  67749. */
  67750. SQLITE_PRIVATE void sqlite3InvalidFunction(
  67751. sqlite3_context *context, /* The function calling context */
  67752. int NotUsed, /* Number of arguments to the function */
  67753. sqlite3_value **NotUsed2 /* Value of each argument */
  67754. ){
  67755. const char *zName = context->pFunc->zName;
  67756. char *zErr;
  67757. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  67758. zErr = sqlite3_mprintf(
  67759. "unable to use function %s in the requested context", zName);
  67760. sqlite3_result_error(context, zErr, -1);
  67761. sqlite3_free(zErr);
  67762. }
  67763. /*
  67764. ** Create a new aggregate context for p and return a pointer to
  67765. ** its pMem->z element.
  67766. */
  67767. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  67768. Mem *pMem = p->pMem;
  67769. assert( (pMem->flags & MEM_Agg)==0 );
  67770. if( nByte<=0 ){
  67771. sqlite3VdbeMemSetNull(pMem);
  67772. pMem->z = 0;
  67773. }else{
  67774. sqlite3VdbeMemClearAndResize(pMem, nByte);
  67775. pMem->flags = MEM_Agg;
  67776. pMem->u.pDef = p->pFunc;
  67777. if( pMem->z ){
  67778. memset(pMem->z, 0, nByte);
  67779. }
  67780. }
  67781. return (void*)pMem->z;
  67782. }
  67783. /*
  67784. ** Allocate or return the aggregate context for a user function. A new
  67785. ** context is allocated on the first call. Subsequent calls return the
  67786. ** same context that was returned on prior calls.
  67787. */
  67788. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  67789. assert( p && p->pFunc && p->pFunc->xStep );
  67790. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  67791. testcase( nByte<0 );
  67792. if( (p->pMem->flags & MEM_Agg)==0 ){
  67793. return createAggContext(p, nByte);
  67794. }else{
  67795. return (void*)p->pMem->z;
  67796. }
  67797. }
  67798. /*
  67799. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  67800. ** the user-function defined by pCtx.
  67801. */
  67802. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  67803. AuxData *pAuxData;
  67804. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67805. #if SQLITE_ENABLE_STAT3_OR_STAT4
  67806. if( pCtx->pVdbe==0 ) return 0;
  67807. #else
  67808. assert( pCtx->pVdbe!=0 );
  67809. #endif
  67810. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  67811. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  67812. }
  67813. return (pAuxData ? pAuxData->pAux : 0);
  67814. }
  67815. /*
  67816. ** Set the auxiliary data pointer and delete function, for the iArg'th
  67817. ** argument to the user-function defined by pCtx. Any previous value is
  67818. ** deleted by calling the delete function specified when it was set.
  67819. */
  67820. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
  67821. sqlite3_context *pCtx,
  67822. int iArg,
  67823. void *pAux,
  67824. void (*xDelete)(void*)
  67825. ){
  67826. AuxData *pAuxData;
  67827. Vdbe *pVdbe = pCtx->pVdbe;
  67828. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  67829. if( iArg<0 ) goto failed;
  67830. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  67831. if( pVdbe==0 ) goto failed;
  67832. #else
  67833. assert( pVdbe!=0 );
  67834. #endif
  67835. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  67836. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  67837. }
  67838. if( pAuxData==0 ){
  67839. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  67840. if( !pAuxData ) goto failed;
  67841. pAuxData->iOp = pCtx->iOp;
  67842. pAuxData->iArg = iArg;
  67843. pAuxData->pNext = pVdbe->pAuxData;
  67844. pVdbe->pAuxData = pAuxData;
  67845. if( pCtx->fErrorOrAux==0 ){
  67846. pCtx->isError = 0;
  67847. pCtx->fErrorOrAux = 1;
  67848. }
  67849. }else if( pAuxData->xDelete ){
  67850. pAuxData->xDelete(pAuxData->pAux);
  67851. }
  67852. pAuxData->pAux = pAux;
  67853. pAuxData->xDelete = xDelete;
  67854. return;
  67855. failed:
  67856. if( xDelete ){
  67857. xDelete(pAux);
  67858. }
  67859. }
  67860. #ifndef SQLITE_OMIT_DEPRECATED
  67861. /*
  67862. ** Return the number of times the Step function of an aggregate has been
  67863. ** called.
  67864. **
  67865. ** This function is deprecated. Do not use it for new code. It is
  67866. ** provide only to avoid breaking legacy code. New aggregate function
  67867. ** implementations should keep their own counts within their aggregate
  67868. ** context.
  67869. */
  67870. SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
  67871. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  67872. return p->pMem->n;
  67873. }
  67874. #endif
  67875. /*
  67876. ** Return the number of columns in the result set for the statement pStmt.
  67877. */
  67878. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
  67879. Vdbe *pVm = (Vdbe *)pStmt;
  67880. return pVm ? pVm->nResColumn : 0;
  67881. }
  67882. /*
  67883. ** Return the number of values available from the current row of the
  67884. ** currently executing statement pStmt.
  67885. */
  67886. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
  67887. Vdbe *pVm = (Vdbe *)pStmt;
  67888. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  67889. return pVm->nResColumn;
  67890. }
  67891. /*
  67892. ** Return a pointer to static memory containing an SQL NULL value.
  67893. */
  67894. static const Mem *columnNullValue(void){
  67895. /* Even though the Mem structure contains an element
  67896. ** of type i64, on certain architectures (x86) with certain compiler
  67897. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  67898. ** instead of an 8-byte one. This all works fine, except that when
  67899. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  67900. ** that a Mem structure is located on an 8-byte boundary. To prevent
  67901. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  67902. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  67903. ** __attribute__((aligned(8))) macro. */
  67904. static const Mem nullMem
  67905. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  67906. __attribute__((aligned(8)))
  67907. #endif
  67908. = {
  67909. /* .u = */ {0},
  67910. /* .flags = */ (u16)MEM_Null,
  67911. /* .enc = */ (u8)0,
  67912. /* .eSubtype = */ (u8)0,
  67913. /* .n = */ (int)0,
  67914. /* .z = */ (char*)0,
  67915. /* .zMalloc = */ (char*)0,
  67916. /* .szMalloc = */ (int)0,
  67917. /* .uTemp = */ (u32)0,
  67918. /* .db = */ (sqlite3*)0,
  67919. /* .xDel = */ (void(*)(void*))0,
  67920. #ifdef SQLITE_DEBUG
  67921. /* .pScopyFrom = */ (Mem*)0,
  67922. /* .pFiller = */ (void*)0,
  67923. #endif
  67924. };
  67925. return &nullMem;
  67926. }
  67927. /*
  67928. ** Check to see if column iCol of the given statement is valid. If
  67929. ** it is, return a pointer to the Mem for the value of that column.
  67930. ** If iCol is not valid, return a pointer to a Mem which has a value
  67931. ** of NULL.
  67932. */
  67933. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  67934. Vdbe *pVm;
  67935. Mem *pOut;
  67936. pVm = (Vdbe *)pStmt;
  67937. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  67938. sqlite3_mutex_enter(pVm->db->mutex);
  67939. pOut = &pVm->pResultSet[i];
  67940. }else{
  67941. if( pVm && ALWAYS(pVm->db) ){
  67942. sqlite3_mutex_enter(pVm->db->mutex);
  67943. sqlite3Error(pVm->db, SQLITE_RANGE);
  67944. }
  67945. pOut = (Mem*)columnNullValue();
  67946. }
  67947. return pOut;
  67948. }
  67949. /*
  67950. ** This function is called after invoking an sqlite3_value_XXX function on a
  67951. ** column value (i.e. a value returned by evaluating an SQL expression in the
  67952. ** select list of a SELECT statement) that may cause a malloc() failure. If
  67953. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  67954. ** code of statement pStmt set to SQLITE_NOMEM.
  67955. **
  67956. ** Specifically, this is called from within:
  67957. **
  67958. ** sqlite3_column_int()
  67959. ** sqlite3_column_int64()
  67960. ** sqlite3_column_text()
  67961. ** sqlite3_column_text16()
  67962. ** sqlite3_column_real()
  67963. ** sqlite3_column_bytes()
  67964. ** sqlite3_column_bytes16()
  67965. ** sqiite3_column_blob()
  67966. */
  67967. static void columnMallocFailure(sqlite3_stmt *pStmt)
  67968. {
  67969. /* If malloc() failed during an encoding conversion within an
  67970. ** sqlite3_column_XXX API, then set the return code of the statement to
  67971. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  67972. ** and _finalize() will return NOMEM.
  67973. */
  67974. Vdbe *p = (Vdbe *)pStmt;
  67975. if( p ){
  67976. p->rc = sqlite3ApiExit(p->db, p->rc);
  67977. sqlite3_mutex_leave(p->db->mutex);
  67978. }
  67979. }
  67980. /**************************** sqlite3_column_ *******************************
  67981. ** The following routines are used to access elements of the current row
  67982. ** in the result set.
  67983. */
  67984. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  67985. const void *val;
  67986. val = sqlite3_value_blob( columnMem(pStmt,i) );
  67987. /* Even though there is no encoding conversion, value_blob() might
  67988. ** need to call malloc() to expand the result of a zeroblob()
  67989. ** expression.
  67990. */
  67991. columnMallocFailure(pStmt);
  67992. return val;
  67993. }
  67994. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  67995. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  67996. columnMallocFailure(pStmt);
  67997. return val;
  67998. }
  67999. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  68000. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  68001. columnMallocFailure(pStmt);
  68002. return val;
  68003. }
  68004. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  68005. double val = sqlite3_value_double( columnMem(pStmt,i) );
  68006. columnMallocFailure(pStmt);
  68007. return val;
  68008. }
  68009. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  68010. int val = sqlite3_value_int( columnMem(pStmt,i) );
  68011. columnMallocFailure(pStmt);
  68012. return val;
  68013. }
  68014. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  68015. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  68016. columnMallocFailure(pStmt);
  68017. return val;
  68018. }
  68019. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  68020. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  68021. columnMallocFailure(pStmt);
  68022. return val;
  68023. }
  68024. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  68025. Mem *pOut = columnMem(pStmt, i);
  68026. if( pOut->flags&MEM_Static ){
  68027. pOut->flags &= ~MEM_Static;
  68028. pOut->flags |= MEM_Ephem;
  68029. }
  68030. columnMallocFailure(pStmt);
  68031. return (sqlite3_value *)pOut;
  68032. }
  68033. #ifndef SQLITE_OMIT_UTF16
  68034. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  68035. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  68036. columnMallocFailure(pStmt);
  68037. return val;
  68038. }
  68039. #endif /* SQLITE_OMIT_UTF16 */
  68040. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  68041. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  68042. columnMallocFailure(pStmt);
  68043. return iType;
  68044. }
  68045. /*
  68046. ** Convert the N-th element of pStmt->pColName[] into a string using
  68047. ** xFunc() then return that string. If N is out of range, return 0.
  68048. **
  68049. ** There are up to 5 names for each column. useType determines which
  68050. ** name is returned. Here are the names:
  68051. **
  68052. ** 0 The column name as it should be displayed for output
  68053. ** 1 The datatype name for the column
  68054. ** 2 The name of the database that the column derives from
  68055. ** 3 The name of the table that the column derives from
  68056. ** 4 The name of the table column that the result column derives from
  68057. **
  68058. ** If the result is not a simple column reference (if it is an expression
  68059. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  68060. */
  68061. static const void *columnName(
  68062. sqlite3_stmt *pStmt,
  68063. int N,
  68064. const void *(*xFunc)(Mem*),
  68065. int useType
  68066. ){
  68067. const void *ret;
  68068. Vdbe *p;
  68069. int n;
  68070. sqlite3 *db;
  68071. #ifdef SQLITE_ENABLE_API_ARMOR
  68072. if( pStmt==0 ){
  68073. (void)SQLITE_MISUSE_BKPT;
  68074. return 0;
  68075. }
  68076. #endif
  68077. ret = 0;
  68078. p = (Vdbe *)pStmt;
  68079. db = p->db;
  68080. assert( db!=0 );
  68081. n = sqlite3_column_count(pStmt);
  68082. if( N<n && N>=0 ){
  68083. N += useType*n;
  68084. sqlite3_mutex_enter(db->mutex);
  68085. assert( db->mallocFailed==0 );
  68086. ret = xFunc(&p->aColName[N]);
  68087. /* A malloc may have failed inside of the xFunc() call. If this
  68088. ** is the case, clear the mallocFailed flag and return NULL.
  68089. */
  68090. if( db->mallocFailed ){
  68091. db->mallocFailed = 0;
  68092. ret = 0;
  68093. }
  68094. sqlite3_mutex_leave(db->mutex);
  68095. }
  68096. return ret;
  68097. }
  68098. /*
  68099. ** Return the name of the Nth column of the result set returned by SQL
  68100. ** statement pStmt.
  68101. */
  68102. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  68103. return columnName(
  68104. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  68105. }
  68106. #ifndef SQLITE_OMIT_UTF16
  68107. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  68108. return columnName(
  68109. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  68110. }
  68111. #endif
  68112. /*
  68113. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  68114. ** not define OMIT_DECLTYPE.
  68115. */
  68116. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  68117. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  68118. and SQLITE_ENABLE_COLUMN_METADATA"
  68119. #endif
  68120. #ifndef SQLITE_OMIT_DECLTYPE
  68121. /*
  68122. ** Return the column declaration type (if applicable) of the 'i'th column
  68123. ** of the result set of SQL statement pStmt.
  68124. */
  68125. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  68126. return columnName(
  68127. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  68128. }
  68129. #ifndef SQLITE_OMIT_UTF16
  68130. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  68131. return columnName(
  68132. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  68133. }
  68134. #endif /* SQLITE_OMIT_UTF16 */
  68135. #endif /* SQLITE_OMIT_DECLTYPE */
  68136. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  68137. /*
  68138. ** Return the name of the database from which a result column derives.
  68139. ** NULL is returned if the result column is an expression or constant or
  68140. ** anything else which is not an unambiguous reference to a database column.
  68141. */
  68142. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  68143. return columnName(
  68144. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  68145. }
  68146. #ifndef SQLITE_OMIT_UTF16
  68147. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  68148. return columnName(
  68149. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  68150. }
  68151. #endif /* SQLITE_OMIT_UTF16 */
  68152. /*
  68153. ** Return the name of the table from which a result column derives.
  68154. ** NULL is returned if the result column is an expression or constant or
  68155. ** anything else which is not an unambiguous reference to a database column.
  68156. */
  68157. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  68158. return columnName(
  68159. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  68160. }
  68161. #ifndef SQLITE_OMIT_UTF16
  68162. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  68163. return columnName(
  68164. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  68165. }
  68166. #endif /* SQLITE_OMIT_UTF16 */
  68167. /*
  68168. ** Return the name of the table column from which a result column derives.
  68169. ** NULL is returned if the result column is an expression or constant or
  68170. ** anything else which is not an unambiguous reference to a database column.
  68171. */
  68172. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  68173. return columnName(
  68174. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  68175. }
  68176. #ifndef SQLITE_OMIT_UTF16
  68177. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  68178. return columnName(
  68179. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  68180. }
  68181. #endif /* SQLITE_OMIT_UTF16 */
  68182. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  68183. /******************************* sqlite3_bind_ ***************************
  68184. **
  68185. ** Routines used to attach values to wildcards in a compiled SQL statement.
  68186. */
  68187. /*
  68188. ** Unbind the value bound to variable i in virtual machine p. This is the
  68189. ** the same as binding a NULL value to the column. If the "i" parameter is
  68190. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  68191. **
  68192. ** A successful evaluation of this routine acquires the mutex on p.
  68193. ** the mutex is released if any kind of error occurs.
  68194. **
  68195. ** The error code stored in database p->db is overwritten with the return
  68196. ** value in any case.
  68197. */
  68198. static int vdbeUnbind(Vdbe *p, int i){
  68199. Mem *pVar;
  68200. if( vdbeSafetyNotNull(p) ){
  68201. return SQLITE_MISUSE_BKPT;
  68202. }
  68203. sqlite3_mutex_enter(p->db->mutex);
  68204. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  68205. sqlite3Error(p->db, SQLITE_MISUSE);
  68206. sqlite3_mutex_leave(p->db->mutex);
  68207. sqlite3_log(SQLITE_MISUSE,
  68208. "bind on a busy prepared statement: [%s]", p->zSql);
  68209. return SQLITE_MISUSE_BKPT;
  68210. }
  68211. if( i<1 || i>p->nVar ){
  68212. sqlite3Error(p->db, SQLITE_RANGE);
  68213. sqlite3_mutex_leave(p->db->mutex);
  68214. return SQLITE_RANGE;
  68215. }
  68216. i--;
  68217. pVar = &p->aVar[i];
  68218. sqlite3VdbeMemRelease(pVar);
  68219. pVar->flags = MEM_Null;
  68220. sqlite3Error(p->db, SQLITE_OK);
  68221. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  68222. ** binding a new value to this variable invalidates the current query plan.
  68223. **
  68224. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  68225. ** parameter in the WHERE clause might influence the choice of query plan
  68226. ** for a statement, then the statement will be automatically recompiled,
  68227. ** as if there had been a schema change, on the first sqlite3_step() call
  68228. ** following any change to the bindings of that parameter.
  68229. */
  68230. if( p->isPrepareV2 &&
  68231. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  68232. ){
  68233. p->expired = 1;
  68234. }
  68235. return SQLITE_OK;
  68236. }
  68237. /*
  68238. ** Bind a text or BLOB value.
  68239. */
  68240. static int bindText(
  68241. sqlite3_stmt *pStmt, /* The statement to bind against */
  68242. int i, /* Index of the parameter to bind */
  68243. const void *zData, /* Pointer to the data to be bound */
  68244. int nData, /* Number of bytes of data to be bound */
  68245. void (*xDel)(void*), /* Destructor for the data */
  68246. u8 encoding /* Encoding for the data */
  68247. ){
  68248. Vdbe *p = (Vdbe *)pStmt;
  68249. Mem *pVar;
  68250. int rc;
  68251. rc = vdbeUnbind(p, i);
  68252. if( rc==SQLITE_OK ){
  68253. if( zData!=0 ){
  68254. pVar = &p->aVar[i-1];
  68255. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  68256. if( rc==SQLITE_OK && encoding!=0 ){
  68257. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  68258. }
  68259. sqlite3Error(p->db, rc);
  68260. rc = sqlite3ApiExit(p->db, rc);
  68261. }
  68262. sqlite3_mutex_leave(p->db->mutex);
  68263. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  68264. xDel((void*)zData);
  68265. }
  68266. return rc;
  68267. }
  68268. /*
  68269. ** Bind a blob value to an SQL statement variable.
  68270. */
  68271. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
  68272. sqlite3_stmt *pStmt,
  68273. int i,
  68274. const void *zData,
  68275. int nData,
  68276. void (*xDel)(void*)
  68277. ){
  68278. return bindText(pStmt, i, zData, nData, xDel, 0);
  68279. }
  68280. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
  68281. sqlite3_stmt *pStmt,
  68282. int i,
  68283. const void *zData,
  68284. sqlite3_uint64 nData,
  68285. void (*xDel)(void*)
  68286. ){
  68287. assert( xDel!=SQLITE_DYNAMIC );
  68288. if( nData>0x7fffffff ){
  68289. return invokeValueDestructor(zData, xDel, 0);
  68290. }else{
  68291. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  68292. }
  68293. }
  68294. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  68295. int rc;
  68296. Vdbe *p = (Vdbe *)pStmt;
  68297. rc = vdbeUnbind(p, i);
  68298. if( rc==SQLITE_OK ){
  68299. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  68300. sqlite3_mutex_leave(p->db->mutex);
  68301. }
  68302. return rc;
  68303. }
  68304. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  68305. return sqlite3_bind_int64(p, i, (i64)iValue);
  68306. }
  68307. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  68308. int rc;
  68309. Vdbe *p = (Vdbe *)pStmt;
  68310. rc = vdbeUnbind(p, i);
  68311. if( rc==SQLITE_OK ){
  68312. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  68313. sqlite3_mutex_leave(p->db->mutex);
  68314. }
  68315. return rc;
  68316. }
  68317. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  68318. int rc;
  68319. Vdbe *p = (Vdbe*)pStmt;
  68320. rc = vdbeUnbind(p, i);
  68321. if( rc==SQLITE_OK ){
  68322. sqlite3_mutex_leave(p->db->mutex);
  68323. }
  68324. return rc;
  68325. }
  68326. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
  68327. sqlite3_stmt *pStmt,
  68328. int i,
  68329. const char *zData,
  68330. int nData,
  68331. void (*xDel)(void*)
  68332. ){
  68333. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  68334. }
  68335. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
  68336. sqlite3_stmt *pStmt,
  68337. int i,
  68338. const char *zData,
  68339. sqlite3_uint64 nData,
  68340. void (*xDel)(void*),
  68341. unsigned char enc
  68342. ){
  68343. assert( xDel!=SQLITE_DYNAMIC );
  68344. if( nData>0x7fffffff ){
  68345. return invokeValueDestructor(zData, xDel, 0);
  68346. }else{
  68347. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  68348. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  68349. }
  68350. }
  68351. #ifndef SQLITE_OMIT_UTF16
  68352. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
  68353. sqlite3_stmt *pStmt,
  68354. int i,
  68355. const void *zData,
  68356. int nData,
  68357. void (*xDel)(void*)
  68358. ){
  68359. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  68360. }
  68361. #endif /* SQLITE_OMIT_UTF16 */
  68362. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  68363. int rc;
  68364. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  68365. case SQLITE_INTEGER: {
  68366. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  68367. break;
  68368. }
  68369. case SQLITE_FLOAT: {
  68370. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  68371. break;
  68372. }
  68373. case SQLITE_BLOB: {
  68374. if( pValue->flags & MEM_Zero ){
  68375. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  68376. }else{
  68377. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  68378. }
  68379. break;
  68380. }
  68381. case SQLITE_TEXT: {
  68382. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  68383. pValue->enc);
  68384. break;
  68385. }
  68386. default: {
  68387. rc = sqlite3_bind_null(pStmt, i);
  68388. break;
  68389. }
  68390. }
  68391. return rc;
  68392. }
  68393. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  68394. int rc;
  68395. Vdbe *p = (Vdbe *)pStmt;
  68396. rc = vdbeUnbind(p, i);
  68397. if( rc==SQLITE_OK ){
  68398. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  68399. sqlite3_mutex_leave(p->db->mutex);
  68400. }
  68401. return rc;
  68402. }
  68403. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  68404. int rc;
  68405. Vdbe *p = (Vdbe *)pStmt;
  68406. sqlite3_mutex_enter(p->db->mutex);
  68407. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68408. rc = SQLITE_TOOBIG;
  68409. }else{
  68410. assert( (n & 0x7FFFFFFF)==n );
  68411. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  68412. }
  68413. rc = sqlite3ApiExit(p->db, rc);
  68414. sqlite3_mutex_leave(p->db->mutex);
  68415. return rc;
  68416. }
  68417. /*
  68418. ** Return the number of wildcards that can be potentially bound to.
  68419. ** This routine is added to support DBD::SQLite.
  68420. */
  68421. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  68422. Vdbe *p = (Vdbe*)pStmt;
  68423. return p ? p->nVar : 0;
  68424. }
  68425. /*
  68426. ** Return the name of a wildcard parameter. Return NULL if the index
  68427. ** is out of range or if the wildcard is unnamed.
  68428. **
  68429. ** The result is always UTF-8.
  68430. */
  68431. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  68432. Vdbe *p = (Vdbe*)pStmt;
  68433. if( p==0 || i<1 || i>p->nzVar ){
  68434. return 0;
  68435. }
  68436. return p->azVar[i-1];
  68437. }
  68438. /*
  68439. ** Given a wildcard parameter name, return the index of the variable
  68440. ** with that name. If there is no variable with the given name,
  68441. ** return 0.
  68442. */
  68443. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  68444. int i;
  68445. if( p==0 ){
  68446. return 0;
  68447. }
  68448. if( zName ){
  68449. for(i=0; i<p->nzVar; i++){
  68450. const char *z = p->azVar[i];
  68451. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  68452. return i+1;
  68453. }
  68454. }
  68455. }
  68456. return 0;
  68457. }
  68458. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  68459. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  68460. }
  68461. /*
  68462. ** Transfer all bindings from the first statement over to the second.
  68463. */
  68464. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  68465. Vdbe *pFrom = (Vdbe*)pFromStmt;
  68466. Vdbe *pTo = (Vdbe*)pToStmt;
  68467. int i;
  68468. assert( pTo->db==pFrom->db );
  68469. assert( pTo->nVar==pFrom->nVar );
  68470. sqlite3_mutex_enter(pTo->db->mutex);
  68471. for(i=0; i<pFrom->nVar; i++){
  68472. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  68473. }
  68474. sqlite3_mutex_leave(pTo->db->mutex);
  68475. return SQLITE_OK;
  68476. }
  68477. #ifndef SQLITE_OMIT_DEPRECATED
  68478. /*
  68479. ** Deprecated external interface. Internal/core SQLite code
  68480. ** should call sqlite3TransferBindings.
  68481. **
  68482. ** It is misuse to call this routine with statements from different
  68483. ** database connections. But as this is a deprecated interface, we
  68484. ** will not bother to check for that condition.
  68485. **
  68486. ** If the two statements contain a different number of bindings, then
  68487. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  68488. ** SQLITE_OK is returned.
  68489. */
  68490. SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  68491. Vdbe *pFrom = (Vdbe*)pFromStmt;
  68492. Vdbe *pTo = (Vdbe*)pToStmt;
  68493. if( pFrom->nVar!=pTo->nVar ){
  68494. return SQLITE_ERROR;
  68495. }
  68496. if( pTo->isPrepareV2 && pTo->expmask ){
  68497. pTo->expired = 1;
  68498. }
  68499. if( pFrom->isPrepareV2 && pFrom->expmask ){
  68500. pFrom->expired = 1;
  68501. }
  68502. return sqlite3TransferBindings(pFromStmt, pToStmt);
  68503. }
  68504. #endif
  68505. /*
  68506. ** Return the sqlite3* database handle to which the prepared statement given
  68507. ** in the argument belongs. This is the same database handle that was
  68508. ** the first argument to the sqlite3_prepare() that was used to create
  68509. ** the statement in the first place.
  68510. */
  68511. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
  68512. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  68513. }
  68514. /*
  68515. ** Return true if the prepared statement is guaranteed to not modify the
  68516. ** database.
  68517. */
  68518. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  68519. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  68520. }
  68521. /*
  68522. ** Return true if the prepared statement is in need of being reset.
  68523. */
  68524. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  68525. Vdbe *v = (Vdbe*)pStmt;
  68526. return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
  68527. }
  68528. /*
  68529. ** Return a pointer to the next prepared statement after pStmt associated
  68530. ** with database connection pDb. If pStmt is NULL, return the first
  68531. ** prepared statement for the database connection. Return NULL if there
  68532. ** are no more.
  68533. */
  68534. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  68535. sqlite3_stmt *pNext;
  68536. #ifdef SQLITE_ENABLE_API_ARMOR
  68537. if( !sqlite3SafetyCheckOk(pDb) ){
  68538. (void)SQLITE_MISUSE_BKPT;
  68539. return 0;
  68540. }
  68541. #endif
  68542. sqlite3_mutex_enter(pDb->mutex);
  68543. if( pStmt==0 ){
  68544. pNext = (sqlite3_stmt*)pDb->pVdbe;
  68545. }else{
  68546. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  68547. }
  68548. sqlite3_mutex_leave(pDb->mutex);
  68549. return pNext;
  68550. }
  68551. /*
  68552. ** Return the value of a status counter for a prepared statement
  68553. */
  68554. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  68555. Vdbe *pVdbe = (Vdbe*)pStmt;
  68556. u32 v;
  68557. #ifdef SQLITE_ENABLE_API_ARMOR
  68558. if( !pStmt ){
  68559. (void)SQLITE_MISUSE_BKPT;
  68560. return 0;
  68561. }
  68562. #endif
  68563. v = pVdbe->aCounter[op];
  68564. if( resetFlag ) pVdbe->aCounter[op] = 0;
  68565. return (int)v;
  68566. }
  68567. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  68568. /*
  68569. ** Return status data for a single loop within query pStmt.
  68570. */
  68571. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  68572. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  68573. int idx, /* Index of loop to report on */
  68574. int iScanStatusOp, /* Which metric to return */
  68575. void *pOut /* OUT: Write the answer here */
  68576. ){
  68577. Vdbe *p = (Vdbe*)pStmt;
  68578. ScanStatus *pScan;
  68579. if( idx<0 || idx>=p->nScan ) return 1;
  68580. pScan = &p->aScan[idx];
  68581. switch( iScanStatusOp ){
  68582. case SQLITE_SCANSTAT_NLOOP: {
  68583. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  68584. break;
  68585. }
  68586. case SQLITE_SCANSTAT_NVISIT: {
  68587. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  68588. break;
  68589. }
  68590. case SQLITE_SCANSTAT_EST: {
  68591. double r = 1.0;
  68592. LogEst x = pScan->nEst;
  68593. while( x<100 ){
  68594. x += 10;
  68595. r *= 0.5;
  68596. }
  68597. *(double*)pOut = r*sqlite3LogEstToInt(x);
  68598. break;
  68599. }
  68600. case SQLITE_SCANSTAT_NAME: {
  68601. *(const char**)pOut = pScan->zName;
  68602. break;
  68603. }
  68604. case SQLITE_SCANSTAT_EXPLAIN: {
  68605. if( pScan->addrExplain ){
  68606. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  68607. }else{
  68608. *(const char**)pOut = 0;
  68609. }
  68610. break;
  68611. }
  68612. case SQLITE_SCANSTAT_SELECTID: {
  68613. if( pScan->addrExplain ){
  68614. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  68615. }else{
  68616. *(int*)pOut = -1;
  68617. }
  68618. break;
  68619. }
  68620. default: {
  68621. return 1;
  68622. }
  68623. }
  68624. return 0;
  68625. }
  68626. /*
  68627. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  68628. */
  68629. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  68630. Vdbe *p = (Vdbe*)pStmt;
  68631. memset(p->anExec, 0, p->nOp * sizeof(i64));
  68632. }
  68633. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  68634. /************** End of vdbeapi.c *********************************************/
  68635. /************** Begin file vdbetrace.c ***************************************/
  68636. /*
  68637. ** 2009 November 25
  68638. **
  68639. ** The author disclaims copyright to this source code. In place of
  68640. ** a legal notice, here is a blessing:
  68641. **
  68642. ** May you do good and not evil.
  68643. ** May you find forgiveness for yourself and forgive others.
  68644. ** May you share freely, never taking more than you give.
  68645. **
  68646. *************************************************************************
  68647. **
  68648. ** This file contains code used to insert the values of host parameters
  68649. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  68650. **
  68651. ** The Vdbe parse-tree explainer is also found here.
  68652. */
  68653. /* #include "sqliteInt.h" */
  68654. /* #include "vdbeInt.h" */
  68655. #ifndef SQLITE_OMIT_TRACE
  68656. /*
  68657. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  68658. ** bytes in this text up to but excluding the first character in
  68659. ** a host parameter. If the text contains no host parameters, return
  68660. ** the total number of bytes in the text.
  68661. */
  68662. static int findNextHostParameter(const char *zSql, int *pnToken){
  68663. int tokenType;
  68664. int nTotal = 0;
  68665. int n;
  68666. *pnToken = 0;
  68667. while( zSql[0] ){
  68668. n = sqlite3GetToken((u8*)zSql, &tokenType);
  68669. assert( n>0 && tokenType!=TK_ILLEGAL );
  68670. if( tokenType==TK_VARIABLE ){
  68671. *pnToken = n;
  68672. break;
  68673. }
  68674. nTotal += n;
  68675. zSql += n;
  68676. }
  68677. return nTotal;
  68678. }
  68679. /*
  68680. ** This function returns a pointer to a nul-terminated string in memory
  68681. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  68682. ** string contains a copy of zRawSql but with host parameters expanded to
  68683. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  68684. ** then the returned string holds a copy of zRawSql with "-- " prepended
  68685. ** to each line of text.
  68686. **
  68687. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  68688. ** then long strings and blobs are truncated to that many bytes. This
  68689. ** can be used to prevent unreasonably large trace strings when dealing
  68690. ** with large (multi-megabyte) strings and blobs.
  68691. **
  68692. ** The calling function is responsible for making sure the memory returned
  68693. ** is eventually freed.
  68694. **
  68695. ** ALGORITHM: Scan the input string looking for host parameters in any of
  68696. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  68697. ** string literals, quoted identifier names, and comments. For text forms,
  68698. ** the host parameter index is found by scanning the prepared
  68699. ** statement for the corresponding OP_Variable opcode. Once the host
  68700. ** parameter index is known, locate the value in p->aVar[]. Then render
  68701. ** the value as a literal in place of the host parameter name.
  68702. */
  68703. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  68704. Vdbe *p, /* The prepared statement being evaluated */
  68705. const char *zRawSql /* Raw text of the SQL statement */
  68706. ){
  68707. sqlite3 *db; /* The database connection */
  68708. int idx = 0; /* Index of a host parameter */
  68709. int nextIndex = 1; /* Index of next ? host parameter */
  68710. int n; /* Length of a token prefix */
  68711. int nToken; /* Length of the parameter token */
  68712. int i; /* Loop counter */
  68713. Mem *pVar; /* Value of a host parameter */
  68714. StrAccum out; /* Accumulate the output here */
  68715. char zBase[100]; /* Initial working space */
  68716. db = p->db;
  68717. sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
  68718. db->aLimit[SQLITE_LIMIT_LENGTH]);
  68719. if( db->nVdbeExec>1 ){
  68720. while( *zRawSql ){
  68721. const char *zStart = zRawSql;
  68722. while( *(zRawSql++)!='\n' && *zRawSql );
  68723. sqlite3StrAccumAppend(&out, "-- ", 3);
  68724. assert( (zRawSql - zStart) > 0 );
  68725. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  68726. }
  68727. }else if( p->nVar==0 ){
  68728. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  68729. }else{
  68730. while( zRawSql[0] ){
  68731. n = findNextHostParameter(zRawSql, &nToken);
  68732. assert( n>0 );
  68733. sqlite3StrAccumAppend(&out, zRawSql, n);
  68734. zRawSql += n;
  68735. assert( zRawSql[0] || nToken==0 );
  68736. if( nToken==0 ) break;
  68737. if( zRawSql[0]=='?' ){
  68738. if( nToken>1 ){
  68739. assert( sqlite3Isdigit(zRawSql[1]) );
  68740. sqlite3GetInt32(&zRawSql[1], &idx);
  68741. }else{
  68742. idx = nextIndex;
  68743. }
  68744. }else{
  68745. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  68746. zRawSql[0]=='@' || zRawSql[0]=='#' );
  68747. testcase( zRawSql[0]==':' );
  68748. testcase( zRawSql[0]=='$' );
  68749. testcase( zRawSql[0]=='@' );
  68750. testcase( zRawSql[0]=='#' );
  68751. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  68752. assert( idx>0 );
  68753. }
  68754. zRawSql += nToken;
  68755. nextIndex = idx + 1;
  68756. assert( idx>0 && idx<=p->nVar );
  68757. pVar = &p->aVar[idx-1];
  68758. if( pVar->flags & MEM_Null ){
  68759. sqlite3StrAccumAppend(&out, "NULL", 4);
  68760. }else if( pVar->flags & MEM_Int ){
  68761. sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
  68762. }else if( pVar->flags & MEM_Real ){
  68763. sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
  68764. }else if( pVar->flags & MEM_Str ){
  68765. int nOut; /* Number of bytes of the string text to include in output */
  68766. #ifndef SQLITE_OMIT_UTF16
  68767. u8 enc = ENC(db);
  68768. Mem utf8;
  68769. if( enc!=SQLITE_UTF8 ){
  68770. memset(&utf8, 0, sizeof(utf8));
  68771. utf8.db = db;
  68772. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  68773. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  68774. pVar = &utf8;
  68775. }
  68776. #endif
  68777. nOut = pVar->n;
  68778. #ifdef SQLITE_TRACE_SIZE_LIMIT
  68779. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  68780. nOut = SQLITE_TRACE_SIZE_LIMIT;
  68781. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  68782. }
  68783. #endif
  68784. sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
  68785. #ifdef SQLITE_TRACE_SIZE_LIMIT
  68786. if( nOut<pVar->n ){
  68787. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  68788. }
  68789. #endif
  68790. #ifndef SQLITE_OMIT_UTF16
  68791. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  68792. #endif
  68793. }else if( pVar->flags & MEM_Zero ){
  68794. sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
  68795. }else{
  68796. int nOut; /* Number of bytes of the blob to include in output */
  68797. assert( pVar->flags & MEM_Blob );
  68798. sqlite3StrAccumAppend(&out, "x'", 2);
  68799. nOut = pVar->n;
  68800. #ifdef SQLITE_TRACE_SIZE_LIMIT
  68801. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  68802. #endif
  68803. for(i=0; i<nOut; i++){
  68804. sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
  68805. }
  68806. sqlite3StrAccumAppend(&out, "'", 1);
  68807. #ifdef SQLITE_TRACE_SIZE_LIMIT
  68808. if( nOut<pVar->n ){
  68809. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  68810. }
  68811. #endif
  68812. }
  68813. }
  68814. }
  68815. return sqlite3StrAccumFinish(&out);
  68816. }
  68817. #endif /* #ifndef SQLITE_OMIT_TRACE */
  68818. /************** End of vdbetrace.c *******************************************/
  68819. /************** Begin file vdbe.c ********************************************/
  68820. /*
  68821. ** 2001 September 15
  68822. **
  68823. ** The author disclaims copyright to this source code. In place of
  68824. ** a legal notice, here is a blessing:
  68825. **
  68826. ** May you do good and not evil.
  68827. ** May you find forgiveness for yourself and forgive others.
  68828. ** May you share freely, never taking more than you give.
  68829. **
  68830. *************************************************************************
  68831. ** The code in this file implements the function that runs the
  68832. ** bytecode of a prepared statement.
  68833. **
  68834. ** Various scripts scan this source file in order to generate HTML
  68835. ** documentation, headers files, or other derived files. The formatting
  68836. ** of the code in this file is, therefore, important. See other comments
  68837. ** in this file for details. If in doubt, do not deviate from existing
  68838. ** commenting and indentation practices when changing or adding code.
  68839. */
  68840. /* #include "sqliteInt.h" */
  68841. /* #include "vdbeInt.h" */
  68842. /*
  68843. ** Invoke this macro on memory cells just prior to changing the
  68844. ** value of the cell. This macro verifies that shallow copies are
  68845. ** not misused. A shallow copy of a string or blob just copies a
  68846. ** pointer to the string or blob, not the content. If the original
  68847. ** is changed while the copy is still in use, the string or blob might
  68848. ** be changed out from under the copy. This macro verifies that nothing
  68849. ** like that ever happens.
  68850. */
  68851. #ifdef SQLITE_DEBUG
  68852. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  68853. #else
  68854. # define memAboutToChange(P,M)
  68855. #endif
  68856. /*
  68857. ** The following global variable is incremented every time a cursor
  68858. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  68859. ** procedures use this information to make sure that indices are
  68860. ** working correctly. This variable has no function other than to
  68861. ** help verify the correct operation of the library.
  68862. */
  68863. #ifdef SQLITE_TEST
  68864. SQLITE_API int sqlite3_search_count = 0;
  68865. #endif
  68866. /*
  68867. ** When this global variable is positive, it gets decremented once before
  68868. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  68869. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  68870. **
  68871. ** This facility is used for testing purposes only. It does not function
  68872. ** in an ordinary build.
  68873. */
  68874. #ifdef SQLITE_TEST
  68875. SQLITE_API int sqlite3_interrupt_count = 0;
  68876. #endif
  68877. /*
  68878. ** The next global variable is incremented each type the OP_Sort opcode
  68879. ** is executed. The test procedures use this information to make sure that
  68880. ** sorting is occurring or not occurring at appropriate times. This variable
  68881. ** has no function other than to help verify the correct operation of the
  68882. ** library.
  68883. */
  68884. #ifdef SQLITE_TEST
  68885. SQLITE_API int sqlite3_sort_count = 0;
  68886. #endif
  68887. /*
  68888. ** The next global variable records the size of the largest MEM_Blob
  68889. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  68890. ** use this information to make sure that the zero-blob functionality
  68891. ** is working correctly. This variable has no function other than to
  68892. ** help verify the correct operation of the library.
  68893. */
  68894. #ifdef SQLITE_TEST
  68895. SQLITE_API int sqlite3_max_blobsize = 0;
  68896. static void updateMaxBlobsize(Mem *p){
  68897. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  68898. sqlite3_max_blobsize = p->n;
  68899. }
  68900. }
  68901. #endif
  68902. /*
  68903. ** The next global variable is incremented each time the OP_Found opcode
  68904. ** is executed. This is used to test whether or not the foreign key
  68905. ** operation implemented using OP_FkIsZero is working. This variable
  68906. ** has no function other than to help verify the correct operation of the
  68907. ** library.
  68908. */
  68909. #ifdef SQLITE_TEST
  68910. SQLITE_API int sqlite3_found_count = 0;
  68911. #endif
  68912. /*
  68913. ** Test a register to see if it exceeds the current maximum blob size.
  68914. ** If it does, record the new maximum blob size.
  68915. */
  68916. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  68917. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  68918. #else
  68919. # define UPDATE_MAX_BLOBSIZE(P)
  68920. #endif
  68921. /*
  68922. ** Invoke the VDBE coverage callback, if that callback is defined. This
  68923. ** feature is used for test suite validation only and does not appear an
  68924. ** production builds.
  68925. **
  68926. ** M is an integer, 2 or 3, that indices how many different ways the
  68927. ** branch can go. It is usually 2. "I" is the direction the branch
  68928. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  68929. ** second alternative branch is taken.
  68930. **
  68931. ** iSrcLine is the source code line (from the __LINE__ macro) that
  68932. ** generated the VDBE instruction. This instrumentation assumes that all
  68933. ** source code is in a single file (the amalgamation). Special values 1
  68934. ** and 2 for the iSrcLine parameter mean that this particular branch is
  68935. ** always taken or never taken, respectively.
  68936. */
  68937. #if !defined(SQLITE_VDBE_COVERAGE)
  68938. # define VdbeBranchTaken(I,M)
  68939. #else
  68940. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  68941. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  68942. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  68943. M = iSrcLine;
  68944. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  68945. ** VdbeCoverageNeverTaken() */
  68946. assert( (M & I)==I );
  68947. }else{
  68948. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  68949. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  68950. iSrcLine,I,M);
  68951. }
  68952. }
  68953. #endif
  68954. /*
  68955. ** Convert the given register into a string if it isn't one
  68956. ** already. Return non-zero if a malloc() fails.
  68957. */
  68958. #define Stringify(P, enc) \
  68959. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  68960. { goto no_mem; }
  68961. /*
  68962. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  68963. ** a pointer to a dynamically allocated string where some other entity
  68964. ** is responsible for deallocating that string. Because the register
  68965. ** does not control the string, it might be deleted without the register
  68966. ** knowing it.
  68967. **
  68968. ** This routine converts an ephemeral string into a dynamically allocated
  68969. ** string that the register itself controls. In other words, it
  68970. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  68971. */
  68972. #define Deephemeralize(P) \
  68973. if( ((P)->flags&MEM_Ephem)!=0 \
  68974. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  68975. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  68976. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  68977. /*
  68978. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  68979. ** if we run out of memory.
  68980. */
  68981. static VdbeCursor *allocateCursor(
  68982. Vdbe *p, /* The virtual machine */
  68983. int iCur, /* Index of the new VdbeCursor */
  68984. int nField, /* Number of fields in the table or index */
  68985. int iDb, /* Database the cursor belongs to, or -1 */
  68986. u8 eCurType /* Type of the new cursor */
  68987. ){
  68988. /* Find the memory cell that will be used to store the blob of memory
  68989. ** required for this VdbeCursor structure. It is convenient to use a
  68990. ** vdbe memory cell to manage the memory allocation required for a
  68991. ** VdbeCursor structure for the following reasons:
  68992. **
  68993. ** * Sometimes cursor numbers are used for a couple of different
  68994. ** purposes in a vdbe program. The different uses might require
  68995. ** different sized allocations. Memory cells provide growable
  68996. ** allocations.
  68997. **
  68998. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  68999. ** be freed lazily via the sqlite3_release_memory() API. This
  69000. ** minimizes the number of malloc calls made by the system.
  69001. **
  69002. ** Memory cells for cursors are allocated at the top of the address
  69003. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  69004. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  69005. */
  69006. Mem *pMem = &p->aMem[p->nMem-iCur];
  69007. int nByte;
  69008. VdbeCursor *pCx = 0;
  69009. nByte =
  69010. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  69011. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  69012. assert( iCur<p->nCursor );
  69013. if( p->apCsr[iCur] ){
  69014. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  69015. p->apCsr[iCur] = 0;
  69016. }
  69017. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  69018. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  69019. memset(pCx, 0, sizeof(VdbeCursor));
  69020. pCx->eCurType = eCurType;
  69021. pCx->iDb = iDb;
  69022. pCx->nField = nField;
  69023. pCx->aOffset = &pCx->aType[nField];
  69024. if( eCurType==CURTYPE_BTREE ){
  69025. pCx->uc.pCursor = (BtCursor*)
  69026. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  69027. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  69028. }
  69029. }
  69030. return pCx;
  69031. }
  69032. /*
  69033. ** Try to convert a value into a numeric representation if we can
  69034. ** do so without loss of information. In other words, if the string
  69035. ** looks like a number, convert it into a number. If it does not
  69036. ** look like a number, leave it alone.
  69037. **
  69038. ** If the bTryForInt flag is true, then extra effort is made to give
  69039. ** an integer representation. Strings that look like floating point
  69040. ** values but which have no fractional component (example: '48.00')
  69041. ** will have a MEM_Int representation when bTryForInt is true.
  69042. **
  69043. ** If bTryForInt is false, then if the input string contains a decimal
  69044. ** point or exponential notation, the result is only MEM_Real, even
  69045. ** if there is an exact integer representation of the quantity.
  69046. */
  69047. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  69048. double rValue;
  69049. i64 iValue;
  69050. u8 enc = pRec->enc;
  69051. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  69052. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  69053. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  69054. pRec->u.i = iValue;
  69055. pRec->flags |= MEM_Int;
  69056. }else{
  69057. pRec->u.r = rValue;
  69058. pRec->flags |= MEM_Real;
  69059. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  69060. }
  69061. }
  69062. /*
  69063. ** Processing is determine by the affinity parameter:
  69064. **
  69065. ** SQLITE_AFF_INTEGER:
  69066. ** SQLITE_AFF_REAL:
  69067. ** SQLITE_AFF_NUMERIC:
  69068. ** Try to convert pRec to an integer representation or a
  69069. ** floating-point representation if an integer representation
  69070. ** is not possible. Note that the integer representation is
  69071. ** always preferred, even if the affinity is REAL, because
  69072. ** an integer representation is more space efficient on disk.
  69073. **
  69074. ** SQLITE_AFF_TEXT:
  69075. ** Convert pRec to a text representation.
  69076. **
  69077. ** SQLITE_AFF_BLOB:
  69078. ** No-op. pRec is unchanged.
  69079. */
  69080. static void applyAffinity(
  69081. Mem *pRec, /* The value to apply affinity to */
  69082. char affinity, /* The affinity to be applied */
  69083. u8 enc /* Use this text encoding */
  69084. ){
  69085. if( affinity>=SQLITE_AFF_NUMERIC ){
  69086. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  69087. || affinity==SQLITE_AFF_NUMERIC );
  69088. if( (pRec->flags & MEM_Int)==0 ){
  69089. if( (pRec->flags & MEM_Real)==0 ){
  69090. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  69091. }else{
  69092. sqlite3VdbeIntegerAffinity(pRec);
  69093. }
  69094. }
  69095. }else if( affinity==SQLITE_AFF_TEXT ){
  69096. /* Only attempt the conversion to TEXT if there is an integer or real
  69097. ** representation (blob and NULL do not get converted) but no string
  69098. ** representation.
  69099. */
  69100. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  69101. sqlite3VdbeMemStringify(pRec, enc, 1);
  69102. }
  69103. pRec->flags &= ~(MEM_Real|MEM_Int);
  69104. }
  69105. }
  69106. /*
  69107. ** Try to convert the type of a function argument or a result column
  69108. ** into a numeric representation. Use either INTEGER or REAL whichever
  69109. ** is appropriate. But only do the conversion if it is possible without
  69110. ** loss of information and return the revised type of the argument.
  69111. */
  69112. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
  69113. int eType = sqlite3_value_type(pVal);
  69114. if( eType==SQLITE_TEXT ){
  69115. Mem *pMem = (Mem*)pVal;
  69116. applyNumericAffinity(pMem, 0);
  69117. eType = sqlite3_value_type(pVal);
  69118. }
  69119. return eType;
  69120. }
  69121. /*
  69122. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  69123. ** not the internal Mem* type.
  69124. */
  69125. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  69126. sqlite3_value *pVal,
  69127. u8 affinity,
  69128. u8 enc
  69129. ){
  69130. applyAffinity((Mem *)pVal, affinity, enc);
  69131. }
  69132. /*
  69133. ** pMem currently only holds a string type (or maybe a BLOB that we can
  69134. ** interpret as a string if we want to). Compute its corresponding
  69135. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  69136. ** accordingly.
  69137. */
  69138. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  69139. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  69140. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  69141. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  69142. return 0;
  69143. }
  69144. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  69145. return MEM_Int;
  69146. }
  69147. return MEM_Real;
  69148. }
  69149. /*
  69150. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  69151. ** none.
  69152. **
  69153. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  69154. ** But it does set pMem->u.r and pMem->u.i appropriately.
  69155. */
  69156. static u16 numericType(Mem *pMem){
  69157. if( pMem->flags & (MEM_Int|MEM_Real) ){
  69158. return pMem->flags & (MEM_Int|MEM_Real);
  69159. }
  69160. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  69161. return computeNumericType(pMem);
  69162. }
  69163. return 0;
  69164. }
  69165. #ifdef SQLITE_DEBUG
  69166. /*
  69167. ** Write a nice string representation of the contents of cell pMem
  69168. ** into buffer zBuf, length nBuf.
  69169. */
  69170. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  69171. char *zCsr = zBuf;
  69172. int f = pMem->flags;
  69173. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  69174. if( f&MEM_Blob ){
  69175. int i;
  69176. char c;
  69177. if( f & MEM_Dyn ){
  69178. c = 'z';
  69179. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  69180. }else if( f & MEM_Static ){
  69181. c = 't';
  69182. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  69183. }else if( f & MEM_Ephem ){
  69184. c = 'e';
  69185. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  69186. }else{
  69187. c = 's';
  69188. }
  69189. sqlite3_snprintf(100, zCsr, "%c", c);
  69190. zCsr += sqlite3Strlen30(zCsr);
  69191. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  69192. zCsr += sqlite3Strlen30(zCsr);
  69193. for(i=0; i<16 && i<pMem->n; i++){
  69194. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  69195. zCsr += sqlite3Strlen30(zCsr);
  69196. }
  69197. for(i=0; i<16 && i<pMem->n; i++){
  69198. char z = pMem->z[i];
  69199. if( z<32 || z>126 ) *zCsr++ = '.';
  69200. else *zCsr++ = z;
  69201. }
  69202. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  69203. zCsr += sqlite3Strlen30(zCsr);
  69204. if( f & MEM_Zero ){
  69205. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  69206. zCsr += sqlite3Strlen30(zCsr);
  69207. }
  69208. *zCsr = '\0';
  69209. }else if( f & MEM_Str ){
  69210. int j, k;
  69211. zBuf[0] = ' ';
  69212. if( f & MEM_Dyn ){
  69213. zBuf[1] = 'z';
  69214. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  69215. }else if( f & MEM_Static ){
  69216. zBuf[1] = 't';
  69217. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  69218. }else if( f & MEM_Ephem ){
  69219. zBuf[1] = 'e';
  69220. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  69221. }else{
  69222. zBuf[1] = 's';
  69223. }
  69224. k = 2;
  69225. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  69226. k += sqlite3Strlen30(&zBuf[k]);
  69227. zBuf[k++] = '[';
  69228. for(j=0; j<15 && j<pMem->n; j++){
  69229. u8 c = pMem->z[j];
  69230. if( c>=0x20 && c<0x7f ){
  69231. zBuf[k++] = c;
  69232. }else{
  69233. zBuf[k++] = '.';
  69234. }
  69235. }
  69236. zBuf[k++] = ']';
  69237. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  69238. k += sqlite3Strlen30(&zBuf[k]);
  69239. zBuf[k++] = 0;
  69240. }
  69241. }
  69242. #endif
  69243. #ifdef SQLITE_DEBUG
  69244. /*
  69245. ** Print the value of a register for tracing purposes:
  69246. */
  69247. static void memTracePrint(Mem *p){
  69248. if( p->flags & MEM_Undefined ){
  69249. printf(" undefined");
  69250. }else if( p->flags & MEM_Null ){
  69251. printf(" NULL");
  69252. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  69253. printf(" si:%lld", p->u.i);
  69254. }else if( p->flags & MEM_Int ){
  69255. printf(" i:%lld", p->u.i);
  69256. #ifndef SQLITE_OMIT_FLOATING_POINT
  69257. }else if( p->flags & MEM_Real ){
  69258. printf(" r:%g", p->u.r);
  69259. #endif
  69260. }else if( p->flags & MEM_RowSet ){
  69261. printf(" (rowset)");
  69262. }else{
  69263. char zBuf[200];
  69264. sqlite3VdbeMemPrettyPrint(p, zBuf);
  69265. printf(" %s", zBuf);
  69266. }
  69267. }
  69268. static void registerTrace(int iReg, Mem *p){
  69269. printf("REG[%d] = ", iReg);
  69270. memTracePrint(p);
  69271. printf("\n");
  69272. }
  69273. #endif
  69274. #ifdef SQLITE_DEBUG
  69275. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  69276. #else
  69277. # define REGISTER_TRACE(R,M)
  69278. #endif
  69279. #ifdef VDBE_PROFILE
  69280. /*
  69281. ** hwtime.h contains inline assembler code for implementing
  69282. ** high-performance timing routines.
  69283. */
  69284. /************** Include hwtime.h in the middle of vdbe.c *********************/
  69285. /************** Begin file hwtime.h ******************************************/
  69286. /*
  69287. ** 2008 May 27
  69288. **
  69289. ** The author disclaims copyright to this source code. In place of
  69290. ** a legal notice, here is a blessing:
  69291. **
  69292. ** May you do good and not evil.
  69293. ** May you find forgiveness for yourself and forgive others.
  69294. ** May you share freely, never taking more than you give.
  69295. **
  69296. ******************************************************************************
  69297. **
  69298. ** This file contains inline asm code for retrieving "high-performance"
  69299. ** counters for x86 class CPUs.
  69300. */
  69301. #ifndef _HWTIME_H_
  69302. #define _HWTIME_H_
  69303. /*
  69304. ** The following routine only works on pentium-class (or newer) processors.
  69305. ** It uses the RDTSC opcode to read the cycle count value out of the
  69306. ** processor and returns that value. This can be used for high-res
  69307. ** profiling.
  69308. */
  69309. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  69310. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  69311. #if defined(__GNUC__)
  69312. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  69313. unsigned int lo, hi;
  69314. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  69315. return (sqlite_uint64)hi << 32 | lo;
  69316. }
  69317. #elif defined(_MSC_VER)
  69318. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  69319. __asm {
  69320. rdtsc
  69321. ret ; return value at EDX:EAX
  69322. }
  69323. }
  69324. #endif
  69325. #elif (defined(__GNUC__) && defined(__x86_64__))
  69326. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  69327. unsigned long val;
  69328. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  69329. return val;
  69330. }
  69331. #elif (defined(__GNUC__) && defined(__ppc__))
  69332. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  69333. unsigned long long retval;
  69334. unsigned long junk;
  69335. __asm__ __volatile__ ("\n\
  69336. 1: mftbu %1\n\
  69337. mftb %L0\n\
  69338. mftbu %0\n\
  69339. cmpw %0,%1\n\
  69340. bne 1b"
  69341. : "=r" (retval), "=r" (junk));
  69342. return retval;
  69343. }
  69344. #else
  69345. #error Need implementation of sqlite3Hwtime() for your platform.
  69346. /*
  69347. ** To compile without implementing sqlite3Hwtime() for your platform,
  69348. ** you can remove the above #error and use the following
  69349. ** stub function. You will lose timing support for many
  69350. ** of the debugging and testing utilities, but it should at
  69351. ** least compile and run.
  69352. */
  69353. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  69354. #endif
  69355. #endif /* !defined(_HWTIME_H_) */
  69356. /************** End of hwtime.h **********************************************/
  69357. /************** Continuing where we left off in vdbe.c ***********************/
  69358. #endif
  69359. #ifndef NDEBUG
  69360. /*
  69361. ** This function is only called from within an assert() expression. It
  69362. ** checks that the sqlite3.nTransaction variable is correctly set to
  69363. ** the number of non-transaction savepoints currently in the
  69364. ** linked list starting at sqlite3.pSavepoint.
  69365. **
  69366. ** Usage:
  69367. **
  69368. ** assert( checkSavepointCount(db) );
  69369. */
  69370. static int checkSavepointCount(sqlite3 *db){
  69371. int n = 0;
  69372. Savepoint *p;
  69373. for(p=db->pSavepoint; p; p=p->pNext) n++;
  69374. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  69375. return 1;
  69376. }
  69377. #endif
  69378. /*
  69379. ** Return the register of pOp->p2 after first preparing it to be
  69380. ** overwritten with an integer value.
  69381. */
  69382. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  69383. sqlite3VdbeMemSetNull(pOut);
  69384. pOut->flags = MEM_Int;
  69385. return pOut;
  69386. }
  69387. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  69388. Mem *pOut;
  69389. assert( pOp->p2>0 );
  69390. assert( pOp->p2<=(p->nMem-p->nCursor) );
  69391. pOut = &p->aMem[pOp->p2];
  69392. memAboutToChange(p, pOut);
  69393. if( VdbeMemDynamic(pOut) ){
  69394. return out2PrereleaseWithClear(pOut);
  69395. }else{
  69396. pOut->flags = MEM_Int;
  69397. return pOut;
  69398. }
  69399. }
  69400. /*
  69401. ** Execute as much of a VDBE program as we can.
  69402. ** This is the core of sqlite3_step().
  69403. */
  69404. SQLITE_PRIVATE int sqlite3VdbeExec(
  69405. Vdbe *p /* The VDBE */
  69406. ){
  69407. Op *aOp = p->aOp; /* Copy of p->aOp */
  69408. Op *pOp = aOp; /* Current operation */
  69409. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  69410. Op *pOrigOp; /* Value of pOp at the top of the loop */
  69411. #endif
  69412. int rc = SQLITE_OK; /* Value to return */
  69413. sqlite3 *db = p->db; /* The database */
  69414. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  69415. u8 encoding = ENC(db); /* The database encoding */
  69416. int iCompare = 0; /* Result of last OP_Compare operation */
  69417. unsigned nVmStep = 0; /* Number of virtual machine steps */
  69418. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  69419. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  69420. #endif
  69421. Mem *aMem = p->aMem; /* Copy of p->aMem */
  69422. Mem *pIn1 = 0; /* 1st input operand */
  69423. Mem *pIn2 = 0; /* 2nd input operand */
  69424. Mem *pIn3 = 0; /* 3rd input operand */
  69425. Mem *pOut = 0; /* Output operand */
  69426. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  69427. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  69428. #ifdef VDBE_PROFILE
  69429. u64 start; /* CPU clock count at start of opcode */
  69430. #endif
  69431. /*** INSERT STACK UNION HERE ***/
  69432. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  69433. sqlite3VdbeEnter(p);
  69434. if( p->rc==SQLITE_NOMEM ){
  69435. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  69436. ** sqlite3_column_text16() failed. */
  69437. goto no_mem;
  69438. }
  69439. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  69440. assert( p->bIsReader || p->readOnly!=0 );
  69441. p->rc = SQLITE_OK;
  69442. p->iCurrentTime = 0;
  69443. assert( p->explain==0 );
  69444. p->pResultSet = 0;
  69445. db->busyHandler.nBusy = 0;
  69446. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  69447. sqlite3VdbeIOTraceSql(p);
  69448. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  69449. if( db->xProgress ){
  69450. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  69451. assert( 0 < db->nProgressOps );
  69452. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  69453. }
  69454. #endif
  69455. #ifdef SQLITE_DEBUG
  69456. sqlite3BeginBenignMalloc();
  69457. if( p->pc==0
  69458. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  69459. ){
  69460. int i;
  69461. int once = 1;
  69462. sqlite3VdbePrintSql(p);
  69463. if( p->db->flags & SQLITE_VdbeListing ){
  69464. printf("VDBE Program Listing:\n");
  69465. for(i=0; i<p->nOp; i++){
  69466. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  69467. }
  69468. }
  69469. if( p->db->flags & SQLITE_VdbeEQP ){
  69470. for(i=0; i<p->nOp; i++){
  69471. if( aOp[i].opcode==OP_Explain ){
  69472. if( once ) printf("VDBE Query Plan:\n");
  69473. printf("%s\n", aOp[i].p4.z);
  69474. once = 0;
  69475. }
  69476. }
  69477. }
  69478. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  69479. }
  69480. sqlite3EndBenignMalloc();
  69481. #endif
  69482. for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
  69483. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  69484. if( db->mallocFailed ) goto no_mem;
  69485. #ifdef VDBE_PROFILE
  69486. start = sqlite3Hwtime();
  69487. #endif
  69488. nVmStep++;
  69489. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  69490. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  69491. #endif
  69492. /* Only allow tracing if SQLITE_DEBUG is defined.
  69493. */
  69494. #ifdef SQLITE_DEBUG
  69495. if( db->flags & SQLITE_VdbeTrace ){
  69496. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  69497. }
  69498. #endif
  69499. /* Check to see if we need to simulate an interrupt. This only happens
  69500. ** if we have a special test build.
  69501. */
  69502. #ifdef SQLITE_TEST
  69503. if( sqlite3_interrupt_count>0 ){
  69504. sqlite3_interrupt_count--;
  69505. if( sqlite3_interrupt_count==0 ){
  69506. sqlite3_interrupt(db);
  69507. }
  69508. }
  69509. #endif
  69510. /* Sanity checking on other operands */
  69511. #ifdef SQLITE_DEBUG
  69512. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  69513. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  69514. assert( pOp->p1>0 );
  69515. assert( pOp->p1<=(p->nMem-p->nCursor) );
  69516. assert( memIsValid(&aMem[pOp->p1]) );
  69517. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  69518. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  69519. }
  69520. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  69521. assert( pOp->p2>0 );
  69522. assert( pOp->p2<=(p->nMem-p->nCursor) );
  69523. assert( memIsValid(&aMem[pOp->p2]) );
  69524. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  69525. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  69526. }
  69527. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  69528. assert( pOp->p3>0 );
  69529. assert( pOp->p3<=(p->nMem-p->nCursor) );
  69530. assert( memIsValid(&aMem[pOp->p3]) );
  69531. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  69532. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  69533. }
  69534. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  69535. assert( pOp->p2>0 );
  69536. assert( pOp->p2<=(p->nMem-p->nCursor) );
  69537. memAboutToChange(p, &aMem[pOp->p2]);
  69538. }
  69539. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  69540. assert( pOp->p3>0 );
  69541. assert( pOp->p3<=(p->nMem-p->nCursor) );
  69542. memAboutToChange(p, &aMem[pOp->p3]);
  69543. }
  69544. #endif
  69545. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  69546. pOrigOp = pOp;
  69547. #endif
  69548. switch( pOp->opcode ){
  69549. /*****************************************************************************
  69550. ** What follows is a massive switch statement where each case implements a
  69551. ** separate instruction in the virtual machine. If we follow the usual
  69552. ** indentation conventions, each case should be indented by 6 spaces. But
  69553. ** that is a lot of wasted space on the left margin. So the code within
  69554. ** the switch statement will break with convention and be flush-left. Another
  69555. ** big comment (similar to this one) will mark the point in the code where
  69556. ** we transition back to normal indentation.
  69557. **
  69558. ** The formatting of each case is important. The makefile for SQLite
  69559. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  69560. ** file looking for lines that begin with "case OP_". The opcodes.h files
  69561. ** will be filled with #defines that give unique integer values to each
  69562. ** opcode and the opcodes.c file is filled with an array of strings where
  69563. ** each string is the symbolic name for the corresponding opcode. If the
  69564. ** case statement is followed by a comment of the form "/# same as ... #/"
  69565. ** that comment is used to determine the particular value of the opcode.
  69566. **
  69567. ** Other keywords in the comment that follows each case are used to
  69568. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  69569. ** Keywords include: in1, in2, in3, out2, out3. See
  69570. ** the mkopcodeh.awk script for additional information.
  69571. **
  69572. ** Documentation about VDBE opcodes is generated by scanning this file
  69573. ** for lines of that contain "Opcode:". That line and all subsequent
  69574. ** comment lines are used in the generation of the opcode.html documentation
  69575. ** file.
  69576. **
  69577. ** SUMMARY:
  69578. **
  69579. ** Formatting is important to scripts that scan this file.
  69580. ** Do not deviate from the formatting style currently in use.
  69581. **
  69582. *****************************************************************************/
  69583. /* Opcode: Goto * P2 * * *
  69584. **
  69585. ** An unconditional jump to address P2.
  69586. ** The next instruction executed will be
  69587. ** the one at index P2 from the beginning of
  69588. ** the program.
  69589. **
  69590. ** The P1 parameter is not actually used by this opcode. However, it
  69591. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  69592. ** that this Goto is the bottom of a loop and that the lines from P2 down
  69593. ** to the current line should be indented for EXPLAIN output.
  69594. */
  69595. case OP_Goto: { /* jump */
  69596. jump_to_p2_and_check_for_interrupt:
  69597. pOp = &aOp[pOp->p2 - 1];
  69598. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  69599. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  69600. ** completion. Check to see if sqlite3_interrupt() has been called
  69601. ** or if the progress callback needs to be invoked.
  69602. **
  69603. ** This code uses unstructured "goto" statements and does not look clean.
  69604. ** But that is not due to sloppy coding habits. The code is written this
  69605. ** way for performance, to avoid having to run the interrupt and progress
  69606. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  69607. ** faster according to "valgrind --tool=cachegrind" */
  69608. check_for_interrupt:
  69609. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  69610. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  69611. /* Call the progress callback if it is configured and the required number
  69612. ** of VDBE ops have been executed (either since this invocation of
  69613. ** sqlite3VdbeExec() or since last time the progress callback was called).
  69614. ** If the progress callback returns non-zero, exit the virtual machine with
  69615. ** a return code SQLITE_ABORT.
  69616. */
  69617. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  69618. assert( db->nProgressOps!=0 );
  69619. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  69620. if( db->xProgress(db->pProgressArg) ){
  69621. rc = SQLITE_INTERRUPT;
  69622. goto vdbe_error_halt;
  69623. }
  69624. }
  69625. #endif
  69626. break;
  69627. }
  69628. /* Opcode: Gosub P1 P2 * * *
  69629. **
  69630. ** Write the current address onto register P1
  69631. ** and then jump to address P2.
  69632. */
  69633. case OP_Gosub: { /* jump */
  69634. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  69635. pIn1 = &aMem[pOp->p1];
  69636. assert( VdbeMemDynamic(pIn1)==0 );
  69637. memAboutToChange(p, pIn1);
  69638. pIn1->flags = MEM_Int;
  69639. pIn1->u.i = (int)(pOp-aOp);
  69640. REGISTER_TRACE(pOp->p1, pIn1);
  69641. /* Most jump operations do a goto to this spot in order to update
  69642. ** the pOp pointer. */
  69643. jump_to_p2:
  69644. pOp = &aOp[pOp->p2 - 1];
  69645. break;
  69646. }
  69647. /* Opcode: Return P1 * * * *
  69648. **
  69649. ** Jump to the next instruction after the address in register P1. After
  69650. ** the jump, register P1 becomes undefined.
  69651. */
  69652. case OP_Return: { /* in1 */
  69653. pIn1 = &aMem[pOp->p1];
  69654. assert( pIn1->flags==MEM_Int );
  69655. pOp = &aOp[pIn1->u.i];
  69656. pIn1->flags = MEM_Undefined;
  69657. break;
  69658. }
  69659. /* Opcode: InitCoroutine P1 P2 P3 * *
  69660. **
  69661. ** Set up register P1 so that it will Yield to the coroutine
  69662. ** located at address P3.
  69663. **
  69664. ** If P2!=0 then the coroutine implementation immediately follows
  69665. ** this opcode. So jump over the coroutine implementation to
  69666. ** address P2.
  69667. **
  69668. ** See also: EndCoroutine
  69669. */
  69670. case OP_InitCoroutine: { /* jump */
  69671. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  69672. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  69673. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  69674. pOut = &aMem[pOp->p1];
  69675. assert( !VdbeMemDynamic(pOut) );
  69676. pOut->u.i = pOp->p3 - 1;
  69677. pOut->flags = MEM_Int;
  69678. if( pOp->p2 ) goto jump_to_p2;
  69679. break;
  69680. }
  69681. /* Opcode: EndCoroutine P1 * * * *
  69682. **
  69683. ** The instruction at the address in register P1 is a Yield.
  69684. ** Jump to the P2 parameter of that Yield.
  69685. ** After the jump, register P1 becomes undefined.
  69686. **
  69687. ** See also: InitCoroutine
  69688. */
  69689. case OP_EndCoroutine: { /* in1 */
  69690. VdbeOp *pCaller;
  69691. pIn1 = &aMem[pOp->p1];
  69692. assert( pIn1->flags==MEM_Int );
  69693. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  69694. pCaller = &aOp[pIn1->u.i];
  69695. assert( pCaller->opcode==OP_Yield );
  69696. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  69697. pOp = &aOp[pCaller->p2 - 1];
  69698. pIn1->flags = MEM_Undefined;
  69699. break;
  69700. }
  69701. /* Opcode: Yield P1 P2 * * *
  69702. **
  69703. ** Swap the program counter with the value in register P1. This
  69704. ** has the effect of yielding to a coroutine.
  69705. **
  69706. ** If the coroutine that is launched by this instruction ends with
  69707. ** Yield or Return then continue to the next instruction. But if
  69708. ** the coroutine launched by this instruction ends with
  69709. ** EndCoroutine, then jump to P2 rather than continuing with the
  69710. ** next instruction.
  69711. **
  69712. ** See also: InitCoroutine
  69713. */
  69714. case OP_Yield: { /* in1, jump */
  69715. int pcDest;
  69716. pIn1 = &aMem[pOp->p1];
  69717. assert( VdbeMemDynamic(pIn1)==0 );
  69718. pIn1->flags = MEM_Int;
  69719. pcDest = (int)pIn1->u.i;
  69720. pIn1->u.i = (int)(pOp - aOp);
  69721. REGISTER_TRACE(pOp->p1, pIn1);
  69722. pOp = &aOp[pcDest];
  69723. break;
  69724. }
  69725. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  69726. ** Synopsis: if r[P3]=null halt
  69727. **
  69728. ** Check the value in register P3. If it is NULL then Halt using
  69729. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  69730. ** value in register P3 is not NULL, then this routine is a no-op.
  69731. ** The P5 parameter should be 1.
  69732. */
  69733. case OP_HaltIfNull: { /* in3 */
  69734. pIn3 = &aMem[pOp->p3];
  69735. if( (pIn3->flags & MEM_Null)==0 ) break;
  69736. /* Fall through into OP_Halt */
  69737. }
  69738. /* Opcode: Halt P1 P2 * P4 P5
  69739. **
  69740. ** Exit immediately. All open cursors, etc are closed
  69741. ** automatically.
  69742. **
  69743. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  69744. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  69745. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  69746. ** whether or not to rollback the current transaction. Do not rollback
  69747. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  69748. ** then back out all changes that have occurred during this execution of the
  69749. ** VDBE, but do not rollback the transaction.
  69750. **
  69751. ** If P4 is not null then it is an error message string.
  69752. **
  69753. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  69754. **
  69755. ** 0: (no change)
  69756. ** 1: NOT NULL contraint failed: P4
  69757. ** 2: UNIQUE constraint failed: P4
  69758. ** 3: CHECK constraint failed: P4
  69759. ** 4: FOREIGN KEY constraint failed: P4
  69760. **
  69761. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  69762. ** omitted.
  69763. **
  69764. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  69765. ** every program. So a jump past the last instruction of the program
  69766. ** is the same as executing Halt.
  69767. */
  69768. case OP_Halt: {
  69769. const char *zType;
  69770. const char *zLogFmt;
  69771. VdbeFrame *pFrame;
  69772. int pcx;
  69773. pcx = (int)(pOp - aOp);
  69774. if( pOp->p1==SQLITE_OK && p->pFrame ){
  69775. /* Halt the sub-program. Return control to the parent frame. */
  69776. pFrame = p->pFrame;
  69777. p->pFrame = pFrame->pParent;
  69778. p->nFrame--;
  69779. sqlite3VdbeSetChanges(db, p->nChange);
  69780. pcx = sqlite3VdbeFrameRestore(pFrame);
  69781. lastRowid = db->lastRowid;
  69782. if( pOp->p2==OE_Ignore ){
  69783. /* Instruction pcx is the OP_Program that invoked the sub-program
  69784. ** currently being halted. If the p2 instruction of this OP_Halt
  69785. ** instruction is set to OE_Ignore, then the sub-program is throwing
  69786. ** an IGNORE exception. In this case jump to the address specified
  69787. ** as the p2 of the calling OP_Program. */
  69788. pcx = p->aOp[pcx].p2-1;
  69789. }
  69790. aOp = p->aOp;
  69791. aMem = p->aMem;
  69792. pOp = &aOp[pcx];
  69793. break;
  69794. }
  69795. p->rc = pOp->p1;
  69796. p->errorAction = (u8)pOp->p2;
  69797. p->pc = pcx;
  69798. if( p->rc ){
  69799. if( pOp->p5 ){
  69800. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  69801. "FOREIGN KEY" };
  69802. assert( pOp->p5>=1 && pOp->p5<=4 );
  69803. testcase( pOp->p5==1 );
  69804. testcase( pOp->p5==2 );
  69805. testcase( pOp->p5==3 );
  69806. testcase( pOp->p5==4 );
  69807. zType = azType[pOp->p5-1];
  69808. }else{
  69809. zType = 0;
  69810. }
  69811. assert( zType!=0 || pOp->p4.z!=0 );
  69812. zLogFmt = "abort at %d in [%s]: %s";
  69813. if( zType && pOp->p4.z ){
  69814. sqlite3VdbeError(p, "%s constraint failed: %s", zType, pOp->p4.z);
  69815. }else if( pOp->p4.z ){
  69816. sqlite3VdbeError(p, "%s", pOp->p4.z);
  69817. }else{
  69818. sqlite3VdbeError(p, "%s constraint failed", zType);
  69819. }
  69820. sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
  69821. }
  69822. rc = sqlite3VdbeHalt(p);
  69823. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  69824. if( rc==SQLITE_BUSY ){
  69825. p->rc = rc = SQLITE_BUSY;
  69826. }else{
  69827. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  69828. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  69829. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  69830. }
  69831. goto vdbe_return;
  69832. }
  69833. /* Opcode: Integer P1 P2 * * *
  69834. ** Synopsis: r[P2]=P1
  69835. **
  69836. ** The 32-bit integer value P1 is written into register P2.
  69837. */
  69838. case OP_Integer: { /* out2 */
  69839. pOut = out2Prerelease(p, pOp);
  69840. pOut->u.i = pOp->p1;
  69841. break;
  69842. }
  69843. /* Opcode: Int64 * P2 * P4 *
  69844. ** Synopsis: r[P2]=P4
  69845. **
  69846. ** P4 is a pointer to a 64-bit integer value.
  69847. ** Write that value into register P2.
  69848. */
  69849. case OP_Int64: { /* out2 */
  69850. pOut = out2Prerelease(p, pOp);
  69851. assert( pOp->p4.pI64!=0 );
  69852. pOut->u.i = *pOp->p4.pI64;
  69853. break;
  69854. }
  69855. #ifndef SQLITE_OMIT_FLOATING_POINT
  69856. /* Opcode: Real * P2 * P4 *
  69857. ** Synopsis: r[P2]=P4
  69858. **
  69859. ** P4 is a pointer to a 64-bit floating point value.
  69860. ** Write that value into register P2.
  69861. */
  69862. case OP_Real: { /* same as TK_FLOAT, out2 */
  69863. pOut = out2Prerelease(p, pOp);
  69864. pOut->flags = MEM_Real;
  69865. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  69866. pOut->u.r = *pOp->p4.pReal;
  69867. break;
  69868. }
  69869. #endif
  69870. /* Opcode: String8 * P2 * P4 *
  69871. ** Synopsis: r[P2]='P4'
  69872. **
  69873. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  69874. ** into a String opcode before it is executed for the first time. During
  69875. ** this transformation, the length of string P4 is computed and stored
  69876. ** as the P1 parameter.
  69877. */
  69878. case OP_String8: { /* same as TK_STRING, out2 */
  69879. assert( pOp->p4.z!=0 );
  69880. pOut = out2Prerelease(p, pOp);
  69881. pOp->opcode = OP_String;
  69882. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  69883. #ifndef SQLITE_OMIT_UTF16
  69884. if( encoding!=SQLITE_UTF8 ){
  69885. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  69886. if( rc==SQLITE_TOOBIG ) goto too_big;
  69887. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  69888. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  69889. assert( VdbeMemDynamic(pOut)==0 );
  69890. pOut->szMalloc = 0;
  69891. pOut->flags |= MEM_Static;
  69892. if( pOp->p4type==P4_DYNAMIC ){
  69893. sqlite3DbFree(db, pOp->p4.z);
  69894. }
  69895. pOp->p4type = P4_DYNAMIC;
  69896. pOp->p4.z = pOut->z;
  69897. pOp->p1 = pOut->n;
  69898. }
  69899. #endif
  69900. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  69901. goto too_big;
  69902. }
  69903. /* Fall through to the next case, OP_String */
  69904. }
  69905. /* Opcode: String P1 P2 P3 P4 P5
  69906. ** Synopsis: r[P2]='P4' (len=P1)
  69907. **
  69908. ** The string value P4 of length P1 (bytes) is stored in register P2.
  69909. **
  69910. ** If P5!=0 and the content of register P3 is greater than zero, then
  69911. ** the datatype of the register P2 is converted to BLOB. The content is
  69912. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  69913. ** of a string, as if it had been CAST.
  69914. */
  69915. case OP_String: { /* out2 */
  69916. assert( pOp->p4.z!=0 );
  69917. pOut = out2Prerelease(p, pOp);
  69918. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  69919. pOut->z = pOp->p4.z;
  69920. pOut->n = pOp->p1;
  69921. pOut->enc = encoding;
  69922. UPDATE_MAX_BLOBSIZE(pOut);
  69923. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  69924. if( pOp->p5 ){
  69925. assert( pOp->p3>0 );
  69926. assert( pOp->p3<=(p->nMem-p->nCursor) );
  69927. pIn3 = &aMem[pOp->p3];
  69928. assert( pIn3->flags & MEM_Int );
  69929. if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  69930. }
  69931. #endif
  69932. break;
  69933. }
  69934. /* Opcode: Null P1 P2 P3 * *
  69935. ** Synopsis: r[P2..P3]=NULL
  69936. **
  69937. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  69938. ** NULL into register P3 and every register in between P2 and P3. If P3
  69939. ** is less than P2 (typically P3 is zero) then only register P2 is
  69940. ** set to NULL.
  69941. **
  69942. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  69943. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  69944. ** OP_Ne or OP_Eq.
  69945. */
  69946. case OP_Null: { /* out2 */
  69947. int cnt;
  69948. u16 nullFlag;
  69949. pOut = out2Prerelease(p, pOp);
  69950. cnt = pOp->p3-pOp->p2;
  69951. assert( pOp->p3<=(p->nMem-p->nCursor) );
  69952. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  69953. while( cnt>0 ){
  69954. pOut++;
  69955. memAboutToChange(p, pOut);
  69956. sqlite3VdbeMemSetNull(pOut);
  69957. pOut->flags = nullFlag;
  69958. cnt--;
  69959. }
  69960. break;
  69961. }
  69962. /* Opcode: SoftNull P1 * * * *
  69963. ** Synopsis: r[P1]=NULL
  69964. **
  69965. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  69966. ** instruction, but do not free any string or blob memory associated with
  69967. ** the register, so that if the value was a string or blob that was
  69968. ** previously copied using OP_SCopy, the copies will continue to be valid.
  69969. */
  69970. case OP_SoftNull: {
  69971. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  69972. pOut = &aMem[pOp->p1];
  69973. pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
  69974. break;
  69975. }
  69976. /* Opcode: Blob P1 P2 * P4 *
  69977. ** Synopsis: r[P2]=P4 (len=P1)
  69978. **
  69979. ** P4 points to a blob of data P1 bytes long. Store this
  69980. ** blob in register P2.
  69981. */
  69982. case OP_Blob: { /* out2 */
  69983. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  69984. pOut = out2Prerelease(p, pOp);
  69985. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  69986. pOut->enc = encoding;
  69987. UPDATE_MAX_BLOBSIZE(pOut);
  69988. break;
  69989. }
  69990. /* Opcode: Variable P1 P2 * P4 *
  69991. ** Synopsis: r[P2]=parameter(P1,P4)
  69992. **
  69993. ** Transfer the values of bound parameter P1 into register P2
  69994. **
  69995. ** If the parameter is named, then its name appears in P4.
  69996. ** The P4 value is used by sqlite3_bind_parameter_name().
  69997. */
  69998. case OP_Variable: { /* out2 */
  69999. Mem *pVar; /* Value being transferred */
  70000. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  70001. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  70002. pVar = &p->aVar[pOp->p1 - 1];
  70003. if( sqlite3VdbeMemTooBig(pVar) ){
  70004. goto too_big;
  70005. }
  70006. pOut = out2Prerelease(p, pOp);
  70007. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  70008. UPDATE_MAX_BLOBSIZE(pOut);
  70009. break;
  70010. }
  70011. /* Opcode: Move P1 P2 P3 * *
  70012. ** Synopsis: r[P2@P3]=r[P1@P3]
  70013. **
  70014. ** Move the P3 values in register P1..P1+P3-1 over into
  70015. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  70016. ** left holding a NULL. It is an error for register ranges
  70017. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  70018. ** for P3 to be less than 1.
  70019. */
  70020. case OP_Move: {
  70021. int n; /* Number of registers left to copy */
  70022. int p1; /* Register to copy from */
  70023. int p2; /* Register to copy to */
  70024. n = pOp->p3;
  70025. p1 = pOp->p1;
  70026. p2 = pOp->p2;
  70027. assert( n>0 && p1>0 && p2>0 );
  70028. assert( p1+n<=p2 || p2+n<=p1 );
  70029. pIn1 = &aMem[p1];
  70030. pOut = &aMem[p2];
  70031. do{
  70032. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  70033. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  70034. assert( memIsValid(pIn1) );
  70035. memAboutToChange(p, pOut);
  70036. sqlite3VdbeMemMove(pOut, pIn1);
  70037. #ifdef SQLITE_DEBUG
  70038. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  70039. pOut->pScopyFrom += pOp->p2 - p1;
  70040. }
  70041. #endif
  70042. Deephemeralize(pOut);
  70043. REGISTER_TRACE(p2++, pOut);
  70044. pIn1++;
  70045. pOut++;
  70046. }while( --n );
  70047. break;
  70048. }
  70049. /* Opcode: Copy P1 P2 P3 * *
  70050. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  70051. **
  70052. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  70053. **
  70054. ** This instruction makes a deep copy of the value. A duplicate
  70055. ** is made of any string or blob constant. See also OP_SCopy.
  70056. */
  70057. case OP_Copy: {
  70058. int n;
  70059. n = pOp->p3;
  70060. pIn1 = &aMem[pOp->p1];
  70061. pOut = &aMem[pOp->p2];
  70062. assert( pOut!=pIn1 );
  70063. while( 1 ){
  70064. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  70065. Deephemeralize(pOut);
  70066. #ifdef SQLITE_DEBUG
  70067. pOut->pScopyFrom = 0;
  70068. #endif
  70069. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  70070. if( (n--)==0 ) break;
  70071. pOut++;
  70072. pIn1++;
  70073. }
  70074. break;
  70075. }
  70076. /* Opcode: SCopy P1 P2 * * *
  70077. ** Synopsis: r[P2]=r[P1]
  70078. **
  70079. ** Make a shallow copy of register P1 into register P2.
  70080. **
  70081. ** This instruction makes a shallow copy of the value. If the value
  70082. ** is a string or blob, then the copy is only a pointer to the
  70083. ** original and hence if the original changes so will the copy.
  70084. ** Worse, if the original is deallocated, the copy becomes invalid.
  70085. ** Thus the program must guarantee that the original will not change
  70086. ** during the lifetime of the copy. Use OP_Copy to make a complete
  70087. ** copy.
  70088. */
  70089. case OP_SCopy: { /* out2 */
  70090. pIn1 = &aMem[pOp->p1];
  70091. pOut = &aMem[pOp->p2];
  70092. assert( pOut!=pIn1 );
  70093. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  70094. #ifdef SQLITE_DEBUG
  70095. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  70096. #endif
  70097. break;
  70098. }
  70099. /* Opcode: IntCopy P1 P2 * * *
  70100. ** Synopsis: r[P2]=r[P1]
  70101. **
  70102. ** Transfer the integer value held in register P1 into register P2.
  70103. **
  70104. ** This is an optimized version of SCopy that works only for integer
  70105. ** values.
  70106. */
  70107. case OP_IntCopy: { /* out2 */
  70108. pIn1 = &aMem[pOp->p1];
  70109. assert( (pIn1->flags & MEM_Int)!=0 );
  70110. pOut = &aMem[pOp->p2];
  70111. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  70112. break;
  70113. }
  70114. /* Opcode: ResultRow P1 P2 * * *
  70115. ** Synopsis: output=r[P1@P2]
  70116. **
  70117. ** The registers P1 through P1+P2-1 contain a single row of
  70118. ** results. This opcode causes the sqlite3_step() call to terminate
  70119. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  70120. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  70121. ** the result row.
  70122. */
  70123. case OP_ResultRow: {
  70124. Mem *pMem;
  70125. int i;
  70126. assert( p->nResColumn==pOp->p2 );
  70127. assert( pOp->p1>0 );
  70128. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  70129. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  70130. /* Run the progress counter just before returning.
  70131. */
  70132. if( db->xProgress!=0
  70133. && nVmStep>=nProgressLimit
  70134. && db->xProgress(db->pProgressArg)!=0
  70135. ){
  70136. rc = SQLITE_INTERRUPT;
  70137. goto vdbe_error_halt;
  70138. }
  70139. #endif
  70140. /* If this statement has violated immediate foreign key constraints, do
  70141. ** not return the number of rows modified. And do not RELEASE the statement
  70142. ** transaction. It needs to be rolled back. */
  70143. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  70144. assert( db->flags&SQLITE_CountRows );
  70145. assert( p->usesStmtJournal );
  70146. break;
  70147. }
  70148. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  70149. ** DML statements invoke this opcode to return the number of rows
  70150. ** modified to the user. This is the only way that a VM that
  70151. ** opens a statement transaction may invoke this opcode.
  70152. **
  70153. ** In case this is such a statement, close any statement transaction
  70154. ** opened by this VM before returning control to the user. This is to
  70155. ** ensure that statement-transactions are always nested, not overlapping.
  70156. ** If the open statement-transaction is not closed here, then the user
  70157. ** may step another VM that opens its own statement transaction. This
  70158. ** may lead to overlapping statement transactions.
  70159. **
  70160. ** The statement transaction is never a top-level transaction. Hence
  70161. ** the RELEASE call below can never fail.
  70162. */
  70163. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  70164. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  70165. if( NEVER(rc!=SQLITE_OK) ){
  70166. break;
  70167. }
  70168. /* Invalidate all ephemeral cursor row caches */
  70169. p->cacheCtr = (p->cacheCtr + 2)|1;
  70170. /* Make sure the results of the current row are \000 terminated
  70171. ** and have an assigned type. The results are de-ephemeralized as
  70172. ** a side effect.
  70173. */
  70174. pMem = p->pResultSet = &aMem[pOp->p1];
  70175. for(i=0; i<pOp->p2; i++){
  70176. assert( memIsValid(&pMem[i]) );
  70177. Deephemeralize(&pMem[i]);
  70178. assert( (pMem[i].flags & MEM_Ephem)==0
  70179. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  70180. sqlite3VdbeMemNulTerminate(&pMem[i]);
  70181. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  70182. }
  70183. if( db->mallocFailed ) goto no_mem;
  70184. /* Return SQLITE_ROW
  70185. */
  70186. p->pc = (int)(pOp - aOp) + 1;
  70187. rc = SQLITE_ROW;
  70188. goto vdbe_return;
  70189. }
  70190. /* Opcode: Concat P1 P2 P3 * *
  70191. ** Synopsis: r[P3]=r[P2]+r[P1]
  70192. **
  70193. ** Add the text in register P1 onto the end of the text in
  70194. ** register P2 and store the result in register P3.
  70195. ** If either the P1 or P2 text are NULL then store NULL in P3.
  70196. **
  70197. ** P3 = P2 || P1
  70198. **
  70199. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  70200. ** if P3 is the same register as P2, the implementation is able
  70201. ** to avoid a memcpy().
  70202. */
  70203. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  70204. i64 nByte;
  70205. pIn1 = &aMem[pOp->p1];
  70206. pIn2 = &aMem[pOp->p2];
  70207. pOut = &aMem[pOp->p3];
  70208. assert( pIn1!=pOut );
  70209. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  70210. sqlite3VdbeMemSetNull(pOut);
  70211. break;
  70212. }
  70213. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  70214. Stringify(pIn1, encoding);
  70215. Stringify(pIn2, encoding);
  70216. nByte = pIn1->n + pIn2->n;
  70217. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  70218. goto too_big;
  70219. }
  70220. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  70221. goto no_mem;
  70222. }
  70223. MemSetTypeFlag(pOut, MEM_Str);
  70224. if( pOut!=pIn2 ){
  70225. memcpy(pOut->z, pIn2->z, pIn2->n);
  70226. }
  70227. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  70228. pOut->z[nByte]=0;
  70229. pOut->z[nByte+1] = 0;
  70230. pOut->flags |= MEM_Term;
  70231. pOut->n = (int)nByte;
  70232. pOut->enc = encoding;
  70233. UPDATE_MAX_BLOBSIZE(pOut);
  70234. break;
  70235. }
  70236. /* Opcode: Add P1 P2 P3 * *
  70237. ** Synopsis: r[P3]=r[P1]+r[P2]
  70238. **
  70239. ** Add the value in register P1 to the value in register P2
  70240. ** and store the result in register P3.
  70241. ** If either input is NULL, the result is NULL.
  70242. */
  70243. /* Opcode: Multiply P1 P2 P3 * *
  70244. ** Synopsis: r[P3]=r[P1]*r[P2]
  70245. **
  70246. **
  70247. ** Multiply the value in register P1 by the value in register P2
  70248. ** and store the result in register P3.
  70249. ** If either input is NULL, the result is NULL.
  70250. */
  70251. /* Opcode: Subtract P1 P2 P3 * *
  70252. ** Synopsis: r[P3]=r[P2]-r[P1]
  70253. **
  70254. ** Subtract the value in register P1 from the value in register P2
  70255. ** and store the result in register P3.
  70256. ** If either input is NULL, the result is NULL.
  70257. */
  70258. /* Opcode: Divide P1 P2 P3 * *
  70259. ** Synopsis: r[P3]=r[P2]/r[P1]
  70260. **
  70261. ** Divide the value in register P1 by the value in register P2
  70262. ** and store the result in register P3 (P3=P2/P1). If the value in
  70263. ** register P1 is zero, then the result is NULL. If either input is
  70264. ** NULL, the result is NULL.
  70265. */
  70266. /* Opcode: Remainder P1 P2 P3 * *
  70267. ** Synopsis: r[P3]=r[P2]%r[P1]
  70268. **
  70269. ** Compute the remainder after integer register P2 is divided by
  70270. ** register P1 and store the result in register P3.
  70271. ** If the value in register P1 is zero the result is NULL.
  70272. ** If either operand is NULL, the result is NULL.
  70273. */
  70274. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  70275. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  70276. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  70277. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  70278. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  70279. char bIntint; /* Started out as two integer operands */
  70280. u16 flags; /* Combined MEM_* flags from both inputs */
  70281. u16 type1; /* Numeric type of left operand */
  70282. u16 type2; /* Numeric type of right operand */
  70283. i64 iA; /* Integer value of left operand */
  70284. i64 iB; /* Integer value of right operand */
  70285. double rA; /* Real value of left operand */
  70286. double rB; /* Real value of right operand */
  70287. pIn1 = &aMem[pOp->p1];
  70288. type1 = numericType(pIn1);
  70289. pIn2 = &aMem[pOp->p2];
  70290. type2 = numericType(pIn2);
  70291. pOut = &aMem[pOp->p3];
  70292. flags = pIn1->flags | pIn2->flags;
  70293. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  70294. if( (type1 & type2 & MEM_Int)!=0 ){
  70295. iA = pIn1->u.i;
  70296. iB = pIn2->u.i;
  70297. bIntint = 1;
  70298. switch( pOp->opcode ){
  70299. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  70300. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  70301. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  70302. case OP_Divide: {
  70303. if( iA==0 ) goto arithmetic_result_is_null;
  70304. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  70305. iB /= iA;
  70306. break;
  70307. }
  70308. default: {
  70309. if( iA==0 ) goto arithmetic_result_is_null;
  70310. if( iA==-1 ) iA = 1;
  70311. iB %= iA;
  70312. break;
  70313. }
  70314. }
  70315. pOut->u.i = iB;
  70316. MemSetTypeFlag(pOut, MEM_Int);
  70317. }else{
  70318. bIntint = 0;
  70319. fp_math:
  70320. rA = sqlite3VdbeRealValue(pIn1);
  70321. rB = sqlite3VdbeRealValue(pIn2);
  70322. switch( pOp->opcode ){
  70323. case OP_Add: rB += rA; break;
  70324. case OP_Subtract: rB -= rA; break;
  70325. case OP_Multiply: rB *= rA; break;
  70326. case OP_Divide: {
  70327. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  70328. if( rA==(double)0 ) goto arithmetic_result_is_null;
  70329. rB /= rA;
  70330. break;
  70331. }
  70332. default: {
  70333. iA = (i64)rA;
  70334. iB = (i64)rB;
  70335. if( iA==0 ) goto arithmetic_result_is_null;
  70336. if( iA==-1 ) iA = 1;
  70337. rB = (double)(iB % iA);
  70338. break;
  70339. }
  70340. }
  70341. #ifdef SQLITE_OMIT_FLOATING_POINT
  70342. pOut->u.i = rB;
  70343. MemSetTypeFlag(pOut, MEM_Int);
  70344. #else
  70345. if( sqlite3IsNaN(rB) ){
  70346. goto arithmetic_result_is_null;
  70347. }
  70348. pOut->u.r = rB;
  70349. MemSetTypeFlag(pOut, MEM_Real);
  70350. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  70351. sqlite3VdbeIntegerAffinity(pOut);
  70352. }
  70353. #endif
  70354. }
  70355. break;
  70356. arithmetic_result_is_null:
  70357. sqlite3VdbeMemSetNull(pOut);
  70358. break;
  70359. }
  70360. /* Opcode: CollSeq P1 * * P4
  70361. **
  70362. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  70363. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  70364. ** be returned. This is used by the built-in min(), max() and nullif()
  70365. ** functions.
  70366. **
  70367. ** If P1 is not zero, then it is a register that a subsequent min() or
  70368. ** max() aggregate will set to 1 if the current row is not the minimum or
  70369. ** maximum. The P1 register is initialized to 0 by this instruction.
  70370. **
  70371. ** The interface used by the implementation of the aforementioned functions
  70372. ** to retrieve the collation sequence set by this opcode is not available
  70373. ** publicly. Only built-in functions have access to this feature.
  70374. */
  70375. case OP_CollSeq: {
  70376. assert( pOp->p4type==P4_COLLSEQ );
  70377. if( pOp->p1 ){
  70378. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  70379. }
  70380. break;
  70381. }
  70382. /* Opcode: Function0 P1 P2 P3 P4 P5
  70383. ** Synopsis: r[P3]=func(r[P2@P5])
  70384. **
  70385. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  70386. ** defines the function) with P5 arguments taken from register P2 and
  70387. ** successors. The result of the function is stored in register P3.
  70388. ** Register P3 must not be one of the function inputs.
  70389. **
  70390. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  70391. ** function was determined to be constant at compile time. If the first
  70392. ** argument was constant then bit 0 of P1 is set. This is used to determine
  70393. ** whether meta data associated with a user function argument using the
  70394. ** sqlite3_set_auxdata() API may be safely retained until the next
  70395. ** invocation of this opcode.
  70396. **
  70397. ** See also: Function, AggStep, AggFinal
  70398. */
  70399. /* Opcode: Function P1 P2 P3 P4 P5
  70400. ** Synopsis: r[P3]=func(r[P2@P5])
  70401. **
  70402. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  70403. ** contains a pointer to the function to be run) with P5 arguments taken
  70404. ** from register P2 and successors. The result of the function is stored
  70405. ** in register P3. Register P3 must not be one of the function inputs.
  70406. **
  70407. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  70408. ** function was determined to be constant at compile time. If the first
  70409. ** argument was constant then bit 0 of P1 is set. This is used to determine
  70410. ** whether meta data associated with a user function argument using the
  70411. ** sqlite3_set_auxdata() API may be safely retained until the next
  70412. ** invocation of this opcode.
  70413. **
  70414. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  70415. ** to a FuncDef object. But on first evaluation, the P4 operand is
  70416. ** automatically converted into an sqlite3_context object and the operation
  70417. ** changed to this OP_Function opcode. In this way, the initialization of
  70418. ** the sqlite3_context object occurs only once, rather than once for each
  70419. ** evaluation of the function.
  70420. **
  70421. ** See also: Function0, AggStep, AggFinal
  70422. */
  70423. case OP_Function0: {
  70424. int n;
  70425. sqlite3_context *pCtx;
  70426. assert( pOp->p4type==P4_FUNCDEF );
  70427. n = pOp->p5;
  70428. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  70429. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  70430. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  70431. pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  70432. if( pCtx==0 ) goto no_mem;
  70433. pCtx->pOut = 0;
  70434. pCtx->pFunc = pOp->p4.pFunc;
  70435. pCtx->iOp = (int)(pOp - aOp);
  70436. pCtx->pVdbe = p;
  70437. pCtx->argc = n;
  70438. pOp->p4type = P4_FUNCCTX;
  70439. pOp->p4.pCtx = pCtx;
  70440. pOp->opcode = OP_Function;
  70441. /* Fall through into OP_Function */
  70442. }
  70443. case OP_Function: {
  70444. int i;
  70445. sqlite3_context *pCtx;
  70446. assert( pOp->p4type==P4_FUNCCTX );
  70447. pCtx = pOp->p4.pCtx;
  70448. /* If this function is inside of a trigger, the register array in aMem[]
  70449. ** might change from one evaluation to the next. The next block of code
  70450. ** checks to see if the register array has changed, and if so it
  70451. ** reinitializes the relavant parts of the sqlite3_context object */
  70452. pOut = &aMem[pOp->p3];
  70453. if( pCtx->pOut != pOut ){
  70454. pCtx->pOut = pOut;
  70455. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  70456. }
  70457. memAboutToChange(p, pCtx->pOut);
  70458. #ifdef SQLITE_DEBUG
  70459. for(i=0; i<pCtx->argc; i++){
  70460. assert( memIsValid(pCtx->argv[i]) );
  70461. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  70462. }
  70463. #endif
  70464. MemSetTypeFlag(pCtx->pOut, MEM_Null);
  70465. pCtx->fErrorOrAux = 0;
  70466. db->lastRowid = lastRowid;
  70467. (*pCtx->pFunc->xFunc)(pCtx, pCtx->argc, pCtx->argv); /* IMP: R-24505-23230 */
  70468. lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
  70469. /* If the function returned an error, throw an exception */
  70470. if( pCtx->fErrorOrAux ){
  70471. if( pCtx->isError ){
  70472. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  70473. rc = pCtx->isError;
  70474. }
  70475. sqlite3VdbeDeleteAuxData(p, pCtx->iOp, pOp->p1);
  70476. }
  70477. /* Copy the result of the function into register P3 */
  70478. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  70479. sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
  70480. if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
  70481. }
  70482. REGISTER_TRACE(pOp->p3, pCtx->pOut);
  70483. UPDATE_MAX_BLOBSIZE(pCtx->pOut);
  70484. break;
  70485. }
  70486. /* Opcode: BitAnd P1 P2 P3 * *
  70487. ** Synopsis: r[P3]=r[P1]&r[P2]
  70488. **
  70489. ** Take the bit-wise AND of the values in register P1 and P2 and
  70490. ** store the result in register P3.
  70491. ** If either input is NULL, the result is NULL.
  70492. */
  70493. /* Opcode: BitOr P1 P2 P3 * *
  70494. ** Synopsis: r[P3]=r[P1]|r[P2]
  70495. **
  70496. ** Take the bit-wise OR of the values in register P1 and P2 and
  70497. ** store the result in register P3.
  70498. ** If either input is NULL, the result is NULL.
  70499. */
  70500. /* Opcode: ShiftLeft P1 P2 P3 * *
  70501. ** Synopsis: r[P3]=r[P2]<<r[P1]
  70502. **
  70503. ** Shift the integer value in register P2 to the left by the
  70504. ** number of bits specified by the integer in register P1.
  70505. ** Store the result in register P3.
  70506. ** If either input is NULL, the result is NULL.
  70507. */
  70508. /* Opcode: ShiftRight P1 P2 P3 * *
  70509. ** Synopsis: r[P3]=r[P2]>>r[P1]
  70510. **
  70511. ** Shift the integer value in register P2 to the right by the
  70512. ** number of bits specified by the integer in register P1.
  70513. ** Store the result in register P3.
  70514. ** If either input is NULL, the result is NULL.
  70515. */
  70516. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  70517. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  70518. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  70519. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  70520. i64 iA;
  70521. u64 uA;
  70522. i64 iB;
  70523. u8 op;
  70524. pIn1 = &aMem[pOp->p1];
  70525. pIn2 = &aMem[pOp->p2];
  70526. pOut = &aMem[pOp->p3];
  70527. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  70528. sqlite3VdbeMemSetNull(pOut);
  70529. break;
  70530. }
  70531. iA = sqlite3VdbeIntValue(pIn2);
  70532. iB = sqlite3VdbeIntValue(pIn1);
  70533. op = pOp->opcode;
  70534. if( op==OP_BitAnd ){
  70535. iA &= iB;
  70536. }else if( op==OP_BitOr ){
  70537. iA |= iB;
  70538. }else if( iB!=0 ){
  70539. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  70540. /* If shifting by a negative amount, shift in the other direction */
  70541. if( iB<0 ){
  70542. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  70543. op = 2*OP_ShiftLeft + 1 - op;
  70544. iB = iB>(-64) ? -iB : 64;
  70545. }
  70546. if( iB>=64 ){
  70547. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  70548. }else{
  70549. memcpy(&uA, &iA, sizeof(uA));
  70550. if( op==OP_ShiftLeft ){
  70551. uA <<= iB;
  70552. }else{
  70553. uA >>= iB;
  70554. /* Sign-extend on a right shift of a negative number */
  70555. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  70556. }
  70557. memcpy(&iA, &uA, sizeof(iA));
  70558. }
  70559. }
  70560. pOut->u.i = iA;
  70561. MemSetTypeFlag(pOut, MEM_Int);
  70562. break;
  70563. }
  70564. /* Opcode: AddImm P1 P2 * * *
  70565. ** Synopsis: r[P1]=r[P1]+P2
  70566. **
  70567. ** Add the constant P2 to the value in register P1.
  70568. ** The result is always an integer.
  70569. **
  70570. ** To force any register to be an integer, just add 0.
  70571. */
  70572. case OP_AddImm: { /* in1 */
  70573. pIn1 = &aMem[pOp->p1];
  70574. memAboutToChange(p, pIn1);
  70575. sqlite3VdbeMemIntegerify(pIn1);
  70576. pIn1->u.i += pOp->p2;
  70577. break;
  70578. }
  70579. /* Opcode: MustBeInt P1 P2 * * *
  70580. **
  70581. ** Force the value in register P1 to be an integer. If the value
  70582. ** in P1 is not an integer and cannot be converted into an integer
  70583. ** without data loss, then jump immediately to P2, or if P2==0
  70584. ** raise an SQLITE_MISMATCH exception.
  70585. */
  70586. case OP_MustBeInt: { /* jump, in1 */
  70587. pIn1 = &aMem[pOp->p1];
  70588. if( (pIn1->flags & MEM_Int)==0 ){
  70589. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  70590. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  70591. if( (pIn1->flags & MEM_Int)==0 ){
  70592. if( pOp->p2==0 ){
  70593. rc = SQLITE_MISMATCH;
  70594. goto abort_due_to_error;
  70595. }else{
  70596. goto jump_to_p2;
  70597. }
  70598. }
  70599. }
  70600. MemSetTypeFlag(pIn1, MEM_Int);
  70601. break;
  70602. }
  70603. #ifndef SQLITE_OMIT_FLOATING_POINT
  70604. /* Opcode: RealAffinity P1 * * * *
  70605. **
  70606. ** If register P1 holds an integer convert it to a real value.
  70607. **
  70608. ** This opcode is used when extracting information from a column that
  70609. ** has REAL affinity. Such column values may still be stored as
  70610. ** integers, for space efficiency, but after extraction we want them
  70611. ** to have only a real value.
  70612. */
  70613. case OP_RealAffinity: { /* in1 */
  70614. pIn1 = &aMem[pOp->p1];
  70615. if( pIn1->flags & MEM_Int ){
  70616. sqlite3VdbeMemRealify(pIn1);
  70617. }
  70618. break;
  70619. }
  70620. #endif
  70621. #ifndef SQLITE_OMIT_CAST
  70622. /* Opcode: Cast P1 P2 * * *
  70623. ** Synopsis: affinity(r[P1])
  70624. **
  70625. ** Force the value in register P1 to be the type defined by P2.
  70626. **
  70627. ** <ul>
  70628. ** <li value="97"> TEXT
  70629. ** <li value="98"> BLOB
  70630. ** <li value="99"> NUMERIC
  70631. ** <li value="100"> INTEGER
  70632. ** <li value="101"> REAL
  70633. ** </ul>
  70634. **
  70635. ** A NULL value is not changed by this routine. It remains NULL.
  70636. */
  70637. case OP_Cast: { /* in1 */
  70638. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  70639. testcase( pOp->p2==SQLITE_AFF_TEXT );
  70640. testcase( pOp->p2==SQLITE_AFF_BLOB );
  70641. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  70642. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  70643. testcase( pOp->p2==SQLITE_AFF_REAL );
  70644. pIn1 = &aMem[pOp->p1];
  70645. memAboutToChange(p, pIn1);
  70646. rc = ExpandBlob(pIn1);
  70647. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  70648. UPDATE_MAX_BLOBSIZE(pIn1);
  70649. break;
  70650. }
  70651. #endif /* SQLITE_OMIT_CAST */
  70652. /* Opcode: Lt P1 P2 P3 P4 P5
  70653. ** Synopsis: if r[P1]<r[P3] goto P2
  70654. **
  70655. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  70656. ** jump to address P2.
  70657. **
  70658. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  70659. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  70660. ** bit is clear then fall through if either operand is NULL.
  70661. **
  70662. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  70663. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  70664. ** to coerce both inputs according to this affinity before the
  70665. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  70666. ** affinity is used. Note that the affinity conversions are stored
  70667. ** back into the input registers P1 and P3. So this opcode can cause
  70668. ** persistent changes to registers P1 and P3.
  70669. **
  70670. ** Once any conversions have taken place, and neither value is NULL,
  70671. ** the values are compared. If both values are blobs then memcmp() is
  70672. ** used to determine the results of the comparison. If both values
  70673. ** are text, then the appropriate collating function specified in
  70674. ** P4 is used to do the comparison. If P4 is not specified then
  70675. ** memcmp() is used to compare text string. If both values are
  70676. ** numeric, then a numeric comparison is used. If the two values
  70677. ** are of different types, then numbers are considered less than
  70678. ** strings and strings are considered less than blobs.
  70679. **
  70680. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  70681. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  70682. **
  70683. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  70684. ** equal to one another, provided that they do not have their MEM_Cleared
  70685. ** bit set.
  70686. */
  70687. /* Opcode: Ne P1 P2 P3 P4 P5
  70688. ** Synopsis: if r[P1]!=r[P3] goto P2
  70689. **
  70690. ** This works just like the Lt opcode except that the jump is taken if
  70691. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  70692. ** additional information.
  70693. **
  70694. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  70695. ** true or false and is never NULL. If both operands are NULL then the result
  70696. ** of comparison is false. If either operand is NULL then the result is true.
  70697. ** If neither operand is NULL the result is the same as it would be if
  70698. ** the SQLITE_NULLEQ flag were omitted from P5.
  70699. */
  70700. /* Opcode: Eq P1 P2 P3 P4 P5
  70701. ** Synopsis: if r[P1]==r[P3] goto P2
  70702. **
  70703. ** This works just like the Lt opcode except that the jump is taken if
  70704. ** the operands in registers P1 and P3 are equal.
  70705. ** See the Lt opcode for additional information.
  70706. **
  70707. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  70708. ** true or false and is never NULL. If both operands are NULL then the result
  70709. ** of comparison is true. If either operand is NULL then the result is false.
  70710. ** If neither operand is NULL the result is the same as it would be if
  70711. ** the SQLITE_NULLEQ flag were omitted from P5.
  70712. */
  70713. /* Opcode: Le P1 P2 P3 P4 P5
  70714. ** Synopsis: if r[P1]<=r[P3] goto P2
  70715. **
  70716. ** This works just like the Lt opcode except that the jump is taken if
  70717. ** the content of register P3 is less than or equal to the content of
  70718. ** register P1. See the Lt opcode for additional information.
  70719. */
  70720. /* Opcode: Gt P1 P2 P3 P4 P5
  70721. ** Synopsis: if r[P1]>r[P3] goto P2
  70722. **
  70723. ** This works just like the Lt opcode except that the jump is taken if
  70724. ** the content of register P3 is greater than the content of
  70725. ** register P1. See the Lt opcode for additional information.
  70726. */
  70727. /* Opcode: Ge P1 P2 P3 P4 P5
  70728. ** Synopsis: if r[P1]>=r[P3] goto P2
  70729. **
  70730. ** This works just like the Lt opcode except that the jump is taken if
  70731. ** the content of register P3 is greater than or equal to the content of
  70732. ** register P1. See the Lt opcode for additional information.
  70733. */
  70734. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  70735. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  70736. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  70737. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  70738. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  70739. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  70740. int res; /* Result of the comparison of pIn1 against pIn3 */
  70741. char affinity; /* Affinity to use for comparison */
  70742. u16 flags1; /* Copy of initial value of pIn1->flags */
  70743. u16 flags3; /* Copy of initial value of pIn3->flags */
  70744. pIn1 = &aMem[pOp->p1];
  70745. pIn3 = &aMem[pOp->p3];
  70746. flags1 = pIn1->flags;
  70747. flags3 = pIn3->flags;
  70748. if( (flags1 | flags3)&MEM_Null ){
  70749. /* One or both operands are NULL */
  70750. if( pOp->p5 & SQLITE_NULLEQ ){
  70751. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  70752. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  70753. ** or not both operands are null.
  70754. */
  70755. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  70756. assert( (flags1 & MEM_Cleared)==0 );
  70757. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  70758. if( (flags1&MEM_Null)!=0
  70759. && (flags3&MEM_Null)!=0
  70760. && (flags3&MEM_Cleared)==0
  70761. ){
  70762. res = 0; /* Results are equal */
  70763. }else{
  70764. res = 1; /* Results are not equal */
  70765. }
  70766. }else{
  70767. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  70768. ** then the result is always NULL.
  70769. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  70770. */
  70771. if( pOp->p5 & SQLITE_STOREP2 ){
  70772. pOut = &aMem[pOp->p2];
  70773. memAboutToChange(p, pOut);
  70774. MemSetTypeFlag(pOut, MEM_Null);
  70775. REGISTER_TRACE(pOp->p2, pOut);
  70776. }else{
  70777. VdbeBranchTaken(2,3);
  70778. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  70779. goto jump_to_p2;
  70780. }
  70781. }
  70782. break;
  70783. }
  70784. }else{
  70785. /* Neither operand is NULL. Do a comparison. */
  70786. affinity = pOp->p5 & SQLITE_AFF_MASK;
  70787. if( affinity>=SQLITE_AFF_NUMERIC ){
  70788. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  70789. applyNumericAffinity(pIn1,0);
  70790. }
  70791. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  70792. applyNumericAffinity(pIn3,0);
  70793. }
  70794. }else if( affinity==SQLITE_AFF_TEXT ){
  70795. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  70796. testcase( pIn1->flags & MEM_Int );
  70797. testcase( pIn1->flags & MEM_Real );
  70798. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  70799. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  70800. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  70801. }
  70802. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  70803. testcase( pIn3->flags & MEM_Int );
  70804. testcase( pIn3->flags & MEM_Real );
  70805. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  70806. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  70807. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  70808. }
  70809. }
  70810. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  70811. if( flags1 & MEM_Zero ){
  70812. sqlite3VdbeMemExpandBlob(pIn1);
  70813. flags1 &= ~MEM_Zero;
  70814. }
  70815. if( flags3 & MEM_Zero ){
  70816. sqlite3VdbeMemExpandBlob(pIn3);
  70817. flags3 &= ~MEM_Zero;
  70818. }
  70819. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  70820. }
  70821. switch( pOp->opcode ){
  70822. case OP_Eq: res = res==0; break;
  70823. case OP_Ne: res = res!=0; break;
  70824. case OP_Lt: res = res<0; break;
  70825. case OP_Le: res = res<=0; break;
  70826. case OP_Gt: res = res>0; break;
  70827. default: res = res>=0; break;
  70828. }
  70829. /* Undo any changes made by applyAffinity() to the input registers. */
  70830. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  70831. pIn1->flags = flags1;
  70832. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  70833. pIn3->flags = flags3;
  70834. if( pOp->p5 & SQLITE_STOREP2 ){
  70835. pOut = &aMem[pOp->p2];
  70836. memAboutToChange(p, pOut);
  70837. MemSetTypeFlag(pOut, MEM_Int);
  70838. pOut->u.i = res;
  70839. REGISTER_TRACE(pOp->p2, pOut);
  70840. }else{
  70841. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  70842. if( res ){
  70843. goto jump_to_p2;
  70844. }
  70845. }
  70846. break;
  70847. }
  70848. /* Opcode: Permutation * * * P4 *
  70849. **
  70850. ** Set the permutation used by the OP_Compare operator to be the array
  70851. ** of integers in P4.
  70852. **
  70853. ** The permutation is only valid until the next OP_Compare that has
  70854. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  70855. ** occur immediately prior to the OP_Compare.
  70856. */
  70857. case OP_Permutation: {
  70858. assert( pOp->p4type==P4_INTARRAY );
  70859. assert( pOp->p4.ai );
  70860. aPermute = pOp->p4.ai;
  70861. break;
  70862. }
  70863. /* Opcode: Compare P1 P2 P3 P4 P5
  70864. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  70865. **
  70866. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  70867. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  70868. ** the comparison for use by the next OP_Jump instruct.
  70869. **
  70870. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  70871. ** determined by the most recent OP_Permutation operator. If the
  70872. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  70873. ** order.
  70874. **
  70875. ** P4 is a KeyInfo structure that defines collating sequences and sort
  70876. ** orders for the comparison. The permutation applies to registers
  70877. ** only. The KeyInfo elements are used sequentially.
  70878. **
  70879. ** The comparison is a sort comparison, so NULLs compare equal,
  70880. ** NULLs are less than numbers, numbers are less than strings,
  70881. ** and strings are less than blobs.
  70882. */
  70883. case OP_Compare: {
  70884. int n;
  70885. int i;
  70886. int p1;
  70887. int p2;
  70888. const KeyInfo *pKeyInfo;
  70889. int idx;
  70890. CollSeq *pColl; /* Collating sequence to use on this term */
  70891. int bRev; /* True for DESCENDING sort order */
  70892. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  70893. n = pOp->p3;
  70894. pKeyInfo = pOp->p4.pKeyInfo;
  70895. assert( n>0 );
  70896. assert( pKeyInfo!=0 );
  70897. p1 = pOp->p1;
  70898. p2 = pOp->p2;
  70899. #if SQLITE_DEBUG
  70900. if( aPermute ){
  70901. int k, mx = 0;
  70902. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  70903. assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
  70904. assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
  70905. }else{
  70906. assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
  70907. assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
  70908. }
  70909. #endif /* SQLITE_DEBUG */
  70910. for(i=0; i<n; i++){
  70911. idx = aPermute ? aPermute[i] : i;
  70912. assert( memIsValid(&aMem[p1+idx]) );
  70913. assert( memIsValid(&aMem[p2+idx]) );
  70914. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  70915. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  70916. assert( i<pKeyInfo->nField );
  70917. pColl = pKeyInfo->aColl[i];
  70918. bRev = pKeyInfo->aSortOrder[i];
  70919. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  70920. if( iCompare ){
  70921. if( bRev ) iCompare = -iCompare;
  70922. break;
  70923. }
  70924. }
  70925. aPermute = 0;
  70926. break;
  70927. }
  70928. /* Opcode: Jump P1 P2 P3 * *
  70929. **
  70930. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  70931. ** in the most recent OP_Compare instruction the P1 vector was less than
  70932. ** equal to, or greater than the P2 vector, respectively.
  70933. */
  70934. case OP_Jump: { /* jump */
  70935. if( iCompare<0 ){
  70936. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  70937. }else if( iCompare==0 ){
  70938. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  70939. }else{
  70940. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  70941. }
  70942. break;
  70943. }
  70944. /* Opcode: And P1 P2 P3 * *
  70945. ** Synopsis: r[P3]=(r[P1] && r[P2])
  70946. **
  70947. ** Take the logical AND of the values in registers P1 and P2 and
  70948. ** write the result into register P3.
  70949. **
  70950. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  70951. ** the other input is NULL. A NULL and true or two NULLs give
  70952. ** a NULL output.
  70953. */
  70954. /* Opcode: Or P1 P2 P3 * *
  70955. ** Synopsis: r[P3]=(r[P1] || r[P2])
  70956. **
  70957. ** Take the logical OR of the values in register P1 and P2 and
  70958. ** store the answer in register P3.
  70959. **
  70960. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  70961. ** even if the other input is NULL. A NULL and false or two NULLs
  70962. ** give a NULL output.
  70963. */
  70964. case OP_And: /* same as TK_AND, in1, in2, out3 */
  70965. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  70966. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  70967. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  70968. pIn1 = &aMem[pOp->p1];
  70969. if( pIn1->flags & MEM_Null ){
  70970. v1 = 2;
  70971. }else{
  70972. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  70973. }
  70974. pIn2 = &aMem[pOp->p2];
  70975. if( pIn2->flags & MEM_Null ){
  70976. v2 = 2;
  70977. }else{
  70978. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  70979. }
  70980. if( pOp->opcode==OP_And ){
  70981. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  70982. v1 = and_logic[v1*3+v2];
  70983. }else{
  70984. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  70985. v1 = or_logic[v1*3+v2];
  70986. }
  70987. pOut = &aMem[pOp->p3];
  70988. if( v1==2 ){
  70989. MemSetTypeFlag(pOut, MEM_Null);
  70990. }else{
  70991. pOut->u.i = v1;
  70992. MemSetTypeFlag(pOut, MEM_Int);
  70993. }
  70994. break;
  70995. }
  70996. /* Opcode: Not P1 P2 * * *
  70997. ** Synopsis: r[P2]= !r[P1]
  70998. **
  70999. ** Interpret the value in register P1 as a boolean value. Store the
  71000. ** boolean complement in register P2. If the value in register P1 is
  71001. ** NULL, then a NULL is stored in P2.
  71002. */
  71003. case OP_Not: { /* same as TK_NOT, in1, out2 */
  71004. pIn1 = &aMem[pOp->p1];
  71005. pOut = &aMem[pOp->p2];
  71006. sqlite3VdbeMemSetNull(pOut);
  71007. if( (pIn1->flags & MEM_Null)==0 ){
  71008. pOut->flags = MEM_Int;
  71009. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  71010. }
  71011. break;
  71012. }
  71013. /* Opcode: BitNot P1 P2 * * *
  71014. ** Synopsis: r[P1]= ~r[P1]
  71015. **
  71016. ** Interpret the content of register P1 as an integer. Store the
  71017. ** ones-complement of the P1 value into register P2. If P1 holds
  71018. ** a NULL then store a NULL in P2.
  71019. */
  71020. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  71021. pIn1 = &aMem[pOp->p1];
  71022. pOut = &aMem[pOp->p2];
  71023. sqlite3VdbeMemSetNull(pOut);
  71024. if( (pIn1->flags & MEM_Null)==0 ){
  71025. pOut->flags = MEM_Int;
  71026. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  71027. }
  71028. break;
  71029. }
  71030. /* Opcode: Once P1 P2 * * *
  71031. **
  71032. ** Check the "once" flag number P1. If it is set, jump to instruction P2.
  71033. ** Otherwise, set the flag and fall through to the next instruction.
  71034. ** In other words, this opcode causes all following opcodes up through P2
  71035. ** (but not including P2) to run just once and to be skipped on subsequent
  71036. ** times through the loop.
  71037. **
  71038. ** All "once" flags are initially cleared whenever a prepared statement
  71039. ** first begins to run.
  71040. */
  71041. case OP_Once: { /* jump */
  71042. assert( pOp->p1<p->nOnceFlag );
  71043. VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
  71044. if( p->aOnceFlag[pOp->p1] ){
  71045. goto jump_to_p2;
  71046. }else{
  71047. p->aOnceFlag[pOp->p1] = 1;
  71048. }
  71049. break;
  71050. }
  71051. /* Opcode: If P1 P2 P3 * *
  71052. **
  71053. ** Jump to P2 if the value in register P1 is true. The value
  71054. ** is considered true if it is numeric and non-zero. If the value
  71055. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  71056. */
  71057. /* Opcode: IfNot P1 P2 P3 * *
  71058. **
  71059. ** Jump to P2 if the value in register P1 is False. The value
  71060. ** is considered false if it has a numeric value of zero. If the value
  71061. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  71062. */
  71063. case OP_If: /* jump, in1 */
  71064. case OP_IfNot: { /* jump, in1 */
  71065. int c;
  71066. pIn1 = &aMem[pOp->p1];
  71067. if( pIn1->flags & MEM_Null ){
  71068. c = pOp->p3;
  71069. }else{
  71070. #ifdef SQLITE_OMIT_FLOATING_POINT
  71071. c = sqlite3VdbeIntValue(pIn1)!=0;
  71072. #else
  71073. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  71074. #endif
  71075. if( pOp->opcode==OP_IfNot ) c = !c;
  71076. }
  71077. VdbeBranchTaken(c!=0, 2);
  71078. if( c ){
  71079. goto jump_to_p2;
  71080. }
  71081. break;
  71082. }
  71083. /* Opcode: IsNull P1 P2 * * *
  71084. ** Synopsis: if r[P1]==NULL goto P2
  71085. **
  71086. ** Jump to P2 if the value in register P1 is NULL.
  71087. */
  71088. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  71089. pIn1 = &aMem[pOp->p1];
  71090. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  71091. if( (pIn1->flags & MEM_Null)!=0 ){
  71092. goto jump_to_p2;
  71093. }
  71094. break;
  71095. }
  71096. /* Opcode: NotNull P1 P2 * * *
  71097. ** Synopsis: if r[P1]!=NULL goto P2
  71098. **
  71099. ** Jump to P2 if the value in register P1 is not NULL.
  71100. */
  71101. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  71102. pIn1 = &aMem[pOp->p1];
  71103. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  71104. if( (pIn1->flags & MEM_Null)==0 ){
  71105. goto jump_to_p2;
  71106. }
  71107. break;
  71108. }
  71109. /* Opcode: Column P1 P2 P3 P4 P5
  71110. ** Synopsis: r[P3]=PX
  71111. **
  71112. ** Interpret the data that cursor P1 points to as a structure built using
  71113. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  71114. ** information about the format of the data.) Extract the P2-th column
  71115. ** from this record. If there are less that (P2+1)
  71116. ** values in the record, extract a NULL.
  71117. **
  71118. ** The value extracted is stored in register P3.
  71119. **
  71120. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  71121. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  71122. ** the result.
  71123. **
  71124. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  71125. ** then the cache of the cursor is reset prior to extracting the column.
  71126. ** The first OP_Column against a pseudo-table after the value of the content
  71127. ** register has changed should have this bit set.
  71128. **
  71129. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  71130. ** the result is guaranteed to only be used as the argument of a length()
  71131. ** or typeof() function, respectively. The loading of large blobs can be
  71132. ** skipped for length() and all content loading can be skipped for typeof().
  71133. */
  71134. case OP_Column: {
  71135. i64 payloadSize64; /* Number of bytes in the record */
  71136. int p2; /* column number to retrieve */
  71137. VdbeCursor *pC; /* The VDBE cursor */
  71138. BtCursor *pCrsr; /* The BTree cursor */
  71139. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  71140. int len; /* The length of the serialized data for the column */
  71141. int i; /* Loop counter */
  71142. Mem *pDest; /* Where to write the extracted value */
  71143. Mem sMem; /* For storing the record being decoded */
  71144. const u8 *zData; /* Part of the record being decoded */
  71145. const u8 *zHdr; /* Next unparsed byte of the header */
  71146. const u8 *zEndHdr; /* Pointer to first byte after the header */
  71147. u32 offset; /* Offset into the data */
  71148. u64 offset64; /* 64-bit offset */
  71149. u32 avail; /* Number of bytes of available data */
  71150. u32 t; /* A type code from the record header */
  71151. u16 fx; /* pDest->flags value */
  71152. Mem *pReg; /* PseudoTable input register */
  71153. p2 = pOp->p2;
  71154. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  71155. pDest = &aMem[pOp->p3];
  71156. memAboutToChange(p, pDest);
  71157. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71158. pC = p->apCsr[pOp->p1];
  71159. assert( pC!=0 );
  71160. assert( p2<pC->nField );
  71161. aOffset = pC->aOffset;
  71162. assert( pC->eCurType!=CURTYPE_VTAB );
  71163. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  71164. assert( pC->eCurType!=CURTYPE_SORTER );
  71165. pCrsr = pC->uc.pCursor;
  71166. /* If the cursor cache is stale, bring it up-to-date */
  71167. rc = sqlite3VdbeCursorMoveto(pC);
  71168. if( rc ) goto abort_due_to_error;
  71169. if( pC->cacheStatus!=p->cacheCtr ){
  71170. if( pC->nullRow ){
  71171. if( pC->eCurType==CURTYPE_PSEUDO ){
  71172. assert( pC->uc.pseudoTableReg>0 );
  71173. pReg = &aMem[pC->uc.pseudoTableReg];
  71174. assert( pReg->flags & MEM_Blob );
  71175. assert( memIsValid(pReg) );
  71176. pC->payloadSize = pC->szRow = avail = pReg->n;
  71177. pC->aRow = (u8*)pReg->z;
  71178. }else{
  71179. sqlite3VdbeMemSetNull(pDest);
  71180. goto op_column_out;
  71181. }
  71182. }else{
  71183. assert( pC->eCurType==CURTYPE_BTREE );
  71184. assert( pCrsr );
  71185. if( pC->isTable==0 ){
  71186. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  71187. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  71188. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  71189. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  71190. ** payload size, so it is impossible for payloadSize64 to be
  71191. ** larger than 32 bits. */
  71192. assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
  71193. pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
  71194. pC->payloadSize = (u32)payloadSize64;
  71195. }else{
  71196. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  71197. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
  71198. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  71199. pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
  71200. }
  71201. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  71202. if( pC->payloadSize <= (u32)avail ){
  71203. pC->szRow = pC->payloadSize;
  71204. }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  71205. goto too_big;
  71206. }else{
  71207. pC->szRow = avail;
  71208. }
  71209. }
  71210. pC->cacheStatus = p->cacheCtr;
  71211. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  71212. pC->nHdrParsed = 0;
  71213. aOffset[0] = offset;
  71214. if( avail<offset ){
  71215. /* pC->aRow does not have to hold the entire row, but it does at least
  71216. ** need to cover the header of the record. If pC->aRow does not contain
  71217. ** the complete header, then set it to zero, forcing the header to be
  71218. ** dynamically allocated. */
  71219. pC->aRow = 0;
  71220. pC->szRow = 0;
  71221. /* Make sure a corrupt database has not given us an oversize header.
  71222. ** Do this now to avoid an oversize memory allocation.
  71223. **
  71224. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  71225. ** types use so much data space that there can only be 4096 and 32 of
  71226. ** them, respectively. So the maximum header length results from a
  71227. ** 3-byte type for each of the maximum of 32768 columns plus three
  71228. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  71229. */
  71230. if( offset > 98307 || offset > pC->payloadSize ){
  71231. rc = SQLITE_CORRUPT_BKPT;
  71232. goto op_column_error;
  71233. }
  71234. }
  71235. /* The following goto is an optimization. It can be omitted and
  71236. ** everything will still work. But OP_Column is measurably faster
  71237. ** by skipping the subsequent conditional, which is always true.
  71238. */
  71239. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  71240. goto op_column_read_header;
  71241. }
  71242. /* Make sure at least the first p2+1 entries of the header have been
  71243. ** parsed and valid information is in aOffset[] and pC->aType[].
  71244. */
  71245. if( pC->nHdrParsed<=p2 ){
  71246. /* If there is more header available for parsing in the record, try
  71247. ** to extract additional fields up through the p2+1-th field
  71248. */
  71249. op_column_read_header:
  71250. if( pC->iHdrOffset<aOffset[0] ){
  71251. /* Make sure zData points to enough of the record to cover the header. */
  71252. if( pC->aRow==0 ){
  71253. memset(&sMem, 0, sizeof(sMem));
  71254. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
  71255. if( rc!=SQLITE_OK ) goto op_column_error;
  71256. zData = (u8*)sMem.z;
  71257. }else{
  71258. zData = pC->aRow;
  71259. }
  71260. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  71261. i = pC->nHdrParsed;
  71262. offset64 = aOffset[i];
  71263. zHdr = zData + pC->iHdrOffset;
  71264. zEndHdr = zData + aOffset[0];
  71265. assert( i<=p2 && zHdr<zEndHdr );
  71266. do{
  71267. if( (t = zHdr[0])<0x80 ){
  71268. zHdr++;
  71269. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  71270. }else{
  71271. zHdr += sqlite3GetVarint32(zHdr, &t);
  71272. offset64 += sqlite3VdbeSerialTypeLen(t);
  71273. }
  71274. pC->aType[i++] = t;
  71275. aOffset[i] = (u32)(offset64 & 0xffffffff);
  71276. }while( i<=p2 && zHdr<zEndHdr );
  71277. pC->nHdrParsed = i;
  71278. pC->iHdrOffset = (u32)(zHdr - zData);
  71279. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  71280. /* The record is corrupt if any of the following are true:
  71281. ** (1) the bytes of the header extend past the declared header size
  71282. ** (2) the entire header was used but not all data was used
  71283. ** (3) the end of the data extends beyond the end of the record.
  71284. */
  71285. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  71286. || (offset64 > pC->payloadSize)
  71287. ){
  71288. rc = SQLITE_CORRUPT_BKPT;
  71289. goto op_column_error;
  71290. }
  71291. }else{
  71292. t = 0;
  71293. }
  71294. /* If after trying to extract new entries from the header, nHdrParsed is
  71295. ** still not up to p2, that means that the record has fewer than p2
  71296. ** columns. So the result will be either the default value or a NULL.
  71297. */
  71298. if( pC->nHdrParsed<=p2 ){
  71299. if( pOp->p4type==P4_MEM ){
  71300. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  71301. }else{
  71302. sqlite3VdbeMemSetNull(pDest);
  71303. }
  71304. goto op_column_out;
  71305. }
  71306. }else{
  71307. t = pC->aType[p2];
  71308. }
  71309. /* Extract the content for the p2+1-th column. Control can only
  71310. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  71311. ** all valid.
  71312. */
  71313. assert( p2<pC->nHdrParsed );
  71314. assert( rc==SQLITE_OK );
  71315. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  71316. if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
  71317. assert( t==pC->aType[p2] );
  71318. if( pC->szRow>=aOffset[p2+1] ){
  71319. /* This is the common case where the desired content fits on the original
  71320. ** page - where the content is not on an overflow page */
  71321. sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
  71322. }else{
  71323. /* This branch happens only when content is on overflow pages */
  71324. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  71325. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  71326. || (len = sqlite3VdbeSerialTypeLen(t))==0
  71327. ){
  71328. /* Content is irrelevant for
  71329. ** 1. the typeof() function,
  71330. ** 2. the length(X) function if X is a blob, and
  71331. ** 3. if the content length is zero.
  71332. ** So we might as well use bogus content rather than reading
  71333. ** content from disk. NULL will work for the value for strings
  71334. ** and blobs and whatever is in the payloadSize64 variable
  71335. ** will work for everything else. */
  71336. sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
  71337. }else{
  71338. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
  71339. pDest);
  71340. if( rc!=SQLITE_OK ){
  71341. goto op_column_error;
  71342. }
  71343. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  71344. pDest->flags &= ~MEM_Ephem;
  71345. }
  71346. }
  71347. pDest->enc = encoding;
  71348. op_column_out:
  71349. /* If the column value is an ephemeral string, go ahead and persist
  71350. ** that string in case the cursor moves before the column value is
  71351. ** used. The following code does the equivalent of Deephemeralize()
  71352. ** but does it faster. */
  71353. if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
  71354. fx = pDest->flags & (MEM_Str|MEM_Blob);
  71355. assert( fx!=0 );
  71356. zData = (const u8*)pDest->z;
  71357. len = pDest->n;
  71358. if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
  71359. memcpy(pDest->z, zData, len);
  71360. pDest->z[len] = 0;
  71361. pDest->z[len+1] = 0;
  71362. pDest->flags = fx|MEM_Term;
  71363. }
  71364. op_column_error:
  71365. UPDATE_MAX_BLOBSIZE(pDest);
  71366. REGISTER_TRACE(pOp->p3, pDest);
  71367. break;
  71368. }
  71369. /* Opcode: Affinity P1 P2 * P4 *
  71370. ** Synopsis: affinity(r[P1@P2])
  71371. **
  71372. ** Apply affinities to a range of P2 registers starting with P1.
  71373. **
  71374. ** P4 is a string that is P2 characters long. The nth character of the
  71375. ** string indicates the column affinity that should be used for the nth
  71376. ** memory cell in the range.
  71377. */
  71378. case OP_Affinity: {
  71379. const char *zAffinity; /* The affinity to be applied */
  71380. char cAff; /* A single character of affinity */
  71381. zAffinity = pOp->p4.z;
  71382. assert( zAffinity!=0 );
  71383. assert( zAffinity[pOp->p2]==0 );
  71384. pIn1 = &aMem[pOp->p1];
  71385. while( (cAff = *(zAffinity++))!=0 ){
  71386. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  71387. assert( memIsValid(pIn1) );
  71388. applyAffinity(pIn1, cAff, encoding);
  71389. pIn1++;
  71390. }
  71391. break;
  71392. }
  71393. /* Opcode: MakeRecord P1 P2 P3 P4 *
  71394. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  71395. **
  71396. ** Convert P2 registers beginning with P1 into the [record format]
  71397. ** use as a data record in a database table or as a key
  71398. ** in an index. The OP_Column opcode can decode the record later.
  71399. **
  71400. ** P4 may be a string that is P2 characters long. The nth character of the
  71401. ** string indicates the column affinity that should be used for the nth
  71402. ** field of the index key.
  71403. **
  71404. ** The mapping from character to affinity is given by the SQLITE_AFF_
  71405. ** macros defined in sqliteInt.h.
  71406. **
  71407. ** If P4 is NULL then all index fields have the affinity BLOB.
  71408. */
  71409. case OP_MakeRecord: {
  71410. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  71411. Mem *pRec; /* The new record */
  71412. u64 nData; /* Number of bytes of data space */
  71413. int nHdr; /* Number of bytes of header space */
  71414. i64 nByte; /* Data space required for this record */
  71415. i64 nZero; /* Number of zero bytes at the end of the record */
  71416. int nVarint; /* Number of bytes in a varint */
  71417. u32 serial_type; /* Type field */
  71418. Mem *pData0; /* First field to be combined into the record */
  71419. Mem *pLast; /* Last field of the record */
  71420. int nField; /* Number of fields in the record */
  71421. char *zAffinity; /* The affinity string for the record */
  71422. int file_format; /* File format to use for encoding */
  71423. int i; /* Space used in zNewRecord[] header */
  71424. int j; /* Space used in zNewRecord[] content */
  71425. u32 len; /* Length of a field */
  71426. /* Assuming the record contains N fields, the record format looks
  71427. ** like this:
  71428. **
  71429. ** ------------------------------------------------------------------------
  71430. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  71431. ** ------------------------------------------------------------------------
  71432. **
  71433. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  71434. ** and so forth.
  71435. **
  71436. ** Each type field is a varint representing the serial type of the
  71437. ** corresponding data element (see sqlite3VdbeSerialType()). The
  71438. ** hdr-size field is also a varint which is the offset from the beginning
  71439. ** of the record to data0.
  71440. */
  71441. nData = 0; /* Number of bytes of data space */
  71442. nHdr = 0; /* Number of bytes of header space */
  71443. nZero = 0; /* Number of zero bytes at the end of the record */
  71444. nField = pOp->p1;
  71445. zAffinity = pOp->p4.z;
  71446. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
  71447. pData0 = &aMem[nField];
  71448. nField = pOp->p2;
  71449. pLast = &pData0[nField-1];
  71450. file_format = p->minWriteFileFormat;
  71451. /* Identify the output register */
  71452. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  71453. pOut = &aMem[pOp->p3];
  71454. memAboutToChange(p, pOut);
  71455. /* Apply the requested affinity to all inputs
  71456. */
  71457. assert( pData0<=pLast );
  71458. if( zAffinity ){
  71459. pRec = pData0;
  71460. do{
  71461. applyAffinity(pRec++, *(zAffinity++), encoding);
  71462. assert( zAffinity[0]==0 || pRec<=pLast );
  71463. }while( zAffinity[0] );
  71464. }
  71465. /* Loop through the elements that will make up the record to figure
  71466. ** out how much space is required for the new record.
  71467. */
  71468. pRec = pLast;
  71469. do{
  71470. assert( memIsValid(pRec) );
  71471. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  71472. if( pRec->flags & MEM_Zero ){
  71473. if( nData ){
  71474. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  71475. }else{
  71476. nZero += pRec->u.nZero;
  71477. len -= pRec->u.nZero;
  71478. }
  71479. }
  71480. nData += len;
  71481. testcase( serial_type==127 );
  71482. testcase( serial_type==128 );
  71483. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  71484. }while( (--pRec)>=pData0 );
  71485. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  71486. ** which determines the total number of bytes in the header. The varint
  71487. ** value is the size of the header in bytes including the size varint
  71488. ** itself. */
  71489. testcase( nHdr==126 );
  71490. testcase( nHdr==127 );
  71491. if( nHdr<=126 ){
  71492. /* The common case */
  71493. nHdr += 1;
  71494. }else{
  71495. /* Rare case of a really large header */
  71496. nVarint = sqlite3VarintLen(nHdr);
  71497. nHdr += nVarint;
  71498. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  71499. }
  71500. nByte = nHdr+nData;
  71501. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  71502. goto too_big;
  71503. }
  71504. /* Make sure the output register has a buffer large enough to store
  71505. ** the new record. The output register (pOp->p3) is not allowed to
  71506. ** be one of the input registers (because the following call to
  71507. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  71508. */
  71509. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  71510. goto no_mem;
  71511. }
  71512. zNewRecord = (u8 *)pOut->z;
  71513. /* Write the record */
  71514. i = putVarint32(zNewRecord, nHdr);
  71515. j = nHdr;
  71516. assert( pData0<=pLast );
  71517. pRec = pData0;
  71518. do{
  71519. serial_type = pRec->uTemp;
  71520. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  71521. ** additional varints, one per column. */
  71522. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  71523. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  71524. ** immediately follow the header. */
  71525. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  71526. }while( (++pRec)<=pLast );
  71527. assert( i==nHdr );
  71528. assert( j==nByte );
  71529. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  71530. pOut->n = (int)nByte;
  71531. pOut->flags = MEM_Blob;
  71532. if( nZero ){
  71533. pOut->u.nZero = nZero;
  71534. pOut->flags |= MEM_Zero;
  71535. }
  71536. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  71537. REGISTER_TRACE(pOp->p3, pOut);
  71538. UPDATE_MAX_BLOBSIZE(pOut);
  71539. break;
  71540. }
  71541. /* Opcode: Count P1 P2 * * *
  71542. ** Synopsis: r[P2]=count()
  71543. **
  71544. ** Store the number of entries (an integer value) in the table or index
  71545. ** opened by cursor P1 in register P2
  71546. */
  71547. #ifndef SQLITE_OMIT_BTREECOUNT
  71548. case OP_Count: { /* out2 */
  71549. i64 nEntry;
  71550. BtCursor *pCrsr;
  71551. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  71552. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  71553. assert( pCrsr );
  71554. nEntry = 0; /* Not needed. Only used to silence a warning. */
  71555. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  71556. pOut = out2Prerelease(p, pOp);
  71557. pOut->u.i = nEntry;
  71558. break;
  71559. }
  71560. #endif
  71561. /* Opcode: Savepoint P1 * * P4 *
  71562. **
  71563. ** Open, release or rollback the savepoint named by parameter P4, depending
  71564. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  71565. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  71566. */
  71567. case OP_Savepoint: {
  71568. int p1; /* Value of P1 operand */
  71569. char *zName; /* Name of savepoint */
  71570. int nName;
  71571. Savepoint *pNew;
  71572. Savepoint *pSavepoint;
  71573. Savepoint *pTmp;
  71574. int iSavepoint;
  71575. int ii;
  71576. p1 = pOp->p1;
  71577. zName = pOp->p4.z;
  71578. /* Assert that the p1 parameter is valid. Also that if there is no open
  71579. ** transaction, then there cannot be any savepoints.
  71580. */
  71581. assert( db->pSavepoint==0 || db->autoCommit==0 );
  71582. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  71583. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  71584. assert( checkSavepointCount(db) );
  71585. assert( p->bIsReader );
  71586. if( p1==SAVEPOINT_BEGIN ){
  71587. if( db->nVdbeWrite>0 ){
  71588. /* A new savepoint cannot be created if there are active write
  71589. ** statements (i.e. open read/write incremental blob handles).
  71590. */
  71591. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  71592. rc = SQLITE_BUSY;
  71593. }else{
  71594. nName = sqlite3Strlen30(zName);
  71595. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71596. /* This call is Ok even if this savepoint is actually a transaction
  71597. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  71598. ** If this is a transaction savepoint being opened, it is guaranteed
  71599. ** that the db->aVTrans[] array is empty. */
  71600. assert( db->autoCommit==0 || db->nVTrans==0 );
  71601. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  71602. db->nStatement+db->nSavepoint);
  71603. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  71604. #endif
  71605. /* Create a new savepoint structure. */
  71606. pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
  71607. if( pNew ){
  71608. pNew->zName = (char *)&pNew[1];
  71609. memcpy(pNew->zName, zName, nName+1);
  71610. /* If there is no open transaction, then mark this as a special
  71611. ** "transaction savepoint". */
  71612. if( db->autoCommit ){
  71613. db->autoCommit = 0;
  71614. db->isTransactionSavepoint = 1;
  71615. }else{
  71616. db->nSavepoint++;
  71617. }
  71618. /* Link the new savepoint into the database handle's list. */
  71619. pNew->pNext = db->pSavepoint;
  71620. db->pSavepoint = pNew;
  71621. pNew->nDeferredCons = db->nDeferredCons;
  71622. pNew->nDeferredImmCons = db->nDeferredImmCons;
  71623. }
  71624. }
  71625. }else{
  71626. iSavepoint = 0;
  71627. /* Find the named savepoint. If there is no such savepoint, then an
  71628. ** an error is returned to the user. */
  71629. for(
  71630. pSavepoint = db->pSavepoint;
  71631. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  71632. pSavepoint = pSavepoint->pNext
  71633. ){
  71634. iSavepoint++;
  71635. }
  71636. if( !pSavepoint ){
  71637. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  71638. rc = SQLITE_ERROR;
  71639. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  71640. /* It is not possible to release (commit) a savepoint if there are
  71641. ** active write statements.
  71642. */
  71643. sqlite3VdbeError(p, "cannot release savepoint - "
  71644. "SQL statements in progress");
  71645. rc = SQLITE_BUSY;
  71646. }else{
  71647. /* Determine whether or not this is a transaction savepoint. If so,
  71648. ** and this is a RELEASE command, then the current transaction
  71649. ** is committed.
  71650. */
  71651. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  71652. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  71653. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  71654. goto vdbe_return;
  71655. }
  71656. db->autoCommit = 1;
  71657. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  71658. p->pc = (int)(pOp - aOp);
  71659. db->autoCommit = 0;
  71660. p->rc = rc = SQLITE_BUSY;
  71661. goto vdbe_return;
  71662. }
  71663. db->isTransactionSavepoint = 0;
  71664. rc = p->rc;
  71665. }else{
  71666. int isSchemaChange;
  71667. iSavepoint = db->nSavepoint - iSavepoint - 1;
  71668. if( p1==SAVEPOINT_ROLLBACK ){
  71669. isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
  71670. for(ii=0; ii<db->nDb; ii++){
  71671. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  71672. SQLITE_ABORT_ROLLBACK,
  71673. isSchemaChange==0);
  71674. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  71675. }
  71676. }else{
  71677. isSchemaChange = 0;
  71678. }
  71679. for(ii=0; ii<db->nDb; ii++){
  71680. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  71681. if( rc!=SQLITE_OK ){
  71682. goto abort_due_to_error;
  71683. }
  71684. }
  71685. if( isSchemaChange ){
  71686. sqlite3ExpirePreparedStatements(db);
  71687. sqlite3ResetAllSchemasOfConnection(db);
  71688. db->flags = (db->flags | SQLITE_InternChanges);
  71689. }
  71690. }
  71691. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  71692. ** savepoints nested inside of the savepoint being operated on. */
  71693. while( db->pSavepoint!=pSavepoint ){
  71694. pTmp = db->pSavepoint;
  71695. db->pSavepoint = pTmp->pNext;
  71696. sqlite3DbFree(db, pTmp);
  71697. db->nSavepoint--;
  71698. }
  71699. /* If it is a RELEASE, then destroy the savepoint being operated on
  71700. ** too. If it is a ROLLBACK TO, then set the number of deferred
  71701. ** constraint violations present in the database to the value stored
  71702. ** when the savepoint was created. */
  71703. if( p1==SAVEPOINT_RELEASE ){
  71704. assert( pSavepoint==db->pSavepoint );
  71705. db->pSavepoint = pSavepoint->pNext;
  71706. sqlite3DbFree(db, pSavepoint);
  71707. if( !isTransaction ){
  71708. db->nSavepoint--;
  71709. }
  71710. }else{
  71711. db->nDeferredCons = pSavepoint->nDeferredCons;
  71712. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  71713. }
  71714. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  71715. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  71716. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  71717. }
  71718. }
  71719. }
  71720. break;
  71721. }
  71722. /* Opcode: AutoCommit P1 P2 * * *
  71723. **
  71724. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  71725. ** back any currently active btree transactions. If there are any active
  71726. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  71727. ** there are active writing VMs or active VMs that use shared cache.
  71728. **
  71729. ** This instruction causes the VM to halt.
  71730. */
  71731. case OP_AutoCommit: {
  71732. int desiredAutoCommit;
  71733. int iRollback;
  71734. int turnOnAC;
  71735. desiredAutoCommit = pOp->p1;
  71736. iRollback = pOp->p2;
  71737. turnOnAC = desiredAutoCommit && !db->autoCommit;
  71738. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  71739. assert( desiredAutoCommit==1 || iRollback==0 );
  71740. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  71741. assert( p->bIsReader );
  71742. if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
  71743. /* If this instruction implements a COMMIT and other VMs are writing
  71744. ** return an error indicating that the other VMs must complete first.
  71745. */
  71746. sqlite3VdbeError(p, "cannot commit transaction - "
  71747. "SQL statements in progress");
  71748. rc = SQLITE_BUSY;
  71749. }else if( desiredAutoCommit!=db->autoCommit ){
  71750. if( iRollback ){
  71751. assert( desiredAutoCommit==1 );
  71752. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  71753. db->autoCommit = 1;
  71754. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  71755. goto vdbe_return;
  71756. }else{
  71757. db->autoCommit = (u8)desiredAutoCommit;
  71758. }
  71759. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  71760. p->pc = (int)(pOp - aOp);
  71761. db->autoCommit = (u8)(1-desiredAutoCommit);
  71762. p->rc = rc = SQLITE_BUSY;
  71763. goto vdbe_return;
  71764. }
  71765. assert( db->nStatement==0 );
  71766. sqlite3CloseSavepoints(db);
  71767. if( p->rc==SQLITE_OK ){
  71768. rc = SQLITE_DONE;
  71769. }else{
  71770. rc = SQLITE_ERROR;
  71771. }
  71772. goto vdbe_return;
  71773. }else{
  71774. sqlite3VdbeError(p,
  71775. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  71776. (iRollback)?"cannot rollback - no transaction is active":
  71777. "cannot commit - no transaction is active"));
  71778. rc = SQLITE_ERROR;
  71779. }
  71780. break;
  71781. }
  71782. /* Opcode: Transaction P1 P2 P3 P4 P5
  71783. **
  71784. ** Begin a transaction on database P1 if a transaction is not already
  71785. ** active.
  71786. ** If P2 is non-zero, then a write-transaction is started, or if a
  71787. ** read-transaction is already active, it is upgraded to a write-transaction.
  71788. ** If P2 is zero, then a read-transaction is started.
  71789. **
  71790. ** P1 is the index of the database file on which the transaction is
  71791. ** started. Index 0 is the main database file and index 1 is the
  71792. ** file used for temporary tables. Indices of 2 or more are used for
  71793. ** attached databases.
  71794. **
  71795. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  71796. ** true (this flag is set if the Vdbe may modify more than one row and may
  71797. ** throw an ABORT exception), a statement transaction may also be opened.
  71798. ** More specifically, a statement transaction is opened iff the database
  71799. ** connection is currently not in autocommit mode, or if there are other
  71800. ** active statements. A statement transaction allows the changes made by this
  71801. ** VDBE to be rolled back after an error without having to roll back the
  71802. ** entire transaction. If no error is encountered, the statement transaction
  71803. ** will automatically commit when the VDBE halts.
  71804. **
  71805. ** If P5!=0 then this opcode also checks the schema cookie against P3
  71806. ** and the schema generation counter against P4.
  71807. ** The cookie changes its value whenever the database schema changes.
  71808. ** This operation is used to detect when that the cookie has changed
  71809. ** and that the current process needs to reread the schema. If the schema
  71810. ** cookie in P3 differs from the schema cookie in the database header or
  71811. ** if the schema generation counter in P4 differs from the current
  71812. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  71813. ** halts. The sqlite3_step() wrapper function might then reprepare the
  71814. ** statement and rerun it from the beginning.
  71815. */
  71816. case OP_Transaction: {
  71817. Btree *pBt;
  71818. int iMeta;
  71819. int iGen;
  71820. assert( p->bIsReader );
  71821. assert( p->readOnly==0 || pOp->p2==0 );
  71822. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  71823. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  71824. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  71825. rc = SQLITE_READONLY;
  71826. goto abort_due_to_error;
  71827. }
  71828. pBt = db->aDb[pOp->p1].pBt;
  71829. if( pBt ){
  71830. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  71831. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  71832. testcase( rc==SQLITE_BUSY_RECOVERY );
  71833. if( (rc&0xff)==SQLITE_BUSY ){
  71834. p->pc = (int)(pOp - aOp);
  71835. p->rc = rc;
  71836. goto vdbe_return;
  71837. }
  71838. if( rc!=SQLITE_OK ){
  71839. goto abort_due_to_error;
  71840. }
  71841. if( pOp->p2 && p->usesStmtJournal
  71842. && (db->autoCommit==0 || db->nVdbeRead>1)
  71843. ){
  71844. assert( sqlite3BtreeIsInTrans(pBt) );
  71845. if( p->iStatement==0 ){
  71846. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  71847. db->nStatement++;
  71848. p->iStatement = db->nSavepoint + db->nStatement;
  71849. }
  71850. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  71851. if( rc==SQLITE_OK ){
  71852. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  71853. }
  71854. /* Store the current value of the database handles deferred constraint
  71855. ** counter. If the statement transaction needs to be rolled back,
  71856. ** the value of this counter needs to be restored too. */
  71857. p->nStmtDefCons = db->nDeferredCons;
  71858. p->nStmtDefImmCons = db->nDeferredImmCons;
  71859. }
  71860. /* Gather the schema version number for checking:
  71861. ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
  71862. ** each time a query is executed to ensure that the internal cache of the
  71863. ** schema used when compiling the SQL query matches the schema of the
  71864. ** database against which the compiled query is actually executed.
  71865. */
  71866. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  71867. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  71868. }else{
  71869. iGen = iMeta = 0;
  71870. }
  71871. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  71872. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  71873. sqlite3DbFree(db, p->zErrMsg);
  71874. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  71875. /* If the schema-cookie from the database file matches the cookie
  71876. ** stored with the in-memory representation of the schema, do
  71877. ** not reload the schema from the database file.
  71878. **
  71879. ** If virtual-tables are in use, this is not just an optimization.
  71880. ** Often, v-tables store their data in other SQLite tables, which
  71881. ** are queried from within xNext() and other v-table methods using
  71882. ** prepared queries. If such a query is out-of-date, we do not want to
  71883. ** discard the database schema, as the user code implementing the
  71884. ** v-table would have to be ready for the sqlite3_vtab structure itself
  71885. ** to be invalidated whenever sqlite3_step() is called from within
  71886. ** a v-table method.
  71887. */
  71888. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  71889. sqlite3ResetOneSchema(db, pOp->p1);
  71890. }
  71891. p->expired = 1;
  71892. rc = SQLITE_SCHEMA;
  71893. }
  71894. break;
  71895. }
  71896. /* Opcode: ReadCookie P1 P2 P3 * *
  71897. **
  71898. ** Read cookie number P3 from database P1 and write it into register P2.
  71899. ** P3==1 is the schema version. P3==2 is the database format.
  71900. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  71901. ** the main database file and P1==1 is the database file used to store
  71902. ** temporary tables.
  71903. **
  71904. ** There must be a read-lock on the database (either a transaction
  71905. ** must be started or there must be an open cursor) before
  71906. ** executing this instruction.
  71907. */
  71908. case OP_ReadCookie: { /* out2 */
  71909. int iMeta;
  71910. int iDb;
  71911. int iCookie;
  71912. assert( p->bIsReader );
  71913. iDb = pOp->p1;
  71914. iCookie = pOp->p3;
  71915. assert( pOp->p3<SQLITE_N_BTREE_META );
  71916. assert( iDb>=0 && iDb<db->nDb );
  71917. assert( db->aDb[iDb].pBt!=0 );
  71918. assert( DbMaskTest(p->btreeMask, iDb) );
  71919. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  71920. pOut = out2Prerelease(p, pOp);
  71921. pOut->u.i = iMeta;
  71922. break;
  71923. }
  71924. /* Opcode: SetCookie P1 P2 P3 * *
  71925. **
  71926. ** Write the content of register P3 (interpreted as an integer)
  71927. ** into cookie number P2 of database P1. P2==1 is the schema version.
  71928. ** P2==2 is the database format. P2==3 is the recommended pager cache
  71929. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  71930. ** database file used to store temporary tables.
  71931. **
  71932. ** A transaction must be started before executing this opcode.
  71933. */
  71934. case OP_SetCookie: { /* in3 */
  71935. Db *pDb;
  71936. assert( pOp->p2<SQLITE_N_BTREE_META );
  71937. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  71938. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  71939. assert( p->readOnly==0 );
  71940. pDb = &db->aDb[pOp->p1];
  71941. assert( pDb->pBt!=0 );
  71942. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  71943. pIn3 = &aMem[pOp->p3];
  71944. sqlite3VdbeMemIntegerify(pIn3);
  71945. /* See note about index shifting on OP_ReadCookie */
  71946. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
  71947. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  71948. /* When the schema cookie changes, record the new cookie internally */
  71949. pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  71950. db->flags |= SQLITE_InternChanges;
  71951. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  71952. /* Record changes in the file format */
  71953. pDb->pSchema->file_format = (u8)pIn3->u.i;
  71954. }
  71955. if( pOp->p1==1 ){
  71956. /* Invalidate all prepared statements whenever the TEMP database
  71957. ** schema is changed. Ticket #1644 */
  71958. sqlite3ExpirePreparedStatements(db);
  71959. p->expired = 0;
  71960. }
  71961. break;
  71962. }
  71963. /* Opcode: OpenRead P1 P2 P3 P4 P5
  71964. ** Synopsis: root=P2 iDb=P3
  71965. **
  71966. ** Open a read-only cursor for the database table whose root page is
  71967. ** P2 in a database file. The database file is determined by P3.
  71968. ** P3==0 means the main database, P3==1 means the database used for
  71969. ** temporary tables, and P3>1 means used the corresponding attached
  71970. ** database. Give the new cursor an identifier of P1. The P1
  71971. ** values need not be contiguous but all P1 values should be small integers.
  71972. ** It is an error for P1 to be negative.
  71973. **
  71974. ** If P5!=0 then use the content of register P2 as the root page, not
  71975. ** the value of P2 itself.
  71976. **
  71977. ** There will be a read lock on the database whenever there is an
  71978. ** open cursor. If the database was unlocked prior to this instruction
  71979. ** then a read lock is acquired as part of this instruction. A read
  71980. ** lock allows other processes to read the database but prohibits
  71981. ** any other process from modifying the database. The read lock is
  71982. ** released when all cursors are closed. If this instruction attempts
  71983. ** to get a read lock but fails, the script terminates with an
  71984. ** SQLITE_BUSY error code.
  71985. **
  71986. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  71987. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  71988. ** structure, then said structure defines the content and collating
  71989. ** sequence of the index being opened. Otherwise, if P4 is an integer
  71990. ** value, it is set to the number of columns in the table.
  71991. **
  71992. ** See also: OpenWrite, ReopenIdx
  71993. */
  71994. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  71995. ** Synopsis: root=P2 iDb=P3
  71996. **
  71997. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  71998. ** checks to see if the cursor on P1 is already open with a root page
  71999. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  72000. ** if the cursor is already open, do not reopen it.
  72001. **
  72002. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  72003. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  72004. ** every other ReopenIdx or OpenRead for the same cursor number.
  72005. **
  72006. ** See the OpenRead opcode documentation for additional information.
  72007. */
  72008. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  72009. ** Synopsis: root=P2 iDb=P3
  72010. **
  72011. ** Open a read/write cursor named P1 on the table or index whose root
  72012. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  72013. ** root page.
  72014. **
  72015. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  72016. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  72017. ** structure, then said structure defines the content and collating
  72018. ** sequence of the index being opened. Otherwise, if P4 is an integer
  72019. ** value, it is set to the number of columns in the table, or to the
  72020. ** largest index of any column of the table that is actually used.
  72021. **
  72022. ** This instruction works just like OpenRead except that it opens the cursor
  72023. ** in read/write mode. For a given table, there can be one or more read-only
  72024. ** cursors or a single read/write cursor but not both.
  72025. **
  72026. ** See also OpenRead.
  72027. */
  72028. case OP_ReopenIdx: {
  72029. int nField;
  72030. KeyInfo *pKeyInfo;
  72031. int p2;
  72032. int iDb;
  72033. int wrFlag;
  72034. Btree *pX;
  72035. VdbeCursor *pCur;
  72036. Db *pDb;
  72037. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  72038. assert( pOp->p4type==P4_KEYINFO );
  72039. pCur = p->apCsr[pOp->p1];
  72040. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  72041. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  72042. goto open_cursor_set_hints;
  72043. }
  72044. /* If the cursor is not currently open or is open on a different
  72045. ** index, then fall through into OP_OpenRead to force a reopen */
  72046. case OP_OpenRead:
  72047. case OP_OpenWrite:
  72048. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  72049. assert( p->bIsReader );
  72050. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  72051. || p->readOnly==0 );
  72052. if( p->expired ){
  72053. rc = SQLITE_ABORT_ROLLBACK;
  72054. break;
  72055. }
  72056. nField = 0;
  72057. pKeyInfo = 0;
  72058. p2 = pOp->p2;
  72059. iDb = pOp->p3;
  72060. assert( iDb>=0 && iDb<db->nDb );
  72061. assert( DbMaskTest(p->btreeMask, iDb) );
  72062. pDb = &db->aDb[iDb];
  72063. pX = pDb->pBt;
  72064. assert( pX!=0 );
  72065. if( pOp->opcode==OP_OpenWrite ){
  72066. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  72067. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  72068. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  72069. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  72070. p->minWriteFileFormat = pDb->pSchema->file_format;
  72071. }
  72072. }else{
  72073. wrFlag = 0;
  72074. }
  72075. if( pOp->p5 & OPFLAG_P2ISREG ){
  72076. assert( p2>0 );
  72077. assert( p2<=(p->nMem-p->nCursor) );
  72078. pIn2 = &aMem[p2];
  72079. assert( memIsValid(pIn2) );
  72080. assert( (pIn2->flags & MEM_Int)!=0 );
  72081. sqlite3VdbeMemIntegerify(pIn2);
  72082. p2 = (int)pIn2->u.i;
  72083. /* The p2 value always comes from a prior OP_CreateTable opcode and
  72084. ** that opcode will always set the p2 value to 2 or more or else fail.
  72085. ** If there were a failure, the prepared statement would have halted
  72086. ** before reaching this instruction. */
  72087. if( NEVER(p2<2) ) {
  72088. rc = SQLITE_CORRUPT_BKPT;
  72089. goto abort_due_to_error;
  72090. }
  72091. }
  72092. if( pOp->p4type==P4_KEYINFO ){
  72093. pKeyInfo = pOp->p4.pKeyInfo;
  72094. assert( pKeyInfo->enc==ENC(db) );
  72095. assert( pKeyInfo->db==db );
  72096. nField = pKeyInfo->nField+pKeyInfo->nXField;
  72097. }else if( pOp->p4type==P4_INT32 ){
  72098. nField = pOp->p4.i;
  72099. }
  72100. assert( pOp->p1>=0 );
  72101. assert( nField>=0 );
  72102. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  72103. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  72104. if( pCur==0 ) goto no_mem;
  72105. pCur->nullRow = 1;
  72106. pCur->isOrdered = 1;
  72107. pCur->pgnoRoot = p2;
  72108. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  72109. pCur->pKeyInfo = pKeyInfo;
  72110. /* Set the VdbeCursor.isTable variable. Previous versions of
  72111. ** SQLite used to check if the root-page flags were sane at this point
  72112. ** and report database corruption if they were not, but this check has
  72113. ** since moved into the btree layer. */
  72114. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  72115. open_cursor_set_hints:
  72116. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  72117. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  72118. testcase( pOp->p5 & OPFLAG_BULKCSR );
  72119. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  72120. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  72121. #endif
  72122. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  72123. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  72124. break;
  72125. }
  72126. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  72127. ** Synopsis: nColumn=P2
  72128. **
  72129. ** Open a new cursor P1 to a transient table.
  72130. ** The cursor is always opened read/write even if
  72131. ** the main database is read-only. The ephemeral
  72132. ** table is deleted automatically when the cursor is closed.
  72133. **
  72134. ** P2 is the number of columns in the ephemeral table.
  72135. ** The cursor points to a BTree table if P4==0 and to a BTree index
  72136. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  72137. ** that defines the format of keys in the index.
  72138. **
  72139. ** The P5 parameter can be a mask of the BTREE_* flags defined
  72140. ** in btree.h. These flags control aspects of the operation of
  72141. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  72142. ** added automatically.
  72143. */
  72144. /* Opcode: OpenAutoindex P1 P2 * P4 *
  72145. ** Synopsis: nColumn=P2
  72146. **
  72147. ** This opcode works the same as OP_OpenEphemeral. It has a
  72148. ** different name to distinguish its use. Tables created using
  72149. ** by this opcode will be used for automatically created transient
  72150. ** indices in joins.
  72151. */
  72152. case OP_OpenAutoindex:
  72153. case OP_OpenEphemeral: {
  72154. VdbeCursor *pCx;
  72155. KeyInfo *pKeyInfo;
  72156. static const int vfsFlags =
  72157. SQLITE_OPEN_READWRITE |
  72158. SQLITE_OPEN_CREATE |
  72159. SQLITE_OPEN_EXCLUSIVE |
  72160. SQLITE_OPEN_DELETEONCLOSE |
  72161. SQLITE_OPEN_TRANSIENT_DB;
  72162. assert( pOp->p1>=0 );
  72163. assert( pOp->p2>=0 );
  72164. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  72165. if( pCx==0 ) goto no_mem;
  72166. pCx->nullRow = 1;
  72167. pCx->isEphemeral = 1;
  72168. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
  72169. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  72170. if( rc==SQLITE_OK ){
  72171. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  72172. }
  72173. if( rc==SQLITE_OK ){
  72174. /* If a transient index is required, create it by calling
  72175. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  72176. ** opening it. If a transient table is required, just use the
  72177. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  72178. */
  72179. if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  72180. int pgno;
  72181. assert( pOp->p4type==P4_KEYINFO );
  72182. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  72183. if( rc==SQLITE_OK ){
  72184. assert( pgno==MASTER_ROOT+1 );
  72185. assert( pKeyInfo->db==db );
  72186. assert( pKeyInfo->enc==ENC(db) );
  72187. pCx->pKeyInfo = pKeyInfo;
  72188. rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR,
  72189. pKeyInfo, pCx->uc.pCursor);
  72190. }
  72191. pCx->isTable = 0;
  72192. }else{
  72193. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR,
  72194. 0, pCx->uc.pCursor);
  72195. pCx->isTable = 1;
  72196. }
  72197. }
  72198. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  72199. break;
  72200. }
  72201. /* Opcode: SorterOpen P1 P2 P3 P4 *
  72202. **
  72203. ** This opcode works like OP_OpenEphemeral except that it opens
  72204. ** a transient index that is specifically designed to sort large
  72205. ** tables using an external merge-sort algorithm.
  72206. **
  72207. ** If argument P3 is non-zero, then it indicates that the sorter may
  72208. ** assume that a stable sort considering the first P3 fields of each
  72209. ** key is sufficient to produce the required results.
  72210. */
  72211. case OP_SorterOpen: {
  72212. VdbeCursor *pCx;
  72213. assert( pOp->p1>=0 );
  72214. assert( pOp->p2>=0 );
  72215. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  72216. if( pCx==0 ) goto no_mem;
  72217. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  72218. assert( pCx->pKeyInfo->db==db );
  72219. assert( pCx->pKeyInfo->enc==ENC(db) );
  72220. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  72221. break;
  72222. }
  72223. /* Opcode: SequenceTest P1 P2 * * *
  72224. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  72225. **
  72226. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  72227. ** to P2. Regardless of whether or not the jump is taken, increment the
  72228. ** the sequence value.
  72229. */
  72230. case OP_SequenceTest: {
  72231. VdbeCursor *pC;
  72232. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72233. pC = p->apCsr[pOp->p1];
  72234. assert( isSorter(pC) );
  72235. if( (pC->seqCount++)==0 ){
  72236. goto jump_to_p2;
  72237. }
  72238. break;
  72239. }
  72240. /* Opcode: OpenPseudo P1 P2 P3 * *
  72241. ** Synopsis: P3 columns in r[P2]
  72242. **
  72243. ** Open a new cursor that points to a fake table that contains a single
  72244. ** row of data. The content of that one row is the content of memory
  72245. ** register P2. In other words, cursor P1 becomes an alias for the
  72246. ** MEM_Blob content contained in register P2.
  72247. **
  72248. ** A pseudo-table created by this opcode is used to hold a single
  72249. ** row output from the sorter so that the row can be decomposed into
  72250. ** individual columns using the OP_Column opcode. The OP_Column opcode
  72251. ** is the only cursor opcode that works with a pseudo-table.
  72252. **
  72253. ** P3 is the number of fields in the records that will be stored by
  72254. ** the pseudo-table.
  72255. */
  72256. case OP_OpenPseudo: {
  72257. VdbeCursor *pCx;
  72258. assert( pOp->p1>=0 );
  72259. assert( pOp->p3>=0 );
  72260. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  72261. if( pCx==0 ) goto no_mem;
  72262. pCx->nullRow = 1;
  72263. pCx->uc.pseudoTableReg = pOp->p2;
  72264. pCx->isTable = 1;
  72265. assert( pOp->p5==0 );
  72266. break;
  72267. }
  72268. /* Opcode: Close P1 * * * *
  72269. **
  72270. ** Close a cursor previously opened as P1. If P1 is not
  72271. ** currently open, this instruction is a no-op.
  72272. */
  72273. case OP_Close: {
  72274. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72275. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  72276. p->apCsr[pOp->p1] = 0;
  72277. break;
  72278. }
  72279. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  72280. /* Opcode: ColumnsUsed P1 * * P4 *
  72281. **
  72282. ** This opcode (which only exists if SQLite was compiled with
  72283. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  72284. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  72285. ** (P4_INT64) in which the first 63 bits are one for each of the
  72286. ** first 63 columns of the table or index that are actually used
  72287. ** by the cursor. The high-order bit is set if any column after
  72288. ** the 64th is used.
  72289. */
  72290. case OP_ColumnsUsed: {
  72291. VdbeCursor *pC;
  72292. pC = p->apCsr[pOp->p1];
  72293. assert( pC->eCurType==CURTYPE_BTREE );
  72294. pC->maskUsed = *(u64*)pOp->p4.pI64;
  72295. break;
  72296. }
  72297. #endif
  72298. /* Opcode: SeekGE P1 P2 P3 P4 *
  72299. ** Synopsis: key=r[P3@P4]
  72300. **
  72301. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  72302. ** use the value in register P3 as the key. If cursor P1 refers
  72303. ** to an SQL index, then P3 is the first in an array of P4 registers
  72304. ** that are used as an unpacked index key.
  72305. **
  72306. ** Reposition cursor P1 so that it points to the smallest entry that
  72307. ** is greater than or equal to the key value. If there are no records
  72308. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  72309. **
  72310. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  72311. ** opcode will always land on a record that equally equals the key, or
  72312. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  72313. ** opcode must be followed by an IdxLE opcode with the same arguments.
  72314. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  72315. ** IdxLE opcode will be used on subsequent loop iterations.
  72316. **
  72317. ** This opcode leaves the cursor configured to move in forward order,
  72318. ** from the beginning toward the end. In other words, the cursor is
  72319. ** configured to use Next, not Prev.
  72320. **
  72321. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  72322. */
  72323. /* Opcode: SeekGT P1 P2 P3 P4 *
  72324. ** Synopsis: key=r[P3@P4]
  72325. **
  72326. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  72327. ** use the value in register P3 as a key. If cursor P1 refers
  72328. ** to an SQL index, then P3 is the first in an array of P4 registers
  72329. ** that are used as an unpacked index key.
  72330. **
  72331. ** Reposition cursor P1 so that it points to the smallest entry that
  72332. ** is greater than the key value. If there are no records greater than
  72333. ** the key and P2 is not zero, then jump to P2.
  72334. **
  72335. ** This opcode leaves the cursor configured to move in forward order,
  72336. ** from the beginning toward the end. In other words, the cursor is
  72337. ** configured to use Next, not Prev.
  72338. **
  72339. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  72340. */
  72341. /* Opcode: SeekLT P1 P2 P3 P4 *
  72342. ** Synopsis: key=r[P3@P4]
  72343. **
  72344. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  72345. ** use the value in register P3 as a key. If cursor P1 refers
  72346. ** to an SQL index, then P3 is the first in an array of P4 registers
  72347. ** that are used as an unpacked index key.
  72348. **
  72349. ** Reposition cursor P1 so that it points to the largest entry that
  72350. ** is less than the key value. If there are no records less than
  72351. ** the key and P2 is not zero, then jump to P2.
  72352. **
  72353. ** This opcode leaves the cursor configured to move in reverse order,
  72354. ** from the end toward the beginning. In other words, the cursor is
  72355. ** configured to use Prev, not Next.
  72356. **
  72357. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  72358. */
  72359. /* Opcode: SeekLE P1 P2 P3 P4 *
  72360. ** Synopsis: key=r[P3@P4]
  72361. **
  72362. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  72363. ** use the value in register P3 as a key. If cursor P1 refers
  72364. ** to an SQL index, then P3 is the first in an array of P4 registers
  72365. ** that are used as an unpacked index key.
  72366. **
  72367. ** Reposition cursor P1 so that it points to the largest entry that
  72368. ** is less than or equal to the key value. If there are no records
  72369. ** less than or equal to the key and P2 is not zero, then jump to P2.
  72370. **
  72371. ** This opcode leaves the cursor configured to move in reverse order,
  72372. ** from the end toward the beginning. In other words, the cursor is
  72373. ** configured to use Prev, not Next.
  72374. **
  72375. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  72376. ** opcode will always land on a record that equally equals the key, or
  72377. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  72378. ** opcode must be followed by an IdxGE opcode with the same arguments.
  72379. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  72380. ** IdxGE opcode will be used on subsequent loop iterations.
  72381. **
  72382. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  72383. */
  72384. case OP_SeekLT: /* jump, in3 */
  72385. case OP_SeekLE: /* jump, in3 */
  72386. case OP_SeekGE: /* jump, in3 */
  72387. case OP_SeekGT: { /* jump, in3 */
  72388. int res; /* Comparison result */
  72389. int oc; /* Opcode */
  72390. VdbeCursor *pC; /* The cursor to seek */
  72391. UnpackedRecord r; /* The key to seek for */
  72392. int nField; /* Number of columns or fields in the key */
  72393. i64 iKey; /* The rowid we are to seek to */
  72394. int eqOnly; /* Only interested in == results */
  72395. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72396. assert( pOp->p2!=0 );
  72397. pC = p->apCsr[pOp->p1];
  72398. assert( pC!=0 );
  72399. assert( pC->eCurType==CURTYPE_BTREE );
  72400. assert( OP_SeekLE == OP_SeekLT+1 );
  72401. assert( OP_SeekGE == OP_SeekLT+2 );
  72402. assert( OP_SeekGT == OP_SeekLT+3 );
  72403. assert( pC->isOrdered );
  72404. assert( pC->uc.pCursor!=0 );
  72405. oc = pOp->opcode;
  72406. eqOnly = 0;
  72407. pC->nullRow = 0;
  72408. #ifdef SQLITE_DEBUG
  72409. pC->seekOp = pOp->opcode;
  72410. #endif
  72411. if( pC->isTable ){
  72412. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  72413. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 );
  72414. /* The input value in P3 might be of any type: integer, real, string,
  72415. ** blob, or NULL. But it needs to be an integer before we can do
  72416. ** the seek, so convert it. */
  72417. pIn3 = &aMem[pOp->p3];
  72418. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  72419. applyNumericAffinity(pIn3, 0);
  72420. }
  72421. iKey = sqlite3VdbeIntValue(pIn3);
  72422. /* If the P3 value could not be converted into an integer without
  72423. ** loss of information, then special processing is required... */
  72424. if( (pIn3->flags & MEM_Int)==0 ){
  72425. if( (pIn3->flags & MEM_Real)==0 ){
  72426. /* If the P3 value cannot be converted into any kind of a number,
  72427. ** then the seek is not possible, so jump to P2 */
  72428. VdbeBranchTaken(1,2); goto jump_to_p2;
  72429. break;
  72430. }
  72431. /* If the approximation iKey is larger than the actual real search
  72432. ** term, substitute >= for > and < for <=. e.g. if the search term
  72433. ** is 4.9 and the integer approximation 5:
  72434. **
  72435. ** (x > 4.9) -> (x >= 5)
  72436. ** (x <= 4.9) -> (x < 5)
  72437. */
  72438. if( pIn3->u.r<(double)iKey ){
  72439. assert( OP_SeekGE==(OP_SeekGT-1) );
  72440. assert( OP_SeekLT==(OP_SeekLE-1) );
  72441. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  72442. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  72443. }
  72444. /* If the approximation iKey is smaller than the actual real search
  72445. ** term, substitute <= for < and > for >=. */
  72446. else if( pIn3->u.r>(double)iKey ){
  72447. assert( OP_SeekLE==(OP_SeekLT+1) );
  72448. assert( OP_SeekGT==(OP_SeekGE+1) );
  72449. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  72450. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  72451. }
  72452. }
  72453. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  72454. pC->movetoTarget = iKey; /* Used by OP_Delete */
  72455. if( rc!=SQLITE_OK ){
  72456. goto abort_due_to_error;
  72457. }
  72458. }else{
  72459. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  72460. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  72461. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  72462. */
  72463. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  72464. eqOnly = 1;
  72465. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  72466. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  72467. assert( pOp[1].p1==pOp[0].p1 );
  72468. assert( pOp[1].p2==pOp[0].p2 );
  72469. assert( pOp[1].p3==pOp[0].p3 );
  72470. assert( pOp[1].p4.i==pOp[0].p4.i );
  72471. }
  72472. nField = pOp->p4.i;
  72473. assert( pOp->p4type==P4_INT32 );
  72474. assert( nField>0 );
  72475. r.pKeyInfo = pC->pKeyInfo;
  72476. r.nField = (u16)nField;
  72477. /* The next line of code computes as follows, only faster:
  72478. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  72479. ** r.default_rc = -1;
  72480. ** }else{
  72481. ** r.default_rc = +1;
  72482. ** }
  72483. */
  72484. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  72485. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  72486. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  72487. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  72488. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  72489. r.aMem = &aMem[pOp->p3];
  72490. #ifdef SQLITE_DEBUG
  72491. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  72492. #endif
  72493. ExpandBlob(r.aMem);
  72494. r.eqSeen = 0;
  72495. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  72496. if( rc!=SQLITE_OK ){
  72497. goto abort_due_to_error;
  72498. }
  72499. if( eqOnly && r.eqSeen==0 ){
  72500. assert( res!=0 );
  72501. goto seek_not_found;
  72502. }
  72503. }
  72504. pC->deferredMoveto = 0;
  72505. pC->cacheStatus = CACHE_STALE;
  72506. #ifdef SQLITE_TEST
  72507. sqlite3_search_count++;
  72508. #endif
  72509. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  72510. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  72511. res = 0;
  72512. rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
  72513. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  72514. }else{
  72515. res = 0;
  72516. }
  72517. }else{
  72518. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  72519. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  72520. res = 0;
  72521. rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
  72522. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  72523. }else{
  72524. /* res might be negative because the table is empty. Check to
  72525. ** see if this is the case.
  72526. */
  72527. res = sqlite3BtreeEof(pC->uc.pCursor);
  72528. }
  72529. }
  72530. seek_not_found:
  72531. assert( pOp->p2>0 );
  72532. VdbeBranchTaken(res!=0,2);
  72533. if( res ){
  72534. goto jump_to_p2;
  72535. }else if( eqOnly ){
  72536. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  72537. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  72538. }
  72539. break;
  72540. }
  72541. /* Opcode: Seek P1 P2 * * *
  72542. ** Synopsis: intkey=r[P2]
  72543. **
  72544. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  72545. ** for P1 to move so that it points to the rowid given by P2.
  72546. **
  72547. ** This is actually a deferred seek. Nothing actually happens until
  72548. ** the cursor is used to read a record. That way, if no reads
  72549. ** occur, no unnecessary I/O happens.
  72550. */
  72551. case OP_Seek: { /* in2 */
  72552. VdbeCursor *pC;
  72553. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72554. pC = p->apCsr[pOp->p1];
  72555. assert( pC!=0 );
  72556. assert( pC->eCurType==CURTYPE_BTREE );
  72557. assert( pC->uc.pCursor!=0 );
  72558. assert( pC->isTable );
  72559. pC->nullRow = 0;
  72560. pIn2 = &aMem[pOp->p2];
  72561. pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  72562. pC->deferredMoveto = 1;
  72563. break;
  72564. }
  72565. /* Opcode: Found P1 P2 P3 P4 *
  72566. ** Synopsis: key=r[P3@P4]
  72567. **
  72568. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  72569. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  72570. ** record.
  72571. **
  72572. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  72573. ** is a prefix of any entry in P1 then a jump is made to P2 and
  72574. ** P1 is left pointing at the matching entry.
  72575. **
  72576. ** This operation leaves the cursor in a state where it can be
  72577. ** advanced in the forward direction. The Next instruction will work,
  72578. ** but not the Prev instruction.
  72579. **
  72580. ** See also: NotFound, NoConflict, NotExists. SeekGe
  72581. */
  72582. /* Opcode: NotFound P1 P2 P3 P4 *
  72583. ** Synopsis: key=r[P3@P4]
  72584. **
  72585. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  72586. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  72587. ** record.
  72588. **
  72589. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  72590. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  72591. ** does contain an entry whose prefix matches the P3/P4 record then control
  72592. ** falls through to the next instruction and P1 is left pointing at the
  72593. ** matching entry.
  72594. **
  72595. ** This operation leaves the cursor in a state where it cannot be
  72596. ** advanced in either direction. In other words, the Next and Prev
  72597. ** opcodes do not work after this operation.
  72598. **
  72599. ** See also: Found, NotExists, NoConflict
  72600. */
  72601. /* Opcode: NoConflict P1 P2 P3 P4 *
  72602. ** Synopsis: key=r[P3@P4]
  72603. **
  72604. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  72605. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  72606. ** record.
  72607. **
  72608. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  72609. ** contains any NULL value, jump immediately to P2. If all terms of the
  72610. ** record are not-NULL then a check is done to determine if any row in the
  72611. ** P1 index btree has a matching key prefix. If there are no matches, jump
  72612. ** immediately to P2. If there is a match, fall through and leave the P1
  72613. ** cursor pointing to the matching row.
  72614. **
  72615. ** This opcode is similar to OP_NotFound with the exceptions that the
  72616. ** branch is always taken if any part of the search key input is NULL.
  72617. **
  72618. ** This operation leaves the cursor in a state where it cannot be
  72619. ** advanced in either direction. In other words, the Next and Prev
  72620. ** opcodes do not work after this operation.
  72621. **
  72622. ** See also: NotFound, Found, NotExists
  72623. */
  72624. case OP_NoConflict: /* jump, in3 */
  72625. case OP_NotFound: /* jump, in3 */
  72626. case OP_Found: { /* jump, in3 */
  72627. int alreadyExists;
  72628. int takeJump;
  72629. int ii;
  72630. VdbeCursor *pC;
  72631. int res;
  72632. char *pFree;
  72633. UnpackedRecord *pIdxKey;
  72634. UnpackedRecord r;
  72635. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
  72636. #ifdef SQLITE_TEST
  72637. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  72638. #endif
  72639. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72640. assert( pOp->p4type==P4_INT32 );
  72641. pC = p->apCsr[pOp->p1];
  72642. assert( pC!=0 );
  72643. #ifdef SQLITE_DEBUG
  72644. pC->seekOp = pOp->opcode;
  72645. #endif
  72646. pIn3 = &aMem[pOp->p3];
  72647. assert( pC->eCurType==CURTYPE_BTREE );
  72648. assert( pC->uc.pCursor!=0 );
  72649. assert( pC->isTable==0 );
  72650. pFree = 0;
  72651. if( pOp->p4.i>0 ){
  72652. r.pKeyInfo = pC->pKeyInfo;
  72653. r.nField = (u16)pOp->p4.i;
  72654. r.aMem = pIn3;
  72655. for(ii=0; ii<r.nField; ii++){
  72656. assert( memIsValid(&r.aMem[ii]) );
  72657. ExpandBlob(&r.aMem[ii]);
  72658. #ifdef SQLITE_DEBUG
  72659. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  72660. #endif
  72661. }
  72662. pIdxKey = &r;
  72663. }else{
  72664. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  72665. pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
  72666. );
  72667. if( pIdxKey==0 ) goto no_mem;
  72668. assert( pIn3->flags & MEM_Blob );
  72669. ExpandBlob(pIn3);
  72670. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  72671. }
  72672. pIdxKey->default_rc = 0;
  72673. takeJump = 0;
  72674. if( pOp->opcode==OP_NoConflict ){
  72675. /* For the OP_NoConflict opcode, take the jump if any of the
  72676. ** input fields are NULL, since any key with a NULL will not
  72677. ** conflict */
  72678. for(ii=0; ii<pIdxKey->nField; ii++){
  72679. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  72680. takeJump = 1;
  72681. break;
  72682. }
  72683. }
  72684. }
  72685. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  72686. sqlite3DbFree(db, pFree);
  72687. if( rc!=SQLITE_OK ){
  72688. break;
  72689. }
  72690. pC->seekResult = res;
  72691. alreadyExists = (res==0);
  72692. pC->nullRow = 1-alreadyExists;
  72693. pC->deferredMoveto = 0;
  72694. pC->cacheStatus = CACHE_STALE;
  72695. if( pOp->opcode==OP_Found ){
  72696. VdbeBranchTaken(alreadyExists!=0,2);
  72697. if( alreadyExists ) goto jump_to_p2;
  72698. }else{
  72699. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  72700. if( takeJump || !alreadyExists ) goto jump_to_p2;
  72701. }
  72702. break;
  72703. }
  72704. /* Opcode: NotExists P1 P2 P3 * *
  72705. ** Synopsis: intkey=r[P3]
  72706. **
  72707. ** P1 is the index of a cursor open on an SQL table btree (with integer
  72708. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  72709. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  72710. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  72711. ** leave the cursor pointing at that record and fall through to the next
  72712. ** instruction.
  72713. **
  72714. ** The OP_NotFound opcode performs the same operation on index btrees
  72715. ** (with arbitrary multi-value keys).
  72716. **
  72717. ** This opcode leaves the cursor in a state where it cannot be advanced
  72718. ** in either direction. In other words, the Next and Prev opcodes will
  72719. ** not work following this opcode.
  72720. **
  72721. ** See also: Found, NotFound, NoConflict
  72722. */
  72723. case OP_NotExists: { /* jump, in3 */
  72724. VdbeCursor *pC;
  72725. BtCursor *pCrsr;
  72726. int res;
  72727. u64 iKey;
  72728. pIn3 = &aMem[pOp->p3];
  72729. assert( pIn3->flags & MEM_Int );
  72730. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72731. pC = p->apCsr[pOp->p1];
  72732. assert( pC!=0 );
  72733. #ifdef SQLITE_DEBUG
  72734. pC->seekOp = 0;
  72735. #endif
  72736. assert( pC->isTable );
  72737. assert( pC->eCurType==CURTYPE_BTREE );
  72738. pCrsr = pC->uc.pCursor;
  72739. assert( pCrsr!=0 );
  72740. res = 0;
  72741. iKey = pIn3->u.i;
  72742. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  72743. assert( rc==SQLITE_OK || res==0 );
  72744. pC->movetoTarget = iKey; /* Used by OP_Delete */
  72745. pC->nullRow = 0;
  72746. pC->cacheStatus = CACHE_STALE;
  72747. pC->deferredMoveto = 0;
  72748. VdbeBranchTaken(res!=0,2);
  72749. pC->seekResult = res;
  72750. if( res!=0 ){
  72751. assert( rc==SQLITE_OK );
  72752. if( pOp->p2==0 ){
  72753. rc = SQLITE_CORRUPT_BKPT;
  72754. }else{
  72755. goto jump_to_p2;
  72756. }
  72757. }
  72758. break;
  72759. }
  72760. /* Opcode: Sequence P1 P2 * * *
  72761. ** Synopsis: r[P2]=cursor[P1].ctr++
  72762. **
  72763. ** Find the next available sequence number for cursor P1.
  72764. ** Write the sequence number into register P2.
  72765. ** The sequence number on the cursor is incremented after this
  72766. ** instruction.
  72767. */
  72768. case OP_Sequence: { /* out2 */
  72769. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72770. assert( p->apCsr[pOp->p1]!=0 );
  72771. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  72772. pOut = out2Prerelease(p, pOp);
  72773. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  72774. break;
  72775. }
  72776. /* Opcode: NewRowid P1 P2 P3 * *
  72777. ** Synopsis: r[P2]=rowid
  72778. **
  72779. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  72780. ** The record number is not previously used as a key in the database
  72781. ** table that cursor P1 points to. The new record number is written
  72782. ** written to register P2.
  72783. **
  72784. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  72785. ** the largest previously generated record number. No new record numbers are
  72786. ** allowed to be less than this value. When this value reaches its maximum,
  72787. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  72788. ** generated record number. This P3 mechanism is used to help implement the
  72789. ** AUTOINCREMENT feature.
  72790. */
  72791. case OP_NewRowid: { /* out2 */
  72792. i64 v; /* The new rowid */
  72793. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  72794. int res; /* Result of an sqlite3BtreeLast() */
  72795. int cnt; /* Counter to limit the number of searches */
  72796. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  72797. VdbeFrame *pFrame; /* Root frame of VDBE */
  72798. v = 0;
  72799. res = 0;
  72800. pOut = out2Prerelease(p, pOp);
  72801. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72802. pC = p->apCsr[pOp->p1];
  72803. assert( pC!=0 );
  72804. assert( pC->eCurType==CURTYPE_BTREE );
  72805. assert( pC->uc.pCursor!=0 );
  72806. {
  72807. /* The next rowid or record number (different terms for the same
  72808. ** thing) is obtained in a two-step algorithm.
  72809. **
  72810. ** First we attempt to find the largest existing rowid and add one
  72811. ** to that. But if the largest existing rowid is already the maximum
  72812. ** positive integer, we have to fall through to the second
  72813. ** probabilistic algorithm
  72814. **
  72815. ** The second algorithm is to select a rowid at random and see if
  72816. ** it already exists in the table. If it does not exist, we have
  72817. ** succeeded. If the random rowid does exist, we select a new one
  72818. ** and try again, up to 100 times.
  72819. */
  72820. assert( pC->isTable );
  72821. #ifdef SQLITE_32BIT_ROWID
  72822. # define MAX_ROWID 0x7fffffff
  72823. #else
  72824. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  72825. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  72826. ** to provide the constant while making all compilers happy.
  72827. */
  72828. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  72829. #endif
  72830. if( !pC->useRandomRowid ){
  72831. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  72832. if( rc!=SQLITE_OK ){
  72833. goto abort_due_to_error;
  72834. }
  72835. if( res ){
  72836. v = 1; /* IMP: R-61914-48074 */
  72837. }else{
  72838. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  72839. rc = sqlite3BtreeKeySize(pC->uc.pCursor, &v);
  72840. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  72841. if( v>=MAX_ROWID ){
  72842. pC->useRandomRowid = 1;
  72843. }else{
  72844. v++; /* IMP: R-29538-34987 */
  72845. }
  72846. }
  72847. }
  72848. #ifndef SQLITE_OMIT_AUTOINCREMENT
  72849. if( pOp->p3 ){
  72850. /* Assert that P3 is a valid memory cell. */
  72851. assert( pOp->p3>0 );
  72852. if( p->pFrame ){
  72853. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  72854. /* Assert that P3 is a valid memory cell. */
  72855. assert( pOp->p3<=pFrame->nMem );
  72856. pMem = &pFrame->aMem[pOp->p3];
  72857. }else{
  72858. /* Assert that P3 is a valid memory cell. */
  72859. assert( pOp->p3<=(p->nMem-p->nCursor) );
  72860. pMem = &aMem[pOp->p3];
  72861. memAboutToChange(p, pMem);
  72862. }
  72863. assert( memIsValid(pMem) );
  72864. REGISTER_TRACE(pOp->p3, pMem);
  72865. sqlite3VdbeMemIntegerify(pMem);
  72866. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  72867. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  72868. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  72869. goto abort_due_to_error;
  72870. }
  72871. if( v<pMem->u.i+1 ){
  72872. v = pMem->u.i + 1;
  72873. }
  72874. pMem->u.i = v;
  72875. }
  72876. #endif
  72877. if( pC->useRandomRowid ){
  72878. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  72879. ** largest possible integer (9223372036854775807) then the database
  72880. ** engine starts picking positive candidate ROWIDs at random until
  72881. ** it finds one that is not previously used. */
  72882. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  72883. ** an AUTOINCREMENT table. */
  72884. cnt = 0;
  72885. do{
  72886. sqlite3_randomness(sizeof(v), &v);
  72887. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  72888. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  72889. 0, &res))==SQLITE_OK)
  72890. && (res==0)
  72891. && (++cnt<100));
  72892. if( rc==SQLITE_OK && res==0 ){
  72893. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  72894. goto abort_due_to_error;
  72895. }
  72896. assert( v>0 ); /* EV: R-40812-03570 */
  72897. }
  72898. pC->deferredMoveto = 0;
  72899. pC->cacheStatus = CACHE_STALE;
  72900. }
  72901. pOut->u.i = v;
  72902. break;
  72903. }
  72904. /* Opcode: Insert P1 P2 P3 P4 P5
  72905. ** Synopsis: intkey=r[P3] data=r[P2]
  72906. **
  72907. ** Write an entry into the table of cursor P1. A new entry is
  72908. ** created if it doesn't already exist or the data for an existing
  72909. ** entry is overwritten. The data is the value MEM_Blob stored in register
  72910. ** number P2. The key is stored in register P3. The key must
  72911. ** be a MEM_Int.
  72912. **
  72913. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  72914. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  72915. ** then rowid is stored for subsequent return by the
  72916. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  72917. **
  72918. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  72919. ** the last seek operation (OP_NotExists) was a success, then this
  72920. ** operation will not attempt to find the appropriate row before doing
  72921. ** the insert but will instead overwrite the row that the cursor is
  72922. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  72923. ** has already positioned the cursor correctly. This is an optimization
  72924. ** that boosts performance by avoiding redundant seeks.
  72925. **
  72926. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  72927. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  72928. ** is part of an INSERT operation. The difference is only important to
  72929. ** the update hook.
  72930. **
  72931. ** Parameter P4 may point to a string containing the table-name, or
  72932. ** may be NULL. If it is not NULL, then the update-hook
  72933. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  72934. **
  72935. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  72936. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  72937. ** and register P2 becomes ephemeral. If the cursor is changed, the
  72938. ** value of register P2 will then change. Make sure this does not
  72939. ** cause any problems.)
  72940. **
  72941. ** This instruction only works on tables. The equivalent instruction
  72942. ** for indices is OP_IdxInsert.
  72943. */
  72944. /* Opcode: InsertInt P1 P2 P3 P4 P5
  72945. ** Synopsis: intkey=P3 data=r[P2]
  72946. **
  72947. ** This works exactly like OP_Insert except that the key is the
  72948. ** integer value P3, not the value of the integer stored in register P3.
  72949. */
  72950. case OP_Insert:
  72951. case OP_InsertInt: {
  72952. Mem *pData; /* MEM cell holding data for the record to be inserted */
  72953. Mem *pKey; /* MEM cell holding key for the record */
  72954. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  72955. VdbeCursor *pC; /* Cursor to table into which insert is written */
  72956. int nZero; /* Number of zero-bytes to append */
  72957. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  72958. const char *zDb; /* database name - used by the update hook */
  72959. const char *zTbl; /* Table name - used by the opdate hook */
  72960. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  72961. pData = &aMem[pOp->p2];
  72962. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72963. assert( memIsValid(pData) );
  72964. pC = p->apCsr[pOp->p1];
  72965. assert( pC!=0 );
  72966. assert( pC->eCurType==CURTYPE_BTREE );
  72967. assert( pC->uc.pCursor!=0 );
  72968. assert( pC->isTable );
  72969. REGISTER_TRACE(pOp->p2, pData);
  72970. if( pOp->opcode==OP_Insert ){
  72971. pKey = &aMem[pOp->p3];
  72972. assert( pKey->flags & MEM_Int );
  72973. assert( memIsValid(pKey) );
  72974. REGISTER_TRACE(pOp->p3, pKey);
  72975. iKey = pKey->u.i;
  72976. }else{
  72977. assert( pOp->opcode==OP_InsertInt );
  72978. iKey = pOp->p3;
  72979. }
  72980. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  72981. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
  72982. if( pData->flags & MEM_Null ){
  72983. pData->z = 0;
  72984. pData->n = 0;
  72985. }else{
  72986. assert( pData->flags & (MEM_Blob|MEM_Str) );
  72987. }
  72988. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  72989. if( pData->flags & MEM_Zero ){
  72990. nZero = pData->u.nZero;
  72991. }else{
  72992. nZero = 0;
  72993. }
  72994. rc = sqlite3BtreeInsert(pC->uc.pCursor, 0, iKey,
  72995. pData->z, pData->n, nZero,
  72996. (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
  72997. );
  72998. pC->deferredMoveto = 0;
  72999. pC->cacheStatus = CACHE_STALE;
  73000. /* Invoke the update-hook if required. */
  73001. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  73002. zDb = db->aDb[pC->iDb].zName;
  73003. zTbl = pOp->p4.z;
  73004. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  73005. assert( pC->isTable );
  73006. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  73007. assert( pC->iDb>=0 );
  73008. }
  73009. break;
  73010. }
  73011. /* Opcode: Delete P1 P2 * P4 P5
  73012. **
  73013. ** Delete the record at which the P1 cursor is currently pointing.
  73014. **
  73015. ** If the P5 parameter is non-zero, the cursor will be left pointing at
  73016. ** either the next or the previous record in the table. If it is left
  73017. ** pointing at the next record, then the next Next instruction will be a
  73018. ** no-op. As a result, in this case it is OK to delete a record from within a
  73019. ** Next loop. If P5 is zero, then the cursor is left in an undefined state.
  73020. **
  73021. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  73022. ** incremented (otherwise not).
  73023. **
  73024. ** P1 must not be pseudo-table. It has to be a real table with
  73025. ** multiple rows.
  73026. **
  73027. ** If P4 is not NULL, then it is the name of the table that P1 is
  73028. ** pointing to. The update hook will be invoked, if it exists.
  73029. ** If P4 is not NULL then the P1 cursor must have been positioned
  73030. ** using OP_NotFound prior to invoking this opcode.
  73031. */
  73032. case OP_Delete: {
  73033. VdbeCursor *pC;
  73034. u8 hasUpdateCallback;
  73035. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73036. pC = p->apCsr[pOp->p1];
  73037. assert( pC!=0 );
  73038. assert( pC->eCurType==CURTYPE_BTREE );
  73039. assert( pC->uc.pCursor!=0 );
  73040. assert( pC->deferredMoveto==0 );
  73041. hasUpdateCallback = db->xUpdateCallback && pOp->p4.z && pC->isTable;
  73042. if( pOp->p5 && hasUpdateCallback ){
  73043. sqlite3BtreeKeySize(pC->uc.pCursor, &pC->movetoTarget);
  73044. }
  73045. #ifdef SQLITE_DEBUG
  73046. /* The seek operation that positioned the cursor prior to OP_Delete will
  73047. ** have also set the pC->movetoTarget field to the rowid of the row that
  73048. ** is being deleted */
  73049. if( pOp->p4.z && pC->isTable && pOp->p5==0 ){
  73050. i64 iKey = 0;
  73051. sqlite3BtreeKeySize(pC->uc.pCursor, &iKey);
  73052. assert( pC->movetoTarget==iKey );
  73053. }
  73054. #endif
  73055. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  73056. pC->cacheStatus = CACHE_STALE;
  73057. /* Invoke the update-hook if required. */
  73058. if( rc==SQLITE_OK && hasUpdateCallback ){
  73059. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
  73060. db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
  73061. assert( pC->iDb>=0 );
  73062. }
  73063. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  73064. break;
  73065. }
  73066. /* Opcode: ResetCount * * * * *
  73067. **
  73068. ** The value of the change counter is copied to the database handle
  73069. ** change counter (returned by subsequent calls to sqlite3_changes()).
  73070. ** Then the VMs internal change counter resets to 0.
  73071. ** This is used by trigger programs.
  73072. */
  73073. case OP_ResetCount: {
  73074. sqlite3VdbeSetChanges(db, p->nChange);
  73075. p->nChange = 0;
  73076. break;
  73077. }
  73078. /* Opcode: SorterCompare P1 P2 P3 P4
  73079. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  73080. **
  73081. ** P1 is a sorter cursor. This instruction compares a prefix of the
  73082. ** record blob in register P3 against a prefix of the entry that
  73083. ** the sorter cursor currently points to. Only the first P4 fields
  73084. ** of r[P3] and the sorter record are compared.
  73085. **
  73086. ** If either P3 or the sorter contains a NULL in one of their significant
  73087. ** fields (not counting the P4 fields at the end which are ignored) then
  73088. ** the comparison is assumed to be equal.
  73089. **
  73090. ** Fall through to next instruction if the two records compare equal to
  73091. ** each other. Jump to P2 if they are different.
  73092. */
  73093. case OP_SorterCompare: {
  73094. VdbeCursor *pC;
  73095. int res;
  73096. int nKeyCol;
  73097. pC = p->apCsr[pOp->p1];
  73098. assert( isSorter(pC) );
  73099. assert( pOp->p4type==P4_INT32 );
  73100. pIn3 = &aMem[pOp->p3];
  73101. nKeyCol = pOp->p4.i;
  73102. res = 0;
  73103. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  73104. VdbeBranchTaken(res!=0,2);
  73105. if( res ) goto jump_to_p2;
  73106. break;
  73107. };
  73108. /* Opcode: SorterData P1 P2 P3 * *
  73109. ** Synopsis: r[P2]=data
  73110. **
  73111. ** Write into register P2 the current sorter data for sorter cursor P1.
  73112. ** Then clear the column header cache on cursor P3.
  73113. **
  73114. ** This opcode is normally use to move a record out of the sorter and into
  73115. ** a register that is the source for a pseudo-table cursor created using
  73116. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  73117. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  73118. ** us from having to issue a separate NullRow instruction to clear that cache.
  73119. */
  73120. case OP_SorterData: {
  73121. VdbeCursor *pC;
  73122. pOut = &aMem[pOp->p2];
  73123. pC = p->apCsr[pOp->p1];
  73124. assert( isSorter(pC) );
  73125. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  73126. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  73127. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73128. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  73129. break;
  73130. }
  73131. /* Opcode: RowData P1 P2 * * *
  73132. ** Synopsis: r[P2]=data
  73133. **
  73134. ** Write into register P2 the complete row data for cursor P1.
  73135. ** There is no interpretation of the data.
  73136. ** It is just copied onto the P2 register exactly as
  73137. ** it is found in the database file.
  73138. **
  73139. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  73140. ** of a real table, not a pseudo-table.
  73141. */
  73142. /* Opcode: RowKey P1 P2 * * *
  73143. ** Synopsis: r[P2]=key
  73144. **
  73145. ** Write into register P2 the complete row key for cursor P1.
  73146. ** There is no interpretation of the data.
  73147. ** The key is copied onto the P2 register exactly as
  73148. ** it is found in the database file.
  73149. **
  73150. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  73151. ** of a real table, not a pseudo-table.
  73152. */
  73153. case OP_RowKey:
  73154. case OP_RowData: {
  73155. VdbeCursor *pC;
  73156. BtCursor *pCrsr;
  73157. u32 n;
  73158. i64 n64;
  73159. pOut = &aMem[pOp->p2];
  73160. memAboutToChange(p, pOut);
  73161. /* Note that RowKey and RowData are really exactly the same instruction */
  73162. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73163. pC = p->apCsr[pOp->p1];
  73164. assert( pC!=0 );
  73165. assert( pC->eCurType==CURTYPE_BTREE );
  73166. assert( isSorter(pC)==0 );
  73167. assert( pC->isTable || pOp->opcode!=OP_RowData );
  73168. assert( pC->isTable==0 || pOp->opcode==OP_RowData );
  73169. assert( pC->nullRow==0 );
  73170. assert( pC->uc.pCursor!=0 );
  73171. pCrsr = pC->uc.pCursor;
  73172. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  73173. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  73174. ** the cursor. If this where not the case, on of the following assert()s
  73175. ** would fail. Should this ever change (because of changes in the code
  73176. ** generator) then the fix would be to insert a call to
  73177. ** sqlite3VdbeCursorMoveto().
  73178. */
  73179. assert( pC->deferredMoveto==0 );
  73180. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  73181. #if 0 /* Not required due to the previous to assert() statements */
  73182. rc = sqlite3VdbeCursorMoveto(pC);
  73183. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  73184. #endif
  73185. if( pC->isTable==0 ){
  73186. assert( !pC->isTable );
  73187. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
  73188. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  73189. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  73190. goto too_big;
  73191. }
  73192. n = (u32)n64;
  73193. }else{
  73194. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
  73195. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  73196. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  73197. goto too_big;
  73198. }
  73199. }
  73200. testcase( n==0 );
  73201. if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
  73202. goto no_mem;
  73203. }
  73204. pOut->n = n;
  73205. MemSetTypeFlag(pOut, MEM_Blob);
  73206. if( pC->isTable==0 ){
  73207. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  73208. }else{
  73209. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  73210. }
  73211. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  73212. UPDATE_MAX_BLOBSIZE(pOut);
  73213. REGISTER_TRACE(pOp->p2, pOut);
  73214. break;
  73215. }
  73216. /* Opcode: Rowid P1 P2 * * *
  73217. ** Synopsis: r[P2]=rowid
  73218. **
  73219. ** Store in register P2 an integer which is the key of the table entry that
  73220. ** P1 is currently point to.
  73221. **
  73222. ** P1 can be either an ordinary table or a virtual table. There used to
  73223. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  73224. ** one opcode now works for both table types.
  73225. */
  73226. case OP_Rowid: { /* out2 */
  73227. VdbeCursor *pC;
  73228. i64 v;
  73229. sqlite3_vtab *pVtab;
  73230. const sqlite3_module *pModule;
  73231. pOut = out2Prerelease(p, pOp);
  73232. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73233. pC = p->apCsr[pOp->p1];
  73234. assert( pC!=0 );
  73235. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  73236. if( pC->nullRow ){
  73237. pOut->flags = MEM_Null;
  73238. break;
  73239. }else if( pC->deferredMoveto ){
  73240. v = pC->movetoTarget;
  73241. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73242. }else if( pC->eCurType==CURTYPE_VTAB ){
  73243. assert( pC->uc.pVCur!=0 );
  73244. pVtab = pC->uc.pVCur->pVtab;
  73245. pModule = pVtab->pModule;
  73246. assert( pModule->xRowid );
  73247. rc = pModule->xRowid(pC->uc.pVCur, &v);
  73248. sqlite3VtabImportErrmsg(p, pVtab);
  73249. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73250. }else{
  73251. assert( pC->eCurType==CURTYPE_BTREE );
  73252. assert( pC->uc.pCursor!=0 );
  73253. rc = sqlite3VdbeCursorRestore(pC);
  73254. if( rc ) goto abort_due_to_error;
  73255. if( pC->nullRow ){
  73256. pOut->flags = MEM_Null;
  73257. break;
  73258. }
  73259. rc = sqlite3BtreeKeySize(pC->uc.pCursor, &v);
  73260. assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
  73261. }
  73262. pOut->u.i = v;
  73263. break;
  73264. }
  73265. /* Opcode: NullRow P1 * * * *
  73266. **
  73267. ** Move the cursor P1 to a null row. Any OP_Column operations
  73268. ** that occur while the cursor is on the null row will always
  73269. ** write a NULL.
  73270. */
  73271. case OP_NullRow: {
  73272. VdbeCursor *pC;
  73273. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73274. pC = p->apCsr[pOp->p1];
  73275. assert( pC!=0 );
  73276. pC->nullRow = 1;
  73277. pC->cacheStatus = CACHE_STALE;
  73278. if( pC->eCurType==CURTYPE_BTREE ){
  73279. assert( pC->uc.pCursor!=0 );
  73280. sqlite3BtreeClearCursor(pC->uc.pCursor);
  73281. }
  73282. break;
  73283. }
  73284. /* Opcode: Last P1 P2 P3 * *
  73285. **
  73286. ** The next use of the Rowid or Column or Prev instruction for P1
  73287. ** will refer to the last entry in the database table or index.
  73288. ** If the table or index is empty and P2>0, then jump immediately to P2.
  73289. ** If P2 is 0 or if the table or index is not empty, fall through
  73290. ** to the following instruction.
  73291. **
  73292. ** This opcode leaves the cursor configured to move in reverse order,
  73293. ** from the end toward the beginning. In other words, the cursor is
  73294. ** configured to use Prev, not Next.
  73295. */
  73296. case OP_Last: { /* jump */
  73297. VdbeCursor *pC;
  73298. BtCursor *pCrsr;
  73299. int res;
  73300. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73301. pC = p->apCsr[pOp->p1];
  73302. assert( pC!=0 );
  73303. assert( pC->eCurType==CURTYPE_BTREE );
  73304. pCrsr = pC->uc.pCursor;
  73305. res = 0;
  73306. assert( pCrsr!=0 );
  73307. rc = sqlite3BtreeLast(pCrsr, &res);
  73308. pC->nullRow = (u8)res;
  73309. pC->deferredMoveto = 0;
  73310. pC->cacheStatus = CACHE_STALE;
  73311. pC->seekResult = pOp->p3;
  73312. #ifdef SQLITE_DEBUG
  73313. pC->seekOp = OP_Last;
  73314. #endif
  73315. if( pOp->p2>0 ){
  73316. VdbeBranchTaken(res!=0,2);
  73317. if( res ) goto jump_to_p2;
  73318. }
  73319. break;
  73320. }
  73321. /* Opcode: Sort P1 P2 * * *
  73322. **
  73323. ** This opcode does exactly the same thing as OP_Rewind except that
  73324. ** it increments an undocumented global variable used for testing.
  73325. **
  73326. ** Sorting is accomplished by writing records into a sorting index,
  73327. ** then rewinding that index and playing it back from beginning to
  73328. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  73329. ** rewinding so that the global variable will be incremented and
  73330. ** regression tests can determine whether or not the optimizer is
  73331. ** correctly optimizing out sorts.
  73332. */
  73333. case OP_SorterSort: /* jump */
  73334. case OP_Sort: { /* jump */
  73335. #ifdef SQLITE_TEST
  73336. sqlite3_sort_count++;
  73337. sqlite3_search_count--;
  73338. #endif
  73339. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  73340. /* Fall through into OP_Rewind */
  73341. }
  73342. /* Opcode: Rewind P1 P2 * * *
  73343. **
  73344. ** The next use of the Rowid or Column or Next instruction for P1
  73345. ** will refer to the first entry in the database table or index.
  73346. ** If the table or index is empty, jump immediately to P2.
  73347. ** If the table or index is not empty, fall through to the following
  73348. ** instruction.
  73349. **
  73350. ** This opcode leaves the cursor configured to move in forward order,
  73351. ** from the beginning toward the end. In other words, the cursor is
  73352. ** configured to use Next, not Prev.
  73353. */
  73354. case OP_Rewind: { /* jump */
  73355. VdbeCursor *pC;
  73356. BtCursor *pCrsr;
  73357. int res;
  73358. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73359. pC = p->apCsr[pOp->p1];
  73360. assert( pC!=0 );
  73361. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  73362. res = 1;
  73363. #ifdef SQLITE_DEBUG
  73364. pC->seekOp = OP_Rewind;
  73365. #endif
  73366. if( isSorter(pC) ){
  73367. rc = sqlite3VdbeSorterRewind(pC, &res);
  73368. }else{
  73369. assert( pC->eCurType==CURTYPE_BTREE );
  73370. pCrsr = pC->uc.pCursor;
  73371. assert( pCrsr );
  73372. rc = sqlite3BtreeFirst(pCrsr, &res);
  73373. pC->deferredMoveto = 0;
  73374. pC->cacheStatus = CACHE_STALE;
  73375. }
  73376. pC->nullRow = (u8)res;
  73377. assert( pOp->p2>0 && pOp->p2<p->nOp );
  73378. VdbeBranchTaken(res!=0,2);
  73379. if( res ) goto jump_to_p2;
  73380. break;
  73381. }
  73382. /* Opcode: Next P1 P2 P3 P4 P5
  73383. **
  73384. ** Advance cursor P1 so that it points to the next key/data pair in its
  73385. ** table or index. If there are no more key/value pairs then fall through
  73386. ** to the following instruction. But if the cursor advance was successful,
  73387. ** jump immediately to P2.
  73388. **
  73389. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  73390. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  73391. ** to follow SeekLT, SeekLE, or OP_Last.
  73392. **
  73393. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  73394. ** been opened prior to this opcode or the program will segfault.
  73395. **
  73396. ** The P3 value is a hint to the btree implementation. If P3==1, that
  73397. ** means P1 is an SQL index and that this instruction could have been
  73398. ** omitted if that index had been unique. P3 is usually 0. P3 is
  73399. ** always either 0 or 1.
  73400. **
  73401. ** P4 is always of type P4_ADVANCE. The function pointer points to
  73402. ** sqlite3BtreeNext().
  73403. **
  73404. ** If P5 is positive and the jump is taken, then event counter
  73405. ** number P5-1 in the prepared statement is incremented.
  73406. **
  73407. ** See also: Prev, NextIfOpen
  73408. */
  73409. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  73410. **
  73411. ** This opcode works just like Next except that if cursor P1 is not
  73412. ** open it behaves a no-op.
  73413. */
  73414. /* Opcode: Prev P1 P2 P3 P4 P5
  73415. **
  73416. ** Back up cursor P1 so that it points to the previous key/data pair in its
  73417. ** table or index. If there is no previous key/value pairs then fall through
  73418. ** to the following instruction. But if the cursor backup was successful,
  73419. ** jump immediately to P2.
  73420. **
  73421. **
  73422. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  73423. ** OP_Last opcode used to position the cursor. Prev is not allowed
  73424. ** to follow SeekGT, SeekGE, or OP_Rewind.
  73425. **
  73426. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  73427. ** not open then the behavior is undefined.
  73428. **
  73429. ** The P3 value is a hint to the btree implementation. If P3==1, that
  73430. ** means P1 is an SQL index and that this instruction could have been
  73431. ** omitted if that index had been unique. P3 is usually 0. P3 is
  73432. ** always either 0 or 1.
  73433. **
  73434. ** P4 is always of type P4_ADVANCE. The function pointer points to
  73435. ** sqlite3BtreePrevious().
  73436. **
  73437. ** If P5 is positive and the jump is taken, then event counter
  73438. ** number P5-1 in the prepared statement is incremented.
  73439. */
  73440. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  73441. **
  73442. ** This opcode works just like Prev except that if cursor P1 is not
  73443. ** open it behaves a no-op.
  73444. */
  73445. case OP_SorterNext: { /* jump */
  73446. VdbeCursor *pC;
  73447. int res;
  73448. pC = p->apCsr[pOp->p1];
  73449. assert( isSorter(pC) );
  73450. res = 0;
  73451. rc = sqlite3VdbeSorterNext(db, pC, &res);
  73452. goto next_tail;
  73453. case OP_PrevIfOpen: /* jump */
  73454. case OP_NextIfOpen: /* jump */
  73455. if( p->apCsr[pOp->p1]==0 ) break;
  73456. /* Fall through */
  73457. case OP_Prev: /* jump */
  73458. case OP_Next: /* jump */
  73459. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73460. assert( pOp->p5<ArraySize(p->aCounter) );
  73461. pC = p->apCsr[pOp->p1];
  73462. res = pOp->p3;
  73463. assert( pC!=0 );
  73464. assert( pC->deferredMoveto==0 );
  73465. assert( pC->eCurType==CURTYPE_BTREE );
  73466. assert( res==0 || (res==1 && pC->isTable==0) );
  73467. testcase( res==1 );
  73468. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  73469. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  73470. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  73471. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  73472. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  73473. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  73474. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  73475. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  73476. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  73477. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  73478. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  73479. || pC->seekOp==OP_Last );
  73480. rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
  73481. next_tail:
  73482. pC->cacheStatus = CACHE_STALE;
  73483. VdbeBranchTaken(res==0,2);
  73484. if( res==0 ){
  73485. pC->nullRow = 0;
  73486. p->aCounter[pOp->p5]++;
  73487. #ifdef SQLITE_TEST
  73488. sqlite3_search_count++;
  73489. #endif
  73490. goto jump_to_p2_and_check_for_interrupt;
  73491. }else{
  73492. pC->nullRow = 1;
  73493. }
  73494. goto check_for_interrupt;
  73495. }
  73496. /* Opcode: IdxInsert P1 P2 P3 * P5
  73497. ** Synopsis: key=r[P2]
  73498. **
  73499. ** Register P2 holds an SQL index key made using the
  73500. ** MakeRecord instructions. This opcode writes that key
  73501. ** into the index P1. Data for the entry is nil.
  73502. **
  73503. ** P3 is a flag that provides a hint to the b-tree layer that this
  73504. ** insert is likely to be an append.
  73505. **
  73506. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  73507. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  73508. ** then the change counter is unchanged.
  73509. **
  73510. ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
  73511. ** just done a seek to the spot where the new entry is to be inserted.
  73512. ** This flag avoids doing an extra seek.
  73513. **
  73514. ** This instruction only works for indices. The equivalent instruction
  73515. ** for tables is OP_Insert.
  73516. */
  73517. case OP_SorterInsert: /* in2 */
  73518. case OP_IdxInsert: { /* in2 */
  73519. VdbeCursor *pC;
  73520. int nKey;
  73521. const char *zKey;
  73522. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73523. pC = p->apCsr[pOp->p1];
  73524. assert( pC!=0 );
  73525. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  73526. pIn2 = &aMem[pOp->p2];
  73527. assert( pIn2->flags & MEM_Blob );
  73528. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  73529. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  73530. assert( pC->isTable==0 );
  73531. rc = ExpandBlob(pIn2);
  73532. if( rc==SQLITE_OK ){
  73533. if( pOp->opcode==OP_SorterInsert ){
  73534. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  73535. }else{
  73536. nKey = pIn2->n;
  73537. zKey = pIn2->z;
  73538. rc = sqlite3BtreeInsert(pC->uc.pCursor, zKey, nKey, "", 0, 0, pOp->p3,
  73539. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  73540. );
  73541. assert( pC->deferredMoveto==0 );
  73542. pC->cacheStatus = CACHE_STALE;
  73543. }
  73544. }
  73545. break;
  73546. }
  73547. /* Opcode: IdxDelete P1 P2 P3 * *
  73548. ** Synopsis: key=r[P2@P3]
  73549. **
  73550. ** The content of P3 registers starting at register P2 form
  73551. ** an unpacked index key. This opcode removes that entry from the
  73552. ** index opened by cursor P1.
  73553. */
  73554. case OP_IdxDelete: {
  73555. VdbeCursor *pC;
  73556. BtCursor *pCrsr;
  73557. int res;
  73558. UnpackedRecord r;
  73559. assert( pOp->p3>0 );
  73560. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  73561. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73562. pC = p->apCsr[pOp->p1];
  73563. assert( pC!=0 );
  73564. assert( pC->eCurType==CURTYPE_BTREE );
  73565. pCrsr = pC->uc.pCursor;
  73566. assert( pCrsr!=0 );
  73567. assert( pOp->p5==0 );
  73568. r.pKeyInfo = pC->pKeyInfo;
  73569. r.nField = (u16)pOp->p3;
  73570. r.default_rc = 0;
  73571. r.aMem = &aMem[pOp->p2];
  73572. #ifdef SQLITE_DEBUG
  73573. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  73574. #endif
  73575. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  73576. if( rc==SQLITE_OK && res==0 ){
  73577. rc = sqlite3BtreeDelete(pCrsr, 0);
  73578. }
  73579. assert( pC->deferredMoveto==0 );
  73580. pC->cacheStatus = CACHE_STALE;
  73581. break;
  73582. }
  73583. /* Opcode: IdxRowid P1 P2 * * *
  73584. ** Synopsis: r[P2]=rowid
  73585. **
  73586. ** Write into register P2 an integer which is the last entry in the record at
  73587. ** the end of the index key pointed to by cursor P1. This integer should be
  73588. ** the rowid of the table entry to which this index entry points.
  73589. **
  73590. ** See also: Rowid, MakeRecord.
  73591. */
  73592. case OP_IdxRowid: { /* out2 */
  73593. BtCursor *pCrsr;
  73594. VdbeCursor *pC;
  73595. i64 rowid;
  73596. pOut = out2Prerelease(p, pOp);
  73597. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73598. pC = p->apCsr[pOp->p1];
  73599. assert( pC!=0 );
  73600. assert( pC->eCurType==CURTYPE_BTREE );
  73601. pCrsr = pC->uc.pCursor;
  73602. assert( pCrsr!=0 );
  73603. pOut->flags = MEM_Null;
  73604. assert( pC->isTable==0 );
  73605. assert( pC->deferredMoveto==0 );
  73606. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  73607. ** out from under the cursor. That will never happend for an IdxRowid
  73608. ** opcode, hence the NEVER() arround the check of the return value.
  73609. */
  73610. rc = sqlite3VdbeCursorRestore(pC);
  73611. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  73612. if( !pC->nullRow ){
  73613. rowid = 0; /* Not needed. Only used to silence a warning. */
  73614. rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
  73615. if( rc!=SQLITE_OK ){
  73616. goto abort_due_to_error;
  73617. }
  73618. pOut->u.i = rowid;
  73619. pOut->flags = MEM_Int;
  73620. }
  73621. break;
  73622. }
  73623. /* Opcode: IdxGE P1 P2 P3 P4 P5
  73624. ** Synopsis: key=r[P3@P4]
  73625. **
  73626. ** The P4 register values beginning with P3 form an unpacked index
  73627. ** key that omits the PRIMARY KEY. Compare this key value against the index
  73628. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  73629. ** fields at the end.
  73630. **
  73631. ** If the P1 index entry is greater than or equal to the key value
  73632. ** then jump to P2. Otherwise fall through to the next instruction.
  73633. */
  73634. /* Opcode: IdxGT P1 P2 P3 P4 P5
  73635. ** Synopsis: key=r[P3@P4]
  73636. **
  73637. ** The P4 register values beginning with P3 form an unpacked index
  73638. ** key that omits the PRIMARY KEY. Compare this key value against the index
  73639. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  73640. ** fields at the end.
  73641. **
  73642. ** If the P1 index entry is greater than the key value
  73643. ** then jump to P2. Otherwise fall through to the next instruction.
  73644. */
  73645. /* Opcode: IdxLT P1 P2 P3 P4 P5
  73646. ** Synopsis: key=r[P3@P4]
  73647. **
  73648. ** The P4 register values beginning with P3 form an unpacked index
  73649. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  73650. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  73651. ** ROWID on the P1 index.
  73652. **
  73653. ** If the P1 index entry is less than the key value then jump to P2.
  73654. ** Otherwise fall through to the next instruction.
  73655. */
  73656. /* Opcode: IdxLE P1 P2 P3 P4 P5
  73657. ** Synopsis: key=r[P3@P4]
  73658. **
  73659. ** The P4 register values beginning with P3 form an unpacked index
  73660. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  73661. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  73662. ** ROWID on the P1 index.
  73663. **
  73664. ** If the P1 index entry is less than or equal to the key value then jump
  73665. ** to P2. Otherwise fall through to the next instruction.
  73666. */
  73667. case OP_IdxLE: /* jump */
  73668. case OP_IdxGT: /* jump */
  73669. case OP_IdxLT: /* jump */
  73670. case OP_IdxGE: { /* jump */
  73671. VdbeCursor *pC;
  73672. int res;
  73673. UnpackedRecord r;
  73674. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73675. pC = p->apCsr[pOp->p1];
  73676. assert( pC!=0 );
  73677. assert( pC->isOrdered );
  73678. assert( pC->eCurType==CURTYPE_BTREE );
  73679. assert( pC->uc.pCursor!=0);
  73680. assert( pC->deferredMoveto==0 );
  73681. assert( pOp->p5==0 || pOp->p5==1 );
  73682. assert( pOp->p4type==P4_INT32 );
  73683. r.pKeyInfo = pC->pKeyInfo;
  73684. r.nField = (u16)pOp->p4.i;
  73685. if( pOp->opcode<OP_IdxLT ){
  73686. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  73687. r.default_rc = -1;
  73688. }else{
  73689. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  73690. r.default_rc = 0;
  73691. }
  73692. r.aMem = &aMem[pOp->p3];
  73693. #ifdef SQLITE_DEBUG
  73694. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  73695. #endif
  73696. res = 0; /* Not needed. Only used to silence a warning. */
  73697. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  73698. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  73699. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  73700. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  73701. res = -res;
  73702. }else{
  73703. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  73704. res++;
  73705. }
  73706. VdbeBranchTaken(res>0,2);
  73707. if( res>0 ) goto jump_to_p2;
  73708. break;
  73709. }
  73710. /* Opcode: Destroy P1 P2 P3 * *
  73711. **
  73712. ** Delete an entire database table or index whose root page in the database
  73713. ** file is given by P1.
  73714. **
  73715. ** The table being destroyed is in the main database file if P3==0. If
  73716. ** P3==1 then the table to be clear is in the auxiliary database file
  73717. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  73718. **
  73719. ** If AUTOVACUUM is enabled then it is possible that another root page
  73720. ** might be moved into the newly deleted root page in order to keep all
  73721. ** root pages contiguous at the beginning of the database. The former
  73722. ** value of the root page that moved - its value before the move occurred -
  73723. ** is stored in register P2. If no page
  73724. ** movement was required (because the table being dropped was already
  73725. ** the last one in the database) then a zero is stored in register P2.
  73726. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  73727. **
  73728. ** See also: Clear
  73729. */
  73730. case OP_Destroy: { /* out2 */
  73731. int iMoved;
  73732. int iDb;
  73733. assert( p->readOnly==0 );
  73734. pOut = out2Prerelease(p, pOp);
  73735. pOut->flags = MEM_Null;
  73736. if( db->nVdbeRead > db->nVDestroy+1 ){
  73737. rc = SQLITE_LOCKED;
  73738. p->errorAction = OE_Abort;
  73739. }else{
  73740. iDb = pOp->p3;
  73741. assert( DbMaskTest(p->btreeMask, iDb) );
  73742. iMoved = 0; /* Not needed. Only to silence a warning. */
  73743. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  73744. pOut->flags = MEM_Int;
  73745. pOut->u.i = iMoved;
  73746. #ifndef SQLITE_OMIT_AUTOVACUUM
  73747. if( rc==SQLITE_OK && iMoved!=0 ){
  73748. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  73749. /* All OP_Destroy operations occur on the same btree */
  73750. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  73751. resetSchemaOnFault = iDb+1;
  73752. }
  73753. #endif
  73754. }
  73755. break;
  73756. }
  73757. /* Opcode: Clear P1 P2 P3
  73758. **
  73759. ** Delete all contents of the database table or index whose root page
  73760. ** in the database file is given by P1. But, unlike Destroy, do not
  73761. ** remove the table or index from the database file.
  73762. **
  73763. ** The table being clear is in the main database file if P2==0. If
  73764. ** P2==1 then the table to be clear is in the auxiliary database file
  73765. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  73766. **
  73767. ** If the P3 value is non-zero, then the table referred to must be an
  73768. ** intkey table (an SQL table, not an index). In this case the row change
  73769. ** count is incremented by the number of rows in the table being cleared.
  73770. ** If P3 is greater than zero, then the value stored in register P3 is
  73771. ** also incremented by the number of rows in the table being cleared.
  73772. **
  73773. ** See also: Destroy
  73774. */
  73775. case OP_Clear: {
  73776. int nChange;
  73777. nChange = 0;
  73778. assert( p->readOnly==0 );
  73779. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  73780. rc = sqlite3BtreeClearTable(
  73781. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  73782. );
  73783. if( pOp->p3 ){
  73784. p->nChange += nChange;
  73785. if( pOp->p3>0 ){
  73786. assert( memIsValid(&aMem[pOp->p3]) );
  73787. memAboutToChange(p, &aMem[pOp->p3]);
  73788. aMem[pOp->p3].u.i += nChange;
  73789. }
  73790. }
  73791. break;
  73792. }
  73793. /* Opcode: ResetSorter P1 * * * *
  73794. **
  73795. ** Delete all contents from the ephemeral table or sorter
  73796. ** that is open on cursor P1.
  73797. **
  73798. ** This opcode only works for cursors used for sorting and
  73799. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  73800. */
  73801. case OP_ResetSorter: {
  73802. VdbeCursor *pC;
  73803. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  73804. pC = p->apCsr[pOp->p1];
  73805. assert( pC!=0 );
  73806. if( isSorter(pC) ){
  73807. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  73808. }else{
  73809. assert( pC->eCurType==CURTYPE_BTREE );
  73810. assert( pC->isEphemeral );
  73811. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  73812. }
  73813. break;
  73814. }
  73815. /* Opcode: CreateTable P1 P2 * * *
  73816. ** Synopsis: r[P2]=root iDb=P1
  73817. **
  73818. ** Allocate a new table in the main database file if P1==0 or in the
  73819. ** auxiliary database file if P1==1 or in an attached database if
  73820. ** P1>1. Write the root page number of the new table into
  73821. ** register P2
  73822. **
  73823. ** The difference between a table and an index is this: A table must
  73824. ** have a 4-byte integer key and can have arbitrary data. An index
  73825. ** has an arbitrary key but no data.
  73826. **
  73827. ** See also: CreateIndex
  73828. */
  73829. /* Opcode: CreateIndex P1 P2 * * *
  73830. ** Synopsis: r[P2]=root iDb=P1
  73831. **
  73832. ** Allocate a new index in the main database file if P1==0 or in the
  73833. ** auxiliary database file if P1==1 or in an attached database if
  73834. ** P1>1. Write the root page number of the new table into
  73835. ** register P2.
  73836. **
  73837. ** See documentation on OP_CreateTable for additional information.
  73838. */
  73839. case OP_CreateIndex: /* out2 */
  73840. case OP_CreateTable: { /* out2 */
  73841. int pgno;
  73842. int flags;
  73843. Db *pDb;
  73844. pOut = out2Prerelease(p, pOp);
  73845. pgno = 0;
  73846. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  73847. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  73848. assert( p->readOnly==0 );
  73849. pDb = &db->aDb[pOp->p1];
  73850. assert( pDb->pBt!=0 );
  73851. if( pOp->opcode==OP_CreateTable ){
  73852. /* flags = BTREE_INTKEY; */
  73853. flags = BTREE_INTKEY;
  73854. }else{
  73855. flags = BTREE_BLOBKEY;
  73856. }
  73857. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  73858. pOut->u.i = pgno;
  73859. break;
  73860. }
  73861. /* Opcode: ParseSchema P1 * * P4 *
  73862. **
  73863. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  73864. ** that match the WHERE clause P4.
  73865. **
  73866. ** This opcode invokes the parser to create a new virtual machine,
  73867. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  73868. */
  73869. case OP_ParseSchema: {
  73870. int iDb;
  73871. const char *zMaster;
  73872. char *zSql;
  73873. InitData initData;
  73874. /* Any prepared statement that invokes this opcode will hold mutexes
  73875. ** on every btree. This is a prerequisite for invoking
  73876. ** sqlite3InitCallback().
  73877. */
  73878. #ifdef SQLITE_DEBUG
  73879. for(iDb=0; iDb<db->nDb; iDb++){
  73880. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  73881. }
  73882. #endif
  73883. iDb = pOp->p1;
  73884. assert( iDb>=0 && iDb<db->nDb );
  73885. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  73886. /* Used to be a conditional */ {
  73887. zMaster = SCHEMA_TABLE(iDb);
  73888. initData.db = db;
  73889. initData.iDb = pOp->p1;
  73890. initData.pzErrMsg = &p->zErrMsg;
  73891. zSql = sqlite3MPrintf(db,
  73892. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  73893. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  73894. if( zSql==0 ){
  73895. rc = SQLITE_NOMEM;
  73896. }else{
  73897. assert( db->init.busy==0 );
  73898. db->init.busy = 1;
  73899. initData.rc = SQLITE_OK;
  73900. assert( !db->mallocFailed );
  73901. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  73902. if( rc==SQLITE_OK ) rc = initData.rc;
  73903. sqlite3DbFree(db, zSql);
  73904. db->init.busy = 0;
  73905. }
  73906. }
  73907. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  73908. if( rc==SQLITE_NOMEM ){
  73909. goto no_mem;
  73910. }
  73911. break;
  73912. }
  73913. #if !defined(SQLITE_OMIT_ANALYZE)
  73914. /* Opcode: LoadAnalysis P1 * * * *
  73915. **
  73916. ** Read the sqlite_stat1 table for database P1 and load the content
  73917. ** of that table into the internal index hash table. This will cause
  73918. ** the analysis to be used when preparing all subsequent queries.
  73919. */
  73920. case OP_LoadAnalysis: {
  73921. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  73922. rc = sqlite3AnalysisLoad(db, pOp->p1);
  73923. break;
  73924. }
  73925. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  73926. /* Opcode: DropTable P1 * * P4 *
  73927. **
  73928. ** Remove the internal (in-memory) data structures that describe
  73929. ** the table named P4 in database P1. This is called after a table
  73930. ** is dropped from disk (using the Destroy opcode) in order to keep
  73931. ** the internal representation of the
  73932. ** schema consistent with what is on disk.
  73933. */
  73934. case OP_DropTable: {
  73935. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  73936. break;
  73937. }
  73938. /* Opcode: DropIndex P1 * * P4 *
  73939. **
  73940. ** Remove the internal (in-memory) data structures that describe
  73941. ** the index named P4 in database P1. This is called after an index
  73942. ** is dropped from disk (using the Destroy opcode)
  73943. ** in order to keep the internal representation of the
  73944. ** schema consistent with what is on disk.
  73945. */
  73946. case OP_DropIndex: {
  73947. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  73948. break;
  73949. }
  73950. /* Opcode: DropTrigger P1 * * P4 *
  73951. **
  73952. ** Remove the internal (in-memory) data structures that describe
  73953. ** the trigger named P4 in database P1. This is called after a trigger
  73954. ** is dropped from disk (using the Destroy opcode) in order to keep
  73955. ** the internal representation of the
  73956. ** schema consistent with what is on disk.
  73957. */
  73958. case OP_DropTrigger: {
  73959. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  73960. break;
  73961. }
  73962. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  73963. /* Opcode: IntegrityCk P1 P2 P3 * P5
  73964. **
  73965. ** Do an analysis of the currently open database. Store in
  73966. ** register P1 the text of an error message describing any problems.
  73967. ** If no problems are found, store a NULL in register P1.
  73968. **
  73969. ** The register P3 contains the maximum number of allowed errors.
  73970. ** At most reg(P3) errors will be reported.
  73971. ** In other words, the analysis stops as soon as reg(P1) errors are
  73972. ** seen. Reg(P1) is updated with the number of errors remaining.
  73973. **
  73974. ** The root page numbers of all tables in the database are integer
  73975. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  73976. ** total.
  73977. **
  73978. ** If P5 is not zero, the check is done on the auxiliary database
  73979. ** file, not the main database file.
  73980. **
  73981. ** This opcode is used to implement the integrity_check pragma.
  73982. */
  73983. case OP_IntegrityCk: {
  73984. int nRoot; /* Number of tables to check. (Number of root pages.) */
  73985. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  73986. int j; /* Loop counter */
  73987. int nErr; /* Number of errors reported */
  73988. char *z; /* Text of the error report */
  73989. Mem *pnErr; /* Register keeping track of errors remaining */
  73990. assert( p->bIsReader );
  73991. nRoot = pOp->p2;
  73992. assert( nRoot>0 );
  73993. aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  73994. if( aRoot==0 ) goto no_mem;
  73995. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  73996. pnErr = &aMem[pOp->p3];
  73997. assert( (pnErr->flags & MEM_Int)!=0 );
  73998. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  73999. pIn1 = &aMem[pOp->p1];
  74000. for(j=0; j<nRoot; j++){
  74001. aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  74002. }
  74003. aRoot[j] = 0;
  74004. assert( pOp->p5<db->nDb );
  74005. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  74006. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  74007. (int)pnErr->u.i, &nErr);
  74008. sqlite3DbFree(db, aRoot);
  74009. pnErr->u.i -= nErr;
  74010. sqlite3VdbeMemSetNull(pIn1);
  74011. if( nErr==0 ){
  74012. assert( z==0 );
  74013. }else if( z==0 ){
  74014. goto no_mem;
  74015. }else{
  74016. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  74017. }
  74018. UPDATE_MAX_BLOBSIZE(pIn1);
  74019. sqlite3VdbeChangeEncoding(pIn1, encoding);
  74020. break;
  74021. }
  74022. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  74023. /* Opcode: RowSetAdd P1 P2 * * *
  74024. ** Synopsis: rowset(P1)=r[P2]
  74025. **
  74026. ** Insert the integer value held by register P2 into a boolean index
  74027. ** held in register P1.
  74028. **
  74029. ** An assertion fails if P2 is not an integer.
  74030. */
  74031. case OP_RowSetAdd: { /* in1, in2 */
  74032. pIn1 = &aMem[pOp->p1];
  74033. pIn2 = &aMem[pOp->p2];
  74034. assert( (pIn2->flags & MEM_Int)!=0 );
  74035. if( (pIn1->flags & MEM_RowSet)==0 ){
  74036. sqlite3VdbeMemSetRowSet(pIn1);
  74037. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  74038. }
  74039. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  74040. break;
  74041. }
  74042. /* Opcode: RowSetRead P1 P2 P3 * *
  74043. ** Synopsis: r[P3]=rowset(P1)
  74044. **
  74045. ** Extract the smallest value from boolean index P1 and put that value into
  74046. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  74047. ** unchanged and jump to instruction P2.
  74048. */
  74049. case OP_RowSetRead: { /* jump, in1, out3 */
  74050. i64 val;
  74051. pIn1 = &aMem[pOp->p1];
  74052. if( (pIn1->flags & MEM_RowSet)==0
  74053. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  74054. ){
  74055. /* The boolean index is empty */
  74056. sqlite3VdbeMemSetNull(pIn1);
  74057. VdbeBranchTaken(1,2);
  74058. goto jump_to_p2_and_check_for_interrupt;
  74059. }else{
  74060. /* A value was pulled from the index */
  74061. VdbeBranchTaken(0,2);
  74062. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  74063. }
  74064. goto check_for_interrupt;
  74065. }
  74066. /* Opcode: RowSetTest P1 P2 P3 P4
  74067. ** Synopsis: if r[P3] in rowset(P1) goto P2
  74068. **
  74069. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  74070. ** contains a RowSet object and that RowSet object contains
  74071. ** the value held in P3, jump to register P2. Otherwise, insert the
  74072. ** integer in P3 into the RowSet and continue on to the
  74073. ** next opcode.
  74074. **
  74075. ** The RowSet object is optimized for the case where successive sets
  74076. ** of integers, where each set contains no duplicates. Each set
  74077. ** of values is identified by a unique P4 value. The first set
  74078. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  74079. ** non-negative. For non-negative values of P4 only the lower 4
  74080. ** bits are significant.
  74081. **
  74082. ** This allows optimizations: (a) when P4==0 there is no need to test
  74083. ** the rowset object for P3, as it is guaranteed not to contain it,
  74084. ** (b) when P4==-1 there is no need to insert the value, as it will
  74085. ** never be tested for, and (c) when a value that is part of set X is
  74086. ** inserted, there is no need to search to see if the same value was
  74087. ** previously inserted as part of set X (only if it was previously
  74088. ** inserted as part of some other set).
  74089. */
  74090. case OP_RowSetTest: { /* jump, in1, in3 */
  74091. int iSet;
  74092. int exists;
  74093. pIn1 = &aMem[pOp->p1];
  74094. pIn3 = &aMem[pOp->p3];
  74095. iSet = pOp->p4.i;
  74096. assert( pIn3->flags&MEM_Int );
  74097. /* If there is anything other than a rowset object in memory cell P1,
  74098. ** delete it now and initialize P1 with an empty rowset
  74099. */
  74100. if( (pIn1->flags & MEM_RowSet)==0 ){
  74101. sqlite3VdbeMemSetRowSet(pIn1);
  74102. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  74103. }
  74104. assert( pOp->p4type==P4_INT32 );
  74105. assert( iSet==-1 || iSet>=0 );
  74106. if( iSet ){
  74107. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  74108. VdbeBranchTaken(exists!=0,2);
  74109. if( exists ) goto jump_to_p2;
  74110. }
  74111. if( iSet>=0 ){
  74112. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  74113. }
  74114. break;
  74115. }
  74116. #ifndef SQLITE_OMIT_TRIGGER
  74117. /* Opcode: Program P1 P2 P3 P4 P5
  74118. **
  74119. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  74120. **
  74121. ** P1 contains the address of the memory cell that contains the first memory
  74122. ** cell in an array of values used as arguments to the sub-program. P2
  74123. ** contains the address to jump to if the sub-program throws an IGNORE
  74124. ** exception using the RAISE() function. Register P3 contains the address
  74125. ** of a memory cell in this (the parent) VM that is used to allocate the
  74126. ** memory required by the sub-vdbe at runtime.
  74127. **
  74128. ** P4 is a pointer to the VM containing the trigger program.
  74129. **
  74130. ** If P5 is non-zero, then recursive program invocation is enabled.
  74131. */
  74132. case OP_Program: { /* jump */
  74133. int nMem; /* Number of memory registers for sub-program */
  74134. int nByte; /* Bytes of runtime space required for sub-program */
  74135. Mem *pRt; /* Register to allocate runtime space */
  74136. Mem *pMem; /* Used to iterate through memory cells */
  74137. Mem *pEnd; /* Last memory cell in new array */
  74138. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  74139. SubProgram *pProgram; /* Sub-program to execute */
  74140. void *t; /* Token identifying trigger */
  74141. pProgram = pOp->p4.pProgram;
  74142. pRt = &aMem[pOp->p3];
  74143. assert( pProgram->nOp>0 );
  74144. /* If the p5 flag is clear, then recursive invocation of triggers is
  74145. ** disabled for backwards compatibility (p5 is set if this sub-program
  74146. ** is really a trigger, not a foreign key action, and the flag set
  74147. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  74148. **
  74149. ** It is recursive invocation of triggers, at the SQL level, that is
  74150. ** disabled. In some cases a single trigger may generate more than one
  74151. ** SubProgram (if the trigger may be executed with more than one different
  74152. ** ON CONFLICT algorithm). SubProgram structures associated with a
  74153. ** single trigger all have the same value for the SubProgram.token
  74154. ** variable. */
  74155. if( pOp->p5 ){
  74156. t = pProgram->token;
  74157. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  74158. if( pFrame ) break;
  74159. }
  74160. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  74161. rc = SQLITE_ERROR;
  74162. sqlite3VdbeError(p, "too many levels of trigger recursion");
  74163. break;
  74164. }
  74165. /* Register pRt is used to store the memory required to save the state
  74166. ** of the current program, and the memory required at runtime to execute
  74167. ** the trigger program. If this trigger has been fired before, then pRt
  74168. ** is already allocated. Otherwise, it must be initialized. */
  74169. if( (pRt->flags&MEM_Frame)==0 ){
  74170. /* SubProgram.nMem is set to the number of memory cells used by the
  74171. ** program stored in SubProgram.aOp. As well as these, one memory
  74172. ** cell is required for each cursor used by the program. Set local
  74173. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  74174. */
  74175. nMem = pProgram->nMem + pProgram->nCsr;
  74176. nByte = ROUND8(sizeof(VdbeFrame))
  74177. + nMem * sizeof(Mem)
  74178. + pProgram->nCsr * sizeof(VdbeCursor *)
  74179. + pProgram->nOnce * sizeof(u8);
  74180. pFrame = sqlite3DbMallocZero(db, nByte);
  74181. if( !pFrame ){
  74182. goto no_mem;
  74183. }
  74184. sqlite3VdbeMemRelease(pRt);
  74185. pRt->flags = MEM_Frame;
  74186. pRt->u.pFrame = pFrame;
  74187. pFrame->v = p;
  74188. pFrame->nChildMem = nMem;
  74189. pFrame->nChildCsr = pProgram->nCsr;
  74190. pFrame->pc = (int)(pOp - aOp);
  74191. pFrame->aMem = p->aMem;
  74192. pFrame->nMem = p->nMem;
  74193. pFrame->apCsr = p->apCsr;
  74194. pFrame->nCursor = p->nCursor;
  74195. pFrame->aOp = p->aOp;
  74196. pFrame->nOp = p->nOp;
  74197. pFrame->token = pProgram->token;
  74198. pFrame->aOnceFlag = p->aOnceFlag;
  74199. pFrame->nOnceFlag = p->nOnceFlag;
  74200. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  74201. pFrame->anExec = p->anExec;
  74202. #endif
  74203. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  74204. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  74205. pMem->flags = MEM_Undefined;
  74206. pMem->db = db;
  74207. }
  74208. }else{
  74209. pFrame = pRt->u.pFrame;
  74210. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
  74211. assert( pProgram->nCsr==pFrame->nChildCsr );
  74212. assert( (int)(pOp - aOp)==pFrame->pc );
  74213. }
  74214. p->nFrame++;
  74215. pFrame->pParent = p->pFrame;
  74216. pFrame->lastRowid = lastRowid;
  74217. pFrame->nChange = p->nChange;
  74218. pFrame->nDbChange = p->db->nChange;
  74219. p->nChange = 0;
  74220. p->pFrame = pFrame;
  74221. p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
  74222. p->nMem = pFrame->nChildMem;
  74223. p->nCursor = (u16)pFrame->nChildCsr;
  74224. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  74225. p->aOp = aOp = pProgram->aOp;
  74226. p->nOp = pProgram->nOp;
  74227. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  74228. p->nOnceFlag = pProgram->nOnce;
  74229. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  74230. p->anExec = 0;
  74231. #endif
  74232. pOp = &aOp[-1];
  74233. memset(p->aOnceFlag, 0, p->nOnceFlag);
  74234. break;
  74235. }
  74236. /* Opcode: Param P1 P2 * * *
  74237. **
  74238. ** This opcode is only ever present in sub-programs called via the
  74239. ** OP_Program instruction. Copy a value currently stored in a memory
  74240. ** cell of the calling (parent) frame to cell P2 in the current frames
  74241. ** address space. This is used by trigger programs to access the new.*
  74242. ** and old.* values.
  74243. **
  74244. ** The address of the cell in the parent frame is determined by adding
  74245. ** the value of the P1 argument to the value of the P1 argument to the
  74246. ** calling OP_Program instruction.
  74247. */
  74248. case OP_Param: { /* out2 */
  74249. VdbeFrame *pFrame;
  74250. Mem *pIn;
  74251. pOut = out2Prerelease(p, pOp);
  74252. pFrame = p->pFrame;
  74253. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  74254. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  74255. break;
  74256. }
  74257. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  74258. #ifndef SQLITE_OMIT_FOREIGN_KEY
  74259. /* Opcode: FkCounter P1 P2 * * *
  74260. ** Synopsis: fkctr[P1]+=P2
  74261. **
  74262. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  74263. ** If P1 is non-zero, the database constraint counter is incremented
  74264. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  74265. ** statement counter is incremented (immediate foreign key constraints).
  74266. */
  74267. case OP_FkCounter: {
  74268. if( db->flags & SQLITE_DeferFKs ){
  74269. db->nDeferredImmCons += pOp->p2;
  74270. }else if( pOp->p1 ){
  74271. db->nDeferredCons += pOp->p2;
  74272. }else{
  74273. p->nFkConstraint += pOp->p2;
  74274. }
  74275. break;
  74276. }
  74277. /* Opcode: FkIfZero P1 P2 * * *
  74278. ** Synopsis: if fkctr[P1]==0 goto P2
  74279. **
  74280. ** This opcode tests if a foreign key constraint-counter is currently zero.
  74281. ** If so, jump to instruction P2. Otherwise, fall through to the next
  74282. ** instruction.
  74283. **
  74284. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  74285. ** is zero (the one that counts deferred constraint violations). If P1 is
  74286. ** zero, the jump is taken if the statement constraint-counter is zero
  74287. ** (immediate foreign key constraint violations).
  74288. */
  74289. case OP_FkIfZero: { /* jump */
  74290. if( pOp->p1 ){
  74291. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  74292. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  74293. }else{
  74294. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  74295. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  74296. }
  74297. break;
  74298. }
  74299. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  74300. #ifndef SQLITE_OMIT_AUTOINCREMENT
  74301. /* Opcode: MemMax P1 P2 * * *
  74302. ** Synopsis: r[P1]=max(r[P1],r[P2])
  74303. **
  74304. ** P1 is a register in the root frame of this VM (the root frame is
  74305. ** different from the current frame if this instruction is being executed
  74306. ** within a sub-program). Set the value of register P1 to the maximum of
  74307. ** its current value and the value in register P2.
  74308. **
  74309. ** This instruction throws an error if the memory cell is not initially
  74310. ** an integer.
  74311. */
  74312. case OP_MemMax: { /* in2 */
  74313. VdbeFrame *pFrame;
  74314. if( p->pFrame ){
  74315. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  74316. pIn1 = &pFrame->aMem[pOp->p1];
  74317. }else{
  74318. pIn1 = &aMem[pOp->p1];
  74319. }
  74320. assert( memIsValid(pIn1) );
  74321. sqlite3VdbeMemIntegerify(pIn1);
  74322. pIn2 = &aMem[pOp->p2];
  74323. sqlite3VdbeMemIntegerify(pIn2);
  74324. if( pIn1->u.i<pIn2->u.i){
  74325. pIn1->u.i = pIn2->u.i;
  74326. }
  74327. break;
  74328. }
  74329. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  74330. /* Opcode: IfPos P1 P2 P3 * *
  74331. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  74332. **
  74333. ** Register P1 must contain an integer.
  74334. ** If the value of register P1 is 1 or greater, subtract P3 from the
  74335. ** value in P1 and jump to P2.
  74336. **
  74337. ** If the initial value of register P1 is less than 1, then the
  74338. ** value is unchanged and control passes through to the next instruction.
  74339. */
  74340. case OP_IfPos: { /* jump, in1 */
  74341. pIn1 = &aMem[pOp->p1];
  74342. assert( pIn1->flags&MEM_Int );
  74343. VdbeBranchTaken( pIn1->u.i>0, 2);
  74344. if( pIn1->u.i>0 ){
  74345. pIn1->u.i -= pOp->p3;
  74346. goto jump_to_p2;
  74347. }
  74348. break;
  74349. }
  74350. /* Opcode: SetIfNotPos P1 P2 P3 * *
  74351. ** Synopsis: if r[P1]<=0 then r[P2]=P3
  74352. **
  74353. ** Register P1 must contain an integer.
  74354. ** If the value of register P1 is not positive (if it is less than 1) then
  74355. ** set the value of register P2 to be the integer P3.
  74356. */
  74357. case OP_SetIfNotPos: { /* in1, in2 */
  74358. pIn1 = &aMem[pOp->p1];
  74359. assert( pIn1->flags&MEM_Int );
  74360. if( pIn1->u.i<=0 ){
  74361. pOut = out2Prerelease(p, pOp);
  74362. pOut->u.i = pOp->p3;
  74363. }
  74364. break;
  74365. }
  74366. /* Opcode: IfNotZero P1 P2 P3 * *
  74367. ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
  74368. **
  74369. ** Register P1 must contain an integer. If the content of register P1 is
  74370. ** initially nonzero, then subtract P3 from the value in register P1 and
  74371. ** jump to P2. If register P1 is initially zero, leave it unchanged
  74372. ** and fall through.
  74373. */
  74374. case OP_IfNotZero: { /* jump, in1 */
  74375. pIn1 = &aMem[pOp->p1];
  74376. assert( pIn1->flags&MEM_Int );
  74377. VdbeBranchTaken(pIn1->u.i<0, 2);
  74378. if( pIn1->u.i ){
  74379. pIn1->u.i -= pOp->p3;
  74380. goto jump_to_p2;
  74381. }
  74382. break;
  74383. }
  74384. /* Opcode: DecrJumpZero P1 P2 * * *
  74385. ** Synopsis: if (--r[P1])==0 goto P2
  74386. **
  74387. ** Register P1 must hold an integer. Decrement the value in register P1
  74388. ** then jump to P2 if the new value is exactly zero.
  74389. */
  74390. case OP_DecrJumpZero: { /* jump, in1 */
  74391. pIn1 = &aMem[pOp->p1];
  74392. assert( pIn1->flags&MEM_Int );
  74393. pIn1->u.i--;
  74394. VdbeBranchTaken(pIn1->u.i==0, 2);
  74395. if( pIn1->u.i==0 ) goto jump_to_p2;
  74396. break;
  74397. }
  74398. /* Opcode: JumpZeroIncr P1 P2 * * *
  74399. ** Synopsis: if (r[P1]++)==0 ) goto P2
  74400. **
  74401. ** The register P1 must contain an integer. If register P1 is initially
  74402. ** zero, then jump to P2. Increment register P1 regardless of whether or
  74403. ** not the jump is taken.
  74404. */
  74405. case OP_JumpZeroIncr: { /* jump, in1 */
  74406. pIn1 = &aMem[pOp->p1];
  74407. assert( pIn1->flags&MEM_Int );
  74408. VdbeBranchTaken(pIn1->u.i==0, 2);
  74409. if( (pIn1->u.i++)==0 ) goto jump_to_p2;
  74410. break;
  74411. }
  74412. /* Opcode: AggStep0 * P2 P3 P4 P5
  74413. ** Synopsis: accum=r[P3] step(r[P2@P5])
  74414. **
  74415. ** Execute the step function for an aggregate. The
  74416. ** function has P5 arguments. P4 is a pointer to the FuncDef
  74417. ** structure that specifies the function. Register P3 is the
  74418. ** accumulator.
  74419. **
  74420. ** The P5 arguments are taken from register P2 and its
  74421. ** successors.
  74422. */
  74423. /* Opcode: AggStep * P2 P3 P4 P5
  74424. ** Synopsis: accum=r[P3] step(r[P2@P5])
  74425. **
  74426. ** Execute the step function for an aggregate. The
  74427. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  74428. ** object that is used to run the function. Register P3 is
  74429. ** as the accumulator.
  74430. **
  74431. ** The P5 arguments are taken from register P2 and its
  74432. ** successors.
  74433. **
  74434. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  74435. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  74436. ** the opcode is changed. In this way, the initialization of the
  74437. ** sqlite3_context only happens once, instead of on each call to the
  74438. ** step function.
  74439. */
  74440. case OP_AggStep0: {
  74441. int n;
  74442. sqlite3_context *pCtx;
  74443. assert( pOp->p4type==P4_FUNCDEF );
  74444. n = pOp->p5;
  74445. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  74446. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  74447. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  74448. pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  74449. if( pCtx==0 ) goto no_mem;
  74450. pCtx->pMem = 0;
  74451. pCtx->pFunc = pOp->p4.pFunc;
  74452. pCtx->iOp = (int)(pOp - aOp);
  74453. pCtx->pVdbe = p;
  74454. pCtx->argc = n;
  74455. pOp->p4type = P4_FUNCCTX;
  74456. pOp->p4.pCtx = pCtx;
  74457. pOp->opcode = OP_AggStep;
  74458. /* Fall through into OP_AggStep */
  74459. }
  74460. case OP_AggStep: {
  74461. int i;
  74462. sqlite3_context *pCtx;
  74463. Mem *pMem;
  74464. Mem t;
  74465. assert( pOp->p4type==P4_FUNCCTX );
  74466. pCtx = pOp->p4.pCtx;
  74467. pMem = &aMem[pOp->p3];
  74468. /* If this function is inside of a trigger, the register array in aMem[]
  74469. ** might change from one evaluation to the next. The next block of code
  74470. ** checks to see if the register array has changed, and if so it
  74471. ** reinitializes the relavant parts of the sqlite3_context object */
  74472. if( pCtx->pMem != pMem ){
  74473. pCtx->pMem = pMem;
  74474. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  74475. }
  74476. #ifdef SQLITE_DEBUG
  74477. for(i=0; i<pCtx->argc; i++){
  74478. assert( memIsValid(pCtx->argv[i]) );
  74479. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  74480. }
  74481. #endif
  74482. pMem->n++;
  74483. sqlite3VdbeMemInit(&t, db, MEM_Null);
  74484. pCtx->pOut = &t;
  74485. pCtx->fErrorOrAux = 0;
  74486. pCtx->skipFlag = 0;
  74487. (pCtx->pFunc->xStep)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  74488. if( pCtx->fErrorOrAux ){
  74489. if( pCtx->isError ){
  74490. sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
  74491. rc = pCtx->isError;
  74492. }
  74493. sqlite3VdbeMemRelease(&t);
  74494. }else{
  74495. assert( t.flags==MEM_Null );
  74496. }
  74497. if( pCtx->skipFlag ){
  74498. assert( pOp[-1].opcode==OP_CollSeq );
  74499. i = pOp[-1].p1;
  74500. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  74501. }
  74502. break;
  74503. }
  74504. /* Opcode: AggFinal P1 P2 * P4 *
  74505. ** Synopsis: accum=r[P1] N=P2
  74506. **
  74507. ** Execute the finalizer function for an aggregate. P1 is
  74508. ** the memory location that is the accumulator for the aggregate.
  74509. **
  74510. ** P2 is the number of arguments that the step function takes and
  74511. ** P4 is a pointer to the FuncDef for this function. The P2
  74512. ** argument is not used by this opcode. It is only there to disambiguate
  74513. ** functions that can take varying numbers of arguments. The
  74514. ** P4 argument is only needed for the degenerate case where
  74515. ** the step function was not previously called.
  74516. */
  74517. case OP_AggFinal: {
  74518. Mem *pMem;
  74519. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  74520. pMem = &aMem[pOp->p1];
  74521. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  74522. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  74523. if( rc ){
  74524. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  74525. }
  74526. sqlite3VdbeChangeEncoding(pMem, encoding);
  74527. UPDATE_MAX_BLOBSIZE(pMem);
  74528. if( sqlite3VdbeMemTooBig(pMem) ){
  74529. goto too_big;
  74530. }
  74531. break;
  74532. }
  74533. #ifndef SQLITE_OMIT_WAL
  74534. /* Opcode: Checkpoint P1 P2 P3 * *
  74535. **
  74536. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  74537. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  74538. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  74539. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  74540. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  74541. ** in the WAL that have been checkpointed after the checkpoint
  74542. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  74543. ** mem[P3+2] are initialized to -1.
  74544. */
  74545. case OP_Checkpoint: {
  74546. int i; /* Loop counter */
  74547. int aRes[3]; /* Results */
  74548. Mem *pMem; /* Write results here */
  74549. assert( p->readOnly==0 );
  74550. aRes[0] = 0;
  74551. aRes[1] = aRes[2] = -1;
  74552. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  74553. || pOp->p2==SQLITE_CHECKPOINT_FULL
  74554. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  74555. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  74556. );
  74557. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  74558. if( rc==SQLITE_BUSY ){
  74559. rc = SQLITE_OK;
  74560. aRes[0] = 1;
  74561. }
  74562. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  74563. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  74564. }
  74565. break;
  74566. };
  74567. #endif
  74568. #ifndef SQLITE_OMIT_PRAGMA
  74569. /* Opcode: JournalMode P1 P2 P3 * *
  74570. **
  74571. ** Change the journal mode of database P1 to P3. P3 must be one of the
  74572. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  74573. ** modes (delete, truncate, persist, off and memory), this is a simple
  74574. ** operation. No IO is required.
  74575. **
  74576. ** If changing into or out of WAL mode the procedure is more complicated.
  74577. **
  74578. ** Write a string containing the final journal-mode to register P2.
  74579. */
  74580. case OP_JournalMode: { /* out2 */
  74581. Btree *pBt; /* Btree to change journal mode of */
  74582. Pager *pPager; /* Pager associated with pBt */
  74583. int eNew; /* New journal mode */
  74584. int eOld; /* The old journal mode */
  74585. #ifndef SQLITE_OMIT_WAL
  74586. const char *zFilename; /* Name of database file for pPager */
  74587. #endif
  74588. pOut = out2Prerelease(p, pOp);
  74589. eNew = pOp->p3;
  74590. assert( eNew==PAGER_JOURNALMODE_DELETE
  74591. || eNew==PAGER_JOURNALMODE_TRUNCATE
  74592. || eNew==PAGER_JOURNALMODE_PERSIST
  74593. || eNew==PAGER_JOURNALMODE_OFF
  74594. || eNew==PAGER_JOURNALMODE_MEMORY
  74595. || eNew==PAGER_JOURNALMODE_WAL
  74596. || eNew==PAGER_JOURNALMODE_QUERY
  74597. );
  74598. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  74599. assert( p->readOnly==0 );
  74600. pBt = db->aDb[pOp->p1].pBt;
  74601. pPager = sqlite3BtreePager(pBt);
  74602. eOld = sqlite3PagerGetJournalMode(pPager);
  74603. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  74604. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  74605. #ifndef SQLITE_OMIT_WAL
  74606. zFilename = sqlite3PagerFilename(pPager, 1);
  74607. /* Do not allow a transition to journal_mode=WAL for a database
  74608. ** in temporary storage or if the VFS does not support shared memory
  74609. */
  74610. if( eNew==PAGER_JOURNALMODE_WAL
  74611. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  74612. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  74613. ){
  74614. eNew = eOld;
  74615. }
  74616. if( (eNew!=eOld)
  74617. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  74618. ){
  74619. if( !db->autoCommit || db->nVdbeRead>1 ){
  74620. rc = SQLITE_ERROR;
  74621. sqlite3VdbeError(p,
  74622. "cannot change %s wal mode from within a transaction",
  74623. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  74624. );
  74625. break;
  74626. }else{
  74627. if( eOld==PAGER_JOURNALMODE_WAL ){
  74628. /* If leaving WAL mode, close the log file. If successful, the call
  74629. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  74630. ** file. An EXCLUSIVE lock may still be held on the database file
  74631. ** after a successful return.
  74632. */
  74633. rc = sqlite3PagerCloseWal(pPager);
  74634. if( rc==SQLITE_OK ){
  74635. sqlite3PagerSetJournalMode(pPager, eNew);
  74636. }
  74637. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  74638. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  74639. ** as an intermediate */
  74640. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  74641. }
  74642. /* Open a transaction on the database file. Regardless of the journal
  74643. ** mode, this transaction always uses a rollback journal.
  74644. */
  74645. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  74646. if( rc==SQLITE_OK ){
  74647. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  74648. }
  74649. }
  74650. }
  74651. #endif /* ifndef SQLITE_OMIT_WAL */
  74652. if( rc ){
  74653. eNew = eOld;
  74654. }
  74655. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  74656. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  74657. pOut->z = (char *)sqlite3JournalModename(eNew);
  74658. pOut->n = sqlite3Strlen30(pOut->z);
  74659. pOut->enc = SQLITE_UTF8;
  74660. sqlite3VdbeChangeEncoding(pOut, encoding);
  74661. break;
  74662. };
  74663. #endif /* SQLITE_OMIT_PRAGMA */
  74664. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  74665. /* Opcode: Vacuum * * * * *
  74666. **
  74667. ** Vacuum the entire database. This opcode will cause other virtual
  74668. ** machines to be created and run. It may not be called from within
  74669. ** a transaction.
  74670. */
  74671. case OP_Vacuum: {
  74672. assert( p->readOnly==0 );
  74673. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  74674. break;
  74675. }
  74676. #endif
  74677. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  74678. /* Opcode: IncrVacuum P1 P2 * * *
  74679. **
  74680. ** Perform a single step of the incremental vacuum procedure on
  74681. ** the P1 database. If the vacuum has finished, jump to instruction
  74682. ** P2. Otherwise, fall through to the next instruction.
  74683. */
  74684. case OP_IncrVacuum: { /* jump */
  74685. Btree *pBt;
  74686. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  74687. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  74688. assert( p->readOnly==0 );
  74689. pBt = db->aDb[pOp->p1].pBt;
  74690. rc = sqlite3BtreeIncrVacuum(pBt);
  74691. VdbeBranchTaken(rc==SQLITE_DONE,2);
  74692. if( rc==SQLITE_DONE ){
  74693. rc = SQLITE_OK;
  74694. goto jump_to_p2;
  74695. }
  74696. break;
  74697. }
  74698. #endif
  74699. /* Opcode: Expire P1 * * * *
  74700. **
  74701. ** Cause precompiled statements to expire. When an expired statement
  74702. ** is executed using sqlite3_step() it will either automatically
  74703. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  74704. ** or it will fail with SQLITE_SCHEMA.
  74705. **
  74706. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  74707. ** then only the currently executing statement is expired.
  74708. */
  74709. case OP_Expire: {
  74710. if( !pOp->p1 ){
  74711. sqlite3ExpirePreparedStatements(db);
  74712. }else{
  74713. p->expired = 1;
  74714. }
  74715. break;
  74716. }
  74717. #ifndef SQLITE_OMIT_SHARED_CACHE
  74718. /* Opcode: TableLock P1 P2 P3 P4 *
  74719. ** Synopsis: iDb=P1 root=P2 write=P3
  74720. **
  74721. ** Obtain a lock on a particular table. This instruction is only used when
  74722. ** the shared-cache feature is enabled.
  74723. **
  74724. ** P1 is the index of the database in sqlite3.aDb[] of the database
  74725. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  74726. ** a write lock if P3==1.
  74727. **
  74728. ** P2 contains the root-page of the table to lock.
  74729. **
  74730. ** P4 contains a pointer to the name of the table being locked. This is only
  74731. ** used to generate an error message if the lock cannot be obtained.
  74732. */
  74733. case OP_TableLock: {
  74734. u8 isWriteLock = (u8)pOp->p3;
  74735. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  74736. int p1 = pOp->p1;
  74737. assert( p1>=0 && p1<db->nDb );
  74738. assert( DbMaskTest(p->btreeMask, p1) );
  74739. assert( isWriteLock==0 || isWriteLock==1 );
  74740. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  74741. if( (rc&0xFF)==SQLITE_LOCKED ){
  74742. const char *z = pOp->p4.z;
  74743. sqlite3VdbeError(p, "database table is locked: %s", z);
  74744. }
  74745. }
  74746. break;
  74747. }
  74748. #endif /* SQLITE_OMIT_SHARED_CACHE */
  74749. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74750. /* Opcode: VBegin * * * P4 *
  74751. **
  74752. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  74753. ** xBegin method for that table.
  74754. **
  74755. ** Also, whether or not P4 is set, check that this is not being called from
  74756. ** within a callback to a virtual table xSync() method. If it is, the error
  74757. ** code will be set to SQLITE_LOCKED.
  74758. */
  74759. case OP_VBegin: {
  74760. VTable *pVTab;
  74761. pVTab = pOp->p4.pVtab;
  74762. rc = sqlite3VtabBegin(db, pVTab);
  74763. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  74764. break;
  74765. }
  74766. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74767. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74768. /* Opcode: VCreate P1 P2 * * *
  74769. **
  74770. ** P2 is a register that holds the name of a virtual table in database
  74771. ** P1. Call the xCreate method for that table.
  74772. */
  74773. case OP_VCreate: {
  74774. Mem sMem; /* For storing the record being decoded */
  74775. const char *zTab; /* Name of the virtual table */
  74776. memset(&sMem, 0, sizeof(sMem));
  74777. sMem.db = db;
  74778. /* Because P2 is always a static string, it is impossible for the
  74779. ** sqlite3VdbeMemCopy() to fail */
  74780. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  74781. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  74782. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  74783. assert( rc==SQLITE_OK );
  74784. zTab = (const char*)sqlite3_value_text(&sMem);
  74785. assert( zTab || db->mallocFailed );
  74786. if( zTab ){
  74787. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  74788. }
  74789. sqlite3VdbeMemRelease(&sMem);
  74790. break;
  74791. }
  74792. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74793. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74794. /* Opcode: VDestroy P1 * * P4 *
  74795. **
  74796. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  74797. ** of that table.
  74798. */
  74799. case OP_VDestroy: {
  74800. db->nVDestroy++;
  74801. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  74802. db->nVDestroy--;
  74803. break;
  74804. }
  74805. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74806. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74807. /* Opcode: VOpen P1 * * P4 *
  74808. **
  74809. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  74810. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  74811. ** table and stores that cursor in P1.
  74812. */
  74813. case OP_VOpen: {
  74814. VdbeCursor *pCur;
  74815. sqlite3_vtab_cursor *pVCur;
  74816. sqlite3_vtab *pVtab;
  74817. const sqlite3_module *pModule;
  74818. assert( p->bIsReader );
  74819. pCur = 0;
  74820. pVCur = 0;
  74821. pVtab = pOp->p4.pVtab->pVtab;
  74822. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  74823. rc = SQLITE_LOCKED;
  74824. break;
  74825. }
  74826. pModule = pVtab->pModule;
  74827. rc = pModule->xOpen(pVtab, &pVCur);
  74828. sqlite3VtabImportErrmsg(p, pVtab);
  74829. if( SQLITE_OK==rc ){
  74830. /* Initialize sqlite3_vtab_cursor base class */
  74831. pVCur->pVtab = pVtab;
  74832. /* Initialize vdbe cursor object */
  74833. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  74834. if( pCur ){
  74835. pCur->uc.pVCur = pVCur;
  74836. pVtab->nRef++;
  74837. }else{
  74838. assert( db->mallocFailed );
  74839. pModule->xClose(pVCur);
  74840. goto no_mem;
  74841. }
  74842. }
  74843. break;
  74844. }
  74845. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74846. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74847. /* Opcode: VFilter P1 P2 P3 P4 *
  74848. ** Synopsis: iplan=r[P3] zplan='P4'
  74849. **
  74850. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  74851. ** the filtered result set is empty.
  74852. **
  74853. ** P4 is either NULL or a string that was generated by the xBestIndex
  74854. ** method of the module. The interpretation of the P4 string is left
  74855. ** to the module implementation.
  74856. **
  74857. ** This opcode invokes the xFilter method on the virtual table specified
  74858. ** by P1. The integer query plan parameter to xFilter is stored in register
  74859. ** P3. Register P3+1 stores the argc parameter to be passed to the
  74860. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  74861. ** additional parameters which are passed to
  74862. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  74863. **
  74864. ** A jump is made to P2 if the result set after filtering would be empty.
  74865. */
  74866. case OP_VFilter: { /* jump */
  74867. int nArg;
  74868. int iQuery;
  74869. const sqlite3_module *pModule;
  74870. Mem *pQuery;
  74871. Mem *pArgc;
  74872. sqlite3_vtab_cursor *pVCur;
  74873. sqlite3_vtab *pVtab;
  74874. VdbeCursor *pCur;
  74875. int res;
  74876. int i;
  74877. Mem **apArg;
  74878. pQuery = &aMem[pOp->p3];
  74879. pArgc = &pQuery[1];
  74880. pCur = p->apCsr[pOp->p1];
  74881. assert( memIsValid(pQuery) );
  74882. REGISTER_TRACE(pOp->p3, pQuery);
  74883. assert( pCur->eCurType==CURTYPE_VTAB );
  74884. pVCur = pCur->uc.pVCur;
  74885. pVtab = pVCur->pVtab;
  74886. pModule = pVtab->pModule;
  74887. /* Grab the index number and argc parameters */
  74888. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  74889. nArg = (int)pArgc->u.i;
  74890. iQuery = (int)pQuery->u.i;
  74891. /* Invoke the xFilter method */
  74892. res = 0;
  74893. apArg = p->apArg;
  74894. for(i = 0; i<nArg; i++){
  74895. apArg[i] = &pArgc[i+1];
  74896. }
  74897. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  74898. sqlite3VtabImportErrmsg(p, pVtab);
  74899. if( rc==SQLITE_OK ){
  74900. res = pModule->xEof(pVCur);
  74901. }
  74902. pCur->nullRow = 0;
  74903. VdbeBranchTaken(res!=0,2);
  74904. if( res ) goto jump_to_p2;
  74905. break;
  74906. }
  74907. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74908. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74909. /* Opcode: VColumn P1 P2 P3 * *
  74910. ** Synopsis: r[P3]=vcolumn(P2)
  74911. **
  74912. ** Store the value of the P2-th column of
  74913. ** the row of the virtual-table that the
  74914. ** P1 cursor is pointing to into register P3.
  74915. */
  74916. case OP_VColumn: {
  74917. sqlite3_vtab *pVtab;
  74918. const sqlite3_module *pModule;
  74919. Mem *pDest;
  74920. sqlite3_context sContext;
  74921. VdbeCursor *pCur = p->apCsr[pOp->p1];
  74922. assert( pCur->eCurType==CURTYPE_VTAB );
  74923. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  74924. pDest = &aMem[pOp->p3];
  74925. memAboutToChange(p, pDest);
  74926. if( pCur->nullRow ){
  74927. sqlite3VdbeMemSetNull(pDest);
  74928. break;
  74929. }
  74930. pVtab = pCur->uc.pVCur->pVtab;
  74931. pModule = pVtab->pModule;
  74932. assert( pModule->xColumn );
  74933. memset(&sContext, 0, sizeof(sContext));
  74934. sContext.pOut = pDest;
  74935. MemSetTypeFlag(pDest, MEM_Null);
  74936. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  74937. sqlite3VtabImportErrmsg(p, pVtab);
  74938. if( sContext.isError ){
  74939. rc = sContext.isError;
  74940. }
  74941. sqlite3VdbeChangeEncoding(pDest, encoding);
  74942. REGISTER_TRACE(pOp->p3, pDest);
  74943. UPDATE_MAX_BLOBSIZE(pDest);
  74944. if( sqlite3VdbeMemTooBig(pDest) ){
  74945. goto too_big;
  74946. }
  74947. break;
  74948. }
  74949. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74950. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74951. /* Opcode: VNext P1 P2 * * *
  74952. **
  74953. ** Advance virtual table P1 to the next row in its result set and
  74954. ** jump to instruction P2. Or, if the virtual table has reached
  74955. ** the end of its result set, then fall through to the next instruction.
  74956. */
  74957. case OP_VNext: { /* jump */
  74958. sqlite3_vtab *pVtab;
  74959. const sqlite3_module *pModule;
  74960. int res;
  74961. VdbeCursor *pCur;
  74962. res = 0;
  74963. pCur = p->apCsr[pOp->p1];
  74964. assert( pCur->eCurType==CURTYPE_VTAB );
  74965. if( pCur->nullRow ){
  74966. break;
  74967. }
  74968. pVtab = pCur->uc.pVCur->pVtab;
  74969. pModule = pVtab->pModule;
  74970. assert( pModule->xNext );
  74971. /* Invoke the xNext() method of the module. There is no way for the
  74972. ** underlying implementation to return an error if one occurs during
  74973. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  74974. ** data is available) and the error code returned when xColumn or
  74975. ** some other method is next invoked on the save virtual table cursor.
  74976. */
  74977. rc = pModule->xNext(pCur->uc.pVCur);
  74978. sqlite3VtabImportErrmsg(p, pVtab);
  74979. if( rc==SQLITE_OK ){
  74980. res = pModule->xEof(pCur->uc.pVCur);
  74981. }
  74982. VdbeBranchTaken(!res,2);
  74983. if( !res ){
  74984. /* If there is data, jump to P2 */
  74985. goto jump_to_p2_and_check_for_interrupt;
  74986. }
  74987. goto check_for_interrupt;
  74988. }
  74989. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  74990. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74991. /* Opcode: VRename P1 * * P4 *
  74992. **
  74993. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  74994. ** This opcode invokes the corresponding xRename method. The value
  74995. ** in register P1 is passed as the zName argument to the xRename method.
  74996. */
  74997. case OP_VRename: {
  74998. sqlite3_vtab *pVtab;
  74999. Mem *pName;
  75000. pVtab = pOp->p4.pVtab->pVtab;
  75001. pName = &aMem[pOp->p1];
  75002. assert( pVtab->pModule->xRename );
  75003. assert( memIsValid(pName) );
  75004. assert( p->readOnly==0 );
  75005. REGISTER_TRACE(pOp->p1, pName);
  75006. assert( pName->flags & MEM_Str );
  75007. testcase( pName->enc==SQLITE_UTF8 );
  75008. testcase( pName->enc==SQLITE_UTF16BE );
  75009. testcase( pName->enc==SQLITE_UTF16LE );
  75010. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  75011. if( rc==SQLITE_OK ){
  75012. rc = pVtab->pModule->xRename(pVtab, pName->z);
  75013. sqlite3VtabImportErrmsg(p, pVtab);
  75014. p->expired = 0;
  75015. }
  75016. break;
  75017. }
  75018. #endif
  75019. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75020. /* Opcode: VUpdate P1 P2 P3 P4 P5
  75021. ** Synopsis: data=r[P3@P2]
  75022. **
  75023. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  75024. ** This opcode invokes the corresponding xUpdate method. P2 values
  75025. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  75026. ** invocation. The value in register (P3+P2-1) corresponds to the
  75027. ** p2th element of the argv array passed to xUpdate.
  75028. **
  75029. ** The xUpdate method will do a DELETE or an INSERT or both.
  75030. ** The argv[0] element (which corresponds to memory cell P3)
  75031. ** is the rowid of a row to delete. If argv[0] is NULL then no
  75032. ** deletion occurs. The argv[1] element is the rowid of the new
  75033. ** row. This can be NULL to have the virtual table select the new
  75034. ** rowid for itself. The subsequent elements in the array are
  75035. ** the values of columns in the new row.
  75036. **
  75037. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  75038. ** a row to delete.
  75039. **
  75040. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  75041. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  75042. ** is set to the value of the rowid for the row just inserted.
  75043. **
  75044. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  75045. ** apply in the case of a constraint failure on an insert or update.
  75046. */
  75047. case OP_VUpdate: {
  75048. sqlite3_vtab *pVtab;
  75049. const sqlite3_module *pModule;
  75050. int nArg;
  75051. int i;
  75052. sqlite_int64 rowid;
  75053. Mem **apArg;
  75054. Mem *pX;
  75055. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  75056. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  75057. );
  75058. assert( p->readOnly==0 );
  75059. pVtab = pOp->p4.pVtab->pVtab;
  75060. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  75061. rc = SQLITE_LOCKED;
  75062. break;
  75063. }
  75064. pModule = pVtab->pModule;
  75065. nArg = pOp->p2;
  75066. assert( pOp->p4type==P4_VTAB );
  75067. if( ALWAYS(pModule->xUpdate) ){
  75068. u8 vtabOnConflict = db->vtabOnConflict;
  75069. apArg = p->apArg;
  75070. pX = &aMem[pOp->p3];
  75071. for(i=0; i<nArg; i++){
  75072. assert( memIsValid(pX) );
  75073. memAboutToChange(p, pX);
  75074. apArg[i] = pX;
  75075. pX++;
  75076. }
  75077. db->vtabOnConflict = pOp->p5;
  75078. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  75079. db->vtabOnConflict = vtabOnConflict;
  75080. sqlite3VtabImportErrmsg(p, pVtab);
  75081. if( rc==SQLITE_OK && pOp->p1 ){
  75082. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  75083. db->lastRowid = lastRowid = rowid;
  75084. }
  75085. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  75086. if( pOp->p5==OE_Ignore ){
  75087. rc = SQLITE_OK;
  75088. }else{
  75089. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  75090. }
  75091. }else{
  75092. p->nChange++;
  75093. }
  75094. }
  75095. break;
  75096. }
  75097. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  75098. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  75099. /* Opcode: Pagecount P1 P2 * * *
  75100. **
  75101. ** Write the current number of pages in database P1 to memory cell P2.
  75102. */
  75103. case OP_Pagecount: { /* out2 */
  75104. pOut = out2Prerelease(p, pOp);
  75105. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  75106. break;
  75107. }
  75108. #endif
  75109. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  75110. /* Opcode: MaxPgcnt P1 P2 P3 * *
  75111. **
  75112. ** Try to set the maximum page count for database P1 to the value in P3.
  75113. ** Do not let the maximum page count fall below the current page count and
  75114. ** do not change the maximum page count value if P3==0.
  75115. **
  75116. ** Store the maximum page count after the change in register P2.
  75117. */
  75118. case OP_MaxPgcnt: { /* out2 */
  75119. unsigned int newMax;
  75120. Btree *pBt;
  75121. pOut = out2Prerelease(p, pOp);
  75122. pBt = db->aDb[pOp->p1].pBt;
  75123. newMax = 0;
  75124. if( pOp->p3 ){
  75125. newMax = sqlite3BtreeLastPage(pBt);
  75126. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  75127. }
  75128. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  75129. break;
  75130. }
  75131. #endif
  75132. /* Opcode: Init * P2 * P4 *
  75133. ** Synopsis: Start at P2
  75134. **
  75135. ** Programs contain a single instance of this opcode as the very first
  75136. ** opcode.
  75137. **
  75138. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  75139. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  75140. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  75141. **
  75142. ** If P2 is not zero, jump to instruction P2.
  75143. */
  75144. case OP_Init: { /* jump */
  75145. char *zTrace;
  75146. char *z;
  75147. #ifndef SQLITE_OMIT_TRACE
  75148. if( db->xTrace
  75149. && !p->doingRerun
  75150. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  75151. ){
  75152. z = sqlite3VdbeExpandSql(p, zTrace);
  75153. db->xTrace(db->pTraceArg, z);
  75154. sqlite3DbFree(db, z);
  75155. }
  75156. #ifdef SQLITE_USE_FCNTL_TRACE
  75157. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  75158. if( zTrace ){
  75159. int i;
  75160. for(i=0; i<db->nDb; i++){
  75161. if( DbMaskTest(p->btreeMask, i)==0 ) continue;
  75162. sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
  75163. }
  75164. }
  75165. #endif /* SQLITE_USE_FCNTL_TRACE */
  75166. #ifdef SQLITE_DEBUG
  75167. if( (db->flags & SQLITE_SqlTrace)!=0
  75168. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  75169. ){
  75170. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  75171. }
  75172. #endif /* SQLITE_DEBUG */
  75173. #endif /* SQLITE_OMIT_TRACE */
  75174. if( pOp->p2 ) goto jump_to_p2;
  75175. break;
  75176. }
  75177. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  75178. /* Opcode: CursorHint P1 * * P4 *
  75179. **
  75180. ** Provide a hint to cursor P1 that it only needs to return rows that
  75181. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  75182. ** to values currently held in registers. TK_COLUMN terms in the P4
  75183. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  75184. */
  75185. case OP_CursorHint: {
  75186. VdbeCursor *pC;
  75187. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  75188. assert( pOp->p4type==P4_EXPR );
  75189. pC = p->apCsr[pOp->p1];
  75190. if( pC ){
  75191. assert( pC->eCurType==CURTYPE_BTREE );
  75192. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  75193. pOp->p4.pExpr, aMem);
  75194. }
  75195. break;
  75196. }
  75197. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  75198. /* Opcode: Noop * * * * *
  75199. **
  75200. ** Do nothing. This instruction is often useful as a jump
  75201. ** destination.
  75202. */
  75203. /*
  75204. ** The magic Explain opcode are only inserted when explain==2 (which
  75205. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  75206. ** This opcode records information from the optimizer. It is the
  75207. ** the same as a no-op. This opcodesnever appears in a real VM program.
  75208. */
  75209. default: { /* This is really OP_Noop and OP_Explain */
  75210. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  75211. break;
  75212. }
  75213. /*****************************************************************************
  75214. ** The cases of the switch statement above this line should all be indented
  75215. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  75216. ** readability. From this point on down, the normal indentation rules are
  75217. ** restored.
  75218. *****************************************************************************/
  75219. }
  75220. #ifdef VDBE_PROFILE
  75221. {
  75222. u64 endTime = sqlite3Hwtime();
  75223. if( endTime>start ) pOrigOp->cycles += endTime - start;
  75224. pOrigOp->cnt++;
  75225. }
  75226. #endif
  75227. /* The following code adds nothing to the actual functionality
  75228. ** of the program. It is only here for testing and debugging.
  75229. ** On the other hand, it does burn CPU cycles every time through
  75230. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  75231. */
  75232. #ifndef NDEBUG
  75233. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  75234. #ifdef SQLITE_DEBUG
  75235. if( db->flags & SQLITE_VdbeTrace ){
  75236. if( rc!=0 ) printf("rc=%d\n",rc);
  75237. if( pOrigOp->opflags & (OPFLG_OUT2) ){
  75238. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  75239. }
  75240. if( pOrigOp->opflags & OPFLG_OUT3 ){
  75241. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  75242. }
  75243. }
  75244. #endif /* SQLITE_DEBUG */
  75245. #endif /* NDEBUG */
  75246. } /* The end of the for(;;) loop the loops through opcodes */
  75247. /* If we reach this point, it means that execution is finished with
  75248. ** an error of some kind.
  75249. */
  75250. vdbe_error_halt:
  75251. assert( rc );
  75252. p->rc = rc;
  75253. testcase( sqlite3GlobalConfig.xLog!=0 );
  75254. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  75255. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  75256. sqlite3VdbeHalt(p);
  75257. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  75258. rc = SQLITE_ERROR;
  75259. if( resetSchemaOnFault>0 ){
  75260. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  75261. }
  75262. /* This is the only way out of this procedure. We have to
  75263. ** release the mutexes on btrees that were acquired at the
  75264. ** top. */
  75265. vdbe_return:
  75266. db->lastRowid = lastRowid;
  75267. testcase( nVmStep>0 );
  75268. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  75269. sqlite3VdbeLeave(p);
  75270. return rc;
  75271. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  75272. ** is encountered.
  75273. */
  75274. too_big:
  75275. sqlite3VdbeError(p, "string or blob too big");
  75276. rc = SQLITE_TOOBIG;
  75277. goto vdbe_error_halt;
  75278. /* Jump to here if a malloc() fails.
  75279. */
  75280. no_mem:
  75281. db->mallocFailed = 1;
  75282. sqlite3VdbeError(p, "out of memory");
  75283. rc = SQLITE_NOMEM;
  75284. goto vdbe_error_halt;
  75285. /* Jump to here for any other kind of fatal error. The "rc" variable
  75286. ** should hold the error number.
  75287. */
  75288. abort_due_to_error:
  75289. assert( p->zErrMsg==0 );
  75290. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  75291. if( rc!=SQLITE_IOERR_NOMEM ){
  75292. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  75293. }
  75294. goto vdbe_error_halt;
  75295. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  75296. ** flag.
  75297. */
  75298. abort_due_to_interrupt:
  75299. assert( db->u1.isInterrupted );
  75300. rc = SQLITE_INTERRUPT;
  75301. p->rc = rc;
  75302. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  75303. goto vdbe_error_halt;
  75304. }
  75305. /************** End of vdbe.c ************************************************/
  75306. /************** Begin file vdbeblob.c ****************************************/
  75307. /*
  75308. ** 2007 May 1
  75309. **
  75310. ** The author disclaims copyright to this source code. In place of
  75311. ** a legal notice, here is a blessing:
  75312. **
  75313. ** May you do good and not evil.
  75314. ** May you find forgiveness for yourself and forgive others.
  75315. ** May you share freely, never taking more than you give.
  75316. **
  75317. *************************************************************************
  75318. **
  75319. ** This file contains code used to implement incremental BLOB I/O.
  75320. */
  75321. /* #include "sqliteInt.h" */
  75322. /* #include "vdbeInt.h" */
  75323. #ifndef SQLITE_OMIT_INCRBLOB
  75324. /*
  75325. ** Valid sqlite3_blob* handles point to Incrblob structures.
  75326. */
  75327. typedef struct Incrblob Incrblob;
  75328. struct Incrblob {
  75329. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  75330. int nByte; /* Size of open blob, in bytes */
  75331. int iOffset; /* Byte offset of blob in cursor data */
  75332. int iCol; /* Table column this handle is open on */
  75333. BtCursor *pCsr; /* Cursor pointing at blob row */
  75334. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  75335. sqlite3 *db; /* The associated database */
  75336. };
  75337. /*
  75338. ** This function is used by both blob_open() and blob_reopen(). It seeks
  75339. ** the b-tree cursor associated with blob handle p to point to row iRow.
  75340. ** If successful, SQLITE_OK is returned and subsequent calls to
  75341. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  75342. **
  75343. ** If an error occurs, or if the specified row does not exist or does not
  75344. ** contain a value of type TEXT or BLOB in the column nominated when the
  75345. ** blob handle was opened, then an error code is returned and *pzErr may
  75346. ** be set to point to a buffer containing an error message. It is the
  75347. ** responsibility of the caller to free the error message buffer using
  75348. ** sqlite3DbFree().
  75349. **
  75350. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  75351. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  75352. ** immediately return SQLITE_ABORT.
  75353. */
  75354. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  75355. int rc; /* Error code */
  75356. char *zErr = 0; /* Error message */
  75357. Vdbe *v = (Vdbe *)p->pStmt;
  75358. /* Set the value of the SQL statements only variable to integer iRow.
  75359. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  75360. ** triggering asserts related to mutexes.
  75361. */
  75362. assert( v->aVar[0].flags&MEM_Int );
  75363. v->aVar[0].u.i = iRow;
  75364. rc = sqlite3_step(p->pStmt);
  75365. if( rc==SQLITE_ROW ){
  75366. VdbeCursor *pC = v->apCsr[0];
  75367. u32 type = pC->aType[p->iCol];
  75368. if( type<12 ){
  75369. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  75370. type==0?"null": type==7?"real": "integer"
  75371. );
  75372. rc = SQLITE_ERROR;
  75373. sqlite3_finalize(p->pStmt);
  75374. p->pStmt = 0;
  75375. }else{
  75376. p->iOffset = pC->aType[p->iCol + pC->nField];
  75377. p->nByte = sqlite3VdbeSerialTypeLen(type);
  75378. p->pCsr = pC->uc.pCursor;
  75379. sqlite3BtreeIncrblobCursor(p->pCsr);
  75380. }
  75381. }
  75382. if( rc==SQLITE_ROW ){
  75383. rc = SQLITE_OK;
  75384. }else if( p->pStmt ){
  75385. rc = sqlite3_finalize(p->pStmt);
  75386. p->pStmt = 0;
  75387. if( rc==SQLITE_OK ){
  75388. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  75389. rc = SQLITE_ERROR;
  75390. }else{
  75391. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  75392. }
  75393. }
  75394. assert( rc!=SQLITE_OK || zErr==0 );
  75395. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  75396. *pzErr = zErr;
  75397. return rc;
  75398. }
  75399. /*
  75400. ** Open a blob handle.
  75401. */
  75402. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  75403. sqlite3* db, /* The database connection */
  75404. const char *zDb, /* The attached database containing the blob */
  75405. const char *zTable, /* The table containing the blob */
  75406. const char *zColumn, /* The column containing the blob */
  75407. sqlite_int64 iRow, /* The row containing the glob */
  75408. int flags, /* True -> read/write access, false -> read-only */
  75409. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  75410. ){
  75411. int nAttempt = 0;
  75412. int iCol; /* Index of zColumn in row-record */
  75413. /* This VDBE program seeks a btree cursor to the identified
  75414. ** db/table/row entry. The reason for using a vdbe program instead
  75415. ** of writing code to use the b-tree layer directly is that the
  75416. ** vdbe program will take advantage of the various transaction,
  75417. ** locking and error handling infrastructure built into the vdbe.
  75418. **
  75419. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  75420. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  75421. ** uses it to implement the blob_read(), blob_write() and
  75422. ** blob_bytes() functions.
  75423. **
  75424. ** The sqlite3_blob_close() function finalizes the vdbe program,
  75425. ** which closes the b-tree cursor and (possibly) commits the
  75426. ** transaction.
  75427. */
  75428. static const int iLn = VDBE_OFFSET_LINENO(4);
  75429. static const VdbeOpList openBlob[] = {
  75430. /* {OP_Transaction, 0, 0, 0}, // 0: Inserted separately */
  75431. {OP_TableLock, 0, 0, 0}, /* 1: Acquire a read or write lock */
  75432. /* One of the following two instructions is replaced by an OP_Noop. */
  75433. {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
  75434. {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
  75435. {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
  75436. {OP_NotExists, 0, 10, 1}, /* 5: Seek the cursor */
  75437. {OP_Column, 0, 0, 1}, /* 6 */
  75438. {OP_ResultRow, 1, 0, 0}, /* 7 */
  75439. {OP_Goto, 0, 4, 0}, /* 8 */
  75440. {OP_Close, 0, 0, 0}, /* 9 */
  75441. {OP_Halt, 0, 0, 0}, /* 10 */
  75442. };
  75443. int rc = SQLITE_OK;
  75444. char *zErr = 0;
  75445. Table *pTab;
  75446. Parse *pParse = 0;
  75447. Incrblob *pBlob = 0;
  75448. #ifdef SQLITE_ENABLE_API_ARMOR
  75449. if( ppBlob==0 ){
  75450. return SQLITE_MISUSE_BKPT;
  75451. }
  75452. #endif
  75453. *ppBlob = 0;
  75454. #ifdef SQLITE_ENABLE_API_ARMOR
  75455. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  75456. return SQLITE_MISUSE_BKPT;
  75457. }
  75458. #endif
  75459. flags = !!flags; /* flags = (flags ? 1 : 0); */
  75460. sqlite3_mutex_enter(db->mutex);
  75461. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  75462. if( !pBlob ) goto blob_open_out;
  75463. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  75464. if( !pParse ) goto blob_open_out;
  75465. do {
  75466. memset(pParse, 0, sizeof(Parse));
  75467. pParse->db = db;
  75468. sqlite3DbFree(db, zErr);
  75469. zErr = 0;
  75470. sqlite3BtreeEnterAll(db);
  75471. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  75472. if( pTab && IsVirtual(pTab) ){
  75473. pTab = 0;
  75474. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  75475. }
  75476. if( pTab && !HasRowid(pTab) ){
  75477. pTab = 0;
  75478. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  75479. }
  75480. #ifndef SQLITE_OMIT_VIEW
  75481. if( pTab && pTab->pSelect ){
  75482. pTab = 0;
  75483. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  75484. }
  75485. #endif
  75486. if( !pTab ){
  75487. if( pParse->zErrMsg ){
  75488. sqlite3DbFree(db, zErr);
  75489. zErr = pParse->zErrMsg;
  75490. pParse->zErrMsg = 0;
  75491. }
  75492. rc = SQLITE_ERROR;
  75493. sqlite3BtreeLeaveAll(db);
  75494. goto blob_open_out;
  75495. }
  75496. /* Now search pTab for the exact column. */
  75497. for(iCol=0; iCol<pTab->nCol; iCol++) {
  75498. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  75499. break;
  75500. }
  75501. }
  75502. if( iCol==pTab->nCol ){
  75503. sqlite3DbFree(db, zErr);
  75504. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  75505. rc = SQLITE_ERROR;
  75506. sqlite3BtreeLeaveAll(db);
  75507. goto blob_open_out;
  75508. }
  75509. /* If the value is being opened for writing, check that the
  75510. ** column is not indexed, and that it is not part of a foreign key.
  75511. ** It is against the rules to open a column to which either of these
  75512. ** descriptions applies for writing. */
  75513. if( flags ){
  75514. const char *zFault = 0;
  75515. Index *pIdx;
  75516. #ifndef SQLITE_OMIT_FOREIGN_KEY
  75517. if( db->flags&SQLITE_ForeignKeys ){
  75518. /* Check that the column is not part of an FK child key definition. It
  75519. ** is not necessary to check if it is part of a parent key, as parent
  75520. ** key columns must be indexed. The check below will pick up this
  75521. ** case. */
  75522. FKey *pFKey;
  75523. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  75524. int j;
  75525. for(j=0; j<pFKey->nCol; j++){
  75526. if( pFKey->aCol[j].iFrom==iCol ){
  75527. zFault = "foreign key";
  75528. }
  75529. }
  75530. }
  75531. }
  75532. #endif
  75533. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  75534. int j;
  75535. for(j=0; j<pIdx->nKeyCol; j++){
  75536. /* FIXME: Be smarter about indexes that use expressions */
  75537. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  75538. zFault = "indexed";
  75539. }
  75540. }
  75541. }
  75542. if( zFault ){
  75543. sqlite3DbFree(db, zErr);
  75544. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  75545. rc = SQLITE_ERROR;
  75546. sqlite3BtreeLeaveAll(db);
  75547. goto blob_open_out;
  75548. }
  75549. }
  75550. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  75551. assert( pBlob->pStmt || db->mallocFailed );
  75552. if( pBlob->pStmt ){
  75553. Vdbe *v = (Vdbe *)pBlob->pStmt;
  75554. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75555. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
  75556. pTab->pSchema->schema_cookie,
  75557. pTab->pSchema->iGeneration);
  75558. sqlite3VdbeChangeP5(v, 1);
  75559. sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  75560. /* Make sure a mutex is held on the table to be accessed */
  75561. sqlite3VdbeUsesBtree(v, iDb);
  75562. /* Configure the OP_TableLock instruction */
  75563. #ifdef SQLITE_OMIT_SHARED_CACHE
  75564. sqlite3VdbeChangeToNoop(v, 1);
  75565. #else
  75566. sqlite3VdbeChangeP1(v, 1, iDb);
  75567. sqlite3VdbeChangeP2(v, 1, pTab->tnum);
  75568. sqlite3VdbeChangeP3(v, 1, flags);
  75569. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  75570. #endif
  75571. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  75572. ** parameter of the other to pTab->tnum. */
  75573. sqlite3VdbeChangeToNoop(v, 3 - flags);
  75574. sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
  75575. sqlite3VdbeChangeP3(v, 2 + flags, iDb);
  75576. /* Configure the number of columns. Configure the cursor to
  75577. ** think that the table has one more column than it really
  75578. ** does. An OP_Column to retrieve this imaginary column will
  75579. ** always return an SQL NULL. This is useful because it means
  75580. ** we can invoke OP_Column to fill in the vdbe cursors type
  75581. ** and offset cache without causing any IO.
  75582. */
  75583. sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  75584. sqlite3VdbeChangeP2(v, 6, pTab->nCol);
  75585. if( !db->mallocFailed ){
  75586. pParse->nVar = 1;
  75587. pParse->nMem = 1;
  75588. pParse->nTab = 1;
  75589. sqlite3VdbeMakeReady(v, pParse);
  75590. }
  75591. }
  75592. pBlob->flags = flags;
  75593. pBlob->iCol = iCol;
  75594. pBlob->db = db;
  75595. sqlite3BtreeLeaveAll(db);
  75596. if( db->mallocFailed ){
  75597. goto blob_open_out;
  75598. }
  75599. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  75600. rc = blobSeekToRow(pBlob, iRow, &zErr);
  75601. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  75602. blob_open_out:
  75603. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  75604. *ppBlob = (sqlite3_blob *)pBlob;
  75605. }else{
  75606. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  75607. sqlite3DbFree(db, pBlob);
  75608. }
  75609. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  75610. sqlite3DbFree(db, zErr);
  75611. sqlite3ParserReset(pParse);
  75612. sqlite3StackFree(db, pParse);
  75613. rc = sqlite3ApiExit(db, rc);
  75614. sqlite3_mutex_leave(db->mutex);
  75615. return rc;
  75616. }
  75617. /*
  75618. ** Close a blob handle that was previously created using
  75619. ** sqlite3_blob_open().
  75620. */
  75621. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
  75622. Incrblob *p = (Incrblob *)pBlob;
  75623. int rc;
  75624. sqlite3 *db;
  75625. if( p ){
  75626. db = p->db;
  75627. sqlite3_mutex_enter(db->mutex);
  75628. rc = sqlite3_finalize(p->pStmt);
  75629. sqlite3DbFree(db, p);
  75630. sqlite3_mutex_leave(db->mutex);
  75631. }else{
  75632. rc = SQLITE_OK;
  75633. }
  75634. return rc;
  75635. }
  75636. /*
  75637. ** Perform a read or write operation on a blob
  75638. */
  75639. static int blobReadWrite(
  75640. sqlite3_blob *pBlob,
  75641. void *z,
  75642. int n,
  75643. int iOffset,
  75644. int (*xCall)(BtCursor*, u32, u32, void*)
  75645. ){
  75646. int rc;
  75647. Incrblob *p = (Incrblob *)pBlob;
  75648. Vdbe *v;
  75649. sqlite3 *db;
  75650. if( p==0 ) return SQLITE_MISUSE_BKPT;
  75651. db = p->db;
  75652. sqlite3_mutex_enter(db->mutex);
  75653. v = (Vdbe*)p->pStmt;
  75654. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  75655. /* Request is out of range. Return a transient error. */
  75656. rc = SQLITE_ERROR;
  75657. }else if( v==0 ){
  75658. /* If there is no statement handle, then the blob-handle has
  75659. ** already been invalidated. Return SQLITE_ABORT in this case.
  75660. */
  75661. rc = SQLITE_ABORT;
  75662. }else{
  75663. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  75664. ** returned, clean-up the statement handle.
  75665. */
  75666. assert( db == v->db );
  75667. sqlite3BtreeEnterCursor(p->pCsr);
  75668. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  75669. sqlite3BtreeLeaveCursor(p->pCsr);
  75670. if( rc==SQLITE_ABORT ){
  75671. sqlite3VdbeFinalize(v);
  75672. p->pStmt = 0;
  75673. }else{
  75674. v->rc = rc;
  75675. }
  75676. }
  75677. sqlite3Error(db, rc);
  75678. rc = sqlite3ApiExit(db, rc);
  75679. sqlite3_mutex_leave(db->mutex);
  75680. return rc;
  75681. }
  75682. /*
  75683. ** Read data from a blob handle.
  75684. */
  75685. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  75686. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  75687. }
  75688. /*
  75689. ** Write data to a blob handle.
  75690. */
  75691. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  75692. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  75693. }
  75694. /*
  75695. ** Query a blob handle for the size of the data.
  75696. **
  75697. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  75698. ** so no mutex is required for access.
  75699. */
  75700. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
  75701. Incrblob *p = (Incrblob *)pBlob;
  75702. return (p && p->pStmt) ? p->nByte : 0;
  75703. }
  75704. /*
  75705. ** Move an existing blob handle to point to a different row of the same
  75706. ** database table.
  75707. **
  75708. ** If an error occurs, or if the specified row does not exist or does not
  75709. ** contain a blob or text value, then an error code is returned and the
  75710. ** database handle error code and message set. If this happens, then all
  75711. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  75712. ** immediately return SQLITE_ABORT.
  75713. */
  75714. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  75715. int rc;
  75716. Incrblob *p = (Incrblob *)pBlob;
  75717. sqlite3 *db;
  75718. if( p==0 ) return SQLITE_MISUSE_BKPT;
  75719. db = p->db;
  75720. sqlite3_mutex_enter(db->mutex);
  75721. if( p->pStmt==0 ){
  75722. /* If there is no statement handle, then the blob-handle has
  75723. ** already been invalidated. Return SQLITE_ABORT in this case.
  75724. */
  75725. rc = SQLITE_ABORT;
  75726. }else{
  75727. char *zErr;
  75728. rc = blobSeekToRow(p, iRow, &zErr);
  75729. if( rc!=SQLITE_OK ){
  75730. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  75731. sqlite3DbFree(db, zErr);
  75732. }
  75733. assert( rc!=SQLITE_SCHEMA );
  75734. }
  75735. rc = sqlite3ApiExit(db, rc);
  75736. assert( rc==SQLITE_OK || p->pStmt==0 );
  75737. sqlite3_mutex_leave(db->mutex);
  75738. return rc;
  75739. }
  75740. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  75741. /************** End of vdbeblob.c ********************************************/
  75742. /************** Begin file vdbesort.c ****************************************/
  75743. /*
  75744. ** 2011-07-09
  75745. **
  75746. ** The author disclaims copyright to this source code. In place of
  75747. ** a legal notice, here is a blessing:
  75748. **
  75749. ** May you do good and not evil.
  75750. ** May you find forgiveness for yourself and forgive others.
  75751. ** May you share freely, never taking more than you give.
  75752. **
  75753. *************************************************************************
  75754. ** This file contains code for the VdbeSorter object, used in concert with
  75755. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  75756. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  75757. ** using indexes and without LIMIT clauses.
  75758. **
  75759. ** The VdbeSorter object implements a multi-threaded external merge sort
  75760. ** algorithm that is efficient even if the number of elements being sorted
  75761. ** exceeds the available memory.
  75762. **
  75763. ** Here is the (internal, non-API) interface between this module and the
  75764. ** rest of the SQLite system:
  75765. **
  75766. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  75767. **
  75768. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  75769. ** object. The row is a binary blob in the
  75770. ** OP_MakeRecord format that contains both
  75771. ** the ORDER BY key columns and result columns
  75772. ** in the case of a SELECT w/ ORDER BY, or
  75773. ** the complete record for an index entry
  75774. ** in the case of a CREATE INDEX.
  75775. **
  75776. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  75777. ** Position the read cursor on the
  75778. ** first sorted element.
  75779. **
  75780. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  75781. ** element.
  75782. **
  75783. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  75784. ** row currently under the read cursor.
  75785. **
  75786. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  75787. ** currently under the read cursor against
  75788. ** another binary blob X and report if
  75789. ** X is strictly less than the read cursor.
  75790. ** Used to enforce uniqueness in a
  75791. ** CREATE UNIQUE INDEX statement.
  75792. **
  75793. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  75794. ** all resources.
  75795. **
  75796. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  75797. ** is like Close() followed by Init() only
  75798. ** much faster.
  75799. **
  75800. ** The interfaces above must be called in a particular order. Write() can
  75801. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  75802. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  75803. **
  75804. ** Init()
  75805. ** for each record: Write()
  75806. ** Rewind()
  75807. ** Rowkey()/Compare()
  75808. ** Next()
  75809. ** Close()
  75810. **
  75811. ** Algorithm:
  75812. **
  75813. ** Records passed to the sorter via calls to Write() are initially held
  75814. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  75815. ** a threshold, when Rewind() is called the set of records is sorted using
  75816. ** an in-memory merge sort. In this case, no temporary files are required
  75817. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  75818. ** directly from main memory.
  75819. **
  75820. ** If the amount of space used to store records in main memory exceeds the
  75821. ** threshold, then the set of records currently in memory are sorted and
  75822. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  75823. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  75824. ** of PMAs may be created by merging existing PMAs together - for example
  75825. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  75826. **
  75827. ** The threshold for the amount of main memory to use before flushing
  75828. ** records to a PMA is roughly the same as the limit configured for the
  75829. ** page-cache of the main database. Specifically, the threshold is set to
  75830. ** the value returned by "PRAGMA main.page_size" multipled by
  75831. ** that returned by "PRAGMA main.cache_size", in bytes.
  75832. **
  75833. ** If the sorter is running in single-threaded mode, then all PMAs generated
  75834. ** are appended to a single temporary file. Or, if the sorter is running in
  75835. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  75836. ** N is the configured number of worker threads. In this case, instead of
  75837. ** sorting the records and writing the PMA to a temporary file itself, the
  75838. ** calling thread usually launches a worker thread to do so. Except, if
  75839. ** there are already N worker threads running, the main thread does the work
  75840. ** itself.
  75841. **
  75842. ** The sorter is running in multi-threaded mode if (a) the library was built
  75843. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  75844. ** than zero, and (b) worker threads have been enabled at runtime by calling
  75845. ** "PRAGMA threads=N" with some value of N greater than 0.
  75846. **
  75847. ** When Rewind() is called, any data remaining in memory is flushed to a
  75848. ** final PMA. So at this point the data is stored in some number of sorted
  75849. ** PMAs within temporary files on disk.
  75850. **
  75851. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  75852. ** sorter is running in single-threaded mode, then these PMAs are merged
  75853. ** incrementally as keys are retreived from the sorter by the VDBE. The
  75854. ** MergeEngine object, described in further detail below, performs this
  75855. ** merge.
  75856. **
  75857. ** Or, if running in multi-threaded mode, then a background thread is
  75858. ** launched to merge the existing PMAs. Once the background thread has
  75859. ** merged T bytes of data into a single sorted PMA, the main thread
  75860. ** begins reading keys from that PMA while the background thread proceeds
  75861. ** with merging the next T bytes of data. And so on.
  75862. **
  75863. ** Parameter T is set to half the value of the memory threshold used
  75864. ** by Write() above to determine when to create a new PMA.
  75865. **
  75866. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  75867. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  75868. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  75869. ** disk are merged together. Then T bytes of data from the second set, and
  75870. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  75871. ** PMAs at a time. This done is to improve locality.
  75872. **
  75873. ** If running in multi-threaded mode and there are more than
  75874. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  75875. ** than one background thread may be created. Specifically, there may be
  75876. ** one background thread for each temporary file on disk, and one background
  75877. ** thread to merge the output of each of the others to a single PMA for
  75878. ** the main thread to read from.
  75879. */
  75880. /* #include "sqliteInt.h" */
  75881. /* #include "vdbeInt.h" */
  75882. /*
  75883. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  75884. ** messages to stderr that may be helpful in understanding the performance
  75885. ** characteristics of the sorter in multi-threaded mode.
  75886. */
  75887. #if 0
  75888. # define SQLITE_DEBUG_SORTER_THREADS 1
  75889. #endif
  75890. /*
  75891. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  75892. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  75893. ** overflows. 512MiB.
  75894. */
  75895. #define SQLITE_MAX_PMASZ (1<<29)
  75896. /*
  75897. ** Private objects used by the sorter
  75898. */
  75899. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  75900. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  75901. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  75902. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  75903. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  75904. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  75905. typedef struct SorterList SorterList; /* In-memory list of records */
  75906. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  75907. /*
  75908. ** A container for a temp file handle and the current amount of data
  75909. ** stored in the file.
  75910. */
  75911. struct SorterFile {
  75912. sqlite3_file *pFd; /* File handle */
  75913. i64 iEof; /* Bytes of data stored in pFd */
  75914. };
  75915. /*
  75916. ** An in-memory list of objects to be sorted.
  75917. **
  75918. ** If aMemory==0 then each object is allocated separately and the objects
  75919. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  75920. ** are stored in the aMemory[] bulk memory, one right after the other, and
  75921. ** are connected using SorterRecord.u.iNext.
  75922. */
  75923. struct SorterList {
  75924. SorterRecord *pList; /* Linked list of records */
  75925. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  75926. int szPMA; /* Size of pList as PMA in bytes */
  75927. };
  75928. /*
  75929. ** The MergeEngine object is used to combine two or more smaller PMAs into
  75930. ** one big PMA using a merge operation. Separate PMAs all need to be
  75931. ** combined into one big PMA in order to be able to step through the sorted
  75932. ** records in order.
  75933. **
  75934. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  75935. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  75936. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  75937. ** For the purposes of the paragraphs below, we assume that the array is
  75938. ** actually N elements in size, where N is the smallest power of 2 greater
  75939. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  75940. ** are treated as if they are empty (always at EOF).
  75941. **
  75942. ** The aTree[] array is also N elements in size. The value of N is stored in
  75943. ** the MergeEngine.nTree variable.
  75944. **
  75945. ** The final (N/2) elements of aTree[] contain the results of comparing
  75946. ** pairs of PMA keys together. Element i contains the result of
  75947. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  75948. ** aTree element is set to the index of it.
  75949. **
  75950. ** For the purposes of this comparison, EOF is considered greater than any
  75951. ** other key value. If the keys are equal (only possible with two EOF
  75952. ** values), it doesn't matter which index is stored.
  75953. **
  75954. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  75955. ** above contains the index of the smallest of each block of 4 PmaReaders
  75956. ** And so on. So that aTree[1] contains the index of the PmaReader that
  75957. ** currently points to the smallest key value. aTree[0] is unused.
  75958. **
  75959. ** Example:
  75960. **
  75961. ** aReadr[0] -> Banana
  75962. ** aReadr[1] -> Feijoa
  75963. ** aReadr[2] -> Elderberry
  75964. ** aReadr[3] -> Currant
  75965. ** aReadr[4] -> Grapefruit
  75966. ** aReadr[5] -> Apple
  75967. ** aReadr[6] -> Durian
  75968. ** aReadr[7] -> EOF
  75969. **
  75970. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  75971. **
  75972. ** The current element is "Apple" (the value of the key indicated by
  75973. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  75974. ** be advanced to the next key in its segment. Say the next key is
  75975. ** "Eggplant":
  75976. **
  75977. ** aReadr[5] -> Eggplant
  75978. **
  75979. ** The contents of aTree[] are updated first by comparing the new PmaReader
  75980. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  75981. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  75982. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  75983. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  75984. ** so the value written into element 1 of the array is 0. As follows:
  75985. **
  75986. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  75987. **
  75988. ** In other words, each time we advance to the next sorter element, log2(N)
  75989. ** key comparison operations are required, where N is the number of segments
  75990. ** being merged (rounded up to the next power of 2).
  75991. */
  75992. struct MergeEngine {
  75993. int nTree; /* Used size of aTree/aReadr (power of 2) */
  75994. SortSubtask *pTask; /* Used by this thread only */
  75995. int *aTree; /* Current state of incremental merge */
  75996. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  75997. };
  75998. /*
  75999. ** This object represents a single thread of control in a sort operation.
  76000. ** Exactly VdbeSorter.nTask instances of this object are allocated
  76001. ** as part of each VdbeSorter object. Instances are never allocated any
  76002. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  76003. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  76004. ** single-threaded operation, there is exactly one instance of this object
  76005. ** and for multi-threaded operation there are two or more instances.
  76006. **
  76007. ** Essentially, this structure contains all those fields of the VdbeSorter
  76008. ** structure for which each thread requires a separate instance. For example,
  76009. ** each thread requries its own UnpackedRecord object to unpack records in
  76010. ** as part of comparison operations.
  76011. **
  76012. ** Before a background thread is launched, variable bDone is set to 0. Then,
  76013. ** right before it exits, the thread itself sets bDone to 1. This is used for
  76014. ** two purposes:
  76015. **
  76016. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  76017. ** attempt to select a SortSubtask for which there is not already an
  76018. ** active background thread (since doing so causes the main thread
  76019. ** to block until it finishes).
  76020. **
  76021. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  76022. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  76023. ** block provoke debugging output.
  76024. **
  76025. ** In both cases, the effects of the main thread seeing (bDone==0) even
  76026. ** after the thread has finished are not dire. So we don't worry about
  76027. ** memory barriers and such here.
  76028. */
  76029. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  76030. struct SortSubtask {
  76031. SQLiteThread *pThread; /* Background thread, if any */
  76032. int bDone; /* Set if thread is finished but not joined */
  76033. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  76034. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  76035. SorterList list; /* List for thread to write to a PMA */
  76036. int nPMA; /* Number of PMAs currently in file */
  76037. SorterCompare xCompare; /* Compare function to use */
  76038. SorterFile file; /* Temp file for level-0 PMAs */
  76039. SorterFile file2; /* Space for other PMAs */
  76040. };
  76041. /*
  76042. ** Main sorter structure. A single instance of this is allocated for each
  76043. ** sorter cursor created by the VDBE.
  76044. **
  76045. ** mxKeysize:
  76046. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  76047. ** this variable is updated so as to be set to the size on disk of the
  76048. ** largest record in the sorter.
  76049. */
  76050. struct VdbeSorter {
  76051. int mnPmaSize; /* Minimum PMA size, in bytes */
  76052. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  76053. int mxKeysize; /* Largest serialized key seen so far */
  76054. int pgsz; /* Main database page size */
  76055. PmaReader *pReader; /* Readr data from here after Rewind() */
  76056. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  76057. sqlite3 *db; /* Database connection */
  76058. KeyInfo *pKeyInfo; /* How to compare records */
  76059. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  76060. SorterList list; /* List of in-memory records */
  76061. int iMemory; /* Offset of free space in list.aMemory */
  76062. int nMemory; /* Size of list.aMemory allocation in bytes */
  76063. u8 bUsePMA; /* True if one or more PMAs created */
  76064. u8 bUseThreads; /* True to use background threads */
  76065. u8 iPrev; /* Previous thread used to flush PMA */
  76066. u8 nTask; /* Size of aTask[] array */
  76067. u8 typeMask;
  76068. SortSubtask aTask[1]; /* One or more subtasks */
  76069. };
  76070. #define SORTER_TYPE_INTEGER 0x01
  76071. #define SORTER_TYPE_TEXT 0x02
  76072. /*
  76073. ** An instance of the following object is used to read records out of a
  76074. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  76075. ** aKey might point into aMap or into aBuffer. If neither of those locations
  76076. ** contain a contiguous representation of the key, then aAlloc is allocated
  76077. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  76078. **
  76079. ** pFd==0 at EOF.
  76080. */
  76081. struct PmaReader {
  76082. i64 iReadOff; /* Current read offset */
  76083. i64 iEof; /* 1 byte past EOF for this PmaReader */
  76084. int nAlloc; /* Bytes of space at aAlloc */
  76085. int nKey; /* Number of bytes in key */
  76086. sqlite3_file *pFd; /* File handle we are reading from */
  76087. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  76088. u8 *aKey; /* Pointer to current key */
  76089. u8 *aBuffer; /* Current read buffer */
  76090. int nBuffer; /* Size of read buffer in bytes */
  76091. u8 *aMap; /* Pointer to mapping of entire file */
  76092. IncrMerger *pIncr; /* Incremental merger */
  76093. };
  76094. /*
  76095. ** Normally, a PmaReader object iterates through an existing PMA stored
  76096. ** within a temp file. However, if the PmaReader.pIncr variable points to
  76097. ** an object of the following type, it may be used to iterate/merge through
  76098. ** multiple PMAs simultaneously.
  76099. **
  76100. ** There are two types of IncrMerger object - single (bUseThread==0) and
  76101. ** multi-threaded (bUseThread==1).
  76102. **
  76103. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  76104. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  76105. ** size. When the IncrMerger is initialized, it reads enough data from
  76106. ** pMerger to populate aFile[0]. It then sets variables within the
  76107. ** corresponding PmaReader object to read from that file and kicks off
  76108. ** a background thread to populate aFile[1] with the next mxSz bytes of
  76109. ** sorted record data from pMerger.
  76110. **
  76111. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  76112. ** background thread has finished populating aFile[1]. It then exchanges
  76113. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  76114. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  76115. ** another background thread to populate the new aFile[1]. And so on, until
  76116. ** the contents of pMerger are exhausted.
  76117. **
  76118. ** A single-threaded IncrMerger does not open any temporary files of its
  76119. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  76120. ** at offset iStartOff of file pTask->file2. And instead of using a
  76121. ** background thread to prepare data for the PmaReader, with a single
  76122. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  76123. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  76124. ** of data.
  76125. */
  76126. struct IncrMerger {
  76127. SortSubtask *pTask; /* Task that owns this merger */
  76128. MergeEngine *pMerger; /* Merge engine thread reads data from */
  76129. i64 iStartOff; /* Offset to start writing file at */
  76130. int mxSz; /* Maximum bytes of data to store */
  76131. int bEof; /* Set to true when merge is finished */
  76132. int bUseThread; /* True to use a bg thread for this object */
  76133. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  76134. };
  76135. /*
  76136. ** An instance of this object is used for writing a PMA.
  76137. **
  76138. ** The PMA is written one record at a time. Each record is of an arbitrary
  76139. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  76140. ** each block is aligned on a page boundary. This object caches writes to
  76141. ** the PMA so that aligned, page-size blocks are written.
  76142. */
  76143. struct PmaWriter {
  76144. int eFWErr; /* Non-zero if in an error state */
  76145. u8 *aBuffer; /* Pointer to write buffer */
  76146. int nBuffer; /* Size of write buffer in bytes */
  76147. int iBufStart; /* First byte of buffer to write */
  76148. int iBufEnd; /* Last byte of buffer to write */
  76149. i64 iWriteOff; /* Offset of start of buffer in file */
  76150. sqlite3_file *pFd; /* File handle to write to */
  76151. };
  76152. /*
  76153. ** This object is the header on a single record while that record is being
  76154. ** held in memory and prior to being written out as part of a PMA.
  76155. **
  76156. ** How the linked list is connected depends on how memory is being managed
  76157. ** by this module. If using a separate allocation for each in-memory record
  76158. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  76159. ** SorterRecord.u.pNext pointers.
  76160. **
  76161. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  76162. ** then while records are being accumulated the list is linked using the
  76163. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  76164. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  76165. ** has finished passing records to the sorter, or when the in-memory buffer
  76166. ** is full, the list is sorted. As part of the sorting process, it is
  76167. ** converted to use the SorterRecord.u.pNext pointers. See function
  76168. ** vdbeSorterSort() for details.
  76169. */
  76170. struct SorterRecord {
  76171. int nVal; /* Size of the record in bytes */
  76172. union {
  76173. SorterRecord *pNext; /* Pointer to next record in list */
  76174. int iNext; /* Offset within aMemory of next record */
  76175. } u;
  76176. /* The data for the record immediately follows this header */
  76177. };
  76178. /* Return a pointer to the buffer containing the record data for SorterRecord
  76179. ** object p. Should be used as if:
  76180. **
  76181. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  76182. */
  76183. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  76184. /* Maximum number of PMAs that a single MergeEngine can merge */
  76185. #define SORTER_MAX_MERGE_COUNT 16
  76186. static int vdbeIncrSwap(IncrMerger*);
  76187. static void vdbeIncrFree(IncrMerger *);
  76188. /*
  76189. ** Free all memory belonging to the PmaReader object passed as the
  76190. ** argument. All structure fields are set to zero before returning.
  76191. */
  76192. static void vdbePmaReaderClear(PmaReader *pReadr){
  76193. sqlite3_free(pReadr->aAlloc);
  76194. sqlite3_free(pReadr->aBuffer);
  76195. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  76196. vdbeIncrFree(pReadr->pIncr);
  76197. memset(pReadr, 0, sizeof(PmaReader));
  76198. }
  76199. /*
  76200. ** Read the next nByte bytes of data from the PMA p.
  76201. ** If successful, set *ppOut to point to a buffer containing the data
  76202. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  76203. ** error code.
  76204. **
  76205. ** The buffer returned in *ppOut is only valid until the
  76206. ** next call to this function.
  76207. */
  76208. static int vdbePmaReadBlob(
  76209. PmaReader *p, /* PmaReader from which to take the blob */
  76210. int nByte, /* Bytes of data to read */
  76211. u8 **ppOut /* OUT: Pointer to buffer containing data */
  76212. ){
  76213. int iBuf; /* Offset within buffer to read from */
  76214. int nAvail; /* Bytes of data available in buffer */
  76215. if( p->aMap ){
  76216. *ppOut = &p->aMap[p->iReadOff];
  76217. p->iReadOff += nByte;
  76218. return SQLITE_OK;
  76219. }
  76220. assert( p->aBuffer );
  76221. /* If there is no more data to be read from the buffer, read the next
  76222. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  76223. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  76224. iBuf = p->iReadOff % p->nBuffer;
  76225. if( iBuf==0 ){
  76226. int nRead; /* Bytes to read from disk */
  76227. int rc; /* sqlite3OsRead() return code */
  76228. /* Determine how many bytes of data to read. */
  76229. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  76230. nRead = p->nBuffer;
  76231. }else{
  76232. nRead = (int)(p->iEof - p->iReadOff);
  76233. }
  76234. assert( nRead>0 );
  76235. /* Readr data from the file. Return early if an error occurs. */
  76236. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  76237. assert( rc!=SQLITE_IOERR_SHORT_READ );
  76238. if( rc!=SQLITE_OK ) return rc;
  76239. }
  76240. nAvail = p->nBuffer - iBuf;
  76241. if( nByte<=nAvail ){
  76242. /* The requested data is available in the in-memory buffer. In this
  76243. ** case there is no need to make a copy of the data, just return a
  76244. ** pointer into the buffer to the caller. */
  76245. *ppOut = &p->aBuffer[iBuf];
  76246. p->iReadOff += nByte;
  76247. }else{
  76248. /* The requested data is not all available in the in-memory buffer.
  76249. ** In this case, allocate space at p->aAlloc[] to copy the requested
  76250. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  76251. int nRem; /* Bytes remaining to copy */
  76252. /* Extend the p->aAlloc[] allocation if required. */
  76253. if( p->nAlloc<nByte ){
  76254. u8 *aNew;
  76255. int nNew = MAX(128, p->nAlloc*2);
  76256. while( nByte>nNew ) nNew = nNew*2;
  76257. aNew = sqlite3Realloc(p->aAlloc, nNew);
  76258. if( !aNew ) return SQLITE_NOMEM;
  76259. p->nAlloc = nNew;
  76260. p->aAlloc = aNew;
  76261. }
  76262. /* Copy as much data as is available in the buffer into the start of
  76263. ** p->aAlloc[]. */
  76264. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  76265. p->iReadOff += nAvail;
  76266. nRem = nByte - nAvail;
  76267. /* The following loop copies up to p->nBuffer bytes per iteration into
  76268. ** the p->aAlloc[] buffer. */
  76269. while( nRem>0 ){
  76270. int rc; /* vdbePmaReadBlob() return code */
  76271. int nCopy; /* Number of bytes to copy */
  76272. u8 *aNext; /* Pointer to buffer to copy data from */
  76273. nCopy = nRem;
  76274. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  76275. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  76276. if( rc!=SQLITE_OK ) return rc;
  76277. assert( aNext!=p->aAlloc );
  76278. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  76279. nRem -= nCopy;
  76280. }
  76281. *ppOut = p->aAlloc;
  76282. }
  76283. return SQLITE_OK;
  76284. }
  76285. /*
  76286. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  76287. ** the value read.
  76288. */
  76289. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  76290. int iBuf;
  76291. if( p->aMap ){
  76292. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  76293. }else{
  76294. iBuf = p->iReadOff % p->nBuffer;
  76295. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  76296. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  76297. }else{
  76298. u8 aVarint[16], *a;
  76299. int i = 0, rc;
  76300. do{
  76301. rc = vdbePmaReadBlob(p, 1, &a);
  76302. if( rc ) return rc;
  76303. aVarint[(i++)&0xf] = a[0];
  76304. }while( (a[0]&0x80)!=0 );
  76305. sqlite3GetVarint(aVarint, pnOut);
  76306. }
  76307. }
  76308. return SQLITE_OK;
  76309. }
  76310. /*
  76311. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  76312. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  76313. ** (because the file is too large or the VFS layer is configured not to use
  76314. ** mmap), return SQLITE_OK and set *pp to NULL.
  76315. **
  76316. ** Or, if an error occurs, return an SQLite error code. The final value of
  76317. ** *pp is undefined in this case.
  76318. */
  76319. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  76320. int rc = SQLITE_OK;
  76321. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  76322. sqlite3_file *pFd = pFile->pFd;
  76323. if( pFd->pMethods->iVersion>=3 ){
  76324. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  76325. testcase( rc!=SQLITE_OK );
  76326. }
  76327. }
  76328. return rc;
  76329. }
  76330. /*
  76331. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  76332. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  76333. ** if successful, or an SQLite error code if an error occurs.
  76334. */
  76335. static int vdbePmaReaderSeek(
  76336. SortSubtask *pTask, /* Task context */
  76337. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  76338. SorterFile *pFile, /* Sorter file to read from */
  76339. i64 iOff /* Offset in pFile */
  76340. ){
  76341. int rc = SQLITE_OK;
  76342. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  76343. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  76344. if( pReadr->aMap ){
  76345. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  76346. pReadr->aMap = 0;
  76347. }
  76348. pReadr->iReadOff = iOff;
  76349. pReadr->iEof = pFile->iEof;
  76350. pReadr->pFd = pFile->pFd;
  76351. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  76352. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  76353. int pgsz = pTask->pSorter->pgsz;
  76354. int iBuf = pReadr->iReadOff % pgsz;
  76355. if( pReadr->aBuffer==0 ){
  76356. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  76357. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
  76358. pReadr->nBuffer = pgsz;
  76359. }
  76360. if( rc==SQLITE_OK && iBuf ){
  76361. int nRead = pgsz - iBuf;
  76362. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  76363. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  76364. }
  76365. rc = sqlite3OsRead(
  76366. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  76367. );
  76368. testcase( rc!=SQLITE_OK );
  76369. }
  76370. }
  76371. return rc;
  76372. }
  76373. /*
  76374. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  76375. ** no error occurs, or an SQLite error code if one does.
  76376. */
  76377. static int vdbePmaReaderNext(PmaReader *pReadr){
  76378. int rc = SQLITE_OK; /* Return Code */
  76379. u64 nRec = 0; /* Size of record in bytes */
  76380. if( pReadr->iReadOff>=pReadr->iEof ){
  76381. IncrMerger *pIncr = pReadr->pIncr;
  76382. int bEof = 1;
  76383. if( pIncr ){
  76384. rc = vdbeIncrSwap(pIncr);
  76385. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  76386. rc = vdbePmaReaderSeek(
  76387. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  76388. );
  76389. bEof = 0;
  76390. }
  76391. }
  76392. if( bEof ){
  76393. /* This is an EOF condition */
  76394. vdbePmaReaderClear(pReadr);
  76395. testcase( rc!=SQLITE_OK );
  76396. return rc;
  76397. }
  76398. }
  76399. if( rc==SQLITE_OK ){
  76400. rc = vdbePmaReadVarint(pReadr, &nRec);
  76401. }
  76402. if( rc==SQLITE_OK ){
  76403. pReadr->nKey = (int)nRec;
  76404. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  76405. testcase( rc!=SQLITE_OK );
  76406. }
  76407. return rc;
  76408. }
  76409. /*
  76410. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  76411. ** starting at offset iStart and ending at offset iEof-1. This function
  76412. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  76413. ** PMA is empty).
  76414. **
  76415. ** If the pnByte parameter is NULL, then it is assumed that the file
  76416. ** contains a single PMA, and that that PMA omits the initial length varint.
  76417. */
  76418. static int vdbePmaReaderInit(
  76419. SortSubtask *pTask, /* Task context */
  76420. SorterFile *pFile, /* Sorter file to read from */
  76421. i64 iStart, /* Start offset in pFile */
  76422. PmaReader *pReadr, /* PmaReader to populate */
  76423. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  76424. ){
  76425. int rc;
  76426. assert( pFile->iEof>iStart );
  76427. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  76428. assert( pReadr->aBuffer==0 );
  76429. assert( pReadr->aMap==0 );
  76430. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  76431. if( rc==SQLITE_OK ){
  76432. u64 nByte; /* Size of PMA in bytes */
  76433. rc = vdbePmaReadVarint(pReadr, &nByte);
  76434. pReadr->iEof = pReadr->iReadOff + nByte;
  76435. *pnByte += nByte;
  76436. }
  76437. if( rc==SQLITE_OK ){
  76438. rc = vdbePmaReaderNext(pReadr);
  76439. }
  76440. return rc;
  76441. }
  76442. /*
  76443. ** A version of vdbeSorterCompare() that assumes that it has already been
  76444. ** determined that the first field of key1 is equal to the first field of
  76445. ** key2.
  76446. */
  76447. static int vdbeSorterCompareTail(
  76448. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  76449. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  76450. const void *pKey1, int nKey1, /* Left side of comparison */
  76451. const void *pKey2, int nKey2 /* Right side of comparison */
  76452. ){
  76453. UnpackedRecord *r2 = pTask->pUnpacked;
  76454. if( *pbKey2Cached==0 ){
  76455. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  76456. *pbKey2Cached = 1;
  76457. }
  76458. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  76459. }
  76460. /*
  76461. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  76462. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  76463. ** used by the comparison. Return the result of the comparison.
  76464. **
  76465. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  76466. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  76467. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  76468. ** version of key2 and *pbKey2Cached set to true before returning.
  76469. **
  76470. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  76471. ** to SQLITE_NOMEM.
  76472. */
  76473. static int vdbeSorterCompare(
  76474. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  76475. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  76476. const void *pKey1, int nKey1, /* Left side of comparison */
  76477. const void *pKey2, int nKey2 /* Right side of comparison */
  76478. ){
  76479. UnpackedRecord *r2 = pTask->pUnpacked;
  76480. if( !*pbKey2Cached ){
  76481. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  76482. *pbKey2Cached = 1;
  76483. }
  76484. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  76485. }
  76486. /*
  76487. ** A specially optimized version of vdbeSorterCompare() that assumes that
  76488. ** the first field of each key is a TEXT value and that the collation
  76489. ** sequence to compare them with is BINARY.
  76490. */
  76491. static int vdbeSorterCompareText(
  76492. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  76493. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  76494. const void *pKey1, int nKey1, /* Left side of comparison */
  76495. const void *pKey2, int nKey2 /* Right side of comparison */
  76496. ){
  76497. const u8 * const p1 = (const u8 * const)pKey1;
  76498. const u8 * const p2 = (const u8 * const)pKey2;
  76499. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  76500. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  76501. int n1;
  76502. int n2;
  76503. int res;
  76504. getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
  76505. getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
  76506. res = memcmp(v1, v2, MIN(n1, n2));
  76507. if( res==0 ){
  76508. res = n1 - n2;
  76509. }
  76510. if( res==0 ){
  76511. if( pTask->pSorter->pKeyInfo->nField>1 ){
  76512. res = vdbeSorterCompareTail(
  76513. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  76514. );
  76515. }
  76516. }else{
  76517. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  76518. res = res * -1;
  76519. }
  76520. }
  76521. return res;
  76522. }
  76523. /*
  76524. ** A specially optimized version of vdbeSorterCompare() that assumes that
  76525. ** the first field of each key is an INTEGER value.
  76526. */
  76527. static int vdbeSorterCompareInt(
  76528. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  76529. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  76530. const void *pKey1, int nKey1, /* Left side of comparison */
  76531. const void *pKey2, int nKey2 /* Right side of comparison */
  76532. ){
  76533. const u8 * const p1 = (const u8 * const)pKey1;
  76534. const u8 * const p2 = (const u8 * const)pKey2;
  76535. const int s1 = p1[1]; /* Left hand serial type */
  76536. const int s2 = p2[1]; /* Right hand serial type */
  76537. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  76538. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  76539. int res; /* Return value */
  76540. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  76541. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  76542. if( s1>7 && s2>7 ){
  76543. res = s1 - s2;
  76544. }else{
  76545. if( s1==s2 ){
  76546. if( (*v1 ^ *v2) & 0x80 ){
  76547. /* The two values have different signs */
  76548. res = (*v1 & 0x80) ? -1 : +1;
  76549. }else{
  76550. /* The two values have the same sign. Compare using memcmp(). */
  76551. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
  76552. int i;
  76553. res = 0;
  76554. for(i=0; i<aLen[s1]; i++){
  76555. if( (res = v1[i] - v2[i]) ) break;
  76556. }
  76557. }
  76558. }else{
  76559. if( s2>7 ){
  76560. res = +1;
  76561. }else if( s1>7 ){
  76562. res = -1;
  76563. }else{
  76564. res = s1 - s2;
  76565. }
  76566. assert( res!=0 );
  76567. if( res>0 ){
  76568. if( *v1 & 0x80 ) res = -1;
  76569. }else{
  76570. if( *v2 & 0x80 ) res = +1;
  76571. }
  76572. }
  76573. }
  76574. if( res==0 ){
  76575. if( pTask->pSorter->pKeyInfo->nField>1 ){
  76576. res = vdbeSorterCompareTail(
  76577. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  76578. );
  76579. }
  76580. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  76581. res = res * -1;
  76582. }
  76583. return res;
  76584. }
  76585. /*
  76586. ** Initialize the temporary index cursor just opened as a sorter cursor.
  76587. **
  76588. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  76589. ** to determine the number of fields that should be compared from the
  76590. ** records being sorted. However, if the value passed as argument nField
  76591. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  76592. ** is used instead. This is used when sorting records for a CREATE INDEX
  76593. ** statement. In this case, keys are always delivered to the sorter in
  76594. ** order of the primary key, which happens to be make up the final part
  76595. ** of the records being sorted. So if the sort is stable, there is never
  76596. ** any reason to compare PK fields and they can be ignored for a small
  76597. ** performance boost.
  76598. **
  76599. ** The sorter can guarantee a stable sort when running in single-threaded
  76600. ** mode, but not in multi-threaded mode.
  76601. **
  76602. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  76603. */
  76604. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  76605. sqlite3 *db, /* Database connection (for malloc()) */
  76606. int nField, /* Number of key fields in each record */
  76607. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  76608. ){
  76609. int pgsz; /* Page size of main database */
  76610. int i; /* Used to iterate through aTask[] */
  76611. int mxCache; /* Cache size */
  76612. VdbeSorter *pSorter; /* The new sorter */
  76613. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  76614. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  76615. int sz; /* Size of pSorter in bytes */
  76616. int rc = SQLITE_OK;
  76617. #if SQLITE_MAX_WORKER_THREADS==0
  76618. # define nWorker 0
  76619. #else
  76620. int nWorker;
  76621. #endif
  76622. /* Initialize the upper limit on the number of worker threads */
  76623. #if SQLITE_MAX_WORKER_THREADS>0
  76624. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  76625. nWorker = 0;
  76626. }else{
  76627. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  76628. }
  76629. #endif
  76630. /* Do not allow the total number of threads (main thread + all workers)
  76631. ** to exceed the maximum merge count */
  76632. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  76633. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  76634. nWorker = SORTER_MAX_MERGE_COUNT-1;
  76635. }
  76636. #endif
  76637. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  76638. assert( pCsr->eCurType==CURTYPE_SORTER );
  76639. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  76640. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  76641. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  76642. pCsr->uc.pSorter = pSorter;
  76643. if( pSorter==0 ){
  76644. rc = SQLITE_NOMEM;
  76645. }else{
  76646. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  76647. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  76648. pKeyInfo->db = 0;
  76649. if( nField && nWorker==0 ){
  76650. pKeyInfo->nXField += (pKeyInfo->nField - nField);
  76651. pKeyInfo->nField = nField;
  76652. }
  76653. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  76654. pSorter->nTask = nWorker + 1;
  76655. pSorter->iPrev = (u8)(nWorker - 1);
  76656. pSorter->bUseThreads = (pSorter->nTask>1);
  76657. pSorter->db = db;
  76658. for(i=0; i<pSorter->nTask; i++){
  76659. SortSubtask *pTask = &pSorter->aTask[i];
  76660. pTask->pSorter = pSorter;
  76661. }
  76662. if( !sqlite3TempInMemory(db) ){
  76663. u32 szPma = sqlite3GlobalConfig.szPma;
  76664. pSorter->mnPmaSize = szPma * pgsz;
  76665. mxCache = db->aDb[0].pSchema->cache_size;
  76666. if( mxCache<(int)szPma ) mxCache = (int)szPma;
  76667. pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
  76668. /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
  76669. ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
  76670. ** large heap allocations.
  76671. */
  76672. if( sqlite3GlobalConfig.pScratch==0 ){
  76673. assert( pSorter->iMemory==0 );
  76674. pSorter->nMemory = pgsz;
  76675. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  76676. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
  76677. }
  76678. }
  76679. if( (pKeyInfo->nField+pKeyInfo->nXField)<13
  76680. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  76681. ){
  76682. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  76683. }
  76684. }
  76685. return rc;
  76686. }
  76687. #undef nWorker /* Defined at the top of this function */
  76688. /*
  76689. ** Free the list of sorted records starting at pRecord.
  76690. */
  76691. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  76692. SorterRecord *p;
  76693. SorterRecord *pNext;
  76694. for(p=pRecord; p; p=pNext){
  76695. pNext = p->u.pNext;
  76696. sqlite3DbFree(db, p);
  76697. }
  76698. }
  76699. /*
  76700. ** Free all resources owned by the object indicated by argument pTask. All
  76701. ** fields of *pTask are zeroed before returning.
  76702. */
  76703. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  76704. sqlite3DbFree(db, pTask->pUnpacked);
  76705. #if SQLITE_MAX_WORKER_THREADS>0
  76706. /* pTask->list.aMemory can only be non-zero if it was handed memory
  76707. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  76708. if( pTask->list.aMemory ){
  76709. sqlite3_free(pTask->list.aMemory);
  76710. }else
  76711. #endif
  76712. {
  76713. assert( pTask->list.aMemory==0 );
  76714. vdbeSorterRecordFree(0, pTask->list.pList);
  76715. }
  76716. if( pTask->file.pFd ){
  76717. sqlite3OsCloseFree(pTask->file.pFd);
  76718. }
  76719. if( pTask->file2.pFd ){
  76720. sqlite3OsCloseFree(pTask->file2.pFd);
  76721. }
  76722. memset(pTask, 0, sizeof(SortSubtask));
  76723. }
  76724. #ifdef SQLITE_DEBUG_SORTER_THREADS
  76725. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  76726. i64 t;
  76727. int iTask = (pTask - pTask->pSorter->aTask);
  76728. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  76729. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  76730. }
  76731. static void vdbeSorterRewindDebug(const char *zEvent){
  76732. i64 t;
  76733. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  76734. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  76735. }
  76736. static void vdbeSorterPopulateDebug(
  76737. SortSubtask *pTask,
  76738. const char *zEvent
  76739. ){
  76740. i64 t;
  76741. int iTask = (pTask - pTask->pSorter->aTask);
  76742. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  76743. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  76744. }
  76745. static void vdbeSorterBlockDebug(
  76746. SortSubtask *pTask,
  76747. int bBlocked,
  76748. const char *zEvent
  76749. ){
  76750. if( bBlocked ){
  76751. i64 t;
  76752. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  76753. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  76754. }
  76755. }
  76756. #else
  76757. # define vdbeSorterWorkDebug(x,y)
  76758. # define vdbeSorterRewindDebug(y)
  76759. # define vdbeSorterPopulateDebug(x,y)
  76760. # define vdbeSorterBlockDebug(x,y,z)
  76761. #endif
  76762. #if SQLITE_MAX_WORKER_THREADS>0
  76763. /*
  76764. ** Join thread pTask->thread.
  76765. */
  76766. static int vdbeSorterJoinThread(SortSubtask *pTask){
  76767. int rc = SQLITE_OK;
  76768. if( pTask->pThread ){
  76769. #ifdef SQLITE_DEBUG_SORTER_THREADS
  76770. int bDone = pTask->bDone;
  76771. #endif
  76772. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  76773. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  76774. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  76775. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  76776. rc = SQLITE_PTR_TO_INT(pRet);
  76777. assert( pTask->bDone==1 );
  76778. pTask->bDone = 0;
  76779. pTask->pThread = 0;
  76780. }
  76781. return rc;
  76782. }
  76783. /*
  76784. ** Launch a background thread to run xTask(pIn).
  76785. */
  76786. static int vdbeSorterCreateThread(
  76787. SortSubtask *pTask, /* Thread will use this task object */
  76788. void *(*xTask)(void*), /* Routine to run in a separate thread */
  76789. void *pIn /* Argument passed into xTask() */
  76790. ){
  76791. assert( pTask->pThread==0 && pTask->bDone==0 );
  76792. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  76793. }
  76794. /*
  76795. ** Join all outstanding threads launched by SorterWrite() to create
  76796. ** level-0 PMAs.
  76797. */
  76798. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  76799. int rc = rcin;
  76800. int i;
  76801. /* This function is always called by the main user thread.
  76802. **
  76803. ** If this function is being called after SorterRewind() has been called,
  76804. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  76805. ** is currently attempt to join one of the other threads. To avoid a race
  76806. ** condition where this thread also attempts to join the same object, join
  76807. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  76808. for(i=pSorter->nTask-1; i>=0; i--){
  76809. SortSubtask *pTask = &pSorter->aTask[i];
  76810. int rc2 = vdbeSorterJoinThread(pTask);
  76811. if( rc==SQLITE_OK ) rc = rc2;
  76812. }
  76813. return rc;
  76814. }
  76815. #else
  76816. # define vdbeSorterJoinAll(x,rcin) (rcin)
  76817. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  76818. #endif
  76819. /*
  76820. ** Allocate a new MergeEngine object capable of handling up to
  76821. ** nReader PmaReader inputs.
  76822. **
  76823. ** nReader is automatically rounded up to the next power of two.
  76824. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  76825. */
  76826. static MergeEngine *vdbeMergeEngineNew(int nReader){
  76827. int N = 2; /* Smallest power of two >= nReader */
  76828. int nByte; /* Total bytes of space to allocate */
  76829. MergeEngine *pNew; /* Pointer to allocated object to return */
  76830. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  76831. while( N<nReader ) N += N;
  76832. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  76833. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  76834. if( pNew ){
  76835. pNew->nTree = N;
  76836. pNew->pTask = 0;
  76837. pNew->aReadr = (PmaReader*)&pNew[1];
  76838. pNew->aTree = (int*)&pNew->aReadr[N];
  76839. }
  76840. return pNew;
  76841. }
  76842. /*
  76843. ** Free the MergeEngine object passed as the only argument.
  76844. */
  76845. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  76846. int i;
  76847. if( pMerger ){
  76848. for(i=0; i<pMerger->nTree; i++){
  76849. vdbePmaReaderClear(&pMerger->aReadr[i]);
  76850. }
  76851. }
  76852. sqlite3_free(pMerger);
  76853. }
  76854. /*
  76855. ** Free all resources associated with the IncrMerger object indicated by
  76856. ** the first argument.
  76857. */
  76858. static void vdbeIncrFree(IncrMerger *pIncr){
  76859. if( pIncr ){
  76860. #if SQLITE_MAX_WORKER_THREADS>0
  76861. if( pIncr->bUseThread ){
  76862. vdbeSorterJoinThread(pIncr->pTask);
  76863. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  76864. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  76865. }
  76866. #endif
  76867. vdbeMergeEngineFree(pIncr->pMerger);
  76868. sqlite3_free(pIncr);
  76869. }
  76870. }
  76871. /*
  76872. ** Reset a sorting cursor back to its original empty state.
  76873. */
  76874. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  76875. int i;
  76876. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  76877. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  76878. #if SQLITE_MAX_WORKER_THREADS>0
  76879. if( pSorter->pReader ){
  76880. vdbePmaReaderClear(pSorter->pReader);
  76881. sqlite3DbFree(db, pSorter->pReader);
  76882. pSorter->pReader = 0;
  76883. }
  76884. #endif
  76885. vdbeMergeEngineFree(pSorter->pMerger);
  76886. pSorter->pMerger = 0;
  76887. for(i=0; i<pSorter->nTask; i++){
  76888. SortSubtask *pTask = &pSorter->aTask[i];
  76889. vdbeSortSubtaskCleanup(db, pTask);
  76890. pTask->pSorter = pSorter;
  76891. }
  76892. if( pSorter->list.aMemory==0 ){
  76893. vdbeSorterRecordFree(0, pSorter->list.pList);
  76894. }
  76895. pSorter->list.pList = 0;
  76896. pSorter->list.szPMA = 0;
  76897. pSorter->bUsePMA = 0;
  76898. pSorter->iMemory = 0;
  76899. pSorter->mxKeysize = 0;
  76900. sqlite3DbFree(db, pSorter->pUnpacked);
  76901. pSorter->pUnpacked = 0;
  76902. }
  76903. /*
  76904. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  76905. */
  76906. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  76907. VdbeSorter *pSorter;
  76908. assert( pCsr->eCurType==CURTYPE_SORTER );
  76909. pSorter = pCsr->uc.pSorter;
  76910. if( pSorter ){
  76911. sqlite3VdbeSorterReset(db, pSorter);
  76912. sqlite3_free(pSorter->list.aMemory);
  76913. sqlite3DbFree(db, pSorter);
  76914. pCsr->uc.pSorter = 0;
  76915. }
  76916. }
  76917. #if SQLITE_MAX_MMAP_SIZE>0
  76918. /*
  76919. ** The first argument is a file-handle open on a temporary file. The file
  76920. ** is guaranteed to be nByte bytes or smaller in size. This function
  76921. ** attempts to extend the file to nByte bytes in size and to ensure that
  76922. ** the VFS has memory mapped it.
  76923. **
  76924. ** Whether or not the file does end up memory mapped of course depends on
  76925. ** the specific VFS implementation.
  76926. */
  76927. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  76928. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  76929. void *p = 0;
  76930. int chunksize = 4*1024;
  76931. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  76932. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  76933. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  76934. sqlite3OsUnfetch(pFd, 0, p);
  76935. }
  76936. }
  76937. #else
  76938. # define vdbeSorterExtendFile(x,y,z)
  76939. #endif
  76940. /*
  76941. ** Allocate space for a file-handle and open a temporary file. If successful,
  76942. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  76943. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  76944. */
  76945. static int vdbeSorterOpenTempFile(
  76946. sqlite3 *db, /* Database handle doing sort */
  76947. i64 nExtend, /* Attempt to extend file to this size */
  76948. sqlite3_file **ppFd
  76949. ){
  76950. int rc;
  76951. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  76952. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  76953. SQLITE_OPEN_TEMP_JOURNAL |
  76954. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  76955. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  76956. );
  76957. if( rc==SQLITE_OK ){
  76958. i64 max = SQLITE_MAX_MMAP_SIZE;
  76959. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  76960. if( nExtend>0 ){
  76961. vdbeSorterExtendFile(db, *ppFd, nExtend);
  76962. }
  76963. }
  76964. return rc;
  76965. }
  76966. /*
  76967. ** If it has not already been allocated, allocate the UnpackedRecord
  76968. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  76969. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  76970. */
  76971. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  76972. if( pTask->pUnpacked==0 ){
  76973. char *pFree;
  76974. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
  76975. pTask->pSorter->pKeyInfo, 0, 0, &pFree
  76976. );
  76977. assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
  76978. if( pFree==0 ) return SQLITE_NOMEM;
  76979. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  76980. pTask->pUnpacked->errCode = 0;
  76981. }
  76982. return SQLITE_OK;
  76983. }
  76984. /*
  76985. ** Merge the two sorted lists p1 and p2 into a single list.
  76986. ** Set *ppOut to the head of the new list.
  76987. */
  76988. static void vdbeSorterMerge(
  76989. SortSubtask *pTask, /* Calling thread context */
  76990. SorterRecord *p1, /* First list to merge */
  76991. SorterRecord *p2, /* Second list to merge */
  76992. SorterRecord **ppOut /* OUT: Head of merged list */
  76993. ){
  76994. SorterRecord *pFinal = 0;
  76995. SorterRecord **pp = &pFinal;
  76996. int bCached = 0;
  76997. while( p1 && p2 ){
  76998. int res;
  76999. res = pTask->xCompare(
  77000. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  77001. );
  77002. if( res<=0 ){
  77003. *pp = p1;
  77004. pp = &p1->u.pNext;
  77005. p1 = p1->u.pNext;
  77006. }else{
  77007. *pp = p2;
  77008. pp = &p2->u.pNext;
  77009. p2 = p2->u.pNext;
  77010. bCached = 0;
  77011. }
  77012. }
  77013. *pp = p1 ? p1 : p2;
  77014. *ppOut = pFinal;
  77015. }
  77016. /*
  77017. ** Return the SorterCompare function to compare values collected by the
  77018. ** sorter object passed as the only argument.
  77019. */
  77020. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  77021. if( p->typeMask==SORTER_TYPE_INTEGER ){
  77022. return vdbeSorterCompareInt;
  77023. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  77024. return vdbeSorterCompareText;
  77025. }
  77026. return vdbeSorterCompare;
  77027. }
  77028. /*
  77029. ** Sort the linked list of records headed at pTask->pList. Return
  77030. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  77031. ** an error occurs.
  77032. */
  77033. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  77034. int i;
  77035. SorterRecord **aSlot;
  77036. SorterRecord *p;
  77037. int rc;
  77038. rc = vdbeSortAllocUnpacked(pTask);
  77039. if( rc!=SQLITE_OK ) return rc;
  77040. p = pList->pList;
  77041. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  77042. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  77043. if( !aSlot ){
  77044. return SQLITE_NOMEM;
  77045. }
  77046. while( p ){
  77047. SorterRecord *pNext;
  77048. if( pList->aMemory ){
  77049. if( (u8*)p==pList->aMemory ){
  77050. pNext = 0;
  77051. }else{
  77052. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  77053. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  77054. }
  77055. }else{
  77056. pNext = p->u.pNext;
  77057. }
  77058. p->u.pNext = 0;
  77059. for(i=0; aSlot[i]; i++){
  77060. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  77061. aSlot[i] = 0;
  77062. }
  77063. aSlot[i] = p;
  77064. p = pNext;
  77065. }
  77066. p = 0;
  77067. for(i=0; i<64; i++){
  77068. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  77069. }
  77070. pList->pList = p;
  77071. sqlite3_free(aSlot);
  77072. assert( pTask->pUnpacked->errCode==SQLITE_OK
  77073. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  77074. );
  77075. return pTask->pUnpacked->errCode;
  77076. }
  77077. /*
  77078. ** Initialize a PMA-writer object.
  77079. */
  77080. static void vdbePmaWriterInit(
  77081. sqlite3_file *pFd, /* File handle to write to */
  77082. PmaWriter *p, /* Object to populate */
  77083. int nBuf, /* Buffer size */
  77084. i64 iStart /* Offset of pFd to begin writing at */
  77085. ){
  77086. memset(p, 0, sizeof(PmaWriter));
  77087. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  77088. if( !p->aBuffer ){
  77089. p->eFWErr = SQLITE_NOMEM;
  77090. }else{
  77091. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  77092. p->iWriteOff = iStart - p->iBufStart;
  77093. p->nBuffer = nBuf;
  77094. p->pFd = pFd;
  77095. }
  77096. }
  77097. /*
  77098. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  77099. ** if successful, or an SQLite error code if an error occurs.
  77100. */
  77101. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  77102. int nRem = nData;
  77103. while( nRem>0 && p->eFWErr==0 ){
  77104. int nCopy = nRem;
  77105. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  77106. nCopy = p->nBuffer - p->iBufEnd;
  77107. }
  77108. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  77109. p->iBufEnd += nCopy;
  77110. if( p->iBufEnd==p->nBuffer ){
  77111. p->eFWErr = sqlite3OsWrite(p->pFd,
  77112. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  77113. p->iWriteOff + p->iBufStart
  77114. );
  77115. p->iBufStart = p->iBufEnd = 0;
  77116. p->iWriteOff += p->nBuffer;
  77117. }
  77118. assert( p->iBufEnd<p->nBuffer );
  77119. nRem -= nCopy;
  77120. }
  77121. }
  77122. /*
  77123. ** Flush any buffered data to disk and clean up the PMA-writer object.
  77124. ** The results of using the PMA-writer after this call are undefined.
  77125. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  77126. ** required. Otherwise, return an SQLite error code.
  77127. **
  77128. ** Before returning, set *piEof to the offset immediately following the
  77129. ** last byte written to the file.
  77130. */
  77131. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  77132. int rc;
  77133. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  77134. p->eFWErr = sqlite3OsWrite(p->pFd,
  77135. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  77136. p->iWriteOff + p->iBufStart
  77137. );
  77138. }
  77139. *piEof = (p->iWriteOff + p->iBufEnd);
  77140. sqlite3_free(p->aBuffer);
  77141. rc = p->eFWErr;
  77142. memset(p, 0, sizeof(PmaWriter));
  77143. return rc;
  77144. }
  77145. /*
  77146. ** Write value iVal encoded as a varint to the PMA. Return
  77147. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  77148. */
  77149. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  77150. int nByte;
  77151. u8 aByte[10];
  77152. nByte = sqlite3PutVarint(aByte, iVal);
  77153. vdbePmaWriteBlob(p, aByte, nByte);
  77154. }
  77155. /*
  77156. ** Write the current contents of in-memory linked-list pList to a level-0
  77157. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  77158. ** successful, or an SQLite error code otherwise.
  77159. **
  77160. ** The format of a PMA is:
  77161. **
  77162. ** * A varint. This varint contains the total number of bytes of content
  77163. ** in the PMA (not including the varint itself).
  77164. **
  77165. ** * One or more records packed end-to-end in order of ascending keys.
  77166. ** Each record consists of a varint followed by a blob of data (the
  77167. ** key). The varint is the number of bytes in the blob of data.
  77168. */
  77169. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  77170. sqlite3 *db = pTask->pSorter->db;
  77171. int rc = SQLITE_OK; /* Return code */
  77172. PmaWriter writer; /* Object used to write to the file */
  77173. #ifdef SQLITE_DEBUG
  77174. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  77175. ** This is used by an assert() statement at the end of this function. */
  77176. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  77177. #endif
  77178. vdbeSorterWorkDebug(pTask, "enter");
  77179. memset(&writer, 0, sizeof(PmaWriter));
  77180. assert( pList->szPMA>0 );
  77181. /* If the first temporary PMA file has not been opened, open it now. */
  77182. if( pTask->file.pFd==0 ){
  77183. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  77184. assert( rc!=SQLITE_OK || pTask->file.pFd );
  77185. assert( pTask->file.iEof==0 );
  77186. assert( pTask->nPMA==0 );
  77187. }
  77188. /* Try to get the file to memory map */
  77189. if( rc==SQLITE_OK ){
  77190. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  77191. }
  77192. /* Sort the list */
  77193. if( rc==SQLITE_OK ){
  77194. rc = vdbeSorterSort(pTask, pList);
  77195. }
  77196. if( rc==SQLITE_OK ){
  77197. SorterRecord *p;
  77198. SorterRecord *pNext = 0;
  77199. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  77200. pTask->file.iEof);
  77201. pTask->nPMA++;
  77202. vdbePmaWriteVarint(&writer, pList->szPMA);
  77203. for(p=pList->pList; p; p=pNext){
  77204. pNext = p->u.pNext;
  77205. vdbePmaWriteVarint(&writer, p->nVal);
  77206. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  77207. if( pList->aMemory==0 ) sqlite3_free(p);
  77208. }
  77209. pList->pList = p;
  77210. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  77211. }
  77212. vdbeSorterWorkDebug(pTask, "exit");
  77213. assert( rc!=SQLITE_OK || pList->pList==0 );
  77214. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  77215. return rc;
  77216. }
  77217. /*
  77218. ** Advance the MergeEngine to its next entry.
  77219. ** Set *pbEof to true there is no next entry because
  77220. ** the MergeEngine has reached the end of all its inputs.
  77221. **
  77222. ** Return SQLITE_OK if successful or an error code if an error occurs.
  77223. */
  77224. static int vdbeMergeEngineStep(
  77225. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  77226. int *pbEof /* Set TRUE at EOF. Set false for more content */
  77227. ){
  77228. int rc;
  77229. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  77230. SortSubtask *pTask = pMerger->pTask;
  77231. /* Advance the current PmaReader */
  77232. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  77233. /* Update contents of aTree[] */
  77234. if( rc==SQLITE_OK ){
  77235. int i; /* Index of aTree[] to recalculate */
  77236. PmaReader *pReadr1; /* First PmaReader to compare */
  77237. PmaReader *pReadr2; /* Second PmaReader to compare */
  77238. int bCached = 0;
  77239. /* Find the first two PmaReaders to compare. The one that was just
  77240. ** advanced (iPrev) and the one next to it in the array. */
  77241. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  77242. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  77243. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  77244. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  77245. int iRes;
  77246. if( pReadr1->pFd==0 ){
  77247. iRes = +1;
  77248. }else if( pReadr2->pFd==0 ){
  77249. iRes = -1;
  77250. }else{
  77251. iRes = pTask->xCompare(pTask, &bCached,
  77252. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  77253. );
  77254. }
  77255. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  77256. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  77257. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  77258. ** pKey2 to point to the record belonging to pReadr2.
  77259. **
  77260. ** Alternatively, if pReadr2 contains the smaller of the two values,
  77261. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  77262. ** was actually called above, then pTask->pUnpacked now contains
  77263. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  77264. ** vdbeSorterCompare() from decoding pReadr2 again.
  77265. **
  77266. ** If the two values were equal, then the value from the oldest
  77267. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  77268. ** is sorted from oldest to newest, so pReadr1 contains older values
  77269. ** than pReadr2 iff (pReadr1<pReadr2). */
  77270. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  77271. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  77272. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  77273. bCached = 0;
  77274. }else{
  77275. if( pReadr1->pFd ) bCached = 0;
  77276. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  77277. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  77278. }
  77279. }
  77280. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  77281. }
  77282. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  77283. }
  77284. #if SQLITE_MAX_WORKER_THREADS>0
  77285. /*
  77286. ** The main routine for background threads that write level-0 PMAs.
  77287. */
  77288. static void *vdbeSorterFlushThread(void *pCtx){
  77289. SortSubtask *pTask = (SortSubtask*)pCtx;
  77290. int rc; /* Return code */
  77291. assert( pTask->bDone==0 );
  77292. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  77293. pTask->bDone = 1;
  77294. return SQLITE_INT_TO_PTR(rc);
  77295. }
  77296. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  77297. /*
  77298. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  77299. ** using a background thread.
  77300. */
  77301. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  77302. #if SQLITE_MAX_WORKER_THREADS==0
  77303. pSorter->bUsePMA = 1;
  77304. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  77305. #else
  77306. int rc = SQLITE_OK;
  77307. int i;
  77308. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  77309. int nWorker = (pSorter->nTask-1);
  77310. /* Set the flag to indicate that at least one PMA has been written.
  77311. ** Or will be, anyhow. */
  77312. pSorter->bUsePMA = 1;
  77313. /* Select a sub-task to sort and flush the current list of in-memory
  77314. ** records to disk. If the sorter is running in multi-threaded mode,
  77315. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  77316. ** the background thread from a sub-tasks previous turn is still running,
  77317. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  77318. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  77319. ** sub-tasks are prefered as they use background threads - the final
  77320. ** sub-task uses the main thread. */
  77321. for(i=0; i<nWorker; i++){
  77322. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  77323. pTask = &pSorter->aTask[iTest];
  77324. if( pTask->bDone ){
  77325. rc = vdbeSorterJoinThread(pTask);
  77326. }
  77327. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  77328. }
  77329. if( rc==SQLITE_OK ){
  77330. if( i==nWorker ){
  77331. /* Use the foreground thread for this operation */
  77332. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  77333. }else{
  77334. /* Launch a background thread for this operation */
  77335. u8 *aMem = pTask->list.aMemory;
  77336. void *pCtx = (void*)pTask;
  77337. assert( pTask->pThread==0 && pTask->bDone==0 );
  77338. assert( pTask->list.pList==0 );
  77339. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  77340. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  77341. pTask->list = pSorter->list;
  77342. pSorter->list.pList = 0;
  77343. pSorter->list.szPMA = 0;
  77344. if( aMem ){
  77345. pSorter->list.aMemory = aMem;
  77346. pSorter->nMemory = sqlite3MallocSize(aMem);
  77347. }else if( pSorter->list.aMemory ){
  77348. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  77349. if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
  77350. }
  77351. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  77352. }
  77353. }
  77354. return rc;
  77355. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  77356. }
  77357. /*
  77358. ** Add a record to the sorter.
  77359. */
  77360. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  77361. const VdbeCursor *pCsr, /* Sorter cursor */
  77362. Mem *pVal /* Memory cell containing record */
  77363. ){
  77364. VdbeSorter *pSorter;
  77365. int rc = SQLITE_OK; /* Return Code */
  77366. SorterRecord *pNew; /* New list element */
  77367. int bFlush; /* True to flush contents of memory to PMA */
  77368. int nReq; /* Bytes of memory required */
  77369. int nPMA; /* Bytes of PMA space required */
  77370. int t; /* serial type of first record field */
  77371. assert( pCsr->eCurType==CURTYPE_SORTER );
  77372. pSorter = pCsr->uc.pSorter;
  77373. getVarint32((const u8*)&pVal->z[1], t);
  77374. if( t>0 && t<10 && t!=7 ){
  77375. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  77376. }else if( t>10 && (t & 0x01) ){
  77377. pSorter->typeMask &= SORTER_TYPE_TEXT;
  77378. }else{
  77379. pSorter->typeMask = 0;
  77380. }
  77381. assert( pSorter );
  77382. /* Figure out whether or not the current contents of memory should be
  77383. ** flushed to a PMA before continuing. If so, do so.
  77384. **
  77385. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  77386. ** flush the contents of memory to a new PMA if (a) at least one value is
  77387. ** already in memory and (b) the new value will not fit in memory.
  77388. **
  77389. ** Or, if using separate allocations for each record, flush the contents
  77390. ** of memory to a PMA if either of the following are true:
  77391. **
  77392. ** * The total memory allocated for the in-memory list is greater
  77393. ** than (page-size * cache-size), or
  77394. **
  77395. ** * The total memory allocated for the in-memory list is greater
  77396. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  77397. */
  77398. nReq = pVal->n + sizeof(SorterRecord);
  77399. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  77400. if( pSorter->mxPmaSize ){
  77401. if( pSorter->list.aMemory ){
  77402. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  77403. }else{
  77404. bFlush = (
  77405. (pSorter->list.szPMA > pSorter->mxPmaSize)
  77406. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  77407. );
  77408. }
  77409. if( bFlush ){
  77410. rc = vdbeSorterFlushPMA(pSorter);
  77411. pSorter->list.szPMA = 0;
  77412. pSorter->iMemory = 0;
  77413. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  77414. }
  77415. }
  77416. pSorter->list.szPMA += nPMA;
  77417. if( nPMA>pSorter->mxKeysize ){
  77418. pSorter->mxKeysize = nPMA;
  77419. }
  77420. if( pSorter->list.aMemory ){
  77421. int nMin = pSorter->iMemory + nReq;
  77422. if( nMin>pSorter->nMemory ){
  77423. u8 *aNew;
  77424. int nNew = pSorter->nMemory * 2;
  77425. while( nNew < nMin ) nNew = nNew*2;
  77426. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  77427. if( nNew < nMin ) nNew = nMin;
  77428. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  77429. if( !aNew ) return SQLITE_NOMEM;
  77430. pSorter->list.pList = (SorterRecord*)(
  77431. aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
  77432. );
  77433. pSorter->list.aMemory = aNew;
  77434. pSorter->nMemory = nNew;
  77435. }
  77436. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  77437. pSorter->iMemory += ROUND8(nReq);
  77438. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  77439. }else{
  77440. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  77441. if( pNew==0 ){
  77442. return SQLITE_NOMEM;
  77443. }
  77444. pNew->u.pNext = pSorter->list.pList;
  77445. }
  77446. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  77447. pNew->nVal = pVal->n;
  77448. pSorter->list.pList = pNew;
  77449. return rc;
  77450. }
  77451. /*
  77452. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  77453. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  77454. ** except that the number-of-bytes varint is omitted from the start.
  77455. */
  77456. static int vdbeIncrPopulate(IncrMerger *pIncr){
  77457. int rc = SQLITE_OK;
  77458. int rc2;
  77459. i64 iStart = pIncr->iStartOff;
  77460. SorterFile *pOut = &pIncr->aFile[1];
  77461. SortSubtask *pTask = pIncr->pTask;
  77462. MergeEngine *pMerger = pIncr->pMerger;
  77463. PmaWriter writer;
  77464. assert( pIncr->bEof==0 );
  77465. vdbeSorterPopulateDebug(pTask, "enter");
  77466. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  77467. while( rc==SQLITE_OK ){
  77468. int dummy;
  77469. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  77470. int nKey = pReader->nKey;
  77471. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  77472. /* Check if the output file is full or if the input has been exhausted.
  77473. ** In either case exit the loop. */
  77474. if( pReader->pFd==0 ) break;
  77475. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  77476. /* Write the next key to the output. */
  77477. vdbePmaWriteVarint(&writer, nKey);
  77478. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  77479. assert( pIncr->pMerger->pTask==pTask );
  77480. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  77481. }
  77482. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  77483. if( rc==SQLITE_OK ) rc = rc2;
  77484. vdbeSorterPopulateDebug(pTask, "exit");
  77485. return rc;
  77486. }
  77487. #if SQLITE_MAX_WORKER_THREADS>0
  77488. /*
  77489. ** The main routine for background threads that populate aFile[1] of
  77490. ** multi-threaded IncrMerger objects.
  77491. */
  77492. static void *vdbeIncrPopulateThread(void *pCtx){
  77493. IncrMerger *pIncr = (IncrMerger*)pCtx;
  77494. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  77495. pIncr->pTask->bDone = 1;
  77496. return pRet;
  77497. }
  77498. /*
  77499. ** Launch a background thread to populate aFile[1] of pIncr.
  77500. */
  77501. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  77502. void *p = (void*)pIncr;
  77503. assert( pIncr->bUseThread );
  77504. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  77505. }
  77506. #endif
  77507. /*
  77508. ** This function is called when the PmaReader corresponding to pIncr has
  77509. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  77510. ** aFile[0] such that the PmaReader should start rereading it from the
  77511. ** beginning.
  77512. **
  77513. ** For single-threaded objects, this is accomplished by literally reading
  77514. ** keys from pIncr->pMerger and repopulating aFile[0].
  77515. **
  77516. ** For multi-threaded objects, all that is required is to wait until the
  77517. ** background thread is finished (if it is not already) and then swap
  77518. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  77519. ** been exhausted, this function also launches a new background thread
  77520. ** to populate the new aFile[1].
  77521. **
  77522. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  77523. */
  77524. static int vdbeIncrSwap(IncrMerger *pIncr){
  77525. int rc = SQLITE_OK;
  77526. #if SQLITE_MAX_WORKER_THREADS>0
  77527. if( pIncr->bUseThread ){
  77528. rc = vdbeSorterJoinThread(pIncr->pTask);
  77529. if( rc==SQLITE_OK ){
  77530. SorterFile f0 = pIncr->aFile[0];
  77531. pIncr->aFile[0] = pIncr->aFile[1];
  77532. pIncr->aFile[1] = f0;
  77533. }
  77534. if( rc==SQLITE_OK ){
  77535. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  77536. pIncr->bEof = 1;
  77537. }else{
  77538. rc = vdbeIncrBgPopulate(pIncr);
  77539. }
  77540. }
  77541. }else
  77542. #endif
  77543. {
  77544. rc = vdbeIncrPopulate(pIncr);
  77545. pIncr->aFile[0] = pIncr->aFile[1];
  77546. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  77547. pIncr->bEof = 1;
  77548. }
  77549. }
  77550. return rc;
  77551. }
  77552. /*
  77553. ** Allocate and return a new IncrMerger object to read data from pMerger.
  77554. **
  77555. ** If an OOM condition is encountered, return NULL. In this case free the
  77556. ** pMerger argument before returning.
  77557. */
  77558. static int vdbeIncrMergerNew(
  77559. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  77560. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  77561. IncrMerger **ppOut /* Write the new IncrMerger here */
  77562. ){
  77563. int rc = SQLITE_OK;
  77564. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  77565. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  77566. if( pIncr ){
  77567. pIncr->pMerger = pMerger;
  77568. pIncr->pTask = pTask;
  77569. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  77570. pTask->file2.iEof += pIncr->mxSz;
  77571. }else{
  77572. vdbeMergeEngineFree(pMerger);
  77573. rc = SQLITE_NOMEM;
  77574. }
  77575. return rc;
  77576. }
  77577. #if SQLITE_MAX_WORKER_THREADS>0
  77578. /*
  77579. ** Set the "use-threads" flag on object pIncr.
  77580. */
  77581. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  77582. pIncr->bUseThread = 1;
  77583. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  77584. }
  77585. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  77586. /*
  77587. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  77588. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  77589. ** are advanced. This routine merely does the comparison.
  77590. */
  77591. static void vdbeMergeEngineCompare(
  77592. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  77593. int iOut /* Store the result in pMerger->aTree[iOut] */
  77594. ){
  77595. int i1;
  77596. int i2;
  77597. int iRes;
  77598. PmaReader *p1;
  77599. PmaReader *p2;
  77600. assert( iOut<pMerger->nTree && iOut>0 );
  77601. if( iOut>=(pMerger->nTree/2) ){
  77602. i1 = (iOut - pMerger->nTree/2) * 2;
  77603. i2 = i1 + 1;
  77604. }else{
  77605. i1 = pMerger->aTree[iOut*2];
  77606. i2 = pMerger->aTree[iOut*2+1];
  77607. }
  77608. p1 = &pMerger->aReadr[i1];
  77609. p2 = &pMerger->aReadr[i2];
  77610. if( p1->pFd==0 ){
  77611. iRes = i2;
  77612. }else if( p2->pFd==0 ){
  77613. iRes = i1;
  77614. }else{
  77615. SortSubtask *pTask = pMerger->pTask;
  77616. int bCached = 0;
  77617. int res;
  77618. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  77619. res = pTask->xCompare(
  77620. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  77621. );
  77622. if( res<=0 ){
  77623. iRes = i1;
  77624. }else{
  77625. iRes = i2;
  77626. }
  77627. }
  77628. pMerger->aTree[iOut] = iRes;
  77629. }
  77630. /*
  77631. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  77632. ** and vdbePmaReaderIncrMergeInit().
  77633. **
  77634. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  77635. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  77636. ** when there exists one or more separate worker threads.
  77637. */
  77638. #define INCRINIT_NORMAL 0
  77639. #define INCRINIT_TASK 1
  77640. #define INCRINIT_ROOT 2
  77641. /*
  77642. ** Forward reference required as the vdbeIncrMergeInit() and
  77643. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  77644. ** building a merge tree.
  77645. */
  77646. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  77647. /*
  77648. ** Initialize the MergeEngine object passed as the second argument. Once this
  77649. ** function returns, the first key of merged data may be read from the
  77650. ** MergeEngine object in the usual fashion.
  77651. **
  77652. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  77653. ** objects attached to the PmaReader objects that the merger reads from have
  77654. ** already been populated, but that they have not yet populated aFile[0] and
  77655. ** set the PmaReader objects up to read from it. In this case all that is
  77656. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  77657. ** its first key.
  77658. **
  77659. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  77660. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  77661. ** to pMerger.
  77662. **
  77663. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  77664. */
  77665. static int vdbeMergeEngineInit(
  77666. SortSubtask *pTask, /* Thread that will run pMerger */
  77667. MergeEngine *pMerger, /* MergeEngine to initialize */
  77668. int eMode /* One of the INCRINIT_XXX constants */
  77669. ){
  77670. int rc = SQLITE_OK; /* Return code */
  77671. int i; /* For looping over PmaReader objects */
  77672. int nTree = pMerger->nTree;
  77673. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  77674. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  77675. /* Verify that the MergeEngine is assigned to a single thread */
  77676. assert( pMerger->pTask==0 );
  77677. pMerger->pTask = pTask;
  77678. for(i=0; i<nTree; i++){
  77679. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  77680. /* PmaReaders should be normally initialized in order, as if they are
  77681. ** reading from the same temp file this makes for more linear file IO.
  77682. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  77683. ** in use it will block the vdbePmaReaderNext() call while it uses
  77684. ** the main thread to fill its buffer. So calling PmaReaderNext()
  77685. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  77686. ** better advantage of multi-processor hardware. */
  77687. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  77688. }else{
  77689. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  77690. }
  77691. if( rc!=SQLITE_OK ) return rc;
  77692. }
  77693. for(i=pMerger->nTree-1; i>0; i--){
  77694. vdbeMergeEngineCompare(pMerger, i);
  77695. }
  77696. return pTask->pUnpacked->errCode;
  77697. }
  77698. /*
  77699. ** The PmaReader passed as the first argument is guaranteed to be an
  77700. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  77701. ** and/or initialize the temp file related fields of the IncrMerge
  77702. ** object at (pReadr->pIncr).
  77703. **
  77704. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  77705. ** in the sub-tree headed by pReadr are also initialized. Data is then
  77706. ** loaded into the buffers belonging to pReadr and it is set to point to
  77707. ** the first key in its range.
  77708. **
  77709. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  77710. ** to be a multi-threaded PmaReader and this function is being called in a
  77711. ** background thread. In this case all PmaReaders in the sub-tree are
  77712. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  77713. ** pReadr is populated. However, pReadr itself is not set up to point
  77714. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  77715. ** that.
  77716. **
  77717. ** The reason this function does not call vdbePmaReaderNext() immediately
  77718. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  77719. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  77720. ** this entire function is being run by thread (pTask->thread), that will
  77721. ** lead to the current background thread attempting to join itself.
  77722. **
  77723. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  77724. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  77725. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  77726. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  77727. ** the current PmaReader set to point to the first key in its range.
  77728. **
  77729. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  77730. */
  77731. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  77732. int rc = SQLITE_OK;
  77733. IncrMerger *pIncr = pReadr->pIncr;
  77734. SortSubtask *pTask = pIncr->pTask;
  77735. sqlite3 *db = pTask->pSorter->db;
  77736. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  77737. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  77738. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  77739. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  77740. ** requires two temp files to itself, whereas a single-threaded object
  77741. ** only requires a region of pTask->file2. */
  77742. if( rc==SQLITE_OK ){
  77743. int mxSz = pIncr->mxSz;
  77744. #if SQLITE_MAX_WORKER_THREADS>0
  77745. if( pIncr->bUseThread ){
  77746. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  77747. if( rc==SQLITE_OK ){
  77748. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  77749. }
  77750. }else
  77751. #endif
  77752. /*if( !pIncr->bUseThread )*/{
  77753. if( pTask->file2.pFd==0 ){
  77754. assert( pTask->file2.iEof>0 );
  77755. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  77756. pTask->file2.iEof = 0;
  77757. }
  77758. if( rc==SQLITE_OK ){
  77759. pIncr->aFile[1].pFd = pTask->file2.pFd;
  77760. pIncr->iStartOff = pTask->file2.iEof;
  77761. pTask->file2.iEof += mxSz;
  77762. }
  77763. }
  77764. }
  77765. #if SQLITE_MAX_WORKER_THREADS>0
  77766. if( rc==SQLITE_OK && pIncr->bUseThread ){
  77767. /* Use the current thread to populate aFile[1], even though this
  77768. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  77769. ** then this function is already running in background thread
  77770. ** pIncr->pTask->thread.
  77771. **
  77772. ** If this is the INCRINIT_ROOT object, then it is running in the
  77773. ** main VDBE thread. But that is Ok, as that thread cannot return
  77774. ** control to the VDBE or proceed with anything useful until the
  77775. ** first results are ready from this merger object anyway.
  77776. */
  77777. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  77778. rc = vdbeIncrPopulate(pIncr);
  77779. }
  77780. #endif
  77781. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  77782. rc = vdbePmaReaderNext(pReadr);
  77783. }
  77784. return rc;
  77785. }
  77786. #if SQLITE_MAX_WORKER_THREADS>0
  77787. /*
  77788. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  77789. ** background threads.
  77790. */
  77791. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  77792. PmaReader *pReader = (PmaReader*)pCtx;
  77793. void *pRet = SQLITE_INT_TO_PTR(
  77794. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  77795. );
  77796. pReader->pIncr->pTask->bDone = 1;
  77797. return pRet;
  77798. }
  77799. #endif
  77800. /*
  77801. ** If the PmaReader passed as the first argument is not an incremental-reader
  77802. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  77803. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  77804. ** this routine to initialize the incremental merge.
  77805. **
  77806. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  77807. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  77808. ** Or, if the IncrMerger is single threaded, the same function is called
  77809. ** using the current thread.
  77810. */
  77811. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  77812. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  77813. int rc = SQLITE_OK; /* Return code */
  77814. if( pIncr ){
  77815. #if SQLITE_MAX_WORKER_THREADS>0
  77816. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  77817. if( pIncr->bUseThread ){
  77818. void *pCtx = (void*)pReadr;
  77819. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  77820. }else
  77821. #endif
  77822. {
  77823. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  77824. }
  77825. }
  77826. return rc;
  77827. }
  77828. /*
  77829. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  77830. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  77831. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  77832. ** to NULL and return an SQLite error code.
  77833. **
  77834. ** When this function is called, *piOffset is set to the offset of the
  77835. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  77836. ** set to the offset immediately following the last byte of the last
  77837. ** PMA before returning. If an error does occur, then the final value of
  77838. ** *piOffset is undefined.
  77839. */
  77840. static int vdbeMergeEngineLevel0(
  77841. SortSubtask *pTask, /* Sorter task to read from */
  77842. int nPMA, /* Number of PMAs to read */
  77843. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  77844. MergeEngine **ppOut /* OUT: New merge-engine */
  77845. ){
  77846. MergeEngine *pNew; /* Merge engine to return */
  77847. i64 iOff = *piOffset;
  77848. int i;
  77849. int rc = SQLITE_OK;
  77850. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  77851. if( pNew==0 ) rc = SQLITE_NOMEM;
  77852. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  77853. i64 nDummy;
  77854. PmaReader *pReadr = &pNew->aReadr[i];
  77855. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  77856. iOff = pReadr->iEof;
  77857. }
  77858. if( rc!=SQLITE_OK ){
  77859. vdbeMergeEngineFree(pNew);
  77860. *ppOut = 0;
  77861. }
  77862. *piOffset = iOff;
  77863. return rc;
  77864. }
  77865. /*
  77866. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  77867. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  77868. **
  77869. ** i.e.
  77870. **
  77871. ** nPMA<=16 -> TreeDepth() == 0
  77872. ** nPMA<=256 -> TreeDepth() == 1
  77873. ** nPMA<=65536 -> TreeDepth() == 2
  77874. */
  77875. static int vdbeSorterTreeDepth(int nPMA){
  77876. int nDepth = 0;
  77877. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  77878. while( nDiv < (i64)nPMA ){
  77879. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  77880. nDepth++;
  77881. }
  77882. return nDepth;
  77883. }
  77884. /*
  77885. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  77886. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  77887. ** tree, counting from zero. This function adds pLeaf to the tree.
  77888. **
  77889. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  77890. ** code is returned and pLeaf is freed.
  77891. */
  77892. static int vdbeSorterAddToTree(
  77893. SortSubtask *pTask, /* Task context */
  77894. int nDepth, /* Depth of tree according to TreeDepth() */
  77895. int iSeq, /* Sequence number of leaf within tree */
  77896. MergeEngine *pRoot, /* Root of tree */
  77897. MergeEngine *pLeaf /* Leaf to add to tree */
  77898. ){
  77899. int rc = SQLITE_OK;
  77900. int nDiv = 1;
  77901. int i;
  77902. MergeEngine *p = pRoot;
  77903. IncrMerger *pIncr;
  77904. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  77905. for(i=1; i<nDepth; i++){
  77906. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  77907. }
  77908. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  77909. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  77910. PmaReader *pReadr = &p->aReadr[iIter];
  77911. if( pReadr->pIncr==0 ){
  77912. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  77913. if( pNew==0 ){
  77914. rc = SQLITE_NOMEM;
  77915. }else{
  77916. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  77917. }
  77918. }
  77919. if( rc==SQLITE_OK ){
  77920. p = pReadr->pIncr->pMerger;
  77921. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  77922. }
  77923. }
  77924. if( rc==SQLITE_OK ){
  77925. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  77926. }else{
  77927. vdbeIncrFree(pIncr);
  77928. }
  77929. return rc;
  77930. }
  77931. /*
  77932. ** This function is called as part of a SorterRewind() operation on a sorter
  77933. ** that has already written two or more level-0 PMAs to one or more temp
  77934. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  77935. ** can be used to incrementally merge all PMAs on disk.
  77936. **
  77937. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  77938. ** MergeEngine object at the root of the tree before returning. Or, if an
  77939. ** error occurs, an SQLite error code is returned and the final value
  77940. ** of *ppOut is undefined.
  77941. */
  77942. static int vdbeSorterMergeTreeBuild(
  77943. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  77944. MergeEngine **ppOut /* Write the MergeEngine here */
  77945. ){
  77946. MergeEngine *pMain = 0;
  77947. int rc = SQLITE_OK;
  77948. int iTask;
  77949. #if SQLITE_MAX_WORKER_THREADS>0
  77950. /* If the sorter uses more than one task, then create the top-level
  77951. ** MergeEngine here. This MergeEngine will read data from exactly
  77952. ** one PmaReader per sub-task. */
  77953. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  77954. if( pSorter->nTask>1 ){
  77955. pMain = vdbeMergeEngineNew(pSorter->nTask);
  77956. if( pMain==0 ) rc = SQLITE_NOMEM;
  77957. }
  77958. #endif
  77959. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  77960. SortSubtask *pTask = &pSorter->aTask[iTask];
  77961. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  77962. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  77963. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  77964. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  77965. i64 iReadOff = 0;
  77966. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  77967. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  77968. }else{
  77969. int i;
  77970. int iSeq = 0;
  77971. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  77972. if( pRoot==0 ) rc = SQLITE_NOMEM;
  77973. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  77974. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  77975. int nReader; /* Number of level-0 PMAs to merge */
  77976. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  77977. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  77978. if( rc==SQLITE_OK ){
  77979. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  77980. }
  77981. }
  77982. }
  77983. if( rc==SQLITE_OK ){
  77984. #if SQLITE_MAX_WORKER_THREADS>0
  77985. if( pMain!=0 ){
  77986. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  77987. }else
  77988. #endif
  77989. {
  77990. assert( pMain==0 );
  77991. pMain = pRoot;
  77992. }
  77993. }else{
  77994. vdbeMergeEngineFree(pRoot);
  77995. }
  77996. }
  77997. }
  77998. if( rc!=SQLITE_OK ){
  77999. vdbeMergeEngineFree(pMain);
  78000. pMain = 0;
  78001. }
  78002. *ppOut = pMain;
  78003. return rc;
  78004. }
  78005. /*
  78006. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  78007. ** on a sorter that has written two or more PMAs to temporary files. It sets
  78008. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  78009. ** (for multi-threaded sorters) so that it can be used to iterate through
  78010. ** all records stored in the sorter.
  78011. **
  78012. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  78013. */
  78014. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  78015. int rc; /* Return code */
  78016. SortSubtask *pTask0 = &pSorter->aTask[0];
  78017. MergeEngine *pMain = 0;
  78018. #if SQLITE_MAX_WORKER_THREADS
  78019. sqlite3 *db = pTask0->pSorter->db;
  78020. int i;
  78021. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  78022. for(i=0; i<pSorter->nTask; i++){
  78023. pSorter->aTask[i].xCompare = xCompare;
  78024. }
  78025. #endif
  78026. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  78027. if( rc==SQLITE_OK ){
  78028. #if SQLITE_MAX_WORKER_THREADS
  78029. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  78030. if( pSorter->bUseThreads ){
  78031. int iTask;
  78032. PmaReader *pReadr = 0;
  78033. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  78034. rc = vdbeSortAllocUnpacked(pLast);
  78035. if( rc==SQLITE_OK ){
  78036. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  78037. pSorter->pReader = pReadr;
  78038. if( pReadr==0 ) rc = SQLITE_NOMEM;
  78039. }
  78040. if( rc==SQLITE_OK ){
  78041. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  78042. if( rc==SQLITE_OK ){
  78043. vdbeIncrMergerSetThreads(pReadr->pIncr);
  78044. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  78045. IncrMerger *pIncr;
  78046. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  78047. vdbeIncrMergerSetThreads(pIncr);
  78048. assert( pIncr->pTask!=pLast );
  78049. }
  78050. }
  78051. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  78052. /* Check that:
  78053. **
  78054. ** a) The incremental merge object is configured to use the
  78055. ** right task, and
  78056. ** b) If it is using task (nTask-1), it is configured to run
  78057. ** in single-threaded mode. This is important, as the
  78058. ** root merge (INCRINIT_ROOT) will be using the same task
  78059. ** object.
  78060. */
  78061. PmaReader *p = &pMain->aReadr[iTask];
  78062. assert( p->pIncr==0 || (
  78063. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  78064. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  78065. ));
  78066. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  78067. }
  78068. }
  78069. pMain = 0;
  78070. }
  78071. if( rc==SQLITE_OK ){
  78072. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  78073. }
  78074. }else
  78075. #endif
  78076. {
  78077. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  78078. pSorter->pMerger = pMain;
  78079. pMain = 0;
  78080. }
  78081. }
  78082. if( rc!=SQLITE_OK ){
  78083. vdbeMergeEngineFree(pMain);
  78084. }
  78085. return rc;
  78086. }
  78087. /*
  78088. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  78089. ** this function is called to prepare for iterating through the records
  78090. ** in sorted order.
  78091. */
  78092. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  78093. VdbeSorter *pSorter;
  78094. int rc = SQLITE_OK; /* Return code */
  78095. assert( pCsr->eCurType==CURTYPE_SORTER );
  78096. pSorter = pCsr->uc.pSorter;
  78097. assert( pSorter );
  78098. /* If no data has been written to disk, then do not do so now. Instead,
  78099. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  78100. ** from the in-memory list. */
  78101. if( pSorter->bUsePMA==0 ){
  78102. if( pSorter->list.pList ){
  78103. *pbEof = 0;
  78104. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  78105. }else{
  78106. *pbEof = 1;
  78107. }
  78108. return rc;
  78109. }
  78110. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  78111. ** function flushes the contents of memory to disk, it immediately always
  78112. ** creates a new list consisting of a single key immediately afterwards.
  78113. ** So the list is never empty at this point. */
  78114. assert( pSorter->list.pList );
  78115. rc = vdbeSorterFlushPMA(pSorter);
  78116. /* Join all threads */
  78117. rc = vdbeSorterJoinAll(pSorter, rc);
  78118. vdbeSorterRewindDebug("rewind");
  78119. /* Assuming no errors have occurred, set up a merger structure to
  78120. ** incrementally read and merge all remaining PMAs. */
  78121. assert( pSorter->pReader==0 );
  78122. if( rc==SQLITE_OK ){
  78123. rc = vdbeSorterSetupMerge(pSorter);
  78124. *pbEof = 0;
  78125. }
  78126. vdbeSorterRewindDebug("rewinddone");
  78127. return rc;
  78128. }
  78129. /*
  78130. ** Advance to the next element in the sorter.
  78131. */
  78132. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  78133. VdbeSorter *pSorter;
  78134. int rc; /* Return code */
  78135. assert( pCsr->eCurType==CURTYPE_SORTER );
  78136. pSorter = pCsr->uc.pSorter;
  78137. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  78138. if( pSorter->bUsePMA ){
  78139. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  78140. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  78141. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  78142. #if SQLITE_MAX_WORKER_THREADS>0
  78143. if( pSorter->bUseThreads ){
  78144. rc = vdbePmaReaderNext(pSorter->pReader);
  78145. *pbEof = (pSorter->pReader->pFd==0);
  78146. }else
  78147. #endif
  78148. /*if( !pSorter->bUseThreads )*/ {
  78149. assert( pSorter->pMerger!=0 );
  78150. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  78151. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  78152. }
  78153. }else{
  78154. SorterRecord *pFree = pSorter->list.pList;
  78155. pSorter->list.pList = pFree->u.pNext;
  78156. pFree->u.pNext = 0;
  78157. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  78158. *pbEof = !pSorter->list.pList;
  78159. rc = SQLITE_OK;
  78160. }
  78161. return rc;
  78162. }
  78163. /*
  78164. ** Return a pointer to a buffer owned by the sorter that contains the
  78165. ** current key.
  78166. */
  78167. static void *vdbeSorterRowkey(
  78168. const VdbeSorter *pSorter, /* Sorter object */
  78169. int *pnKey /* OUT: Size of current key in bytes */
  78170. ){
  78171. void *pKey;
  78172. if( pSorter->bUsePMA ){
  78173. PmaReader *pReader;
  78174. #if SQLITE_MAX_WORKER_THREADS>0
  78175. if( pSorter->bUseThreads ){
  78176. pReader = pSorter->pReader;
  78177. }else
  78178. #endif
  78179. /*if( !pSorter->bUseThreads )*/{
  78180. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  78181. }
  78182. *pnKey = pReader->nKey;
  78183. pKey = pReader->aKey;
  78184. }else{
  78185. *pnKey = pSorter->list.pList->nVal;
  78186. pKey = SRVAL(pSorter->list.pList);
  78187. }
  78188. return pKey;
  78189. }
  78190. /*
  78191. ** Copy the current sorter key into the memory cell pOut.
  78192. */
  78193. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  78194. VdbeSorter *pSorter;
  78195. void *pKey; int nKey; /* Sorter key to copy into pOut */
  78196. assert( pCsr->eCurType==CURTYPE_SORTER );
  78197. pSorter = pCsr->uc.pSorter;
  78198. pKey = vdbeSorterRowkey(pSorter, &nKey);
  78199. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  78200. return SQLITE_NOMEM;
  78201. }
  78202. pOut->n = nKey;
  78203. MemSetTypeFlag(pOut, MEM_Blob);
  78204. memcpy(pOut->z, pKey, nKey);
  78205. return SQLITE_OK;
  78206. }
  78207. /*
  78208. ** Compare the key in memory cell pVal with the key that the sorter cursor
  78209. ** passed as the first argument currently points to. For the purposes of
  78210. ** the comparison, ignore the rowid field at the end of each record.
  78211. **
  78212. ** If the sorter cursor key contains any NULL values, consider it to be
  78213. ** less than pVal. Even if pVal also contains NULL values.
  78214. **
  78215. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  78216. ** Otherwise, set *pRes to a negative, zero or positive value if the
  78217. ** key in pVal is smaller than, equal to or larger than the current sorter
  78218. ** key.
  78219. **
  78220. ** This routine forms the core of the OP_SorterCompare opcode, which in
  78221. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  78222. */
  78223. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  78224. const VdbeCursor *pCsr, /* Sorter cursor */
  78225. Mem *pVal, /* Value to compare to current sorter key */
  78226. int nKeyCol, /* Compare this many columns */
  78227. int *pRes /* OUT: Result of comparison */
  78228. ){
  78229. VdbeSorter *pSorter;
  78230. UnpackedRecord *r2;
  78231. KeyInfo *pKeyInfo;
  78232. int i;
  78233. void *pKey; int nKey; /* Sorter key to compare pVal with */
  78234. assert( pCsr->eCurType==CURTYPE_SORTER );
  78235. pSorter = pCsr->uc.pSorter;
  78236. r2 = pSorter->pUnpacked;
  78237. pKeyInfo = pCsr->pKeyInfo;
  78238. if( r2==0 ){
  78239. char *p;
  78240. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
  78241. assert( pSorter->pUnpacked==(UnpackedRecord*)p );
  78242. if( r2==0 ) return SQLITE_NOMEM;
  78243. r2->nField = nKeyCol;
  78244. }
  78245. assert( r2->nField==nKeyCol );
  78246. pKey = vdbeSorterRowkey(pSorter, &nKey);
  78247. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  78248. for(i=0; i<nKeyCol; i++){
  78249. if( r2->aMem[i].flags & MEM_Null ){
  78250. *pRes = -1;
  78251. return SQLITE_OK;
  78252. }
  78253. }
  78254. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  78255. return SQLITE_OK;
  78256. }
  78257. /************** End of vdbesort.c ********************************************/
  78258. /************** Begin file journal.c *****************************************/
  78259. /*
  78260. ** 2007 August 22
  78261. **
  78262. ** The author disclaims copyright to this source code. In place of
  78263. ** a legal notice, here is a blessing:
  78264. **
  78265. ** May you do good and not evil.
  78266. ** May you find forgiveness for yourself and forgive others.
  78267. ** May you share freely, never taking more than you give.
  78268. **
  78269. *************************************************************************
  78270. **
  78271. ** This file implements a special kind of sqlite3_file object used
  78272. ** by SQLite to create journal files if the atomic-write optimization
  78273. ** is enabled.
  78274. **
  78275. ** The distinctive characteristic of this sqlite3_file is that the
  78276. ** actual on disk file is created lazily. When the file is created,
  78277. ** the caller specifies a buffer size for an in-memory buffer to
  78278. ** be used to service read() and write() requests. The actual file
  78279. ** on disk is not created or populated until either:
  78280. **
  78281. ** 1) The in-memory representation grows too large for the allocated
  78282. ** buffer, or
  78283. ** 2) The sqlite3JournalCreate() function is called.
  78284. */
  78285. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  78286. /* #include "sqliteInt.h" */
  78287. /*
  78288. ** A JournalFile object is a subclass of sqlite3_file used by
  78289. ** as an open file handle for journal files.
  78290. */
  78291. struct JournalFile {
  78292. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  78293. int nBuf; /* Size of zBuf[] in bytes */
  78294. char *zBuf; /* Space to buffer journal writes */
  78295. int iSize; /* Amount of zBuf[] currently used */
  78296. int flags; /* xOpen flags */
  78297. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  78298. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  78299. const char *zJournal; /* Name of the journal file */
  78300. };
  78301. typedef struct JournalFile JournalFile;
  78302. /*
  78303. ** If it does not already exists, create and populate the on-disk file
  78304. ** for JournalFile p.
  78305. */
  78306. static int createFile(JournalFile *p){
  78307. int rc = SQLITE_OK;
  78308. if( !p->pReal ){
  78309. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  78310. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  78311. if( rc==SQLITE_OK ){
  78312. p->pReal = pReal;
  78313. if( p->iSize>0 ){
  78314. assert(p->iSize<=p->nBuf);
  78315. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  78316. }
  78317. if( rc!=SQLITE_OK ){
  78318. /* If an error occurred while writing to the file, close it before
  78319. ** returning. This way, SQLite uses the in-memory journal data to
  78320. ** roll back changes made to the internal page-cache before this
  78321. ** function was called. */
  78322. sqlite3OsClose(pReal);
  78323. p->pReal = 0;
  78324. }
  78325. }
  78326. }
  78327. return rc;
  78328. }
  78329. /*
  78330. ** Close the file.
  78331. */
  78332. static int jrnlClose(sqlite3_file *pJfd){
  78333. JournalFile *p = (JournalFile *)pJfd;
  78334. if( p->pReal ){
  78335. sqlite3OsClose(p->pReal);
  78336. }
  78337. sqlite3_free(p->zBuf);
  78338. return SQLITE_OK;
  78339. }
  78340. /*
  78341. ** Read data from the file.
  78342. */
  78343. static int jrnlRead(
  78344. sqlite3_file *pJfd, /* The journal file from which to read */
  78345. void *zBuf, /* Put the results here */
  78346. int iAmt, /* Number of bytes to read */
  78347. sqlite_int64 iOfst /* Begin reading at this offset */
  78348. ){
  78349. int rc = SQLITE_OK;
  78350. JournalFile *p = (JournalFile *)pJfd;
  78351. if( p->pReal ){
  78352. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  78353. }else if( (iAmt+iOfst)>p->iSize ){
  78354. rc = SQLITE_IOERR_SHORT_READ;
  78355. }else{
  78356. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  78357. }
  78358. return rc;
  78359. }
  78360. /*
  78361. ** Write data to the file.
  78362. */
  78363. static int jrnlWrite(
  78364. sqlite3_file *pJfd, /* The journal file into which to write */
  78365. const void *zBuf, /* Take data to be written from here */
  78366. int iAmt, /* Number of bytes to write */
  78367. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  78368. ){
  78369. int rc = SQLITE_OK;
  78370. JournalFile *p = (JournalFile *)pJfd;
  78371. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  78372. rc = createFile(p);
  78373. }
  78374. if( rc==SQLITE_OK ){
  78375. if( p->pReal ){
  78376. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  78377. }else{
  78378. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  78379. if( p->iSize<(iOfst+iAmt) ){
  78380. p->iSize = (iOfst+iAmt);
  78381. }
  78382. }
  78383. }
  78384. return rc;
  78385. }
  78386. /*
  78387. ** Truncate the file.
  78388. */
  78389. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  78390. int rc = SQLITE_OK;
  78391. JournalFile *p = (JournalFile *)pJfd;
  78392. if( p->pReal ){
  78393. rc = sqlite3OsTruncate(p->pReal, size);
  78394. }else if( size<p->iSize ){
  78395. p->iSize = size;
  78396. }
  78397. return rc;
  78398. }
  78399. /*
  78400. ** Sync the file.
  78401. */
  78402. static int jrnlSync(sqlite3_file *pJfd, int flags){
  78403. int rc;
  78404. JournalFile *p = (JournalFile *)pJfd;
  78405. if( p->pReal ){
  78406. rc = sqlite3OsSync(p->pReal, flags);
  78407. }else{
  78408. rc = SQLITE_OK;
  78409. }
  78410. return rc;
  78411. }
  78412. /*
  78413. ** Query the size of the file in bytes.
  78414. */
  78415. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  78416. int rc = SQLITE_OK;
  78417. JournalFile *p = (JournalFile *)pJfd;
  78418. if( p->pReal ){
  78419. rc = sqlite3OsFileSize(p->pReal, pSize);
  78420. }else{
  78421. *pSize = (sqlite_int64) p->iSize;
  78422. }
  78423. return rc;
  78424. }
  78425. /*
  78426. ** Table of methods for JournalFile sqlite3_file object.
  78427. */
  78428. static struct sqlite3_io_methods JournalFileMethods = {
  78429. 1, /* iVersion */
  78430. jrnlClose, /* xClose */
  78431. jrnlRead, /* xRead */
  78432. jrnlWrite, /* xWrite */
  78433. jrnlTruncate, /* xTruncate */
  78434. jrnlSync, /* xSync */
  78435. jrnlFileSize, /* xFileSize */
  78436. 0, /* xLock */
  78437. 0, /* xUnlock */
  78438. 0, /* xCheckReservedLock */
  78439. 0, /* xFileControl */
  78440. 0, /* xSectorSize */
  78441. 0, /* xDeviceCharacteristics */
  78442. 0, /* xShmMap */
  78443. 0, /* xShmLock */
  78444. 0, /* xShmBarrier */
  78445. 0 /* xShmUnmap */
  78446. };
  78447. /*
  78448. ** Open a journal file.
  78449. */
  78450. SQLITE_PRIVATE int sqlite3JournalOpen(
  78451. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  78452. const char *zName, /* Name of the journal file */
  78453. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  78454. int flags, /* Opening flags */
  78455. int nBuf /* Bytes buffered before opening the file */
  78456. ){
  78457. JournalFile *p = (JournalFile *)pJfd;
  78458. memset(p, 0, sqlite3JournalSize(pVfs));
  78459. if( nBuf>0 ){
  78460. p->zBuf = sqlite3MallocZero(nBuf);
  78461. if( !p->zBuf ){
  78462. return SQLITE_NOMEM;
  78463. }
  78464. }else{
  78465. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  78466. }
  78467. p->pMethod = &JournalFileMethods;
  78468. p->nBuf = nBuf;
  78469. p->flags = flags;
  78470. p->zJournal = zName;
  78471. p->pVfs = pVfs;
  78472. return SQLITE_OK;
  78473. }
  78474. /*
  78475. ** If the argument p points to a JournalFile structure, and the underlying
  78476. ** file has not yet been created, create it now.
  78477. */
  78478. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  78479. if( p->pMethods!=&JournalFileMethods ){
  78480. return SQLITE_OK;
  78481. }
  78482. return createFile((JournalFile *)p);
  78483. }
  78484. /*
  78485. ** The file-handle passed as the only argument is guaranteed to be an open
  78486. ** file. It may or may not be of class JournalFile. If the file is a
  78487. ** JournalFile, and the underlying file on disk has not yet been opened,
  78488. ** return 0. Otherwise, return 1.
  78489. */
  78490. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  78491. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  78492. }
  78493. /*
  78494. ** Return the number of bytes required to store a JournalFile that uses vfs
  78495. ** pVfs to create the underlying on-disk files.
  78496. */
  78497. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  78498. return (pVfs->szOsFile+sizeof(JournalFile));
  78499. }
  78500. #endif
  78501. /************** End of journal.c *********************************************/
  78502. /************** Begin file memjournal.c **************************************/
  78503. /*
  78504. ** 2008 October 7
  78505. **
  78506. ** The author disclaims copyright to this source code. In place of
  78507. ** a legal notice, here is a blessing:
  78508. **
  78509. ** May you do good and not evil.
  78510. ** May you find forgiveness for yourself and forgive others.
  78511. ** May you share freely, never taking more than you give.
  78512. **
  78513. *************************************************************************
  78514. **
  78515. ** This file contains code use to implement an in-memory rollback journal.
  78516. ** The in-memory rollback journal is used to journal transactions for
  78517. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  78518. */
  78519. /* #include "sqliteInt.h" */
  78520. /* Forward references to internal structures */
  78521. typedef struct MemJournal MemJournal;
  78522. typedef struct FilePoint FilePoint;
  78523. typedef struct FileChunk FileChunk;
  78524. /* Space to hold the rollback journal is allocated in increments of
  78525. ** this many bytes.
  78526. **
  78527. ** The size chosen is a little less than a power of two. That way,
  78528. ** the FileChunk object will have a size that almost exactly fills
  78529. ** a power-of-two allocation. This minimizes wasted space in power-of-two
  78530. ** memory allocators.
  78531. */
  78532. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  78533. /*
  78534. ** The rollback journal is composed of a linked list of these structures.
  78535. */
  78536. struct FileChunk {
  78537. FileChunk *pNext; /* Next chunk in the journal */
  78538. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  78539. };
  78540. /*
  78541. ** An instance of this object serves as a cursor into the rollback journal.
  78542. ** The cursor can be either for reading or writing.
  78543. */
  78544. struct FilePoint {
  78545. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  78546. FileChunk *pChunk; /* Specific chunk into which cursor points */
  78547. };
  78548. /*
  78549. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  78550. ** is an instance of this class.
  78551. */
  78552. struct MemJournal {
  78553. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  78554. FileChunk *pFirst; /* Head of in-memory chunk-list */
  78555. FilePoint endpoint; /* Pointer to the end of the file */
  78556. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  78557. };
  78558. /*
  78559. ** Read data from the in-memory journal file. This is the implementation
  78560. ** of the sqlite3_vfs.xRead method.
  78561. */
  78562. static int memjrnlRead(
  78563. sqlite3_file *pJfd, /* The journal file from which to read */
  78564. void *zBuf, /* Put the results here */
  78565. int iAmt, /* Number of bytes to read */
  78566. sqlite_int64 iOfst /* Begin reading at this offset */
  78567. ){
  78568. MemJournal *p = (MemJournal *)pJfd;
  78569. u8 *zOut = zBuf;
  78570. int nRead = iAmt;
  78571. int iChunkOffset;
  78572. FileChunk *pChunk;
  78573. /* SQLite never tries to read past the end of a rollback journal file */
  78574. assert( iOfst+iAmt<=p->endpoint.iOffset );
  78575. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  78576. sqlite3_int64 iOff = 0;
  78577. for(pChunk=p->pFirst;
  78578. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  78579. pChunk=pChunk->pNext
  78580. ){
  78581. iOff += JOURNAL_CHUNKSIZE;
  78582. }
  78583. }else{
  78584. pChunk = p->readpoint.pChunk;
  78585. }
  78586. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  78587. do {
  78588. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  78589. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  78590. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  78591. zOut += nCopy;
  78592. nRead -= iSpace;
  78593. iChunkOffset = 0;
  78594. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  78595. p->readpoint.iOffset = iOfst+iAmt;
  78596. p->readpoint.pChunk = pChunk;
  78597. return SQLITE_OK;
  78598. }
  78599. /*
  78600. ** Write data to the file.
  78601. */
  78602. static int memjrnlWrite(
  78603. sqlite3_file *pJfd, /* The journal file into which to write */
  78604. const void *zBuf, /* Take data to be written from here */
  78605. int iAmt, /* Number of bytes to write */
  78606. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  78607. ){
  78608. MemJournal *p = (MemJournal *)pJfd;
  78609. int nWrite = iAmt;
  78610. u8 *zWrite = (u8 *)zBuf;
  78611. /* An in-memory journal file should only ever be appended to. Random
  78612. ** access writes are not required by sqlite.
  78613. */
  78614. assert( iOfst==p->endpoint.iOffset );
  78615. UNUSED_PARAMETER(iOfst);
  78616. while( nWrite>0 ){
  78617. FileChunk *pChunk = p->endpoint.pChunk;
  78618. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  78619. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  78620. if( iChunkOffset==0 ){
  78621. /* New chunk is required to extend the file. */
  78622. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  78623. if( !pNew ){
  78624. return SQLITE_IOERR_NOMEM;
  78625. }
  78626. pNew->pNext = 0;
  78627. if( pChunk ){
  78628. assert( p->pFirst );
  78629. pChunk->pNext = pNew;
  78630. }else{
  78631. assert( !p->pFirst );
  78632. p->pFirst = pNew;
  78633. }
  78634. p->endpoint.pChunk = pNew;
  78635. }
  78636. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  78637. zWrite += iSpace;
  78638. nWrite -= iSpace;
  78639. p->endpoint.iOffset += iSpace;
  78640. }
  78641. return SQLITE_OK;
  78642. }
  78643. /*
  78644. ** Truncate the file.
  78645. */
  78646. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  78647. MemJournal *p = (MemJournal *)pJfd;
  78648. FileChunk *pChunk;
  78649. assert(size==0);
  78650. UNUSED_PARAMETER(size);
  78651. pChunk = p->pFirst;
  78652. while( pChunk ){
  78653. FileChunk *pTmp = pChunk;
  78654. pChunk = pChunk->pNext;
  78655. sqlite3_free(pTmp);
  78656. }
  78657. sqlite3MemJournalOpen(pJfd);
  78658. return SQLITE_OK;
  78659. }
  78660. /*
  78661. ** Close the file.
  78662. */
  78663. static int memjrnlClose(sqlite3_file *pJfd){
  78664. memjrnlTruncate(pJfd, 0);
  78665. return SQLITE_OK;
  78666. }
  78667. /*
  78668. ** Sync the file.
  78669. **
  78670. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  78671. ** is never called in a working implementation. This implementation
  78672. ** exists purely as a contingency, in case some malfunction in some other
  78673. ** part of SQLite causes Sync to be called by mistake.
  78674. */
  78675. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  78676. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  78677. return SQLITE_OK;
  78678. }
  78679. /*
  78680. ** Query the size of the file in bytes.
  78681. */
  78682. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  78683. MemJournal *p = (MemJournal *)pJfd;
  78684. *pSize = (sqlite_int64) p->endpoint.iOffset;
  78685. return SQLITE_OK;
  78686. }
  78687. /*
  78688. ** Table of methods for MemJournal sqlite3_file object.
  78689. */
  78690. static const struct sqlite3_io_methods MemJournalMethods = {
  78691. 1, /* iVersion */
  78692. memjrnlClose, /* xClose */
  78693. memjrnlRead, /* xRead */
  78694. memjrnlWrite, /* xWrite */
  78695. memjrnlTruncate, /* xTruncate */
  78696. memjrnlSync, /* xSync */
  78697. memjrnlFileSize, /* xFileSize */
  78698. 0, /* xLock */
  78699. 0, /* xUnlock */
  78700. 0, /* xCheckReservedLock */
  78701. 0, /* xFileControl */
  78702. 0, /* xSectorSize */
  78703. 0, /* xDeviceCharacteristics */
  78704. 0, /* xShmMap */
  78705. 0, /* xShmLock */
  78706. 0, /* xShmBarrier */
  78707. 0, /* xShmUnmap */
  78708. 0, /* xFetch */
  78709. 0 /* xUnfetch */
  78710. };
  78711. /*
  78712. ** Open a journal file.
  78713. */
  78714. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  78715. MemJournal *p = (MemJournal *)pJfd;
  78716. assert( EIGHT_BYTE_ALIGNMENT(p) );
  78717. memset(p, 0, sqlite3MemJournalSize());
  78718. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  78719. }
  78720. /*
  78721. ** Return true if the file-handle passed as an argument is
  78722. ** an in-memory journal
  78723. */
  78724. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  78725. return pJfd->pMethods==&MemJournalMethods;
  78726. }
  78727. /*
  78728. ** Return the number of bytes required to store a MemJournal file descriptor.
  78729. */
  78730. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  78731. return sizeof(MemJournal);
  78732. }
  78733. /************** End of memjournal.c ******************************************/
  78734. /************** Begin file walker.c ******************************************/
  78735. /*
  78736. ** 2008 August 16
  78737. **
  78738. ** The author disclaims copyright to this source code. In place of
  78739. ** a legal notice, here is a blessing:
  78740. **
  78741. ** May you do good and not evil.
  78742. ** May you find forgiveness for yourself and forgive others.
  78743. ** May you share freely, never taking more than you give.
  78744. **
  78745. *************************************************************************
  78746. ** This file contains routines used for walking the parser tree for
  78747. ** an SQL statement.
  78748. */
  78749. /* #include "sqliteInt.h" */
  78750. /* #include <stdlib.h> */
  78751. /* #include <string.h> */
  78752. /*
  78753. ** Walk an expression tree. Invoke the callback once for each node
  78754. ** of the expression, while descending. (In other words, the callback
  78755. ** is invoked before visiting children.)
  78756. **
  78757. ** The return value from the callback should be one of the WRC_*
  78758. ** constants to specify how to proceed with the walk.
  78759. **
  78760. ** WRC_Continue Continue descending down the tree.
  78761. **
  78762. ** WRC_Prune Do not descend into child nodes. But allow
  78763. ** the walk to continue with sibling nodes.
  78764. **
  78765. ** WRC_Abort Do no more callbacks. Unwind the stack and
  78766. ** return the top-level walk call.
  78767. **
  78768. ** The return value from this routine is WRC_Abort to abandon the tree walk
  78769. ** and WRC_Continue to continue.
  78770. */
  78771. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  78772. int rc;
  78773. if( pExpr==0 ) return WRC_Continue;
  78774. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  78775. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  78776. rc = pWalker->xExprCallback(pWalker, pExpr);
  78777. if( rc==WRC_Continue
  78778. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  78779. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  78780. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  78781. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  78782. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  78783. }else{
  78784. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  78785. }
  78786. }
  78787. return rc & WRC_Abort;
  78788. }
  78789. /*
  78790. ** Call sqlite3WalkExpr() for every expression in list p or until
  78791. ** an abort request is seen.
  78792. */
  78793. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  78794. int i;
  78795. struct ExprList_item *pItem;
  78796. if( p ){
  78797. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  78798. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  78799. }
  78800. }
  78801. return WRC_Continue;
  78802. }
  78803. /*
  78804. ** Walk all expressions associated with SELECT statement p. Do
  78805. ** not invoke the SELECT callback on p, but do (of course) invoke
  78806. ** any expr callbacks and SELECT callbacks that come from subqueries.
  78807. ** Return WRC_Abort or WRC_Continue.
  78808. */
  78809. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  78810. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  78811. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  78812. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  78813. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  78814. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  78815. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  78816. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  78817. return WRC_Continue;
  78818. }
  78819. /*
  78820. ** Walk the parse trees associated with all subqueries in the
  78821. ** FROM clause of SELECT statement p. Do not invoke the select
  78822. ** callback on p, but do invoke it on each FROM clause subquery
  78823. ** and on any subqueries further down in the tree. Return
  78824. ** WRC_Abort or WRC_Continue;
  78825. */
  78826. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  78827. SrcList *pSrc;
  78828. int i;
  78829. struct SrcList_item *pItem;
  78830. pSrc = p->pSrc;
  78831. if( ALWAYS(pSrc) ){
  78832. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  78833. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  78834. return WRC_Abort;
  78835. }
  78836. if( pItem->fg.isTabFunc
  78837. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  78838. ){
  78839. return WRC_Abort;
  78840. }
  78841. }
  78842. }
  78843. return WRC_Continue;
  78844. }
  78845. /*
  78846. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  78847. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  78848. ** on the compound select chain, p->pPrior.
  78849. **
  78850. ** If it is not NULL, the xSelectCallback() callback is invoked before
  78851. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  78852. ** method, if it is not NULL, is invoked following the walk of the
  78853. ** expressions and FROM clause.
  78854. **
  78855. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  78856. ** there is an abort request.
  78857. **
  78858. ** If the Walker does not have an xSelectCallback() then this routine
  78859. ** is a no-op returning WRC_Continue.
  78860. */
  78861. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  78862. int rc;
  78863. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  78864. return WRC_Continue;
  78865. }
  78866. rc = WRC_Continue;
  78867. pWalker->walkerDepth++;
  78868. while( p ){
  78869. if( pWalker->xSelectCallback ){
  78870. rc = pWalker->xSelectCallback(pWalker, p);
  78871. if( rc ) break;
  78872. }
  78873. if( sqlite3WalkSelectExpr(pWalker, p)
  78874. || sqlite3WalkSelectFrom(pWalker, p)
  78875. ){
  78876. pWalker->walkerDepth--;
  78877. return WRC_Abort;
  78878. }
  78879. if( pWalker->xSelectCallback2 ){
  78880. pWalker->xSelectCallback2(pWalker, p);
  78881. }
  78882. p = p->pPrior;
  78883. }
  78884. pWalker->walkerDepth--;
  78885. return rc & WRC_Abort;
  78886. }
  78887. /************** End of walker.c **********************************************/
  78888. /************** Begin file resolve.c *****************************************/
  78889. /*
  78890. ** 2008 August 18
  78891. **
  78892. ** The author disclaims copyright to this source code. In place of
  78893. ** a legal notice, here is a blessing:
  78894. **
  78895. ** May you do good and not evil.
  78896. ** May you find forgiveness for yourself and forgive others.
  78897. ** May you share freely, never taking more than you give.
  78898. **
  78899. *************************************************************************
  78900. **
  78901. ** This file contains routines used for walking the parser tree and
  78902. ** resolve all identifiers by associating them with a particular
  78903. ** table and column.
  78904. */
  78905. /* #include "sqliteInt.h" */
  78906. /* #include <stdlib.h> */
  78907. /* #include <string.h> */
  78908. /*
  78909. ** Walk the expression tree pExpr and increase the aggregate function
  78910. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  78911. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  78912. ** outer query into an inner subquery.
  78913. **
  78914. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  78915. ** is a helper function - a callback for the tree walker.
  78916. */
  78917. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  78918. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  78919. return WRC_Continue;
  78920. }
  78921. static void incrAggFunctionDepth(Expr *pExpr, int N){
  78922. if( N>0 ){
  78923. Walker w;
  78924. memset(&w, 0, sizeof(w));
  78925. w.xExprCallback = incrAggDepth;
  78926. w.u.n = N;
  78927. sqlite3WalkExpr(&w, pExpr);
  78928. }
  78929. }
  78930. /*
  78931. ** Turn the pExpr expression into an alias for the iCol-th column of the
  78932. ** result set in pEList.
  78933. **
  78934. ** If the reference is followed by a COLLATE operator, then make sure
  78935. ** the COLLATE operator is preserved. For example:
  78936. **
  78937. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  78938. **
  78939. ** Should be transformed into:
  78940. **
  78941. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  78942. **
  78943. ** The nSubquery parameter specifies how many levels of subquery the
  78944. ** alias is removed from the original expression. The usual value is
  78945. ** zero but it might be more if the alias is contained within a subquery
  78946. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  78947. ** structures must be increased by the nSubquery amount.
  78948. */
  78949. static void resolveAlias(
  78950. Parse *pParse, /* Parsing context */
  78951. ExprList *pEList, /* A result set */
  78952. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  78953. Expr *pExpr, /* Transform this into an alias to the result set */
  78954. const char *zType, /* "GROUP" or "ORDER" or "" */
  78955. int nSubquery /* Number of subqueries that the label is moving */
  78956. ){
  78957. Expr *pOrig; /* The iCol-th column of the result set */
  78958. Expr *pDup; /* Copy of pOrig */
  78959. sqlite3 *db; /* The database connection */
  78960. assert( iCol>=0 && iCol<pEList->nExpr );
  78961. pOrig = pEList->a[iCol].pExpr;
  78962. assert( pOrig!=0 );
  78963. db = pParse->db;
  78964. pDup = sqlite3ExprDup(db, pOrig, 0);
  78965. if( pDup==0 ) return;
  78966. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  78967. if( pExpr->op==TK_COLLATE ){
  78968. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  78969. }
  78970. ExprSetProperty(pDup, EP_Alias);
  78971. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  78972. ** prevents ExprDelete() from deleting the Expr structure itself,
  78973. ** allowing it to be repopulated by the memcpy() on the following line.
  78974. ** The pExpr->u.zToken might point into memory that will be freed by the
  78975. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  78976. ** make a copy of the token before doing the sqlite3DbFree().
  78977. */
  78978. ExprSetProperty(pExpr, EP_Static);
  78979. sqlite3ExprDelete(db, pExpr);
  78980. memcpy(pExpr, pDup, sizeof(*pExpr));
  78981. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  78982. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  78983. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  78984. pExpr->flags |= EP_MemToken;
  78985. }
  78986. sqlite3DbFree(db, pDup);
  78987. }
  78988. /*
  78989. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  78990. **
  78991. ** Return FALSE if the USING clause is NULL or if it does not contain
  78992. ** zCol.
  78993. */
  78994. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  78995. if( pUsing ){
  78996. int k;
  78997. for(k=0; k<pUsing->nId; k++){
  78998. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  78999. }
  79000. }
  79001. return 0;
  79002. }
  79003. /*
  79004. ** Subqueries stores the original database, table and column names for their
  79005. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  79006. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  79007. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  79008. ** match anything.
  79009. */
  79010. SQLITE_PRIVATE int sqlite3MatchSpanName(
  79011. const char *zSpan,
  79012. const char *zCol,
  79013. const char *zTab,
  79014. const char *zDb
  79015. ){
  79016. int n;
  79017. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  79018. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  79019. return 0;
  79020. }
  79021. zSpan += n+1;
  79022. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  79023. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  79024. return 0;
  79025. }
  79026. zSpan += n+1;
  79027. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  79028. return 0;
  79029. }
  79030. return 1;
  79031. }
  79032. /*
  79033. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  79034. ** that name in the set of source tables in pSrcList and make the pExpr
  79035. ** expression node refer back to that source column. The following changes
  79036. ** are made to pExpr:
  79037. **
  79038. ** pExpr->iDb Set the index in db->aDb[] of the database X
  79039. ** (even if X is implied).
  79040. ** pExpr->iTable Set to the cursor number for the table obtained
  79041. ** from pSrcList.
  79042. ** pExpr->pTab Points to the Table structure of X.Y (even if
  79043. ** X and/or Y are implied.)
  79044. ** pExpr->iColumn Set to the column number within the table.
  79045. ** pExpr->op Set to TK_COLUMN.
  79046. ** pExpr->pLeft Any expression this points to is deleted
  79047. ** pExpr->pRight Any expression this points to is deleted.
  79048. **
  79049. ** The zDb variable is the name of the database (the "X"). This value may be
  79050. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  79051. ** can be used. The zTable variable is the name of the table (the "Y"). This
  79052. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  79053. ** means that the form of the name is Z and that columns from any table
  79054. ** can be used.
  79055. **
  79056. ** If the name cannot be resolved unambiguously, leave an error message
  79057. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  79058. */
  79059. static int lookupName(
  79060. Parse *pParse, /* The parsing context */
  79061. const char *zDb, /* Name of the database containing table, or NULL */
  79062. const char *zTab, /* Name of table containing column, or NULL */
  79063. const char *zCol, /* Name of the column. */
  79064. NameContext *pNC, /* The name context used to resolve the name */
  79065. Expr *pExpr /* Make this EXPR node point to the selected column */
  79066. ){
  79067. int i, j; /* Loop counters */
  79068. int cnt = 0; /* Number of matching column names */
  79069. int cntTab = 0; /* Number of matching table names */
  79070. int nSubquery = 0; /* How many levels of subquery */
  79071. sqlite3 *db = pParse->db; /* The database connection */
  79072. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  79073. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  79074. NameContext *pTopNC = pNC; /* First namecontext in the list */
  79075. Schema *pSchema = 0; /* Schema of the expression */
  79076. int isTrigger = 0; /* True if resolved to a trigger column */
  79077. Table *pTab = 0; /* Table hold the row */
  79078. Column *pCol; /* A column of pTab */
  79079. assert( pNC ); /* the name context cannot be NULL. */
  79080. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  79081. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  79082. /* Initialize the node to no-match */
  79083. pExpr->iTable = -1;
  79084. pExpr->pTab = 0;
  79085. ExprSetVVAProperty(pExpr, EP_NoReduce);
  79086. /* Translate the schema name in zDb into a pointer to the corresponding
  79087. ** schema. If not found, pSchema will remain NULL and nothing will match
  79088. ** resulting in an appropriate error message toward the end of this routine
  79089. */
  79090. if( zDb ){
  79091. testcase( pNC->ncFlags & NC_PartIdx );
  79092. testcase( pNC->ncFlags & NC_IsCheck );
  79093. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  79094. /* Silently ignore database qualifiers inside CHECK constraints and
  79095. ** partial indices. Do not raise errors because that might break
  79096. ** legacy and because it does not hurt anything to just ignore the
  79097. ** database name. */
  79098. zDb = 0;
  79099. }else{
  79100. for(i=0; i<db->nDb; i++){
  79101. assert( db->aDb[i].zName );
  79102. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  79103. pSchema = db->aDb[i].pSchema;
  79104. break;
  79105. }
  79106. }
  79107. }
  79108. }
  79109. /* Start at the inner-most context and move outward until a match is found */
  79110. while( pNC && cnt==0 ){
  79111. ExprList *pEList;
  79112. SrcList *pSrcList = pNC->pSrcList;
  79113. if( pSrcList ){
  79114. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  79115. pTab = pItem->pTab;
  79116. assert( pTab!=0 && pTab->zName!=0 );
  79117. assert( pTab->nCol>0 );
  79118. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  79119. int hit = 0;
  79120. pEList = pItem->pSelect->pEList;
  79121. for(j=0; j<pEList->nExpr; j++){
  79122. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  79123. cnt++;
  79124. cntTab = 2;
  79125. pMatch = pItem;
  79126. pExpr->iColumn = j;
  79127. hit = 1;
  79128. }
  79129. }
  79130. if( hit || zTab==0 ) continue;
  79131. }
  79132. if( zDb && pTab->pSchema!=pSchema ){
  79133. continue;
  79134. }
  79135. if( zTab ){
  79136. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  79137. assert( zTabName!=0 );
  79138. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  79139. continue;
  79140. }
  79141. }
  79142. if( 0==(cntTab++) ){
  79143. pMatch = pItem;
  79144. }
  79145. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  79146. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  79147. /* If there has been exactly one prior match and this match
  79148. ** is for the right-hand table of a NATURAL JOIN or is in a
  79149. ** USING clause, then skip this match.
  79150. */
  79151. if( cnt==1 ){
  79152. if( pItem->fg.jointype & JT_NATURAL ) continue;
  79153. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  79154. }
  79155. cnt++;
  79156. pMatch = pItem;
  79157. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  79158. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  79159. break;
  79160. }
  79161. }
  79162. }
  79163. if( pMatch ){
  79164. pExpr->iTable = pMatch->iCursor;
  79165. pExpr->pTab = pMatch->pTab;
  79166. /* RIGHT JOIN not (yet) supported */
  79167. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  79168. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  79169. ExprSetProperty(pExpr, EP_CanBeNull);
  79170. }
  79171. pSchema = pExpr->pTab->pSchema;
  79172. }
  79173. } /* if( pSrcList ) */
  79174. #ifndef SQLITE_OMIT_TRIGGER
  79175. /* If we have not already resolved the name, then maybe
  79176. ** it is a new.* or old.* trigger argument reference
  79177. */
  79178. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  79179. int op = pParse->eTriggerOp;
  79180. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  79181. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  79182. pExpr->iTable = 1;
  79183. pTab = pParse->pTriggerTab;
  79184. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  79185. pExpr->iTable = 0;
  79186. pTab = pParse->pTriggerTab;
  79187. }else{
  79188. pTab = 0;
  79189. }
  79190. if( pTab ){
  79191. int iCol;
  79192. pSchema = pTab->pSchema;
  79193. cntTab++;
  79194. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  79195. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  79196. if( iCol==pTab->iPKey ){
  79197. iCol = -1;
  79198. }
  79199. break;
  79200. }
  79201. }
  79202. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  79203. /* IMP: R-51414-32910 */
  79204. iCol = -1;
  79205. }
  79206. if( iCol<pTab->nCol ){
  79207. cnt++;
  79208. if( iCol<0 ){
  79209. pExpr->affinity = SQLITE_AFF_INTEGER;
  79210. }else if( pExpr->iTable==0 ){
  79211. testcase( iCol==31 );
  79212. testcase( iCol==32 );
  79213. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  79214. }else{
  79215. testcase( iCol==31 );
  79216. testcase( iCol==32 );
  79217. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  79218. }
  79219. pExpr->iColumn = (i16)iCol;
  79220. pExpr->pTab = pTab;
  79221. isTrigger = 1;
  79222. }
  79223. }
  79224. }
  79225. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  79226. /*
  79227. ** Perhaps the name is a reference to the ROWID
  79228. */
  79229. if( cnt==0
  79230. && cntTab==1
  79231. && pMatch
  79232. && (pNC->ncFlags & NC_IdxExpr)==0
  79233. && sqlite3IsRowid(zCol)
  79234. && VisibleRowid(pMatch->pTab)
  79235. ){
  79236. cnt = 1;
  79237. pExpr->iColumn = -1;
  79238. pExpr->affinity = SQLITE_AFF_INTEGER;
  79239. }
  79240. /*
  79241. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  79242. ** might refer to an result-set alias. This happens, for example, when
  79243. ** we are resolving names in the WHERE clause of the following command:
  79244. **
  79245. ** SELECT a+b AS x FROM table WHERE x<10;
  79246. **
  79247. ** In cases like this, replace pExpr with a copy of the expression that
  79248. ** forms the result set entry ("a+b" in the example) and return immediately.
  79249. ** Note that the expression in the result set should have already been
  79250. ** resolved by the time the WHERE clause is resolved.
  79251. **
  79252. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  79253. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  79254. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  79255. ** is supported for backwards compatibility only. Hence, we issue a warning
  79256. ** on sqlite3_log() whenever the capability is used.
  79257. */
  79258. if( (pEList = pNC->pEList)!=0
  79259. && zTab==0
  79260. && cnt==0
  79261. ){
  79262. for(j=0; j<pEList->nExpr; j++){
  79263. char *zAs = pEList->a[j].zName;
  79264. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  79265. Expr *pOrig;
  79266. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  79267. assert( pExpr->x.pList==0 );
  79268. assert( pExpr->x.pSelect==0 );
  79269. pOrig = pEList->a[j].pExpr;
  79270. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  79271. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  79272. return WRC_Abort;
  79273. }
  79274. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  79275. cnt = 1;
  79276. pMatch = 0;
  79277. assert( zTab==0 && zDb==0 );
  79278. goto lookupname_end;
  79279. }
  79280. }
  79281. }
  79282. /* Advance to the next name context. The loop will exit when either
  79283. ** we have a match (cnt>0) or when we run out of name contexts.
  79284. */
  79285. if( cnt==0 ){
  79286. pNC = pNC->pNext;
  79287. nSubquery++;
  79288. }
  79289. }
  79290. /*
  79291. ** If X and Y are NULL (in other words if only the column name Z is
  79292. ** supplied) and the value of Z is enclosed in double-quotes, then
  79293. ** Z is a string literal if it doesn't match any column names. In that
  79294. ** case, we need to return right away and not make any changes to
  79295. ** pExpr.
  79296. **
  79297. ** Because no reference was made to outer contexts, the pNC->nRef
  79298. ** fields are not changed in any context.
  79299. */
  79300. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  79301. pExpr->op = TK_STRING;
  79302. pExpr->pTab = 0;
  79303. return WRC_Prune;
  79304. }
  79305. /*
  79306. ** cnt==0 means there was not match. cnt>1 means there were two or
  79307. ** more matches. Either way, we have an error.
  79308. */
  79309. if( cnt!=1 ){
  79310. const char *zErr;
  79311. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  79312. if( zDb ){
  79313. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  79314. }else if( zTab ){
  79315. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  79316. }else{
  79317. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  79318. }
  79319. pParse->checkSchema = 1;
  79320. pTopNC->nErr++;
  79321. }
  79322. /* If a column from a table in pSrcList is referenced, then record
  79323. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  79324. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  79325. ** column number is greater than the number of bits in the bitmask
  79326. ** then set the high-order bit of the bitmask.
  79327. */
  79328. if( pExpr->iColumn>=0 && pMatch!=0 ){
  79329. int n = pExpr->iColumn;
  79330. testcase( n==BMS-1 );
  79331. if( n>=BMS ){
  79332. n = BMS-1;
  79333. }
  79334. assert( pMatch->iCursor==pExpr->iTable );
  79335. pMatch->colUsed |= ((Bitmask)1)<<n;
  79336. }
  79337. /* Clean up and return
  79338. */
  79339. sqlite3ExprDelete(db, pExpr->pLeft);
  79340. pExpr->pLeft = 0;
  79341. sqlite3ExprDelete(db, pExpr->pRight);
  79342. pExpr->pRight = 0;
  79343. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  79344. lookupname_end:
  79345. if( cnt==1 ){
  79346. assert( pNC!=0 );
  79347. if( !ExprHasProperty(pExpr, EP_Alias) ){
  79348. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  79349. }
  79350. /* Increment the nRef value on all name contexts from TopNC up to
  79351. ** the point where the name matched. */
  79352. for(;;){
  79353. assert( pTopNC!=0 );
  79354. pTopNC->nRef++;
  79355. if( pTopNC==pNC ) break;
  79356. pTopNC = pTopNC->pNext;
  79357. }
  79358. return WRC_Prune;
  79359. } else {
  79360. return WRC_Abort;
  79361. }
  79362. }
  79363. /*
  79364. ** Allocate and return a pointer to an expression to load the column iCol
  79365. ** from datasource iSrc in SrcList pSrc.
  79366. */
  79367. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  79368. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  79369. if( p ){
  79370. struct SrcList_item *pItem = &pSrc->a[iSrc];
  79371. p->pTab = pItem->pTab;
  79372. p->iTable = pItem->iCursor;
  79373. if( p->pTab->iPKey==iCol ){
  79374. p->iColumn = -1;
  79375. }else{
  79376. p->iColumn = (ynVar)iCol;
  79377. testcase( iCol==BMS );
  79378. testcase( iCol==BMS-1 );
  79379. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  79380. }
  79381. ExprSetProperty(p, EP_Resolved);
  79382. }
  79383. return p;
  79384. }
  79385. /*
  79386. ** Report an error that an expression is not valid for some set of
  79387. ** pNC->ncFlags values determined by validMask.
  79388. */
  79389. static void notValid(
  79390. Parse *pParse, /* Leave error message here */
  79391. NameContext *pNC, /* The name context */
  79392. const char *zMsg, /* Type of error */
  79393. int validMask /* Set of contexts for which prohibited */
  79394. ){
  79395. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  79396. if( (pNC->ncFlags & validMask)!=0 ){
  79397. const char *zIn = "partial index WHERE clauses";
  79398. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  79399. #ifndef SQLITE_OMIT_CHECK
  79400. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  79401. #endif
  79402. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  79403. }
  79404. }
  79405. /*
  79406. ** Expression p should encode a floating point value between 1.0 and 0.0.
  79407. ** Return 1024 times this value. Or return -1 if p is not a floating point
  79408. ** value between 1.0 and 0.0.
  79409. */
  79410. static int exprProbability(Expr *p){
  79411. double r = -1.0;
  79412. if( p->op!=TK_FLOAT ) return -1;
  79413. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  79414. assert( r>=0.0 );
  79415. if( r>1.0 ) return -1;
  79416. return (int)(r*134217728.0);
  79417. }
  79418. /*
  79419. ** This routine is callback for sqlite3WalkExpr().
  79420. **
  79421. ** Resolve symbolic names into TK_COLUMN operators for the current
  79422. ** node in the expression tree. Return 0 to continue the search down
  79423. ** the tree or 2 to abort the tree walk.
  79424. **
  79425. ** This routine also does error checking and name resolution for
  79426. ** function names. The operator for aggregate functions is changed
  79427. ** to TK_AGG_FUNCTION.
  79428. */
  79429. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  79430. NameContext *pNC;
  79431. Parse *pParse;
  79432. pNC = pWalker->u.pNC;
  79433. assert( pNC!=0 );
  79434. pParse = pNC->pParse;
  79435. assert( pParse==pWalker->pParse );
  79436. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  79437. ExprSetProperty(pExpr, EP_Resolved);
  79438. #ifndef NDEBUG
  79439. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  79440. SrcList *pSrcList = pNC->pSrcList;
  79441. int i;
  79442. for(i=0; i<pNC->pSrcList->nSrc; i++){
  79443. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  79444. }
  79445. }
  79446. #endif
  79447. switch( pExpr->op ){
  79448. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  79449. /* The special operator TK_ROW means use the rowid for the first
  79450. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  79451. ** clause processing on UPDATE and DELETE statements.
  79452. */
  79453. case TK_ROW: {
  79454. SrcList *pSrcList = pNC->pSrcList;
  79455. struct SrcList_item *pItem;
  79456. assert( pSrcList && pSrcList->nSrc==1 );
  79457. pItem = pSrcList->a;
  79458. pExpr->op = TK_COLUMN;
  79459. pExpr->pTab = pItem->pTab;
  79460. pExpr->iTable = pItem->iCursor;
  79461. pExpr->iColumn = -1;
  79462. pExpr->affinity = SQLITE_AFF_INTEGER;
  79463. break;
  79464. }
  79465. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  79466. && !defined(SQLITE_OMIT_SUBQUERY) */
  79467. /* A lone identifier is the name of a column.
  79468. */
  79469. case TK_ID: {
  79470. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  79471. }
  79472. /* A table name and column name: ID.ID
  79473. ** Or a database, table and column: ID.ID.ID
  79474. */
  79475. case TK_DOT: {
  79476. const char *zColumn;
  79477. const char *zTable;
  79478. const char *zDb;
  79479. Expr *pRight;
  79480. /* if( pSrcList==0 ) break; */
  79481. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  79482. /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
  79483. pRight = pExpr->pRight;
  79484. if( pRight->op==TK_ID ){
  79485. zDb = 0;
  79486. zTable = pExpr->pLeft->u.zToken;
  79487. zColumn = pRight->u.zToken;
  79488. }else{
  79489. assert( pRight->op==TK_DOT );
  79490. zDb = pExpr->pLeft->u.zToken;
  79491. zTable = pRight->pLeft->u.zToken;
  79492. zColumn = pRight->pRight->u.zToken;
  79493. }
  79494. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  79495. }
  79496. /* Resolve function names
  79497. */
  79498. case TK_FUNCTION: {
  79499. ExprList *pList = pExpr->x.pList; /* The argument list */
  79500. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  79501. int no_such_func = 0; /* True if no such function exists */
  79502. int wrong_num_args = 0; /* True if wrong number of arguments */
  79503. int is_agg = 0; /* True if is an aggregate function */
  79504. int auth; /* Authorization to use the function */
  79505. int nId; /* Number of characters in function name */
  79506. const char *zId; /* The function name. */
  79507. FuncDef *pDef; /* Information about the function */
  79508. u8 enc = ENC(pParse->db); /* The database encoding */
  79509. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  79510. notValid(pParse, pNC, "functions", NC_PartIdx);
  79511. zId = pExpr->u.zToken;
  79512. nId = sqlite3Strlen30(zId);
  79513. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  79514. if( pDef==0 ){
  79515. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  79516. if( pDef==0 ){
  79517. no_such_func = 1;
  79518. }else{
  79519. wrong_num_args = 1;
  79520. }
  79521. }else{
  79522. is_agg = pDef->xFunc==0;
  79523. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  79524. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  79525. if( n==2 ){
  79526. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  79527. if( pExpr->iTable<0 ){
  79528. sqlite3ErrorMsg(pParse,
  79529. "second argument to likelihood() must be a "
  79530. "constant between 0.0 and 1.0");
  79531. pNC->nErr++;
  79532. }
  79533. }else{
  79534. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  79535. ** equivalent to likelihood(X, 0.0625).
  79536. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  79537. ** short-hand for likelihood(X,0.0625).
  79538. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  79539. ** for likelihood(X,0.9375).
  79540. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  79541. ** to likelihood(X,0.9375). */
  79542. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  79543. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  79544. }
  79545. }
  79546. #ifndef SQLITE_OMIT_AUTHORIZATION
  79547. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  79548. if( auth!=SQLITE_OK ){
  79549. if( auth==SQLITE_DENY ){
  79550. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  79551. pDef->zName);
  79552. pNC->nErr++;
  79553. }
  79554. pExpr->op = TK_NULL;
  79555. return WRC_Prune;
  79556. }
  79557. #endif
  79558. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  79559. /* For the purposes of the EP_ConstFunc flag, date and time
  79560. ** functions and other functions that change slowly are considered
  79561. ** constant because they are constant for the duration of one query */
  79562. ExprSetProperty(pExpr,EP_ConstFunc);
  79563. }
  79564. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  79565. /* Date/time functions that use 'now', and other functions like
  79566. ** sqlite_version() that might change over time cannot be used
  79567. ** in an index. */
  79568. notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
  79569. }
  79570. }
  79571. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  79572. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  79573. pNC->nErr++;
  79574. is_agg = 0;
  79575. }else if( no_such_func && pParse->db->init.busy==0 ){
  79576. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  79577. pNC->nErr++;
  79578. }else if( wrong_num_args ){
  79579. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  79580. nId, zId);
  79581. pNC->nErr++;
  79582. }
  79583. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  79584. sqlite3WalkExprList(pWalker, pList);
  79585. if( is_agg ){
  79586. NameContext *pNC2 = pNC;
  79587. pExpr->op = TK_AGG_FUNCTION;
  79588. pExpr->op2 = 0;
  79589. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  79590. pExpr->op2++;
  79591. pNC2 = pNC2->pNext;
  79592. }
  79593. assert( pDef!=0 );
  79594. if( pNC2 ){
  79595. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  79596. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  79597. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  79598. }
  79599. pNC->ncFlags |= NC_AllowAgg;
  79600. }
  79601. /* FIX ME: Compute pExpr->affinity based on the expected return
  79602. ** type of the function
  79603. */
  79604. return WRC_Prune;
  79605. }
  79606. #ifndef SQLITE_OMIT_SUBQUERY
  79607. case TK_SELECT:
  79608. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  79609. #endif
  79610. case TK_IN: {
  79611. testcase( pExpr->op==TK_IN );
  79612. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  79613. int nRef = pNC->nRef;
  79614. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  79615. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  79616. assert( pNC->nRef>=nRef );
  79617. if( nRef!=pNC->nRef ){
  79618. ExprSetProperty(pExpr, EP_VarSelect);
  79619. }
  79620. }
  79621. break;
  79622. }
  79623. case TK_VARIABLE: {
  79624. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  79625. break;
  79626. }
  79627. }
  79628. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  79629. }
  79630. /*
  79631. ** pEList is a list of expressions which are really the result set of the
  79632. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  79633. ** This routine checks to see if pE is a simple identifier which corresponds
  79634. ** to the AS-name of one of the terms of the expression list. If it is,
  79635. ** this routine return an integer between 1 and N where N is the number of
  79636. ** elements in pEList, corresponding to the matching entry. If there is
  79637. ** no match, or if pE is not a simple identifier, then this routine
  79638. ** return 0.
  79639. **
  79640. ** pEList has been resolved. pE has not.
  79641. */
  79642. static int resolveAsName(
  79643. Parse *pParse, /* Parsing context for error messages */
  79644. ExprList *pEList, /* List of expressions to scan */
  79645. Expr *pE /* Expression we are trying to match */
  79646. ){
  79647. int i; /* Loop counter */
  79648. UNUSED_PARAMETER(pParse);
  79649. if( pE->op==TK_ID ){
  79650. char *zCol = pE->u.zToken;
  79651. for(i=0; i<pEList->nExpr; i++){
  79652. char *zAs = pEList->a[i].zName;
  79653. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  79654. return i+1;
  79655. }
  79656. }
  79657. }
  79658. return 0;
  79659. }
  79660. /*
  79661. ** pE is a pointer to an expression which is a single term in the
  79662. ** ORDER BY of a compound SELECT. The expression has not been
  79663. ** name resolved.
  79664. **
  79665. ** At the point this routine is called, we already know that the
  79666. ** ORDER BY term is not an integer index into the result set. That
  79667. ** case is handled by the calling routine.
  79668. **
  79669. ** Attempt to match pE against result set columns in the left-most
  79670. ** SELECT statement. Return the index i of the matching column,
  79671. ** as an indication to the caller that it should sort by the i-th column.
  79672. ** The left-most column is 1. In other words, the value returned is the
  79673. ** same integer value that would be used in the SQL statement to indicate
  79674. ** the column.
  79675. **
  79676. ** If there is no match, return 0. Return -1 if an error occurs.
  79677. */
  79678. static int resolveOrderByTermToExprList(
  79679. Parse *pParse, /* Parsing context for error messages */
  79680. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  79681. Expr *pE /* The specific ORDER BY term */
  79682. ){
  79683. int i; /* Loop counter */
  79684. ExprList *pEList; /* The columns of the result set */
  79685. NameContext nc; /* Name context for resolving pE */
  79686. sqlite3 *db; /* Database connection */
  79687. int rc; /* Return code from subprocedures */
  79688. u8 savedSuppErr; /* Saved value of db->suppressErr */
  79689. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  79690. pEList = pSelect->pEList;
  79691. /* Resolve all names in the ORDER BY term expression
  79692. */
  79693. memset(&nc, 0, sizeof(nc));
  79694. nc.pParse = pParse;
  79695. nc.pSrcList = pSelect->pSrc;
  79696. nc.pEList = pEList;
  79697. nc.ncFlags = NC_AllowAgg;
  79698. nc.nErr = 0;
  79699. db = pParse->db;
  79700. savedSuppErr = db->suppressErr;
  79701. db->suppressErr = 1;
  79702. rc = sqlite3ResolveExprNames(&nc, pE);
  79703. db->suppressErr = savedSuppErr;
  79704. if( rc ) return 0;
  79705. /* Try to match the ORDER BY expression against an expression
  79706. ** in the result set. Return an 1-based index of the matching
  79707. ** result-set entry.
  79708. */
  79709. for(i=0; i<pEList->nExpr; i++){
  79710. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  79711. return i+1;
  79712. }
  79713. }
  79714. /* If no match, return 0. */
  79715. return 0;
  79716. }
  79717. /*
  79718. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  79719. */
  79720. static void resolveOutOfRangeError(
  79721. Parse *pParse, /* The error context into which to write the error */
  79722. const char *zType, /* "ORDER" or "GROUP" */
  79723. int i, /* The index (1-based) of the term out of range */
  79724. int mx /* Largest permissible value of i */
  79725. ){
  79726. sqlite3ErrorMsg(pParse,
  79727. "%r %s BY term out of range - should be "
  79728. "between 1 and %d", i, zType, mx);
  79729. }
  79730. /*
  79731. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  79732. ** each term of the ORDER BY clause is a constant integer between 1
  79733. ** and N where N is the number of columns in the compound SELECT.
  79734. **
  79735. ** ORDER BY terms that are already an integer between 1 and N are
  79736. ** unmodified. ORDER BY terms that are integers outside the range of
  79737. ** 1 through N generate an error. ORDER BY terms that are expressions
  79738. ** are matched against result set expressions of compound SELECT
  79739. ** beginning with the left-most SELECT and working toward the right.
  79740. ** At the first match, the ORDER BY expression is transformed into
  79741. ** the integer column number.
  79742. **
  79743. ** Return the number of errors seen.
  79744. */
  79745. static int resolveCompoundOrderBy(
  79746. Parse *pParse, /* Parsing context. Leave error messages here */
  79747. Select *pSelect /* The SELECT statement containing the ORDER BY */
  79748. ){
  79749. int i;
  79750. ExprList *pOrderBy;
  79751. ExprList *pEList;
  79752. sqlite3 *db;
  79753. int moreToDo = 1;
  79754. pOrderBy = pSelect->pOrderBy;
  79755. if( pOrderBy==0 ) return 0;
  79756. db = pParse->db;
  79757. #if SQLITE_MAX_COLUMN
  79758. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  79759. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  79760. return 1;
  79761. }
  79762. #endif
  79763. for(i=0; i<pOrderBy->nExpr; i++){
  79764. pOrderBy->a[i].done = 0;
  79765. }
  79766. pSelect->pNext = 0;
  79767. while( pSelect->pPrior ){
  79768. pSelect->pPrior->pNext = pSelect;
  79769. pSelect = pSelect->pPrior;
  79770. }
  79771. while( pSelect && moreToDo ){
  79772. struct ExprList_item *pItem;
  79773. moreToDo = 0;
  79774. pEList = pSelect->pEList;
  79775. assert( pEList!=0 );
  79776. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  79777. int iCol = -1;
  79778. Expr *pE, *pDup;
  79779. if( pItem->done ) continue;
  79780. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  79781. if( sqlite3ExprIsInteger(pE, &iCol) ){
  79782. if( iCol<=0 || iCol>pEList->nExpr ){
  79783. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  79784. return 1;
  79785. }
  79786. }else{
  79787. iCol = resolveAsName(pParse, pEList, pE);
  79788. if( iCol==0 ){
  79789. pDup = sqlite3ExprDup(db, pE, 0);
  79790. if( !db->mallocFailed ){
  79791. assert(pDup);
  79792. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  79793. }
  79794. sqlite3ExprDelete(db, pDup);
  79795. }
  79796. }
  79797. if( iCol>0 ){
  79798. /* Convert the ORDER BY term into an integer column number iCol,
  79799. ** taking care to preserve the COLLATE clause if it exists */
  79800. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  79801. if( pNew==0 ) return 1;
  79802. pNew->flags |= EP_IntValue;
  79803. pNew->u.iValue = iCol;
  79804. if( pItem->pExpr==pE ){
  79805. pItem->pExpr = pNew;
  79806. }else{
  79807. Expr *pParent = pItem->pExpr;
  79808. assert( pParent->op==TK_COLLATE );
  79809. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  79810. assert( pParent->pLeft==pE );
  79811. pParent->pLeft = pNew;
  79812. }
  79813. sqlite3ExprDelete(db, pE);
  79814. pItem->u.x.iOrderByCol = (u16)iCol;
  79815. pItem->done = 1;
  79816. }else{
  79817. moreToDo = 1;
  79818. }
  79819. }
  79820. pSelect = pSelect->pNext;
  79821. }
  79822. for(i=0; i<pOrderBy->nExpr; i++){
  79823. if( pOrderBy->a[i].done==0 ){
  79824. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  79825. "column in the result set", i+1);
  79826. return 1;
  79827. }
  79828. }
  79829. return 0;
  79830. }
  79831. /*
  79832. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  79833. ** the SELECT statement pSelect. If any term is reference to a
  79834. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  79835. ** field) then convert that term into a copy of the corresponding result set
  79836. ** column.
  79837. **
  79838. ** If any errors are detected, add an error message to pParse and
  79839. ** return non-zero. Return zero if no errors are seen.
  79840. */
  79841. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  79842. Parse *pParse, /* Parsing context. Leave error messages here */
  79843. Select *pSelect, /* The SELECT statement containing the clause */
  79844. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  79845. const char *zType /* "ORDER" or "GROUP" */
  79846. ){
  79847. int i;
  79848. sqlite3 *db = pParse->db;
  79849. ExprList *pEList;
  79850. struct ExprList_item *pItem;
  79851. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  79852. #if SQLITE_MAX_COLUMN
  79853. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  79854. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  79855. return 1;
  79856. }
  79857. #endif
  79858. pEList = pSelect->pEList;
  79859. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  79860. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  79861. if( pItem->u.x.iOrderByCol ){
  79862. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  79863. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  79864. return 1;
  79865. }
  79866. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  79867. zType,0);
  79868. }
  79869. }
  79870. return 0;
  79871. }
  79872. /*
  79873. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  79874. ** The Name context of the SELECT statement is pNC. zType is either
  79875. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  79876. **
  79877. ** This routine resolves each term of the clause into an expression.
  79878. ** If the order-by term is an integer I between 1 and N (where N is the
  79879. ** number of columns in the result set of the SELECT) then the expression
  79880. ** in the resolution is a copy of the I-th result-set expression. If
  79881. ** the order-by term is an identifier that corresponds to the AS-name of
  79882. ** a result-set expression, then the term resolves to a copy of the
  79883. ** result-set expression. Otherwise, the expression is resolved in
  79884. ** the usual way - using sqlite3ResolveExprNames().
  79885. **
  79886. ** This routine returns the number of errors. If errors occur, then
  79887. ** an appropriate error message might be left in pParse. (OOM errors
  79888. ** excepted.)
  79889. */
  79890. static int resolveOrderGroupBy(
  79891. NameContext *pNC, /* The name context of the SELECT statement */
  79892. Select *pSelect, /* The SELECT statement holding pOrderBy */
  79893. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  79894. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  79895. ){
  79896. int i, j; /* Loop counters */
  79897. int iCol; /* Column number */
  79898. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  79899. Parse *pParse; /* Parsing context */
  79900. int nResult; /* Number of terms in the result set */
  79901. if( pOrderBy==0 ) return 0;
  79902. nResult = pSelect->pEList->nExpr;
  79903. pParse = pNC->pParse;
  79904. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  79905. Expr *pE = pItem->pExpr;
  79906. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  79907. if( zType[0]!='G' ){
  79908. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  79909. if( iCol>0 ){
  79910. /* If an AS-name match is found, mark this ORDER BY column as being
  79911. ** a copy of the iCol-th result-set column. The subsequent call to
  79912. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  79913. ** copy of the iCol-th result-set expression. */
  79914. pItem->u.x.iOrderByCol = (u16)iCol;
  79915. continue;
  79916. }
  79917. }
  79918. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  79919. /* The ORDER BY term is an integer constant. Again, set the column
  79920. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  79921. ** order-by term to a copy of the result-set expression */
  79922. if( iCol<1 || iCol>0xffff ){
  79923. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  79924. return 1;
  79925. }
  79926. pItem->u.x.iOrderByCol = (u16)iCol;
  79927. continue;
  79928. }
  79929. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  79930. pItem->u.x.iOrderByCol = 0;
  79931. if( sqlite3ResolveExprNames(pNC, pE) ){
  79932. return 1;
  79933. }
  79934. for(j=0; j<pSelect->pEList->nExpr; j++){
  79935. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  79936. pItem->u.x.iOrderByCol = j+1;
  79937. }
  79938. }
  79939. }
  79940. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  79941. }
  79942. /*
  79943. ** Resolve names in the SELECT statement p and all of its descendants.
  79944. */
  79945. static int resolveSelectStep(Walker *pWalker, Select *p){
  79946. NameContext *pOuterNC; /* Context that contains this SELECT */
  79947. NameContext sNC; /* Name context of this SELECT */
  79948. int isCompound; /* True if p is a compound select */
  79949. int nCompound; /* Number of compound terms processed so far */
  79950. Parse *pParse; /* Parsing context */
  79951. int i; /* Loop counter */
  79952. ExprList *pGroupBy; /* The GROUP BY clause */
  79953. Select *pLeftmost; /* Left-most of SELECT of a compound */
  79954. sqlite3 *db; /* Database connection */
  79955. assert( p!=0 );
  79956. if( p->selFlags & SF_Resolved ){
  79957. return WRC_Prune;
  79958. }
  79959. pOuterNC = pWalker->u.pNC;
  79960. pParse = pWalker->pParse;
  79961. db = pParse->db;
  79962. /* Normally sqlite3SelectExpand() will be called first and will have
  79963. ** already expanded this SELECT. However, if this is a subquery within
  79964. ** an expression, sqlite3ResolveExprNames() will be called without a
  79965. ** prior call to sqlite3SelectExpand(). When that happens, let
  79966. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  79967. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  79968. ** this routine in the correct order.
  79969. */
  79970. if( (p->selFlags & SF_Expanded)==0 ){
  79971. sqlite3SelectPrep(pParse, p, pOuterNC);
  79972. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  79973. }
  79974. isCompound = p->pPrior!=0;
  79975. nCompound = 0;
  79976. pLeftmost = p;
  79977. while( p ){
  79978. assert( (p->selFlags & SF_Expanded)!=0 );
  79979. assert( (p->selFlags & SF_Resolved)==0 );
  79980. p->selFlags |= SF_Resolved;
  79981. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  79982. ** are not allowed to refer to any names, so pass an empty NameContext.
  79983. */
  79984. memset(&sNC, 0, sizeof(sNC));
  79985. sNC.pParse = pParse;
  79986. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  79987. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  79988. return WRC_Abort;
  79989. }
  79990. /* If the SF_Converted flags is set, then this Select object was
  79991. ** was created by the convertCompoundSelectToSubquery() function.
  79992. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  79993. ** as if it were part of the sub-query, not the parent. This block
  79994. ** moves the pOrderBy down to the sub-query. It will be moved back
  79995. ** after the names have been resolved. */
  79996. if( p->selFlags & SF_Converted ){
  79997. Select *pSub = p->pSrc->a[0].pSelect;
  79998. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  79999. assert( pSub->pPrior && pSub->pOrderBy==0 );
  80000. pSub->pOrderBy = p->pOrderBy;
  80001. p->pOrderBy = 0;
  80002. }
  80003. /* Recursively resolve names in all subqueries
  80004. */
  80005. for(i=0; i<p->pSrc->nSrc; i++){
  80006. struct SrcList_item *pItem = &p->pSrc->a[i];
  80007. if( pItem->pSelect ){
  80008. NameContext *pNC; /* Used to iterate name contexts */
  80009. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  80010. const char *zSavedContext = pParse->zAuthContext;
  80011. /* Count the total number of references to pOuterNC and all of its
  80012. ** parent contexts. After resolving references to expressions in
  80013. ** pItem->pSelect, check if this value has changed. If so, then
  80014. ** SELECT statement pItem->pSelect must be correlated. Set the
  80015. ** pItem->fg.isCorrelated flag if this is the case. */
  80016. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  80017. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  80018. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  80019. pParse->zAuthContext = zSavedContext;
  80020. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  80021. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  80022. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  80023. pItem->fg.isCorrelated = (nRef!=0);
  80024. }
  80025. }
  80026. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  80027. ** resolve the result-set expression list.
  80028. */
  80029. sNC.ncFlags = NC_AllowAgg;
  80030. sNC.pSrcList = p->pSrc;
  80031. sNC.pNext = pOuterNC;
  80032. /* Resolve names in the result set. */
  80033. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  80034. /* If there are no aggregate functions in the result-set, and no GROUP BY
  80035. ** expression, do not allow aggregates in any of the other expressions.
  80036. */
  80037. assert( (p->selFlags & SF_Aggregate)==0 );
  80038. pGroupBy = p->pGroupBy;
  80039. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  80040. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  80041. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  80042. }else{
  80043. sNC.ncFlags &= ~NC_AllowAgg;
  80044. }
  80045. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  80046. */
  80047. if( p->pHaving && !pGroupBy ){
  80048. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  80049. return WRC_Abort;
  80050. }
  80051. /* Add the output column list to the name-context before parsing the
  80052. ** other expressions in the SELECT statement. This is so that
  80053. ** expressions in the WHERE clause (etc.) can refer to expressions by
  80054. ** aliases in the result set.
  80055. **
  80056. ** Minor point: If this is the case, then the expression will be
  80057. ** re-evaluated for each reference to it.
  80058. */
  80059. sNC.pEList = p->pEList;
  80060. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  80061. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  80062. /* Resolve names in table-valued-function arguments */
  80063. for(i=0; i<p->pSrc->nSrc; i++){
  80064. struct SrcList_item *pItem = &p->pSrc->a[i];
  80065. if( pItem->fg.isTabFunc
  80066. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  80067. ){
  80068. return WRC_Abort;
  80069. }
  80070. }
  80071. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  80072. ** outer queries
  80073. */
  80074. sNC.pNext = 0;
  80075. sNC.ncFlags |= NC_AllowAgg;
  80076. /* If this is a converted compound query, move the ORDER BY clause from
  80077. ** the sub-query back to the parent query. At this point each term
  80078. ** within the ORDER BY clause has been transformed to an integer value.
  80079. ** These integers will be replaced by copies of the corresponding result
  80080. ** set expressions by the call to resolveOrderGroupBy() below. */
  80081. if( p->selFlags & SF_Converted ){
  80082. Select *pSub = p->pSrc->a[0].pSelect;
  80083. p->pOrderBy = pSub->pOrderBy;
  80084. pSub->pOrderBy = 0;
  80085. }
  80086. /* Process the ORDER BY clause for singleton SELECT statements.
  80087. ** The ORDER BY clause for compounds SELECT statements is handled
  80088. ** below, after all of the result-sets for all of the elements of
  80089. ** the compound have been resolved.
  80090. **
  80091. ** If there is an ORDER BY clause on a term of a compound-select other
  80092. ** than the right-most term, then that is a syntax error. But the error
  80093. ** is not detected until much later, and so we need to go ahead and
  80094. ** resolve those symbols on the incorrect ORDER BY for consistency.
  80095. */
  80096. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  80097. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  80098. ){
  80099. return WRC_Abort;
  80100. }
  80101. if( db->mallocFailed ){
  80102. return WRC_Abort;
  80103. }
  80104. /* Resolve the GROUP BY clause. At the same time, make sure
  80105. ** the GROUP BY clause does not contain aggregate functions.
  80106. */
  80107. if( pGroupBy ){
  80108. struct ExprList_item *pItem;
  80109. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  80110. return WRC_Abort;
  80111. }
  80112. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  80113. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  80114. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  80115. "the GROUP BY clause");
  80116. return WRC_Abort;
  80117. }
  80118. }
  80119. }
  80120. /* If this is part of a compound SELECT, check that it has the right
  80121. ** number of expressions in the select list. */
  80122. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  80123. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  80124. return WRC_Abort;
  80125. }
  80126. /* Advance to the next term of the compound
  80127. */
  80128. p = p->pPrior;
  80129. nCompound++;
  80130. }
  80131. /* Resolve the ORDER BY on a compound SELECT after all terms of
  80132. ** the compound have been resolved.
  80133. */
  80134. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  80135. return WRC_Abort;
  80136. }
  80137. return WRC_Prune;
  80138. }
  80139. /*
  80140. ** This routine walks an expression tree and resolves references to
  80141. ** table columns and result-set columns. At the same time, do error
  80142. ** checking on function usage and set a flag if any aggregate functions
  80143. ** are seen.
  80144. **
  80145. ** To resolve table columns references we look for nodes (or subtrees) of the
  80146. ** form X.Y.Z or Y.Z or just Z where
  80147. **
  80148. ** X: The name of a database. Ex: "main" or "temp" or
  80149. ** the symbolic name assigned to an ATTACH-ed database.
  80150. **
  80151. ** Y: The name of a table in a FROM clause. Or in a trigger
  80152. ** one of the special names "old" or "new".
  80153. **
  80154. ** Z: The name of a column in table Y.
  80155. **
  80156. ** The node at the root of the subtree is modified as follows:
  80157. **
  80158. ** Expr.op Changed to TK_COLUMN
  80159. ** Expr.pTab Points to the Table object for X.Y
  80160. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  80161. ** Expr.iTable The VDBE cursor number for X.Y
  80162. **
  80163. **
  80164. ** To resolve result-set references, look for expression nodes of the
  80165. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  80166. ** size of an AS clause in the result-set of a SELECT. The Z expression
  80167. ** is replaced by a copy of the left-hand side of the result-set expression.
  80168. ** Table-name and function resolution occurs on the substituted expression
  80169. ** tree. For example, in:
  80170. **
  80171. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  80172. **
  80173. ** The "x" term of the order by is replaced by "a+b" to render:
  80174. **
  80175. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  80176. **
  80177. ** Function calls are checked to make sure that the function is
  80178. ** defined and that the correct number of arguments are specified.
  80179. ** If the function is an aggregate function, then the NC_HasAgg flag is
  80180. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  80181. ** If an expression contains aggregate functions then the EP_Agg
  80182. ** property on the expression is set.
  80183. **
  80184. ** An error message is left in pParse if anything is amiss. The number
  80185. ** if errors is returned.
  80186. */
  80187. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  80188. NameContext *pNC, /* Namespace to resolve expressions in. */
  80189. Expr *pExpr /* The expression to be analyzed. */
  80190. ){
  80191. u16 savedHasAgg;
  80192. Walker w;
  80193. if( pExpr==0 ) return 0;
  80194. #if SQLITE_MAX_EXPR_DEPTH>0
  80195. {
  80196. Parse *pParse = pNC->pParse;
  80197. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  80198. return 1;
  80199. }
  80200. pParse->nHeight += pExpr->nHeight;
  80201. }
  80202. #endif
  80203. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  80204. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  80205. memset(&w, 0, sizeof(w));
  80206. w.xExprCallback = resolveExprStep;
  80207. w.xSelectCallback = resolveSelectStep;
  80208. w.pParse = pNC->pParse;
  80209. w.u.pNC = pNC;
  80210. sqlite3WalkExpr(&w, pExpr);
  80211. #if SQLITE_MAX_EXPR_DEPTH>0
  80212. pNC->pParse->nHeight -= pExpr->nHeight;
  80213. #endif
  80214. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  80215. ExprSetProperty(pExpr, EP_Error);
  80216. }
  80217. if( pNC->ncFlags & NC_HasAgg ){
  80218. ExprSetProperty(pExpr, EP_Agg);
  80219. }
  80220. pNC->ncFlags |= savedHasAgg;
  80221. return ExprHasProperty(pExpr, EP_Error);
  80222. }
  80223. /*
  80224. ** Resolve all names for all expression in an expression list. This is
  80225. ** just like sqlite3ResolveExprNames() except that it works for an expression
  80226. ** list rather than a single expression.
  80227. */
  80228. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  80229. NameContext *pNC, /* Namespace to resolve expressions in. */
  80230. ExprList *pList /* The expression list to be analyzed. */
  80231. ){
  80232. int i;
  80233. if( pList ){
  80234. for(i=0; i<pList->nExpr; i++){
  80235. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  80236. }
  80237. }
  80238. return WRC_Continue;
  80239. }
  80240. /*
  80241. ** Resolve all names in all expressions of a SELECT and in all
  80242. ** decendents of the SELECT, including compounds off of p->pPrior,
  80243. ** subqueries in expressions, and subqueries used as FROM clause
  80244. ** terms.
  80245. **
  80246. ** See sqlite3ResolveExprNames() for a description of the kinds of
  80247. ** transformations that occur.
  80248. **
  80249. ** All SELECT statements should have been expanded using
  80250. ** sqlite3SelectExpand() prior to invoking this routine.
  80251. */
  80252. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  80253. Parse *pParse, /* The parser context */
  80254. Select *p, /* The SELECT statement being coded. */
  80255. NameContext *pOuterNC /* Name context for parent SELECT statement */
  80256. ){
  80257. Walker w;
  80258. assert( p!=0 );
  80259. memset(&w, 0, sizeof(w));
  80260. w.xExprCallback = resolveExprStep;
  80261. w.xSelectCallback = resolveSelectStep;
  80262. w.pParse = pParse;
  80263. w.u.pNC = pOuterNC;
  80264. sqlite3WalkSelect(&w, p);
  80265. }
  80266. /*
  80267. ** Resolve names in expressions that can only reference a single table:
  80268. **
  80269. ** * CHECK constraints
  80270. ** * WHERE clauses on partial indices
  80271. **
  80272. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  80273. ** is set to -1 and the Expr.iColumn value is set to the column number.
  80274. **
  80275. ** Any errors cause an error message to be set in pParse.
  80276. */
  80277. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  80278. Parse *pParse, /* Parsing context */
  80279. Table *pTab, /* The table being referenced */
  80280. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  80281. Expr *pExpr, /* Expression to resolve. May be NULL. */
  80282. ExprList *pList /* Expression list to resolve. May be NUL. */
  80283. ){
  80284. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  80285. NameContext sNC; /* Name context for pParse->pNewTable */
  80286. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  80287. memset(&sNC, 0, sizeof(sNC));
  80288. memset(&sSrc, 0, sizeof(sSrc));
  80289. sSrc.nSrc = 1;
  80290. sSrc.a[0].zName = pTab->zName;
  80291. sSrc.a[0].pTab = pTab;
  80292. sSrc.a[0].iCursor = -1;
  80293. sNC.pParse = pParse;
  80294. sNC.pSrcList = &sSrc;
  80295. sNC.ncFlags = type;
  80296. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  80297. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  80298. }
  80299. /************** End of resolve.c *********************************************/
  80300. /************** Begin file expr.c ********************************************/
  80301. /*
  80302. ** 2001 September 15
  80303. **
  80304. ** The author disclaims copyright to this source code. In place of
  80305. ** a legal notice, here is a blessing:
  80306. **
  80307. ** May you do good and not evil.
  80308. ** May you find forgiveness for yourself and forgive others.
  80309. ** May you share freely, never taking more than you give.
  80310. **
  80311. *************************************************************************
  80312. ** This file contains routines used for analyzing expressions and
  80313. ** for generating VDBE code that evaluates expressions in SQLite.
  80314. */
  80315. /* #include "sqliteInt.h" */
  80316. /*
  80317. ** Return the 'affinity' of the expression pExpr if any.
  80318. **
  80319. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  80320. ** or a sub-select with a column as the return value, then the
  80321. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  80322. ** indicating no affinity for the expression.
  80323. **
  80324. ** i.e. the WHERE clause expressions in the following statements all
  80325. ** have an affinity:
  80326. **
  80327. ** CREATE TABLE t1(a);
  80328. ** SELECT * FROM t1 WHERE a;
  80329. ** SELECT a AS b FROM t1 WHERE b;
  80330. ** SELECT * FROM t1 WHERE (select a from t1);
  80331. */
  80332. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  80333. int op;
  80334. pExpr = sqlite3ExprSkipCollate(pExpr);
  80335. if( pExpr->flags & EP_Generic ) return 0;
  80336. op = pExpr->op;
  80337. if( op==TK_SELECT ){
  80338. assert( pExpr->flags&EP_xIsSelect );
  80339. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  80340. }
  80341. #ifndef SQLITE_OMIT_CAST
  80342. if( op==TK_CAST ){
  80343. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  80344. return sqlite3AffinityType(pExpr->u.zToken, 0);
  80345. }
  80346. #endif
  80347. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  80348. && pExpr->pTab!=0
  80349. ){
  80350. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  80351. ** a TK_COLUMN but was previously evaluated and cached in a register */
  80352. int j = pExpr->iColumn;
  80353. if( j<0 ) return SQLITE_AFF_INTEGER;
  80354. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  80355. return pExpr->pTab->aCol[j].affinity;
  80356. }
  80357. return pExpr->affinity;
  80358. }
  80359. /*
  80360. ** Set the collating sequence for expression pExpr to be the collating
  80361. ** sequence named by pToken. Return a pointer to a new Expr node that
  80362. ** implements the COLLATE operator.
  80363. **
  80364. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  80365. ** and the pExpr parameter is returned unchanged.
  80366. */
  80367. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  80368. Parse *pParse, /* Parsing context */
  80369. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  80370. const Token *pCollName, /* Name of collating sequence */
  80371. int dequote /* True to dequote pCollName */
  80372. ){
  80373. if( pCollName->n>0 ){
  80374. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  80375. if( pNew ){
  80376. pNew->pLeft = pExpr;
  80377. pNew->flags |= EP_Collate|EP_Skip;
  80378. pExpr = pNew;
  80379. }
  80380. }
  80381. return pExpr;
  80382. }
  80383. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  80384. Token s;
  80385. assert( zC!=0 );
  80386. s.z = zC;
  80387. s.n = sqlite3Strlen30(s.z);
  80388. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  80389. }
  80390. /*
  80391. ** Skip over any TK_COLLATE operators and any unlikely()
  80392. ** or likelihood() function at the root of an expression.
  80393. */
  80394. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  80395. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  80396. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  80397. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  80398. assert( pExpr->x.pList->nExpr>0 );
  80399. assert( pExpr->op==TK_FUNCTION );
  80400. pExpr = pExpr->x.pList->a[0].pExpr;
  80401. }else{
  80402. assert( pExpr->op==TK_COLLATE );
  80403. pExpr = pExpr->pLeft;
  80404. }
  80405. }
  80406. return pExpr;
  80407. }
  80408. /*
  80409. ** Return the collation sequence for the expression pExpr. If
  80410. ** there is no defined collating sequence, return NULL.
  80411. **
  80412. ** The collating sequence might be determined by a COLLATE operator
  80413. ** or by the presence of a column with a defined collating sequence.
  80414. ** COLLATE operators take first precedence. Left operands take
  80415. ** precedence over right operands.
  80416. */
  80417. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  80418. sqlite3 *db = pParse->db;
  80419. CollSeq *pColl = 0;
  80420. Expr *p = pExpr;
  80421. while( p ){
  80422. int op = p->op;
  80423. if( p->flags & EP_Generic ) break;
  80424. if( op==TK_CAST || op==TK_UPLUS ){
  80425. p = p->pLeft;
  80426. continue;
  80427. }
  80428. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  80429. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  80430. break;
  80431. }
  80432. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  80433. || op==TK_REGISTER || op==TK_TRIGGER)
  80434. && p->pTab!=0
  80435. ){
  80436. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  80437. ** a TK_COLUMN but was previously evaluated and cached in a register */
  80438. int j = p->iColumn;
  80439. if( j>=0 ){
  80440. const char *zColl = p->pTab->aCol[j].zColl;
  80441. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  80442. }
  80443. break;
  80444. }
  80445. if( p->flags & EP_Collate ){
  80446. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  80447. p = p->pLeft;
  80448. }else{
  80449. Expr *pNext = p->pRight;
  80450. /* The Expr.x union is never used at the same time as Expr.pRight */
  80451. assert( p->x.pList==0 || p->pRight==0 );
  80452. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  80453. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  80454. ** least one EP_Collate. Thus the following two ALWAYS. */
  80455. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  80456. int i;
  80457. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  80458. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  80459. pNext = p->x.pList->a[i].pExpr;
  80460. break;
  80461. }
  80462. }
  80463. }
  80464. p = pNext;
  80465. }
  80466. }else{
  80467. break;
  80468. }
  80469. }
  80470. if( sqlite3CheckCollSeq(pParse, pColl) ){
  80471. pColl = 0;
  80472. }
  80473. return pColl;
  80474. }
  80475. /*
  80476. ** pExpr is an operand of a comparison operator. aff2 is the
  80477. ** type affinity of the other operand. This routine returns the
  80478. ** type affinity that should be used for the comparison operator.
  80479. */
  80480. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  80481. char aff1 = sqlite3ExprAffinity(pExpr);
  80482. if( aff1 && aff2 ){
  80483. /* Both sides of the comparison are columns. If one has numeric
  80484. ** affinity, use that. Otherwise use no affinity.
  80485. */
  80486. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  80487. return SQLITE_AFF_NUMERIC;
  80488. }else{
  80489. return SQLITE_AFF_BLOB;
  80490. }
  80491. }else if( !aff1 && !aff2 ){
  80492. /* Neither side of the comparison is a column. Compare the
  80493. ** results directly.
  80494. */
  80495. return SQLITE_AFF_BLOB;
  80496. }else{
  80497. /* One side is a column, the other is not. Use the columns affinity. */
  80498. assert( aff1==0 || aff2==0 );
  80499. return (aff1 + aff2);
  80500. }
  80501. }
  80502. /*
  80503. ** pExpr is a comparison operator. Return the type affinity that should
  80504. ** be applied to both operands prior to doing the comparison.
  80505. */
  80506. static char comparisonAffinity(Expr *pExpr){
  80507. char aff;
  80508. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  80509. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  80510. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  80511. assert( pExpr->pLeft );
  80512. aff = sqlite3ExprAffinity(pExpr->pLeft);
  80513. if( pExpr->pRight ){
  80514. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  80515. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  80516. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  80517. }else if( !aff ){
  80518. aff = SQLITE_AFF_BLOB;
  80519. }
  80520. return aff;
  80521. }
  80522. /*
  80523. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  80524. ** idx_affinity is the affinity of an indexed column. Return true
  80525. ** if the index with affinity idx_affinity may be used to implement
  80526. ** the comparison in pExpr.
  80527. */
  80528. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  80529. char aff = comparisonAffinity(pExpr);
  80530. switch( aff ){
  80531. case SQLITE_AFF_BLOB:
  80532. return 1;
  80533. case SQLITE_AFF_TEXT:
  80534. return idx_affinity==SQLITE_AFF_TEXT;
  80535. default:
  80536. return sqlite3IsNumericAffinity(idx_affinity);
  80537. }
  80538. }
  80539. /*
  80540. ** Return the P5 value that should be used for a binary comparison
  80541. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  80542. */
  80543. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  80544. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  80545. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  80546. return aff;
  80547. }
  80548. /*
  80549. ** Return a pointer to the collation sequence that should be used by
  80550. ** a binary comparison operator comparing pLeft and pRight.
  80551. **
  80552. ** If the left hand expression has a collating sequence type, then it is
  80553. ** used. Otherwise the collation sequence for the right hand expression
  80554. ** is used, or the default (BINARY) if neither expression has a collating
  80555. ** type.
  80556. **
  80557. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  80558. ** it is not considered.
  80559. */
  80560. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  80561. Parse *pParse,
  80562. Expr *pLeft,
  80563. Expr *pRight
  80564. ){
  80565. CollSeq *pColl;
  80566. assert( pLeft );
  80567. if( pLeft->flags & EP_Collate ){
  80568. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  80569. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  80570. pColl = sqlite3ExprCollSeq(pParse, pRight);
  80571. }else{
  80572. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  80573. if( !pColl ){
  80574. pColl = sqlite3ExprCollSeq(pParse, pRight);
  80575. }
  80576. }
  80577. return pColl;
  80578. }
  80579. /*
  80580. ** Generate code for a comparison operator.
  80581. */
  80582. static int codeCompare(
  80583. Parse *pParse, /* The parsing (and code generating) context */
  80584. Expr *pLeft, /* The left operand */
  80585. Expr *pRight, /* The right operand */
  80586. int opcode, /* The comparison opcode */
  80587. int in1, int in2, /* Register holding operands */
  80588. int dest, /* Jump here if true. */
  80589. int jumpIfNull /* If true, jump if either operand is NULL */
  80590. ){
  80591. int p5;
  80592. int addr;
  80593. CollSeq *p4;
  80594. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  80595. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  80596. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  80597. (void*)p4, P4_COLLSEQ);
  80598. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  80599. return addr;
  80600. }
  80601. #if SQLITE_MAX_EXPR_DEPTH>0
  80602. /*
  80603. ** Check that argument nHeight is less than or equal to the maximum
  80604. ** expression depth allowed. If it is not, leave an error message in
  80605. ** pParse.
  80606. */
  80607. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  80608. int rc = SQLITE_OK;
  80609. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  80610. if( nHeight>mxHeight ){
  80611. sqlite3ErrorMsg(pParse,
  80612. "Expression tree is too large (maximum depth %d)", mxHeight
  80613. );
  80614. rc = SQLITE_ERROR;
  80615. }
  80616. return rc;
  80617. }
  80618. /* The following three functions, heightOfExpr(), heightOfExprList()
  80619. ** and heightOfSelect(), are used to determine the maximum height
  80620. ** of any expression tree referenced by the structure passed as the
  80621. ** first argument.
  80622. **
  80623. ** If this maximum height is greater than the current value pointed
  80624. ** to by pnHeight, the second parameter, then set *pnHeight to that
  80625. ** value.
  80626. */
  80627. static void heightOfExpr(Expr *p, int *pnHeight){
  80628. if( p ){
  80629. if( p->nHeight>*pnHeight ){
  80630. *pnHeight = p->nHeight;
  80631. }
  80632. }
  80633. }
  80634. static void heightOfExprList(ExprList *p, int *pnHeight){
  80635. if( p ){
  80636. int i;
  80637. for(i=0; i<p->nExpr; i++){
  80638. heightOfExpr(p->a[i].pExpr, pnHeight);
  80639. }
  80640. }
  80641. }
  80642. static void heightOfSelect(Select *p, int *pnHeight){
  80643. if( p ){
  80644. heightOfExpr(p->pWhere, pnHeight);
  80645. heightOfExpr(p->pHaving, pnHeight);
  80646. heightOfExpr(p->pLimit, pnHeight);
  80647. heightOfExpr(p->pOffset, pnHeight);
  80648. heightOfExprList(p->pEList, pnHeight);
  80649. heightOfExprList(p->pGroupBy, pnHeight);
  80650. heightOfExprList(p->pOrderBy, pnHeight);
  80651. heightOfSelect(p->pPrior, pnHeight);
  80652. }
  80653. }
  80654. /*
  80655. ** Set the Expr.nHeight variable in the structure passed as an
  80656. ** argument. An expression with no children, Expr.pList or
  80657. ** Expr.pSelect member has a height of 1. Any other expression
  80658. ** has a height equal to the maximum height of any other
  80659. ** referenced Expr plus one.
  80660. **
  80661. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  80662. ** if appropriate.
  80663. */
  80664. static void exprSetHeight(Expr *p){
  80665. int nHeight = 0;
  80666. heightOfExpr(p->pLeft, &nHeight);
  80667. heightOfExpr(p->pRight, &nHeight);
  80668. if( ExprHasProperty(p, EP_xIsSelect) ){
  80669. heightOfSelect(p->x.pSelect, &nHeight);
  80670. }else if( p->x.pList ){
  80671. heightOfExprList(p->x.pList, &nHeight);
  80672. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  80673. }
  80674. p->nHeight = nHeight + 1;
  80675. }
  80676. /*
  80677. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  80678. ** the height is greater than the maximum allowed expression depth,
  80679. ** leave an error in pParse.
  80680. **
  80681. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  80682. ** Expr.flags.
  80683. */
  80684. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  80685. if( pParse->nErr ) return;
  80686. exprSetHeight(p);
  80687. sqlite3ExprCheckHeight(pParse, p->nHeight);
  80688. }
  80689. /*
  80690. ** Return the maximum height of any expression tree referenced
  80691. ** by the select statement passed as an argument.
  80692. */
  80693. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  80694. int nHeight = 0;
  80695. heightOfSelect(p, &nHeight);
  80696. return nHeight;
  80697. }
  80698. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  80699. /*
  80700. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  80701. ** Expr.flags.
  80702. */
  80703. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  80704. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  80705. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  80706. }
  80707. }
  80708. #define exprSetHeight(y)
  80709. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  80710. /*
  80711. ** This routine is the core allocator for Expr nodes.
  80712. **
  80713. ** Construct a new expression node and return a pointer to it. Memory
  80714. ** for this node and for the pToken argument is a single allocation
  80715. ** obtained from sqlite3DbMalloc(). The calling function
  80716. ** is responsible for making sure the node eventually gets freed.
  80717. **
  80718. ** If dequote is true, then the token (if it exists) is dequoted.
  80719. ** If dequote is false, no dequoting is performed. The deQuote
  80720. ** parameter is ignored if pToken is NULL or if the token does not
  80721. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  80722. ** then the EP_DblQuoted flag is set on the expression node.
  80723. **
  80724. ** Special case: If op==TK_INTEGER and pToken points to a string that
  80725. ** can be translated into a 32-bit integer, then the token is not
  80726. ** stored in u.zToken. Instead, the integer values is written
  80727. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  80728. ** is allocated to hold the integer text and the dequote flag is ignored.
  80729. */
  80730. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  80731. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  80732. int op, /* Expression opcode */
  80733. const Token *pToken, /* Token argument. Might be NULL */
  80734. int dequote /* True to dequote */
  80735. ){
  80736. Expr *pNew;
  80737. int nExtra = 0;
  80738. int iValue = 0;
  80739. if( pToken ){
  80740. if( op!=TK_INTEGER || pToken->z==0
  80741. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  80742. nExtra = pToken->n+1;
  80743. assert( iValue>=0 );
  80744. }
  80745. }
  80746. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  80747. if( pNew ){
  80748. pNew->op = (u8)op;
  80749. pNew->iAgg = -1;
  80750. if( pToken ){
  80751. if( nExtra==0 ){
  80752. pNew->flags |= EP_IntValue;
  80753. pNew->u.iValue = iValue;
  80754. }else{
  80755. int c;
  80756. pNew->u.zToken = (char*)&pNew[1];
  80757. assert( pToken->z!=0 || pToken->n==0 );
  80758. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  80759. pNew->u.zToken[pToken->n] = 0;
  80760. if( dequote && nExtra>=3
  80761. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  80762. sqlite3Dequote(pNew->u.zToken);
  80763. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  80764. }
  80765. }
  80766. }
  80767. #if SQLITE_MAX_EXPR_DEPTH>0
  80768. pNew->nHeight = 1;
  80769. #endif
  80770. }
  80771. return pNew;
  80772. }
  80773. /*
  80774. ** Allocate a new expression node from a zero-terminated token that has
  80775. ** already been dequoted.
  80776. */
  80777. SQLITE_PRIVATE Expr *sqlite3Expr(
  80778. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  80779. int op, /* Expression opcode */
  80780. const char *zToken /* Token argument. Might be NULL */
  80781. ){
  80782. Token x;
  80783. x.z = zToken;
  80784. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  80785. return sqlite3ExprAlloc(db, op, &x, 0);
  80786. }
  80787. /*
  80788. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  80789. **
  80790. ** If pRoot==NULL that means that a memory allocation error has occurred.
  80791. ** In that case, delete the subtrees pLeft and pRight.
  80792. */
  80793. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  80794. sqlite3 *db,
  80795. Expr *pRoot,
  80796. Expr *pLeft,
  80797. Expr *pRight
  80798. ){
  80799. if( pRoot==0 ){
  80800. assert( db->mallocFailed );
  80801. sqlite3ExprDelete(db, pLeft);
  80802. sqlite3ExprDelete(db, pRight);
  80803. }else{
  80804. if( pRight ){
  80805. pRoot->pRight = pRight;
  80806. pRoot->flags |= EP_Propagate & pRight->flags;
  80807. }
  80808. if( pLeft ){
  80809. pRoot->pLeft = pLeft;
  80810. pRoot->flags |= EP_Propagate & pLeft->flags;
  80811. }
  80812. exprSetHeight(pRoot);
  80813. }
  80814. }
  80815. /*
  80816. ** Allocate an Expr node which joins as many as two subtrees.
  80817. **
  80818. ** One or both of the subtrees can be NULL. Return a pointer to the new
  80819. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  80820. ** free the subtrees and return NULL.
  80821. */
  80822. SQLITE_PRIVATE Expr *sqlite3PExpr(
  80823. Parse *pParse, /* Parsing context */
  80824. int op, /* Expression opcode */
  80825. Expr *pLeft, /* Left operand */
  80826. Expr *pRight, /* Right operand */
  80827. const Token *pToken /* Argument token */
  80828. ){
  80829. Expr *p;
  80830. if( op==TK_AND && pParse->nErr==0 ){
  80831. /* Take advantage of short-circuit false optimization for AND */
  80832. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  80833. }else{
  80834. p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
  80835. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  80836. }
  80837. if( p ) {
  80838. sqlite3ExprCheckHeight(pParse, p->nHeight);
  80839. }
  80840. return p;
  80841. }
  80842. /*
  80843. ** If the expression is always either TRUE or FALSE (respectively),
  80844. ** then return 1. If one cannot determine the truth value of the
  80845. ** expression at compile-time return 0.
  80846. **
  80847. ** This is an optimization. If is OK to return 0 here even if
  80848. ** the expression really is always false or false (a false negative).
  80849. ** But it is a bug to return 1 if the expression might have different
  80850. ** boolean values in different circumstances (a false positive.)
  80851. **
  80852. ** Note that if the expression is part of conditional for a
  80853. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  80854. ** is it true or false, so always return 0.
  80855. */
  80856. static int exprAlwaysTrue(Expr *p){
  80857. int v = 0;
  80858. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  80859. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  80860. return v!=0;
  80861. }
  80862. static int exprAlwaysFalse(Expr *p){
  80863. int v = 0;
  80864. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  80865. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  80866. return v==0;
  80867. }
  80868. /*
  80869. ** Join two expressions using an AND operator. If either expression is
  80870. ** NULL, then just return the other expression.
  80871. **
  80872. ** If one side or the other of the AND is known to be false, then instead
  80873. ** of returning an AND expression, just return a constant expression with
  80874. ** a value of false.
  80875. */
  80876. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  80877. if( pLeft==0 ){
  80878. return pRight;
  80879. }else if( pRight==0 ){
  80880. return pLeft;
  80881. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  80882. sqlite3ExprDelete(db, pLeft);
  80883. sqlite3ExprDelete(db, pRight);
  80884. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  80885. }else{
  80886. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  80887. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  80888. return pNew;
  80889. }
  80890. }
  80891. /*
  80892. ** Construct a new expression node for a function with multiple
  80893. ** arguments.
  80894. */
  80895. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  80896. Expr *pNew;
  80897. sqlite3 *db = pParse->db;
  80898. assert( pToken );
  80899. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  80900. if( pNew==0 ){
  80901. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  80902. return 0;
  80903. }
  80904. pNew->x.pList = pList;
  80905. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  80906. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  80907. return pNew;
  80908. }
  80909. /*
  80910. ** Assign a variable number to an expression that encodes a wildcard
  80911. ** in the original SQL statement.
  80912. **
  80913. ** Wildcards consisting of a single "?" are assigned the next sequential
  80914. ** variable number.
  80915. **
  80916. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  80917. ** sure "nnn" is not too be to avoid a denial of service attack when
  80918. ** the SQL statement comes from an external source.
  80919. **
  80920. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  80921. ** as the previous instance of the same wildcard. Or if this is the first
  80922. ** instance of the wildcard, the next sequential variable number is
  80923. ** assigned.
  80924. */
  80925. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  80926. sqlite3 *db = pParse->db;
  80927. const char *z;
  80928. if( pExpr==0 ) return;
  80929. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  80930. z = pExpr->u.zToken;
  80931. assert( z!=0 );
  80932. assert( z[0]!=0 );
  80933. if( z[1]==0 ){
  80934. /* Wildcard of the form "?". Assign the next variable number */
  80935. assert( z[0]=='?' );
  80936. pExpr->iColumn = (ynVar)(++pParse->nVar);
  80937. }else{
  80938. ynVar x = 0;
  80939. u32 n = sqlite3Strlen30(z);
  80940. if( z[0]=='?' ){
  80941. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  80942. ** use it as the variable number */
  80943. i64 i;
  80944. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  80945. pExpr->iColumn = x = (ynVar)i;
  80946. testcase( i==0 );
  80947. testcase( i==1 );
  80948. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  80949. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  80950. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  80951. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  80952. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  80953. x = 0;
  80954. }
  80955. if( i>pParse->nVar ){
  80956. pParse->nVar = (int)i;
  80957. }
  80958. }else{
  80959. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  80960. ** number as the prior appearance of the same name, or if the name
  80961. ** has never appeared before, reuse the same variable number
  80962. */
  80963. ynVar i;
  80964. for(i=0; i<pParse->nzVar; i++){
  80965. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  80966. pExpr->iColumn = x = (ynVar)i+1;
  80967. break;
  80968. }
  80969. }
  80970. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  80971. }
  80972. if( x>0 ){
  80973. if( x>pParse->nzVar ){
  80974. char **a;
  80975. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  80976. if( a==0 ) return; /* Error reported through db->mallocFailed */
  80977. pParse->azVar = a;
  80978. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  80979. pParse->nzVar = x;
  80980. }
  80981. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  80982. sqlite3DbFree(db, pParse->azVar[x-1]);
  80983. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  80984. }
  80985. }
  80986. }
  80987. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  80988. sqlite3ErrorMsg(pParse, "too many SQL variables");
  80989. }
  80990. }
  80991. /*
  80992. ** Recursively delete an expression tree.
  80993. */
  80994. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  80995. if( p==0 ) return;
  80996. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  80997. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  80998. if( !ExprHasProperty(p, EP_TokenOnly) ){
  80999. /* The Expr.x union is never used at the same time as Expr.pRight */
  81000. assert( p->x.pList==0 || p->pRight==0 );
  81001. sqlite3ExprDelete(db, p->pLeft);
  81002. sqlite3ExprDelete(db, p->pRight);
  81003. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  81004. if( ExprHasProperty(p, EP_xIsSelect) ){
  81005. sqlite3SelectDelete(db, p->x.pSelect);
  81006. }else{
  81007. sqlite3ExprListDelete(db, p->x.pList);
  81008. }
  81009. }
  81010. if( !ExprHasProperty(p, EP_Static) ){
  81011. sqlite3DbFree(db, p);
  81012. }
  81013. }
  81014. /*
  81015. ** Return the number of bytes allocated for the expression structure
  81016. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  81017. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  81018. */
  81019. static int exprStructSize(Expr *p){
  81020. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  81021. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  81022. return EXPR_FULLSIZE;
  81023. }
  81024. /*
  81025. ** The dupedExpr*Size() routines each return the number of bytes required
  81026. ** to store a copy of an expression or expression tree. They differ in
  81027. ** how much of the tree is measured.
  81028. **
  81029. ** dupedExprStructSize() Size of only the Expr structure
  81030. ** dupedExprNodeSize() Size of Expr + space for token
  81031. ** dupedExprSize() Expr + token + subtree components
  81032. **
  81033. ***************************************************************************
  81034. **
  81035. ** The dupedExprStructSize() function returns two values OR-ed together:
  81036. ** (1) the space required for a copy of the Expr structure only and
  81037. ** (2) the EP_xxx flags that indicate what the structure size should be.
  81038. ** The return values is always one of:
  81039. **
  81040. ** EXPR_FULLSIZE
  81041. ** EXPR_REDUCEDSIZE | EP_Reduced
  81042. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  81043. **
  81044. ** The size of the structure can be found by masking the return value
  81045. ** of this routine with 0xfff. The flags can be found by masking the
  81046. ** return value with EP_Reduced|EP_TokenOnly.
  81047. **
  81048. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  81049. ** (unreduced) Expr objects as they or originally constructed by the parser.
  81050. ** During expression analysis, extra information is computed and moved into
  81051. ** later parts of teh Expr object and that extra information might get chopped
  81052. ** off if the expression is reduced. Note also that it does not work to
  81053. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  81054. ** to reduce a pristine expression tree from the parser. The implementation
  81055. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  81056. ** to enforce this constraint.
  81057. */
  81058. static int dupedExprStructSize(Expr *p, int flags){
  81059. int nSize;
  81060. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  81061. assert( EXPR_FULLSIZE<=0xfff );
  81062. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  81063. if( 0==(flags&EXPRDUP_REDUCE) ){
  81064. nSize = EXPR_FULLSIZE;
  81065. }else{
  81066. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  81067. assert( !ExprHasProperty(p, EP_FromJoin) );
  81068. assert( !ExprHasProperty(p, EP_MemToken) );
  81069. assert( !ExprHasProperty(p, EP_NoReduce) );
  81070. if( p->pLeft || p->x.pList ){
  81071. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  81072. }else{
  81073. assert( p->pRight==0 );
  81074. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  81075. }
  81076. }
  81077. return nSize;
  81078. }
  81079. /*
  81080. ** This function returns the space in bytes required to store the copy
  81081. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  81082. ** string is defined.)
  81083. */
  81084. static int dupedExprNodeSize(Expr *p, int flags){
  81085. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  81086. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  81087. nByte += sqlite3Strlen30(p->u.zToken)+1;
  81088. }
  81089. return ROUND8(nByte);
  81090. }
  81091. /*
  81092. ** Return the number of bytes required to create a duplicate of the
  81093. ** expression passed as the first argument. The second argument is a
  81094. ** mask containing EXPRDUP_XXX flags.
  81095. **
  81096. ** The value returned includes space to create a copy of the Expr struct
  81097. ** itself and the buffer referred to by Expr.u.zToken, if any.
  81098. **
  81099. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  81100. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  81101. ** and Expr.pRight variables (but not for any structures pointed to or
  81102. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  81103. */
  81104. static int dupedExprSize(Expr *p, int flags){
  81105. int nByte = 0;
  81106. if( p ){
  81107. nByte = dupedExprNodeSize(p, flags);
  81108. if( flags&EXPRDUP_REDUCE ){
  81109. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  81110. }
  81111. }
  81112. return nByte;
  81113. }
  81114. /*
  81115. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  81116. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  81117. ** to store the copy of expression p, the copies of p->u.zToken
  81118. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  81119. ** if any. Before returning, *pzBuffer is set to the first byte past the
  81120. ** portion of the buffer copied into by this function.
  81121. */
  81122. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  81123. Expr *pNew = 0; /* Value to return */
  81124. assert( flags==0 || flags==EXPRDUP_REDUCE );
  81125. if( p ){
  81126. const int isReduced = (flags&EXPRDUP_REDUCE);
  81127. u8 *zAlloc;
  81128. u32 staticFlag = 0;
  81129. assert( pzBuffer==0 || isReduced );
  81130. /* Figure out where to write the new Expr structure. */
  81131. if( pzBuffer ){
  81132. zAlloc = *pzBuffer;
  81133. staticFlag = EP_Static;
  81134. }else{
  81135. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  81136. }
  81137. pNew = (Expr *)zAlloc;
  81138. if( pNew ){
  81139. /* Set nNewSize to the size allocated for the structure pointed to
  81140. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  81141. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  81142. ** by the copy of the p->u.zToken string (if any).
  81143. */
  81144. const unsigned nStructSize = dupedExprStructSize(p, flags);
  81145. const int nNewSize = nStructSize & 0xfff;
  81146. int nToken;
  81147. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  81148. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  81149. }else{
  81150. nToken = 0;
  81151. }
  81152. if( isReduced ){
  81153. assert( ExprHasProperty(p, EP_Reduced)==0 );
  81154. memcpy(zAlloc, p, nNewSize);
  81155. }else{
  81156. u32 nSize = (u32)exprStructSize(p);
  81157. memcpy(zAlloc, p, nSize);
  81158. if( nSize<EXPR_FULLSIZE ){
  81159. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  81160. }
  81161. }
  81162. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  81163. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  81164. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  81165. pNew->flags |= staticFlag;
  81166. /* Copy the p->u.zToken string, if any. */
  81167. if( nToken ){
  81168. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  81169. memcpy(zToken, p->u.zToken, nToken);
  81170. }
  81171. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  81172. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  81173. if( ExprHasProperty(p, EP_xIsSelect) ){
  81174. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  81175. }else{
  81176. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  81177. }
  81178. }
  81179. /* Fill in pNew->pLeft and pNew->pRight. */
  81180. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  81181. zAlloc += dupedExprNodeSize(p, flags);
  81182. if( ExprHasProperty(pNew, EP_Reduced) ){
  81183. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  81184. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  81185. }
  81186. if( pzBuffer ){
  81187. *pzBuffer = zAlloc;
  81188. }
  81189. }else{
  81190. if( !ExprHasProperty(p, EP_TokenOnly) ){
  81191. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  81192. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  81193. }
  81194. }
  81195. }
  81196. }
  81197. return pNew;
  81198. }
  81199. /*
  81200. ** Create and return a deep copy of the object passed as the second
  81201. ** argument. If an OOM condition is encountered, NULL is returned
  81202. ** and the db->mallocFailed flag set.
  81203. */
  81204. #ifndef SQLITE_OMIT_CTE
  81205. static With *withDup(sqlite3 *db, With *p){
  81206. With *pRet = 0;
  81207. if( p ){
  81208. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  81209. pRet = sqlite3DbMallocZero(db, nByte);
  81210. if( pRet ){
  81211. int i;
  81212. pRet->nCte = p->nCte;
  81213. for(i=0; i<p->nCte; i++){
  81214. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  81215. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  81216. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  81217. }
  81218. }
  81219. }
  81220. return pRet;
  81221. }
  81222. #else
  81223. # define withDup(x,y) 0
  81224. #endif
  81225. /*
  81226. ** The following group of routines make deep copies of expressions,
  81227. ** expression lists, ID lists, and select statements. The copies can
  81228. ** be deleted (by being passed to their respective ...Delete() routines)
  81229. ** without effecting the originals.
  81230. **
  81231. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  81232. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  81233. ** by subsequent calls to sqlite*ListAppend() routines.
  81234. **
  81235. ** Any tables that the SrcList might point to are not duplicated.
  81236. **
  81237. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  81238. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  81239. ** truncated version of the usual Expr structure that will be stored as
  81240. ** part of the in-memory representation of the database schema.
  81241. */
  81242. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  81243. assert( flags==0 || flags==EXPRDUP_REDUCE );
  81244. return exprDup(db, p, flags, 0);
  81245. }
  81246. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  81247. ExprList *pNew;
  81248. struct ExprList_item *pItem, *pOldItem;
  81249. int i;
  81250. if( p==0 ) return 0;
  81251. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  81252. if( pNew==0 ) return 0;
  81253. pNew->nExpr = i = p->nExpr;
  81254. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  81255. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  81256. if( pItem==0 ){
  81257. sqlite3DbFree(db, pNew);
  81258. return 0;
  81259. }
  81260. pOldItem = p->a;
  81261. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  81262. Expr *pOldExpr = pOldItem->pExpr;
  81263. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  81264. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  81265. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  81266. pItem->sortOrder = pOldItem->sortOrder;
  81267. pItem->done = 0;
  81268. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  81269. pItem->u = pOldItem->u;
  81270. }
  81271. return pNew;
  81272. }
  81273. /*
  81274. ** If cursors, triggers, views and subqueries are all omitted from
  81275. ** the build, then none of the following routines, except for
  81276. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  81277. ** called with a NULL argument.
  81278. */
  81279. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  81280. || !defined(SQLITE_OMIT_SUBQUERY)
  81281. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  81282. SrcList *pNew;
  81283. int i;
  81284. int nByte;
  81285. if( p==0 ) return 0;
  81286. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  81287. pNew = sqlite3DbMallocRaw(db, nByte );
  81288. if( pNew==0 ) return 0;
  81289. pNew->nSrc = pNew->nAlloc = p->nSrc;
  81290. for(i=0; i<p->nSrc; i++){
  81291. struct SrcList_item *pNewItem = &pNew->a[i];
  81292. struct SrcList_item *pOldItem = &p->a[i];
  81293. Table *pTab;
  81294. pNewItem->pSchema = pOldItem->pSchema;
  81295. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  81296. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  81297. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  81298. pNewItem->fg = pOldItem->fg;
  81299. pNewItem->iCursor = pOldItem->iCursor;
  81300. pNewItem->addrFillSub = pOldItem->addrFillSub;
  81301. pNewItem->regReturn = pOldItem->regReturn;
  81302. if( pNewItem->fg.isIndexedBy ){
  81303. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  81304. }
  81305. pNewItem->pIBIndex = pOldItem->pIBIndex;
  81306. if( pNewItem->fg.isTabFunc ){
  81307. pNewItem->u1.pFuncArg =
  81308. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  81309. }
  81310. pTab = pNewItem->pTab = pOldItem->pTab;
  81311. if( pTab ){
  81312. pTab->nRef++;
  81313. }
  81314. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  81315. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  81316. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  81317. pNewItem->colUsed = pOldItem->colUsed;
  81318. }
  81319. return pNew;
  81320. }
  81321. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  81322. IdList *pNew;
  81323. int i;
  81324. if( p==0 ) return 0;
  81325. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  81326. if( pNew==0 ) return 0;
  81327. pNew->nId = p->nId;
  81328. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  81329. if( pNew->a==0 ){
  81330. sqlite3DbFree(db, pNew);
  81331. return 0;
  81332. }
  81333. /* Note that because the size of the allocation for p->a[] is not
  81334. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  81335. ** on the duplicate created by this function. */
  81336. for(i=0; i<p->nId; i++){
  81337. struct IdList_item *pNewItem = &pNew->a[i];
  81338. struct IdList_item *pOldItem = &p->a[i];
  81339. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  81340. pNewItem->idx = pOldItem->idx;
  81341. }
  81342. return pNew;
  81343. }
  81344. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  81345. Select *pNew, *pPrior;
  81346. if( p==0 ) return 0;
  81347. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  81348. if( pNew==0 ) return 0;
  81349. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  81350. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  81351. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  81352. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  81353. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  81354. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  81355. pNew->op = p->op;
  81356. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  81357. if( pPrior ) pPrior->pNext = pNew;
  81358. pNew->pNext = 0;
  81359. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  81360. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  81361. pNew->iLimit = 0;
  81362. pNew->iOffset = 0;
  81363. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  81364. pNew->addrOpenEphm[0] = -1;
  81365. pNew->addrOpenEphm[1] = -1;
  81366. pNew->nSelectRow = p->nSelectRow;
  81367. pNew->pWith = withDup(db, p->pWith);
  81368. sqlite3SelectSetName(pNew, p->zSelName);
  81369. return pNew;
  81370. }
  81371. #else
  81372. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  81373. assert( p==0 );
  81374. return 0;
  81375. }
  81376. #endif
  81377. /*
  81378. ** Add a new element to the end of an expression list. If pList is
  81379. ** initially NULL, then create a new expression list.
  81380. **
  81381. ** If a memory allocation error occurs, the entire list is freed and
  81382. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  81383. ** that the new entry was successfully appended.
  81384. */
  81385. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  81386. Parse *pParse, /* Parsing context */
  81387. ExprList *pList, /* List to which to append. Might be NULL */
  81388. Expr *pExpr /* Expression to be appended. Might be NULL */
  81389. ){
  81390. sqlite3 *db = pParse->db;
  81391. if( pList==0 ){
  81392. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  81393. if( pList==0 ){
  81394. goto no_mem;
  81395. }
  81396. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  81397. if( pList->a==0 ) goto no_mem;
  81398. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  81399. struct ExprList_item *a;
  81400. assert( pList->nExpr>0 );
  81401. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  81402. if( a==0 ){
  81403. goto no_mem;
  81404. }
  81405. pList->a = a;
  81406. }
  81407. assert( pList->a!=0 );
  81408. if( 1 ){
  81409. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  81410. memset(pItem, 0, sizeof(*pItem));
  81411. pItem->pExpr = pExpr;
  81412. }
  81413. return pList;
  81414. no_mem:
  81415. /* Avoid leaking memory if malloc has failed. */
  81416. sqlite3ExprDelete(db, pExpr);
  81417. sqlite3ExprListDelete(db, pList);
  81418. return 0;
  81419. }
  81420. /*
  81421. ** Set the sort order for the last element on the given ExprList.
  81422. */
  81423. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  81424. if( p==0 ) return;
  81425. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  81426. assert( p->nExpr>0 );
  81427. if( iSortOrder<0 ){
  81428. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  81429. return;
  81430. }
  81431. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  81432. }
  81433. /*
  81434. ** Set the ExprList.a[].zName element of the most recently added item
  81435. ** on the expression list.
  81436. **
  81437. ** pList might be NULL following an OOM error. But pName should never be
  81438. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  81439. ** is set.
  81440. */
  81441. SQLITE_PRIVATE void sqlite3ExprListSetName(
  81442. Parse *pParse, /* Parsing context */
  81443. ExprList *pList, /* List to which to add the span. */
  81444. Token *pName, /* Name to be added */
  81445. int dequote /* True to cause the name to be dequoted */
  81446. ){
  81447. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  81448. if( pList ){
  81449. struct ExprList_item *pItem;
  81450. assert( pList->nExpr>0 );
  81451. pItem = &pList->a[pList->nExpr-1];
  81452. assert( pItem->zName==0 );
  81453. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  81454. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  81455. }
  81456. }
  81457. /*
  81458. ** Set the ExprList.a[].zSpan element of the most recently added item
  81459. ** on the expression list.
  81460. **
  81461. ** pList might be NULL following an OOM error. But pSpan should never be
  81462. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  81463. ** is set.
  81464. */
  81465. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  81466. Parse *pParse, /* Parsing context */
  81467. ExprList *pList, /* List to which to add the span. */
  81468. ExprSpan *pSpan /* The span to be added */
  81469. ){
  81470. sqlite3 *db = pParse->db;
  81471. assert( pList!=0 || db->mallocFailed!=0 );
  81472. if( pList ){
  81473. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  81474. assert( pList->nExpr>0 );
  81475. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  81476. sqlite3DbFree(db, pItem->zSpan);
  81477. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  81478. (int)(pSpan->zEnd - pSpan->zStart));
  81479. }
  81480. }
  81481. /*
  81482. ** If the expression list pEList contains more than iLimit elements,
  81483. ** leave an error message in pParse.
  81484. */
  81485. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  81486. Parse *pParse,
  81487. ExprList *pEList,
  81488. const char *zObject
  81489. ){
  81490. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  81491. testcase( pEList && pEList->nExpr==mx );
  81492. testcase( pEList && pEList->nExpr==mx+1 );
  81493. if( pEList && pEList->nExpr>mx ){
  81494. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  81495. }
  81496. }
  81497. /*
  81498. ** Delete an entire expression list.
  81499. */
  81500. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  81501. int i;
  81502. struct ExprList_item *pItem;
  81503. if( pList==0 ) return;
  81504. assert( pList->a!=0 || pList->nExpr==0 );
  81505. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  81506. sqlite3ExprDelete(db, pItem->pExpr);
  81507. sqlite3DbFree(db, pItem->zName);
  81508. sqlite3DbFree(db, pItem->zSpan);
  81509. }
  81510. sqlite3DbFree(db, pList->a);
  81511. sqlite3DbFree(db, pList);
  81512. }
  81513. /*
  81514. ** Return the bitwise-OR of all Expr.flags fields in the given
  81515. ** ExprList.
  81516. */
  81517. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  81518. int i;
  81519. u32 m = 0;
  81520. if( pList ){
  81521. for(i=0; i<pList->nExpr; i++){
  81522. Expr *pExpr = pList->a[i].pExpr;
  81523. if( ALWAYS(pExpr) ) m |= pExpr->flags;
  81524. }
  81525. }
  81526. return m;
  81527. }
  81528. /*
  81529. ** These routines are Walker callbacks used to check expressions to
  81530. ** see if they are "constant" for some definition of constant. The
  81531. ** Walker.eCode value determines the type of "constant" we are looking
  81532. ** for.
  81533. **
  81534. ** These callback routines are used to implement the following:
  81535. **
  81536. ** sqlite3ExprIsConstant() pWalker->eCode==1
  81537. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  81538. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  81539. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  81540. **
  81541. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  81542. ** is found to not be a constant.
  81543. **
  81544. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  81545. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  81546. ** an existing schema and 4 when processing a new statement. A bound
  81547. ** parameter raises an error for new statements, but is silently converted
  81548. ** to NULL for existing schemas. This allows sqlite_master tables that
  81549. ** contain a bound parameter because they were generated by older versions
  81550. ** of SQLite to be parsed by newer versions of SQLite without raising a
  81551. ** malformed schema error.
  81552. */
  81553. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  81554. /* If pWalker->eCode is 2 then any term of the expression that comes from
  81555. ** the ON or USING clauses of a left join disqualifies the expression
  81556. ** from being considered constant. */
  81557. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  81558. pWalker->eCode = 0;
  81559. return WRC_Abort;
  81560. }
  81561. switch( pExpr->op ){
  81562. /* Consider functions to be constant if all their arguments are constant
  81563. ** and either pWalker->eCode==4 or 5 or the function has the
  81564. ** SQLITE_FUNC_CONST flag. */
  81565. case TK_FUNCTION:
  81566. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  81567. return WRC_Continue;
  81568. }else{
  81569. pWalker->eCode = 0;
  81570. return WRC_Abort;
  81571. }
  81572. case TK_ID:
  81573. case TK_COLUMN:
  81574. case TK_AGG_FUNCTION:
  81575. case TK_AGG_COLUMN:
  81576. testcase( pExpr->op==TK_ID );
  81577. testcase( pExpr->op==TK_COLUMN );
  81578. testcase( pExpr->op==TK_AGG_FUNCTION );
  81579. testcase( pExpr->op==TK_AGG_COLUMN );
  81580. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  81581. return WRC_Continue;
  81582. }else{
  81583. pWalker->eCode = 0;
  81584. return WRC_Abort;
  81585. }
  81586. case TK_VARIABLE:
  81587. if( pWalker->eCode==5 ){
  81588. /* Silently convert bound parameters that appear inside of CREATE
  81589. ** statements into a NULL when parsing the CREATE statement text out
  81590. ** of the sqlite_master table */
  81591. pExpr->op = TK_NULL;
  81592. }else if( pWalker->eCode==4 ){
  81593. /* A bound parameter in a CREATE statement that originates from
  81594. ** sqlite3_prepare() causes an error */
  81595. pWalker->eCode = 0;
  81596. return WRC_Abort;
  81597. }
  81598. /* Fall through */
  81599. default:
  81600. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  81601. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  81602. return WRC_Continue;
  81603. }
  81604. }
  81605. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  81606. UNUSED_PARAMETER(NotUsed);
  81607. pWalker->eCode = 0;
  81608. return WRC_Abort;
  81609. }
  81610. static int exprIsConst(Expr *p, int initFlag, int iCur){
  81611. Walker w;
  81612. memset(&w, 0, sizeof(w));
  81613. w.eCode = initFlag;
  81614. w.xExprCallback = exprNodeIsConstant;
  81615. w.xSelectCallback = selectNodeIsConstant;
  81616. w.u.iCur = iCur;
  81617. sqlite3WalkExpr(&w, p);
  81618. return w.eCode;
  81619. }
  81620. /*
  81621. ** Walk an expression tree. Return non-zero if the expression is constant
  81622. ** and 0 if it involves variables or function calls.
  81623. **
  81624. ** For the purposes of this function, a double-quoted string (ex: "abc")
  81625. ** is considered a variable but a single-quoted string (ex: 'abc') is
  81626. ** a constant.
  81627. */
  81628. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  81629. return exprIsConst(p, 1, 0);
  81630. }
  81631. /*
  81632. ** Walk an expression tree. Return non-zero if the expression is constant
  81633. ** that does no originate from the ON or USING clauses of a join.
  81634. ** Return 0 if it involves variables or function calls or terms from
  81635. ** an ON or USING clause.
  81636. */
  81637. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  81638. return exprIsConst(p, 2, 0);
  81639. }
  81640. /*
  81641. ** Walk an expression tree. Return non-zero if the expression is constant
  81642. ** for any single row of the table with cursor iCur. In other words, the
  81643. ** expression must not refer to any non-deterministic function nor any
  81644. ** table other than iCur.
  81645. */
  81646. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  81647. return exprIsConst(p, 3, iCur);
  81648. }
  81649. /*
  81650. ** Walk an expression tree. Return non-zero if the expression is constant
  81651. ** or a function call with constant arguments. Return and 0 if there
  81652. ** are any variables.
  81653. **
  81654. ** For the purposes of this function, a double-quoted string (ex: "abc")
  81655. ** is considered a variable but a single-quoted string (ex: 'abc') is
  81656. ** a constant.
  81657. */
  81658. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  81659. assert( isInit==0 || isInit==1 );
  81660. return exprIsConst(p, 4+isInit, 0);
  81661. }
  81662. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  81663. /*
  81664. ** Walk an expression tree. Return 1 if the expression contains a
  81665. ** subquery of some kind. Return 0 if there are no subqueries.
  81666. */
  81667. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  81668. Walker w;
  81669. memset(&w, 0, sizeof(w));
  81670. w.eCode = 1;
  81671. w.xExprCallback = sqlite3ExprWalkNoop;
  81672. w.xSelectCallback = selectNodeIsConstant;
  81673. sqlite3WalkExpr(&w, p);
  81674. return w.eCode==0;
  81675. }
  81676. #endif
  81677. /*
  81678. ** If the expression p codes a constant integer that is small enough
  81679. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  81680. ** in *pValue. If the expression is not an integer or if it is too big
  81681. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  81682. */
  81683. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  81684. int rc = 0;
  81685. /* If an expression is an integer literal that fits in a signed 32-bit
  81686. ** integer, then the EP_IntValue flag will have already been set */
  81687. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  81688. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  81689. if( p->flags & EP_IntValue ){
  81690. *pValue = p->u.iValue;
  81691. return 1;
  81692. }
  81693. switch( p->op ){
  81694. case TK_UPLUS: {
  81695. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  81696. break;
  81697. }
  81698. case TK_UMINUS: {
  81699. int v;
  81700. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  81701. assert( v!=(-2147483647-1) );
  81702. *pValue = -v;
  81703. rc = 1;
  81704. }
  81705. break;
  81706. }
  81707. default: break;
  81708. }
  81709. return rc;
  81710. }
  81711. /*
  81712. ** Return FALSE if there is no chance that the expression can be NULL.
  81713. **
  81714. ** If the expression might be NULL or if the expression is too complex
  81715. ** to tell return TRUE.
  81716. **
  81717. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  81718. ** when we know that a value cannot be NULL. Hence, a false positive
  81719. ** (returning TRUE when in fact the expression can never be NULL) might
  81720. ** be a small performance hit but is otherwise harmless. On the other
  81721. ** hand, a false negative (returning FALSE when the result could be NULL)
  81722. ** will likely result in an incorrect answer. So when in doubt, return
  81723. ** TRUE.
  81724. */
  81725. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  81726. u8 op;
  81727. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  81728. op = p->op;
  81729. if( op==TK_REGISTER ) op = p->op2;
  81730. switch( op ){
  81731. case TK_INTEGER:
  81732. case TK_STRING:
  81733. case TK_FLOAT:
  81734. case TK_BLOB:
  81735. return 0;
  81736. case TK_COLUMN:
  81737. assert( p->pTab!=0 );
  81738. return ExprHasProperty(p, EP_CanBeNull) ||
  81739. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  81740. default:
  81741. return 1;
  81742. }
  81743. }
  81744. /*
  81745. ** Return TRUE if the given expression is a constant which would be
  81746. ** unchanged by OP_Affinity with the affinity given in the second
  81747. ** argument.
  81748. **
  81749. ** This routine is used to determine if the OP_Affinity operation
  81750. ** can be omitted. When in doubt return FALSE. A false negative
  81751. ** is harmless. A false positive, however, can result in the wrong
  81752. ** answer.
  81753. */
  81754. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  81755. u8 op;
  81756. if( aff==SQLITE_AFF_BLOB ) return 1;
  81757. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  81758. op = p->op;
  81759. if( op==TK_REGISTER ) op = p->op2;
  81760. switch( op ){
  81761. case TK_INTEGER: {
  81762. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  81763. }
  81764. case TK_FLOAT: {
  81765. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  81766. }
  81767. case TK_STRING: {
  81768. return aff==SQLITE_AFF_TEXT;
  81769. }
  81770. case TK_BLOB: {
  81771. return 1;
  81772. }
  81773. case TK_COLUMN: {
  81774. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  81775. return p->iColumn<0
  81776. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  81777. }
  81778. default: {
  81779. return 0;
  81780. }
  81781. }
  81782. }
  81783. /*
  81784. ** Return TRUE if the given string is a row-id column name.
  81785. */
  81786. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  81787. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  81788. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  81789. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  81790. return 0;
  81791. }
  81792. /*
  81793. ** Return true if we are able to the IN operator optimization on a
  81794. ** query of the form
  81795. **
  81796. ** x IN (SELECT ...)
  81797. **
  81798. ** Where the SELECT... clause is as specified by the parameter to this
  81799. ** routine.
  81800. **
  81801. ** The Select object passed in has already been preprocessed and no
  81802. ** errors have been found.
  81803. */
  81804. #ifndef SQLITE_OMIT_SUBQUERY
  81805. static int isCandidateForInOpt(Select *p){
  81806. SrcList *pSrc;
  81807. ExprList *pEList;
  81808. Table *pTab;
  81809. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  81810. if( p->pPrior ) return 0; /* Not a compound SELECT */
  81811. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  81812. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  81813. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  81814. return 0; /* No DISTINCT keyword and no aggregate functions */
  81815. }
  81816. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  81817. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  81818. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  81819. if( p->pWhere ) return 0; /* Has no WHERE clause */
  81820. pSrc = p->pSrc;
  81821. assert( pSrc!=0 );
  81822. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  81823. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  81824. pTab = pSrc->a[0].pTab;
  81825. if( NEVER(pTab==0) ) return 0;
  81826. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  81827. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  81828. pEList = p->pEList;
  81829. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  81830. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  81831. return 1;
  81832. }
  81833. #endif /* SQLITE_OMIT_SUBQUERY */
  81834. /*
  81835. ** Code an OP_Once instruction and allocate space for its flag. Return the
  81836. ** address of the new instruction.
  81837. */
  81838. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  81839. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  81840. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  81841. }
  81842. /*
  81843. ** Generate code that checks the left-most column of index table iCur to see if
  81844. ** it contains any NULL entries. Cause the register at regHasNull to be set
  81845. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  81846. ** to be set to NULL if iCur contains one or more NULL values.
  81847. */
  81848. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  81849. int addr1;
  81850. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  81851. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  81852. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  81853. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  81854. VdbeComment((v, "first_entry_in(%d)", iCur));
  81855. sqlite3VdbeJumpHere(v, addr1);
  81856. }
  81857. #ifndef SQLITE_OMIT_SUBQUERY
  81858. /*
  81859. ** The argument is an IN operator with a list (not a subquery) on the
  81860. ** right-hand side. Return TRUE if that list is constant.
  81861. */
  81862. static int sqlite3InRhsIsConstant(Expr *pIn){
  81863. Expr *pLHS;
  81864. int res;
  81865. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  81866. pLHS = pIn->pLeft;
  81867. pIn->pLeft = 0;
  81868. res = sqlite3ExprIsConstant(pIn);
  81869. pIn->pLeft = pLHS;
  81870. return res;
  81871. }
  81872. #endif
  81873. /*
  81874. ** This function is used by the implementation of the IN (...) operator.
  81875. ** The pX parameter is the expression on the RHS of the IN operator, which
  81876. ** might be either a list of expressions or a subquery.
  81877. **
  81878. ** The job of this routine is to find or create a b-tree object that can
  81879. ** be used either to test for membership in the RHS set or to iterate through
  81880. ** all members of the RHS set, skipping duplicates.
  81881. **
  81882. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  81883. ** and pX->iTable is set to the index of that cursor.
  81884. **
  81885. ** The returned value of this function indicates the b-tree type, as follows:
  81886. **
  81887. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  81888. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  81889. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  81890. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  81891. ** populated epheremal table.
  81892. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  81893. ** implemented as a sequence of comparisons.
  81894. **
  81895. ** An existing b-tree might be used if the RHS expression pX is a simple
  81896. ** subquery such as:
  81897. **
  81898. ** SELECT <column> FROM <table>
  81899. **
  81900. ** If the RHS of the IN operator is a list or a more complex subquery, then
  81901. ** an ephemeral table might need to be generated from the RHS and then
  81902. ** pX->iTable made to point to the ephemeral table instead of an
  81903. ** existing table.
  81904. **
  81905. ** The inFlags parameter must contain exactly one of the bits
  81906. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  81907. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  81908. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  81909. ** IN index will be used to loop over all values of the RHS of the
  81910. ** IN operator.
  81911. **
  81912. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  81913. ** through the set members) then the b-tree must not contain duplicates.
  81914. ** An epheremal table must be used unless the selected <column> is guaranteed
  81915. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  81916. ** has a UNIQUE constraint or UNIQUE index.
  81917. **
  81918. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  81919. ** for fast set membership tests) then an epheremal table must
  81920. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  81921. ** be found with <column> as its left-most column.
  81922. **
  81923. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  81924. ** if the RHS of the IN operator is a list (not a subquery) then this
  81925. ** routine might decide that creating an ephemeral b-tree for membership
  81926. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  81927. ** calling routine should implement the IN operator using a sequence
  81928. ** of Eq or Ne comparison operations.
  81929. **
  81930. ** When the b-tree is being used for membership tests, the calling function
  81931. ** might need to know whether or not the RHS side of the IN operator
  81932. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  81933. ** if there is any chance that the (...) might contain a NULL value at
  81934. ** runtime, then a register is allocated and the register number written
  81935. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  81936. ** NULL value, then *prRhsHasNull is left unchanged.
  81937. **
  81938. ** If a register is allocated and its location stored in *prRhsHasNull, then
  81939. ** the value in that register will be NULL if the b-tree contains one or more
  81940. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  81941. ** NULL values.
  81942. */
  81943. #ifndef SQLITE_OMIT_SUBQUERY
  81944. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
  81945. Select *p; /* SELECT to the right of IN operator */
  81946. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  81947. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  81948. int mustBeUnique; /* True if RHS must be unique */
  81949. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  81950. assert( pX->op==TK_IN );
  81951. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  81952. /* Check to see if an existing table or index can be used to
  81953. ** satisfy the query. This is preferable to generating a new
  81954. ** ephemeral table.
  81955. */
  81956. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  81957. if( pParse->nErr==0 && isCandidateForInOpt(p) ){
  81958. sqlite3 *db = pParse->db; /* Database connection */
  81959. Table *pTab; /* Table <table>. */
  81960. Expr *pExpr; /* Expression <column> */
  81961. i16 iCol; /* Index of column <column> */
  81962. i16 iDb; /* Database idx for pTab */
  81963. assert( p ); /* Because of isCandidateForInOpt(p) */
  81964. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  81965. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  81966. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  81967. pTab = p->pSrc->a[0].pTab;
  81968. pExpr = p->pEList->a[0].pExpr;
  81969. iCol = (i16)pExpr->iColumn;
  81970. /* Code an OP_Transaction and OP_TableLock for <table>. */
  81971. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  81972. sqlite3CodeVerifySchema(pParse, iDb);
  81973. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  81974. /* This function is only called from two places. In both cases the vdbe
  81975. ** has already been allocated. So assume sqlite3GetVdbe() is always
  81976. ** successful here.
  81977. */
  81978. assert(v);
  81979. if( iCol<0 ){
  81980. int iAddr = sqlite3CodeOnce(pParse);
  81981. VdbeCoverage(v);
  81982. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  81983. eType = IN_INDEX_ROWID;
  81984. sqlite3VdbeJumpHere(v, iAddr);
  81985. }else{
  81986. Index *pIdx; /* Iterator variable */
  81987. /* The collation sequence used by the comparison. If an index is to
  81988. ** be used in place of a temp-table, it must be ordered according
  81989. ** to this collation sequence. */
  81990. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  81991. /* Check that the affinity that will be used to perform the
  81992. ** comparison is the same as the affinity of the column. If
  81993. ** it is not, it is not possible to use any index.
  81994. */
  81995. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  81996. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  81997. if( (pIdx->aiColumn[0]==iCol)
  81998. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  81999. && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
  82000. ){
  82001. int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  82002. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  82003. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  82004. VdbeComment((v, "%s", pIdx->zName));
  82005. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  82006. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  82007. if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
  82008. *prRhsHasNull = ++pParse->nMem;
  82009. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  82010. }
  82011. sqlite3VdbeJumpHere(v, iAddr);
  82012. }
  82013. }
  82014. }
  82015. }
  82016. /* If no preexisting index is available for the IN clause
  82017. ** and IN_INDEX_NOOP is an allowed reply
  82018. ** and the RHS of the IN operator is a list, not a subquery
  82019. ** and the RHS is not contant or has two or fewer terms,
  82020. ** then it is not worth creating an ephemeral table to evaluate
  82021. ** the IN operator so return IN_INDEX_NOOP.
  82022. */
  82023. if( eType==0
  82024. && (inFlags & IN_INDEX_NOOP_OK)
  82025. && !ExprHasProperty(pX, EP_xIsSelect)
  82026. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  82027. ){
  82028. eType = IN_INDEX_NOOP;
  82029. }
  82030. if( eType==0 ){
  82031. /* Could not find an existing table or index to use as the RHS b-tree.
  82032. ** We will have to generate an ephemeral table to do the job.
  82033. */
  82034. u32 savedNQueryLoop = pParse->nQueryLoop;
  82035. int rMayHaveNull = 0;
  82036. eType = IN_INDEX_EPH;
  82037. if( inFlags & IN_INDEX_LOOP ){
  82038. pParse->nQueryLoop = 0;
  82039. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  82040. eType = IN_INDEX_ROWID;
  82041. }
  82042. }else if( prRhsHasNull ){
  82043. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  82044. }
  82045. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  82046. pParse->nQueryLoop = savedNQueryLoop;
  82047. }else{
  82048. pX->iTable = iTab;
  82049. }
  82050. return eType;
  82051. }
  82052. #endif
  82053. /*
  82054. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  82055. ** or IN operators. Examples:
  82056. **
  82057. ** (SELECT a FROM b) -- subquery
  82058. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  82059. ** x IN (4,5,11) -- IN operator with list on right-hand side
  82060. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  82061. **
  82062. ** The pExpr parameter describes the expression that contains the IN
  82063. ** operator or subquery.
  82064. **
  82065. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  82066. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  82067. ** to some integer key column of a table B-Tree. In this case, use an
  82068. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  82069. ** (slower) variable length keys B-Tree.
  82070. **
  82071. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  82072. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  82073. ** All this routine does is initialize the register given by rMayHaveNull
  82074. ** to NULL. Calling routines will take care of changing this register
  82075. ** value to non-NULL if the RHS is NULL-free.
  82076. **
  82077. ** For a SELECT or EXISTS operator, return the register that holds the
  82078. ** result. For IN operators or if an error occurs, the return value is 0.
  82079. */
  82080. #ifndef SQLITE_OMIT_SUBQUERY
  82081. SQLITE_PRIVATE int sqlite3CodeSubselect(
  82082. Parse *pParse, /* Parsing context */
  82083. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  82084. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  82085. int isRowid /* If true, LHS of IN operator is a rowid */
  82086. ){
  82087. int jmpIfDynamic = -1; /* One-time test address */
  82088. int rReg = 0; /* Register storing resulting */
  82089. Vdbe *v = sqlite3GetVdbe(pParse);
  82090. if( NEVER(v==0) ) return 0;
  82091. sqlite3ExprCachePush(pParse);
  82092. /* This code must be run in its entirety every time it is encountered
  82093. ** if any of the following is true:
  82094. **
  82095. ** * The right-hand side is a correlated subquery
  82096. ** * The right-hand side is an expression list containing variables
  82097. ** * We are inside a trigger
  82098. **
  82099. ** If all of the above are false, then we can run this code just once
  82100. ** save the results, and reuse the same result on subsequent invocations.
  82101. */
  82102. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  82103. jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  82104. }
  82105. #ifndef SQLITE_OMIT_EXPLAIN
  82106. if( pParse->explain==2 ){
  82107. char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
  82108. jmpIfDynamic>=0?"":"CORRELATED ",
  82109. pExpr->op==TK_IN?"LIST":"SCALAR",
  82110. pParse->iNextSelectId
  82111. );
  82112. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  82113. }
  82114. #endif
  82115. switch( pExpr->op ){
  82116. case TK_IN: {
  82117. char affinity; /* Affinity of the LHS of the IN */
  82118. int addr; /* Address of OP_OpenEphemeral instruction */
  82119. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  82120. KeyInfo *pKeyInfo = 0; /* Key information */
  82121. affinity = sqlite3ExprAffinity(pLeft);
  82122. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  82123. ** expression it is handled the same way. An ephemeral table is
  82124. ** filled with single-field index keys representing the results
  82125. ** from the SELECT or the <exprlist>.
  82126. **
  82127. ** If the 'x' expression is a column value, or the SELECT...
  82128. ** statement returns a column value, then the affinity of that
  82129. ** column is used to build the index keys. If both 'x' and the
  82130. ** SELECT... statement are columns, then numeric affinity is used
  82131. ** if either column has NUMERIC or INTEGER affinity. If neither
  82132. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  82133. ** is used.
  82134. */
  82135. pExpr->iTable = pParse->nTab++;
  82136. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  82137. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
  82138. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  82139. /* Case 1: expr IN (SELECT ...)
  82140. **
  82141. ** Generate code to write the results of the select into the temporary
  82142. ** table allocated and opened above.
  82143. */
  82144. Select *pSelect = pExpr->x.pSelect;
  82145. SelectDest dest;
  82146. ExprList *pEList;
  82147. assert( !isRowid );
  82148. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  82149. dest.affSdst = (u8)affinity;
  82150. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  82151. pSelect->iLimit = 0;
  82152. testcase( pSelect->selFlags & SF_Distinct );
  82153. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  82154. if( sqlite3Select(pParse, pSelect, &dest) ){
  82155. sqlite3KeyInfoUnref(pKeyInfo);
  82156. return 0;
  82157. }
  82158. pEList = pSelect->pEList;
  82159. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  82160. assert( pEList!=0 );
  82161. assert( pEList->nExpr>0 );
  82162. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  82163. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  82164. pEList->a[0].pExpr);
  82165. }else if( ALWAYS(pExpr->x.pList!=0) ){
  82166. /* Case 2: expr IN (exprlist)
  82167. **
  82168. ** For each expression, build an index key from the evaluation and
  82169. ** store it in the temporary table. If <expr> is a column, then use
  82170. ** that columns affinity when building index keys. If <expr> is not
  82171. ** a column, use numeric affinity.
  82172. */
  82173. int i;
  82174. ExprList *pList = pExpr->x.pList;
  82175. struct ExprList_item *pItem;
  82176. int r1, r2, r3;
  82177. if( !affinity ){
  82178. affinity = SQLITE_AFF_BLOB;
  82179. }
  82180. if( pKeyInfo ){
  82181. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  82182. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  82183. }
  82184. /* Loop through each expression in <exprlist>. */
  82185. r1 = sqlite3GetTempReg(pParse);
  82186. r2 = sqlite3GetTempReg(pParse);
  82187. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  82188. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  82189. Expr *pE2 = pItem->pExpr;
  82190. int iValToIns;
  82191. /* If the expression is not constant then we will need to
  82192. ** disable the test that was generated above that makes sure
  82193. ** this code only executes once. Because for a non-constant
  82194. ** expression we need to rerun this code each time.
  82195. */
  82196. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  82197. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  82198. jmpIfDynamic = -1;
  82199. }
  82200. /* Evaluate the expression and insert it into the temp table */
  82201. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  82202. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  82203. }else{
  82204. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  82205. if( isRowid ){
  82206. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  82207. sqlite3VdbeCurrentAddr(v)+2);
  82208. VdbeCoverage(v);
  82209. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  82210. }else{
  82211. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  82212. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  82213. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  82214. }
  82215. }
  82216. }
  82217. sqlite3ReleaseTempReg(pParse, r1);
  82218. sqlite3ReleaseTempReg(pParse, r2);
  82219. }
  82220. if( pKeyInfo ){
  82221. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  82222. }
  82223. break;
  82224. }
  82225. case TK_EXISTS:
  82226. case TK_SELECT:
  82227. default: {
  82228. /* If this has to be a scalar SELECT. Generate code to put the
  82229. ** value of this select in a memory cell and record the number
  82230. ** of the memory cell in iColumn. If this is an EXISTS, write
  82231. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  82232. ** and record that memory cell in iColumn.
  82233. */
  82234. Select *pSel; /* SELECT statement to encode */
  82235. SelectDest dest; /* How to deal with SELECt result */
  82236. testcase( pExpr->op==TK_EXISTS );
  82237. testcase( pExpr->op==TK_SELECT );
  82238. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  82239. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  82240. pSel = pExpr->x.pSelect;
  82241. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  82242. if( pExpr->op==TK_SELECT ){
  82243. dest.eDest = SRT_Mem;
  82244. dest.iSdst = dest.iSDParm;
  82245. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  82246. VdbeComment((v, "Init subquery result"));
  82247. }else{
  82248. dest.eDest = SRT_Exists;
  82249. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  82250. VdbeComment((v, "Init EXISTS result"));
  82251. }
  82252. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  82253. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  82254. &sqlite3IntTokens[1]);
  82255. pSel->iLimit = 0;
  82256. pSel->selFlags &= ~SF_MultiValue;
  82257. if( sqlite3Select(pParse, pSel, &dest) ){
  82258. return 0;
  82259. }
  82260. rReg = dest.iSDParm;
  82261. ExprSetVVAProperty(pExpr, EP_NoReduce);
  82262. break;
  82263. }
  82264. }
  82265. if( rHasNullFlag ){
  82266. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  82267. }
  82268. if( jmpIfDynamic>=0 ){
  82269. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  82270. }
  82271. sqlite3ExprCachePop(pParse);
  82272. return rReg;
  82273. }
  82274. #endif /* SQLITE_OMIT_SUBQUERY */
  82275. #ifndef SQLITE_OMIT_SUBQUERY
  82276. /*
  82277. ** Generate code for an IN expression.
  82278. **
  82279. ** x IN (SELECT ...)
  82280. ** x IN (value, value, ...)
  82281. **
  82282. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  82283. ** is an array of zero or more values. The expression is true if the LHS is
  82284. ** contained within the RHS. The value of the expression is unknown (NULL)
  82285. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  82286. ** RHS contains one or more NULL values.
  82287. **
  82288. ** This routine generates code that jumps to destIfFalse if the LHS is not
  82289. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  82290. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  82291. ** within the RHS then fall through.
  82292. */
  82293. static void sqlite3ExprCodeIN(
  82294. Parse *pParse, /* Parsing and code generating context */
  82295. Expr *pExpr, /* The IN expression */
  82296. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  82297. int destIfNull /* Jump here if the results are unknown due to NULLs */
  82298. ){
  82299. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  82300. char affinity; /* Comparison affinity to use */
  82301. int eType; /* Type of the RHS */
  82302. int r1; /* Temporary use register */
  82303. Vdbe *v; /* Statement under construction */
  82304. /* Compute the RHS. After this step, the table with cursor
  82305. ** pExpr->iTable will contains the values that make up the RHS.
  82306. */
  82307. v = pParse->pVdbe;
  82308. assert( v!=0 ); /* OOM detected prior to this routine */
  82309. VdbeNoopComment((v, "begin IN expr"));
  82310. eType = sqlite3FindInIndex(pParse, pExpr,
  82311. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  82312. destIfFalse==destIfNull ? 0 : &rRhsHasNull);
  82313. /* Figure out the affinity to use to create a key from the results
  82314. ** of the expression. affinityStr stores a static string suitable for
  82315. ** P4 of OP_MakeRecord.
  82316. */
  82317. affinity = comparisonAffinity(pExpr);
  82318. /* Code the LHS, the <expr> from "<expr> IN (...)".
  82319. */
  82320. sqlite3ExprCachePush(pParse);
  82321. r1 = sqlite3GetTempReg(pParse);
  82322. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  82323. /* If sqlite3FindInIndex() did not find or create an index that is
  82324. ** suitable for evaluating the IN operator, then evaluate using a
  82325. ** sequence of comparisons.
  82326. */
  82327. if( eType==IN_INDEX_NOOP ){
  82328. ExprList *pList = pExpr->x.pList;
  82329. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  82330. int labelOk = sqlite3VdbeMakeLabel(v);
  82331. int r2, regToFree;
  82332. int regCkNull = 0;
  82333. int ii;
  82334. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  82335. if( destIfNull!=destIfFalse ){
  82336. regCkNull = sqlite3GetTempReg(pParse);
  82337. sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
  82338. }
  82339. for(ii=0; ii<pList->nExpr; ii++){
  82340. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  82341. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  82342. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  82343. }
  82344. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  82345. sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
  82346. (void*)pColl, P4_COLLSEQ);
  82347. VdbeCoverageIf(v, ii<pList->nExpr-1);
  82348. VdbeCoverageIf(v, ii==pList->nExpr-1);
  82349. sqlite3VdbeChangeP5(v, affinity);
  82350. }else{
  82351. assert( destIfNull==destIfFalse );
  82352. sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
  82353. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  82354. sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
  82355. }
  82356. sqlite3ReleaseTempReg(pParse, regToFree);
  82357. }
  82358. if( regCkNull ){
  82359. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  82360. sqlite3VdbeGoto(v, destIfFalse);
  82361. }
  82362. sqlite3VdbeResolveLabel(v, labelOk);
  82363. sqlite3ReleaseTempReg(pParse, regCkNull);
  82364. }else{
  82365. /* If the LHS is NULL, then the result is either false or NULL depending
  82366. ** on whether the RHS is empty or not, respectively.
  82367. */
  82368. if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
  82369. if( destIfNull==destIfFalse ){
  82370. /* Shortcut for the common case where the false and NULL outcomes are
  82371. ** the same. */
  82372. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
  82373. }else{
  82374. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
  82375. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  82376. VdbeCoverage(v);
  82377. sqlite3VdbeGoto(v, destIfNull);
  82378. sqlite3VdbeJumpHere(v, addr1);
  82379. }
  82380. }
  82381. if( eType==IN_INDEX_ROWID ){
  82382. /* In this case, the RHS is the ROWID of table b-tree
  82383. */
  82384. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
  82385. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  82386. VdbeCoverage(v);
  82387. }else{
  82388. /* In this case, the RHS is an index b-tree.
  82389. */
  82390. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  82391. /* If the set membership test fails, then the result of the
  82392. ** "x IN (...)" expression must be either 0 or NULL. If the set
  82393. ** contains no NULL values, then the result is 0. If the set
  82394. ** contains one or more NULL values, then the result of the
  82395. ** expression is also NULL.
  82396. */
  82397. assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
  82398. if( rRhsHasNull==0 ){
  82399. /* This branch runs if it is known at compile time that the RHS
  82400. ** cannot contain NULL values. This happens as the result
  82401. ** of a "NOT NULL" constraint in the database schema.
  82402. **
  82403. ** Also run this branch if NULL is equivalent to FALSE
  82404. ** for this particular IN operator.
  82405. */
  82406. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  82407. VdbeCoverage(v);
  82408. }else{
  82409. /* In this branch, the RHS of the IN might contain a NULL and
  82410. ** the presence of a NULL on the RHS makes a difference in the
  82411. ** outcome.
  82412. */
  82413. int addr1;
  82414. /* First check to see if the LHS is contained in the RHS. If so,
  82415. ** then the answer is TRUE the presence of NULLs in the RHS does
  82416. ** not matter. If the LHS is not contained in the RHS, then the
  82417. ** answer is NULL if the RHS contains NULLs and the answer is
  82418. ** FALSE if the RHS is NULL-free.
  82419. */
  82420. addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  82421. VdbeCoverage(v);
  82422. sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
  82423. VdbeCoverage(v);
  82424. sqlite3VdbeGoto(v, destIfFalse);
  82425. sqlite3VdbeJumpHere(v, addr1);
  82426. }
  82427. }
  82428. }
  82429. sqlite3ReleaseTempReg(pParse, r1);
  82430. sqlite3ExprCachePop(pParse);
  82431. VdbeComment((v, "end IN expr"));
  82432. }
  82433. #endif /* SQLITE_OMIT_SUBQUERY */
  82434. #ifndef SQLITE_OMIT_FLOATING_POINT
  82435. /*
  82436. ** Generate an instruction that will put the floating point
  82437. ** value described by z[0..n-1] into register iMem.
  82438. **
  82439. ** The z[] string will probably not be zero-terminated. But the
  82440. ** z[n] character is guaranteed to be something that does not look
  82441. ** like the continuation of the number.
  82442. */
  82443. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  82444. if( ALWAYS(z!=0) ){
  82445. double value;
  82446. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  82447. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  82448. if( negateFlag ) value = -value;
  82449. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  82450. }
  82451. }
  82452. #endif
  82453. /*
  82454. ** Generate an instruction that will put the integer describe by
  82455. ** text z[0..n-1] into register iMem.
  82456. **
  82457. ** Expr.u.zToken is always UTF8 and zero-terminated.
  82458. */
  82459. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  82460. Vdbe *v = pParse->pVdbe;
  82461. if( pExpr->flags & EP_IntValue ){
  82462. int i = pExpr->u.iValue;
  82463. assert( i>=0 );
  82464. if( negFlag ) i = -i;
  82465. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  82466. }else{
  82467. int c;
  82468. i64 value;
  82469. const char *z = pExpr->u.zToken;
  82470. assert( z!=0 );
  82471. c = sqlite3DecOrHexToI64(z, &value);
  82472. if( c==0 || (c==2 && negFlag) ){
  82473. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  82474. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  82475. }else{
  82476. #ifdef SQLITE_OMIT_FLOATING_POINT
  82477. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  82478. #else
  82479. #ifndef SQLITE_OMIT_HEX_INTEGER
  82480. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  82481. sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
  82482. }else
  82483. #endif
  82484. {
  82485. codeReal(v, z, negFlag, iMem);
  82486. }
  82487. #endif
  82488. }
  82489. }
  82490. }
  82491. /*
  82492. ** Clear a cache entry.
  82493. */
  82494. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  82495. if( p->tempReg ){
  82496. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  82497. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  82498. }
  82499. p->tempReg = 0;
  82500. }
  82501. }
  82502. /*
  82503. ** Record in the column cache that a particular column from a
  82504. ** particular table is stored in a particular register.
  82505. */
  82506. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  82507. int i;
  82508. int minLru;
  82509. int idxLru;
  82510. struct yColCache *p;
  82511. /* Unless an error has occurred, register numbers are always positive. */
  82512. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  82513. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  82514. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  82515. ** for testing only - to verify that SQLite always gets the same answer
  82516. ** with and without the column cache.
  82517. */
  82518. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  82519. /* First replace any existing entry.
  82520. **
  82521. ** Actually, the way the column cache is currently used, we are guaranteed
  82522. ** that the object will never already be in cache. Verify this guarantee.
  82523. */
  82524. #ifndef NDEBUG
  82525. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82526. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  82527. }
  82528. #endif
  82529. /* Find an empty slot and replace it */
  82530. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82531. if( p->iReg==0 ){
  82532. p->iLevel = pParse->iCacheLevel;
  82533. p->iTable = iTab;
  82534. p->iColumn = iCol;
  82535. p->iReg = iReg;
  82536. p->tempReg = 0;
  82537. p->lru = pParse->iCacheCnt++;
  82538. return;
  82539. }
  82540. }
  82541. /* Replace the last recently used */
  82542. minLru = 0x7fffffff;
  82543. idxLru = -1;
  82544. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82545. if( p->lru<minLru ){
  82546. idxLru = i;
  82547. minLru = p->lru;
  82548. }
  82549. }
  82550. if( ALWAYS(idxLru>=0) ){
  82551. p = &pParse->aColCache[idxLru];
  82552. p->iLevel = pParse->iCacheLevel;
  82553. p->iTable = iTab;
  82554. p->iColumn = iCol;
  82555. p->iReg = iReg;
  82556. p->tempReg = 0;
  82557. p->lru = pParse->iCacheCnt++;
  82558. return;
  82559. }
  82560. }
  82561. /*
  82562. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  82563. ** Purge the range of registers from the column cache.
  82564. */
  82565. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  82566. int i;
  82567. int iLast = iReg + nReg - 1;
  82568. struct yColCache *p;
  82569. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82570. int r = p->iReg;
  82571. if( r>=iReg && r<=iLast ){
  82572. cacheEntryClear(pParse, p);
  82573. p->iReg = 0;
  82574. }
  82575. }
  82576. }
  82577. /*
  82578. ** Remember the current column cache context. Any new entries added
  82579. ** added to the column cache after this call are removed when the
  82580. ** corresponding pop occurs.
  82581. */
  82582. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  82583. pParse->iCacheLevel++;
  82584. #ifdef SQLITE_DEBUG
  82585. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  82586. printf("PUSH to %d\n", pParse->iCacheLevel);
  82587. }
  82588. #endif
  82589. }
  82590. /*
  82591. ** Remove from the column cache any entries that were added since the
  82592. ** the previous sqlite3ExprCachePush operation. In other words, restore
  82593. ** the cache to the state it was in prior the most recent Push.
  82594. */
  82595. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  82596. int i;
  82597. struct yColCache *p;
  82598. assert( pParse->iCacheLevel>=1 );
  82599. pParse->iCacheLevel--;
  82600. #ifdef SQLITE_DEBUG
  82601. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  82602. printf("POP to %d\n", pParse->iCacheLevel);
  82603. }
  82604. #endif
  82605. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82606. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  82607. cacheEntryClear(pParse, p);
  82608. p->iReg = 0;
  82609. }
  82610. }
  82611. }
  82612. /*
  82613. ** When a cached column is reused, make sure that its register is
  82614. ** no longer available as a temp register. ticket #3879: that same
  82615. ** register might be in the cache in multiple places, so be sure to
  82616. ** get them all.
  82617. */
  82618. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  82619. int i;
  82620. struct yColCache *p;
  82621. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82622. if( p->iReg==iReg ){
  82623. p->tempReg = 0;
  82624. }
  82625. }
  82626. }
  82627. /* Generate code that will load into register regOut a value that is
  82628. ** appropriate for the iIdxCol-th column of index pIdx.
  82629. */
  82630. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  82631. Parse *pParse, /* The parsing context */
  82632. Index *pIdx, /* The index whose column is to be loaded */
  82633. int iTabCur, /* Cursor pointing to a table row */
  82634. int iIdxCol, /* The column of the index to be loaded */
  82635. int regOut /* Store the index column value in this register */
  82636. ){
  82637. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  82638. if( iTabCol==XN_EXPR ){
  82639. assert( pIdx->aColExpr );
  82640. assert( pIdx->aColExpr->nExpr>iIdxCol );
  82641. pParse->iSelfTab = iTabCur;
  82642. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  82643. }else{
  82644. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  82645. iTabCol, regOut);
  82646. }
  82647. }
  82648. /*
  82649. ** Generate code to extract the value of the iCol-th column of a table.
  82650. */
  82651. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  82652. Vdbe *v, /* The VDBE under construction */
  82653. Table *pTab, /* The table containing the value */
  82654. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  82655. int iCol, /* Index of the column to extract */
  82656. int regOut /* Extract the value into this register */
  82657. ){
  82658. if( iCol<0 || iCol==pTab->iPKey ){
  82659. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  82660. }else{
  82661. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  82662. int x = iCol;
  82663. if( !HasRowid(pTab) ){
  82664. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  82665. }
  82666. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  82667. }
  82668. if( iCol>=0 ){
  82669. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  82670. }
  82671. }
  82672. /*
  82673. ** Generate code that will extract the iColumn-th column from
  82674. ** table pTab and store the column value in a register.
  82675. **
  82676. ** An effort is made to store the column value in register iReg. This
  82677. ** is not garanteeed for GetColumn() - the result can be stored in
  82678. ** any register. But the result is guaranteed to land in register iReg
  82679. ** for GetColumnToReg().
  82680. **
  82681. ** There must be an open cursor to pTab in iTable when this routine
  82682. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  82683. */
  82684. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  82685. Parse *pParse, /* Parsing and code generating context */
  82686. Table *pTab, /* Description of the table we are reading from */
  82687. int iColumn, /* Index of the table column */
  82688. int iTable, /* The cursor pointing to the table */
  82689. int iReg, /* Store results here */
  82690. u8 p5 /* P5 value for OP_Column + FLAGS */
  82691. ){
  82692. Vdbe *v = pParse->pVdbe;
  82693. int i;
  82694. struct yColCache *p;
  82695. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82696. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  82697. p->lru = pParse->iCacheCnt++;
  82698. sqlite3ExprCachePinRegister(pParse, p->iReg);
  82699. return p->iReg;
  82700. }
  82701. }
  82702. assert( v!=0 );
  82703. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  82704. if( p5 ){
  82705. sqlite3VdbeChangeP5(v, p5);
  82706. }else{
  82707. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  82708. }
  82709. return iReg;
  82710. }
  82711. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
  82712. Parse *pParse, /* Parsing and code generating context */
  82713. Table *pTab, /* Description of the table we are reading from */
  82714. int iColumn, /* Index of the table column */
  82715. int iTable, /* The cursor pointing to the table */
  82716. int iReg /* Store results here */
  82717. ){
  82718. int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
  82719. if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
  82720. }
  82721. /*
  82722. ** Clear all column cache entries.
  82723. */
  82724. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  82725. int i;
  82726. struct yColCache *p;
  82727. #if SQLITE_DEBUG
  82728. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  82729. printf("CLEAR\n");
  82730. }
  82731. #endif
  82732. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82733. if( p->iReg ){
  82734. cacheEntryClear(pParse, p);
  82735. p->iReg = 0;
  82736. }
  82737. }
  82738. }
  82739. /*
  82740. ** Record the fact that an affinity change has occurred on iCount
  82741. ** registers starting with iStart.
  82742. */
  82743. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  82744. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  82745. }
  82746. /*
  82747. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  82748. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  82749. */
  82750. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  82751. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  82752. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  82753. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  82754. }
  82755. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  82756. /*
  82757. ** Return true if any register in the range iFrom..iTo (inclusive)
  82758. ** is used as part of the column cache.
  82759. **
  82760. ** This routine is used within assert() and testcase() macros only
  82761. ** and does not appear in a normal build.
  82762. */
  82763. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  82764. int i;
  82765. struct yColCache *p;
  82766. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82767. int r = p->iReg;
  82768. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  82769. }
  82770. return 0;
  82771. }
  82772. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  82773. /*
  82774. ** Convert an expression node to a TK_REGISTER
  82775. */
  82776. static void exprToRegister(Expr *p, int iReg){
  82777. p->op2 = p->op;
  82778. p->op = TK_REGISTER;
  82779. p->iTable = iReg;
  82780. ExprClearProperty(p, EP_Skip);
  82781. }
  82782. /*
  82783. ** Generate code into the current Vdbe to evaluate the given
  82784. ** expression. Attempt to store the results in register "target".
  82785. ** Return the register where results are stored.
  82786. **
  82787. ** With this routine, there is no guarantee that results will
  82788. ** be stored in target. The result might be stored in some other
  82789. ** register if it is convenient to do so. The calling function
  82790. ** must check the return code and move the results to the desired
  82791. ** register.
  82792. */
  82793. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  82794. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  82795. int op; /* The opcode being coded */
  82796. int inReg = target; /* Results stored in register inReg */
  82797. int regFree1 = 0; /* If non-zero free this temporary register */
  82798. int regFree2 = 0; /* If non-zero free this temporary register */
  82799. int r1, r2, r3, r4; /* Various register numbers */
  82800. sqlite3 *db = pParse->db; /* The database connection */
  82801. Expr tempX; /* Temporary expression node */
  82802. assert( target>0 && target<=pParse->nMem );
  82803. if( v==0 ){
  82804. assert( pParse->db->mallocFailed );
  82805. return 0;
  82806. }
  82807. if( pExpr==0 ){
  82808. op = TK_NULL;
  82809. }else{
  82810. op = pExpr->op;
  82811. }
  82812. switch( op ){
  82813. case TK_AGG_COLUMN: {
  82814. AggInfo *pAggInfo = pExpr->pAggInfo;
  82815. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  82816. if( !pAggInfo->directMode ){
  82817. assert( pCol->iMem>0 );
  82818. inReg = pCol->iMem;
  82819. break;
  82820. }else if( pAggInfo->useSortingIdx ){
  82821. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  82822. pCol->iSorterColumn, target);
  82823. break;
  82824. }
  82825. /* Otherwise, fall thru into the TK_COLUMN case */
  82826. }
  82827. case TK_COLUMN: {
  82828. int iTab = pExpr->iTable;
  82829. if( iTab<0 ){
  82830. if( pParse->ckBase>0 ){
  82831. /* Generating CHECK constraints or inserting into partial index */
  82832. inReg = pExpr->iColumn + pParse->ckBase;
  82833. break;
  82834. }else{
  82835. /* Coding an expression that is part of an index where column names
  82836. ** in the index refer to the table to which the index belongs */
  82837. iTab = pParse->iSelfTab;
  82838. }
  82839. }
  82840. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  82841. pExpr->iColumn, iTab, target,
  82842. pExpr->op2);
  82843. break;
  82844. }
  82845. case TK_INTEGER: {
  82846. codeInteger(pParse, pExpr, 0, target);
  82847. break;
  82848. }
  82849. #ifndef SQLITE_OMIT_FLOATING_POINT
  82850. case TK_FLOAT: {
  82851. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82852. codeReal(v, pExpr->u.zToken, 0, target);
  82853. break;
  82854. }
  82855. #endif
  82856. case TK_STRING: {
  82857. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82858. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  82859. break;
  82860. }
  82861. case TK_NULL: {
  82862. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  82863. break;
  82864. }
  82865. #ifndef SQLITE_OMIT_BLOB_LITERAL
  82866. case TK_BLOB: {
  82867. int n;
  82868. const char *z;
  82869. char *zBlob;
  82870. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82871. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  82872. assert( pExpr->u.zToken[1]=='\'' );
  82873. z = &pExpr->u.zToken[2];
  82874. n = sqlite3Strlen30(z) - 1;
  82875. assert( z[n]=='\'' );
  82876. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  82877. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  82878. break;
  82879. }
  82880. #endif
  82881. case TK_VARIABLE: {
  82882. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82883. assert( pExpr->u.zToken!=0 );
  82884. assert( pExpr->u.zToken[0]!=0 );
  82885. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  82886. if( pExpr->u.zToken[1]!=0 ){
  82887. assert( pExpr->u.zToken[0]=='?'
  82888. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  82889. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  82890. }
  82891. break;
  82892. }
  82893. case TK_REGISTER: {
  82894. inReg = pExpr->iTable;
  82895. break;
  82896. }
  82897. #ifndef SQLITE_OMIT_CAST
  82898. case TK_CAST: {
  82899. /* Expressions of the form: CAST(pLeft AS token) */
  82900. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  82901. if( inReg!=target ){
  82902. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  82903. inReg = target;
  82904. }
  82905. sqlite3VdbeAddOp2(v, OP_Cast, target,
  82906. sqlite3AffinityType(pExpr->u.zToken, 0));
  82907. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  82908. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  82909. break;
  82910. }
  82911. #endif /* SQLITE_OMIT_CAST */
  82912. case TK_LT:
  82913. case TK_LE:
  82914. case TK_GT:
  82915. case TK_GE:
  82916. case TK_NE:
  82917. case TK_EQ: {
  82918. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82919. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82920. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82921. r1, r2, inReg, SQLITE_STOREP2);
  82922. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  82923. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  82924. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  82925. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  82926. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  82927. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  82928. testcase( regFree1==0 );
  82929. testcase( regFree2==0 );
  82930. break;
  82931. }
  82932. case TK_IS:
  82933. case TK_ISNOT: {
  82934. testcase( op==TK_IS );
  82935. testcase( op==TK_ISNOT );
  82936. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82937. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82938. op = (op==TK_IS) ? TK_EQ : TK_NE;
  82939. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82940. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  82941. VdbeCoverageIf(v, op==TK_EQ);
  82942. VdbeCoverageIf(v, op==TK_NE);
  82943. testcase( regFree1==0 );
  82944. testcase( regFree2==0 );
  82945. break;
  82946. }
  82947. case TK_AND:
  82948. case TK_OR:
  82949. case TK_PLUS:
  82950. case TK_STAR:
  82951. case TK_MINUS:
  82952. case TK_REM:
  82953. case TK_BITAND:
  82954. case TK_BITOR:
  82955. case TK_SLASH:
  82956. case TK_LSHIFT:
  82957. case TK_RSHIFT:
  82958. case TK_CONCAT: {
  82959. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  82960. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  82961. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  82962. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  82963. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  82964. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  82965. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  82966. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  82967. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  82968. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  82969. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  82970. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82971. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82972. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  82973. testcase( regFree1==0 );
  82974. testcase( regFree2==0 );
  82975. break;
  82976. }
  82977. case TK_UMINUS: {
  82978. Expr *pLeft = pExpr->pLeft;
  82979. assert( pLeft );
  82980. if( pLeft->op==TK_INTEGER ){
  82981. codeInteger(pParse, pLeft, 1, target);
  82982. #ifndef SQLITE_OMIT_FLOATING_POINT
  82983. }else if( pLeft->op==TK_FLOAT ){
  82984. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82985. codeReal(v, pLeft->u.zToken, 1, target);
  82986. #endif
  82987. }else{
  82988. tempX.op = TK_INTEGER;
  82989. tempX.flags = EP_IntValue|EP_TokenOnly;
  82990. tempX.u.iValue = 0;
  82991. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  82992. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  82993. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  82994. testcase( regFree2==0 );
  82995. }
  82996. inReg = target;
  82997. break;
  82998. }
  82999. case TK_BITNOT:
  83000. case TK_NOT: {
  83001. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  83002. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  83003. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83004. testcase( regFree1==0 );
  83005. inReg = target;
  83006. sqlite3VdbeAddOp2(v, op, r1, inReg);
  83007. break;
  83008. }
  83009. case TK_ISNULL:
  83010. case TK_NOTNULL: {
  83011. int addr;
  83012. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  83013. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  83014. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  83015. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83016. testcase( regFree1==0 );
  83017. addr = sqlite3VdbeAddOp1(v, op, r1);
  83018. VdbeCoverageIf(v, op==TK_ISNULL);
  83019. VdbeCoverageIf(v, op==TK_NOTNULL);
  83020. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  83021. sqlite3VdbeJumpHere(v, addr);
  83022. break;
  83023. }
  83024. case TK_AGG_FUNCTION: {
  83025. AggInfo *pInfo = pExpr->pAggInfo;
  83026. if( pInfo==0 ){
  83027. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83028. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  83029. }else{
  83030. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  83031. }
  83032. break;
  83033. }
  83034. case TK_FUNCTION: {
  83035. ExprList *pFarg; /* List of function arguments */
  83036. int nFarg; /* Number of function arguments */
  83037. FuncDef *pDef; /* The function definition object */
  83038. int nId; /* Length of the function name in bytes */
  83039. const char *zId; /* The function name */
  83040. u32 constMask = 0; /* Mask of function arguments that are constant */
  83041. int i; /* Loop counter */
  83042. u8 enc = ENC(db); /* The text encoding used by this database */
  83043. CollSeq *pColl = 0; /* A collating sequence */
  83044. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  83045. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  83046. pFarg = 0;
  83047. }else{
  83048. pFarg = pExpr->x.pList;
  83049. }
  83050. nFarg = pFarg ? pFarg->nExpr : 0;
  83051. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83052. zId = pExpr->u.zToken;
  83053. nId = sqlite3Strlen30(zId);
  83054. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  83055. if( pDef==0 || pDef->xFunc==0 ){
  83056. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  83057. break;
  83058. }
  83059. /* Attempt a direct implementation of the built-in COALESCE() and
  83060. ** IFNULL() functions. This avoids unnecessary evaluation of
  83061. ** arguments past the first non-NULL argument.
  83062. */
  83063. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  83064. int endCoalesce = sqlite3VdbeMakeLabel(v);
  83065. assert( nFarg>=2 );
  83066. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  83067. for(i=1; i<nFarg; i++){
  83068. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  83069. VdbeCoverage(v);
  83070. sqlite3ExprCacheRemove(pParse, target, 1);
  83071. sqlite3ExprCachePush(pParse);
  83072. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  83073. sqlite3ExprCachePop(pParse);
  83074. }
  83075. sqlite3VdbeResolveLabel(v, endCoalesce);
  83076. break;
  83077. }
  83078. /* The UNLIKELY() function is a no-op. The result is the value
  83079. ** of the first argument.
  83080. */
  83081. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  83082. assert( nFarg>=1 );
  83083. inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  83084. break;
  83085. }
  83086. for(i=0; i<nFarg; i++){
  83087. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  83088. testcase( i==31 );
  83089. constMask |= MASKBIT32(i);
  83090. }
  83091. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  83092. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  83093. }
  83094. }
  83095. if( pFarg ){
  83096. if( constMask ){
  83097. r1 = pParse->nMem+1;
  83098. pParse->nMem += nFarg;
  83099. }else{
  83100. r1 = sqlite3GetTempRange(pParse, nFarg);
  83101. }
  83102. /* For length() and typeof() functions with a column argument,
  83103. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  83104. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  83105. ** loading.
  83106. */
  83107. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  83108. u8 exprOp;
  83109. assert( nFarg==1 );
  83110. assert( pFarg->a[0].pExpr!=0 );
  83111. exprOp = pFarg->a[0].pExpr->op;
  83112. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  83113. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  83114. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  83115. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  83116. pFarg->a[0].pExpr->op2 =
  83117. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  83118. }
  83119. }
  83120. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  83121. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  83122. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  83123. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  83124. }else{
  83125. r1 = 0;
  83126. }
  83127. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83128. /* Possibly overload the function if the first argument is
  83129. ** a virtual table column.
  83130. **
  83131. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  83132. ** second argument, not the first, as the argument to test to
  83133. ** see if it is a column in a virtual table. This is done because
  83134. ** the left operand of infix functions (the operand we want to
  83135. ** control overloading) ends up as the second argument to the
  83136. ** function. The expression "A glob B" is equivalent to
  83137. ** "glob(B,A). We want to use the A in "A glob B" to test
  83138. ** for function overloading. But we use the B term in "glob(B,A)".
  83139. */
  83140. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  83141. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  83142. }else if( nFarg>0 ){
  83143. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  83144. }
  83145. #endif
  83146. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  83147. if( !pColl ) pColl = db->pDfltColl;
  83148. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  83149. }
  83150. sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
  83151. (char*)pDef, P4_FUNCDEF);
  83152. sqlite3VdbeChangeP5(v, (u8)nFarg);
  83153. if( nFarg && constMask==0 ){
  83154. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  83155. }
  83156. break;
  83157. }
  83158. #ifndef SQLITE_OMIT_SUBQUERY
  83159. case TK_EXISTS:
  83160. case TK_SELECT: {
  83161. testcase( op==TK_EXISTS );
  83162. testcase( op==TK_SELECT );
  83163. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  83164. break;
  83165. }
  83166. case TK_IN: {
  83167. int destIfFalse = sqlite3VdbeMakeLabel(v);
  83168. int destIfNull = sqlite3VdbeMakeLabel(v);
  83169. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  83170. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  83171. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  83172. sqlite3VdbeResolveLabel(v, destIfFalse);
  83173. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  83174. sqlite3VdbeResolveLabel(v, destIfNull);
  83175. break;
  83176. }
  83177. #endif /* SQLITE_OMIT_SUBQUERY */
  83178. /*
  83179. ** x BETWEEN y AND z
  83180. **
  83181. ** This is equivalent to
  83182. **
  83183. ** x>=y AND x<=z
  83184. **
  83185. ** X is stored in pExpr->pLeft.
  83186. ** Y is stored in pExpr->pList->a[0].pExpr.
  83187. ** Z is stored in pExpr->pList->a[1].pExpr.
  83188. */
  83189. case TK_BETWEEN: {
  83190. Expr *pLeft = pExpr->pLeft;
  83191. struct ExprList_item *pLItem = pExpr->x.pList->a;
  83192. Expr *pRight = pLItem->pExpr;
  83193. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  83194. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  83195. testcase( regFree1==0 );
  83196. testcase( regFree2==0 );
  83197. r3 = sqlite3GetTempReg(pParse);
  83198. r4 = sqlite3GetTempReg(pParse);
  83199. codeCompare(pParse, pLeft, pRight, OP_Ge,
  83200. r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
  83201. pLItem++;
  83202. pRight = pLItem->pExpr;
  83203. sqlite3ReleaseTempReg(pParse, regFree2);
  83204. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  83205. testcase( regFree2==0 );
  83206. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  83207. VdbeCoverage(v);
  83208. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  83209. sqlite3ReleaseTempReg(pParse, r3);
  83210. sqlite3ReleaseTempReg(pParse, r4);
  83211. break;
  83212. }
  83213. case TK_COLLATE:
  83214. case TK_UPLUS: {
  83215. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  83216. break;
  83217. }
  83218. case TK_TRIGGER: {
  83219. /* If the opcode is TK_TRIGGER, then the expression is a reference
  83220. ** to a column in the new.* or old.* pseudo-tables available to
  83221. ** trigger programs. In this case Expr.iTable is set to 1 for the
  83222. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  83223. ** is set to the column of the pseudo-table to read, or to -1 to
  83224. ** read the rowid field.
  83225. **
  83226. ** The expression is implemented using an OP_Param opcode. The p1
  83227. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  83228. ** to reference another column of the old.* pseudo-table, where
  83229. ** i is the index of the column. For a new.rowid reference, p1 is
  83230. ** set to (n+1), where n is the number of columns in each pseudo-table.
  83231. ** For a reference to any other column in the new.* pseudo-table, p1
  83232. ** is set to (n+2+i), where n and i are as defined previously. For
  83233. ** example, if the table on which triggers are being fired is
  83234. ** declared as:
  83235. **
  83236. ** CREATE TABLE t1(a, b);
  83237. **
  83238. ** Then p1 is interpreted as follows:
  83239. **
  83240. ** p1==0 -> old.rowid p1==3 -> new.rowid
  83241. ** p1==1 -> old.a p1==4 -> new.a
  83242. ** p1==2 -> old.b p1==5 -> new.b
  83243. */
  83244. Table *pTab = pExpr->pTab;
  83245. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  83246. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  83247. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  83248. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  83249. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  83250. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  83251. VdbeComment((v, "%s.%s -> $%d",
  83252. (pExpr->iTable ? "new" : "old"),
  83253. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  83254. target
  83255. ));
  83256. #ifndef SQLITE_OMIT_FLOATING_POINT
  83257. /* If the column has REAL affinity, it may currently be stored as an
  83258. ** integer. Use OP_RealAffinity to make sure it is really real.
  83259. **
  83260. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  83261. ** floating point when extracting it from the record. */
  83262. if( pExpr->iColumn>=0
  83263. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  83264. ){
  83265. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  83266. }
  83267. #endif
  83268. break;
  83269. }
  83270. /*
  83271. ** Form A:
  83272. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  83273. **
  83274. ** Form B:
  83275. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  83276. **
  83277. ** Form A is can be transformed into the equivalent form B as follows:
  83278. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  83279. ** WHEN x=eN THEN rN ELSE y END
  83280. **
  83281. ** X (if it exists) is in pExpr->pLeft.
  83282. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  83283. ** odd. The Y is also optional. If the number of elements in x.pList
  83284. ** is even, then Y is omitted and the "otherwise" result is NULL.
  83285. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  83286. **
  83287. ** The result of the expression is the Ri for the first matching Ei,
  83288. ** or if there is no matching Ei, the ELSE term Y, or if there is
  83289. ** no ELSE term, NULL.
  83290. */
  83291. default: assert( op==TK_CASE ); {
  83292. int endLabel; /* GOTO label for end of CASE stmt */
  83293. int nextCase; /* GOTO label for next WHEN clause */
  83294. int nExpr; /* 2x number of WHEN terms */
  83295. int i; /* Loop counter */
  83296. ExprList *pEList; /* List of WHEN terms */
  83297. struct ExprList_item *aListelem; /* Array of WHEN terms */
  83298. Expr opCompare; /* The X==Ei expression */
  83299. Expr *pX; /* The X expression */
  83300. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  83301. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  83302. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  83303. assert(pExpr->x.pList->nExpr > 0);
  83304. pEList = pExpr->x.pList;
  83305. aListelem = pEList->a;
  83306. nExpr = pEList->nExpr;
  83307. endLabel = sqlite3VdbeMakeLabel(v);
  83308. if( (pX = pExpr->pLeft)!=0 ){
  83309. tempX = *pX;
  83310. testcase( pX->op==TK_COLUMN );
  83311. exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  83312. testcase( regFree1==0 );
  83313. opCompare.op = TK_EQ;
  83314. opCompare.pLeft = &tempX;
  83315. pTest = &opCompare;
  83316. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  83317. ** The value in regFree1 might get SCopy-ed into the file result.
  83318. ** So make sure that the regFree1 register is not reused for other
  83319. ** purposes and possibly overwritten. */
  83320. regFree1 = 0;
  83321. }
  83322. for(i=0; i<nExpr-1; i=i+2){
  83323. sqlite3ExprCachePush(pParse);
  83324. if( pX ){
  83325. assert( pTest!=0 );
  83326. opCompare.pRight = aListelem[i].pExpr;
  83327. }else{
  83328. pTest = aListelem[i].pExpr;
  83329. }
  83330. nextCase = sqlite3VdbeMakeLabel(v);
  83331. testcase( pTest->op==TK_COLUMN );
  83332. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  83333. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  83334. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  83335. sqlite3VdbeGoto(v, endLabel);
  83336. sqlite3ExprCachePop(pParse);
  83337. sqlite3VdbeResolveLabel(v, nextCase);
  83338. }
  83339. if( (nExpr&1)!=0 ){
  83340. sqlite3ExprCachePush(pParse);
  83341. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  83342. sqlite3ExprCachePop(pParse);
  83343. }else{
  83344. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  83345. }
  83346. assert( db->mallocFailed || pParse->nErr>0
  83347. || pParse->iCacheLevel==iCacheLevel );
  83348. sqlite3VdbeResolveLabel(v, endLabel);
  83349. break;
  83350. }
  83351. #ifndef SQLITE_OMIT_TRIGGER
  83352. case TK_RAISE: {
  83353. assert( pExpr->affinity==OE_Rollback
  83354. || pExpr->affinity==OE_Abort
  83355. || pExpr->affinity==OE_Fail
  83356. || pExpr->affinity==OE_Ignore
  83357. );
  83358. if( !pParse->pTriggerTab ){
  83359. sqlite3ErrorMsg(pParse,
  83360. "RAISE() may only be used within a trigger-program");
  83361. return 0;
  83362. }
  83363. if( pExpr->affinity==OE_Abort ){
  83364. sqlite3MayAbort(pParse);
  83365. }
  83366. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  83367. if( pExpr->affinity==OE_Ignore ){
  83368. sqlite3VdbeAddOp4(
  83369. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  83370. VdbeCoverage(v);
  83371. }else{
  83372. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  83373. pExpr->affinity, pExpr->u.zToken, 0, 0);
  83374. }
  83375. break;
  83376. }
  83377. #endif
  83378. }
  83379. sqlite3ReleaseTempReg(pParse, regFree1);
  83380. sqlite3ReleaseTempReg(pParse, regFree2);
  83381. return inReg;
  83382. }
  83383. /*
  83384. ** Factor out the code of the given expression to initialization time.
  83385. */
  83386. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
  83387. Parse *pParse, /* Parsing context */
  83388. Expr *pExpr, /* The expression to code when the VDBE initializes */
  83389. int regDest, /* Store the value in this register */
  83390. u8 reusable /* True if this expression is reusable */
  83391. ){
  83392. ExprList *p;
  83393. assert( ConstFactorOk(pParse) );
  83394. p = pParse->pConstExpr;
  83395. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  83396. p = sqlite3ExprListAppend(pParse, p, pExpr);
  83397. if( p ){
  83398. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  83399. pItem->u.iConstExprReg = regDest;
  83400. pItem->reusable = reusable;
  83401. }
  83402. pParse->pConstExpr = p;
  83403. }
  83404. /*
  83405. ** Generate code to evaluate an expression and store the results
  83406. ** into a register. Return the register number where the results
  83407. ** are stored.
  83408. **
  83409. ** If the register is a temporary register that can be deallocated,
  83410. ** then write its number into *pReg. If the result register is not
  83411. ** a temporary, then set *pReg to zero.
  83412. **
  83413. ** If pExpr is a constant, then this routine might generate this
  83414. ** code to fill the register in the initialization section of the
  83415. ** VDBE program, in order to factor it out of the evaluation loop.
  83416. */
  83417. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  83418. int r2;
  83419. pExpr = sqlite3ExprSkipCollate(pExpr);
  83420. if( ConstFactorOk(pParse)
  83421. && pExpr->op!=TK_REGISTER
  83422. && sqlite3ExprIsConstantNotJoin(pExpr)
  83423. ){
  83424. ExprList *p = pParse->pConstExpr;
  83425. int i;
  83426. *pReg = 0;
  83427. if( p ){
  83428. struct ExprList_item *pItem;
  83429. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  83430. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  83431. return pItem->u.iConstExprReg;
  83432. }
  83433. }
  83434. }
  83435. r2 = ++pParse->nMem;
  83436. sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
  83437. }else{
  83438. int r1 = sqlite3GetTempReg(pParse);
  83439. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  83440. if( r2==r1 ){
  83441. *pReg = r1;
  83442. }else{
  83443. sqlite3ReleaseTempReg(pParse, r1);
  83444. *pReg = 0;
  83445. }
  83446. }
  83447. return r2;
  83448. }
  83449. /*
  83450. ** Generate code that will evaluate expression pExpr and store the
  83451. ** results in register target. The results are guaranteed to appear
  83452. ** in register target.
  83453. */
  83454. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  83455. int inReg;
  83456. assert( target>0 && target<=pParse->nMem );
  83457. if( pExpr && pExpr->op==TK_REGISTER ){
  83458. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  83459. }else{
  83460. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  83461. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  83462. if( inReg!=target && pParse->pVdbe ){
  83463. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  83464. }
  83465. }
  83466. }
  83467. /*
  83468. ** Make a transient copy of expression pExpr and then code it using
  83469. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  83470. ** except that the input expression is guaranteed to be unchanged.
  83471. */
  83472. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  83473. sqlite3 *db = pParse->db;
  83474. pExpr = sqlite3ExprDup(db, pExpr, 0);
  83475. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  83476. sqlite3ExprDelete(db, pExpr);
  83477. }
  83478. /*
  83479. ** Generate code that will evaluate expression pExpr and store the
  83480. ** results in register target. The results are guaranteed to appear
  83481. ** in register target. If the expression is constant, then this routine
  83482. ** might choose to code the expression at initialization time.
  83483. */
  83484. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  83485. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  83486. sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
  83487. }else{
  83488. sqlite3ExprCode(pParse, pExpr, target);
  83489. }
  83490. }
  83491. /*
  83492. ** Generate code that evaluates the given expression and puts the result
  83493. ** in register target.
  83494. **
  83495. ** Also make a copy of the expression results into another "cache" register
  83496. ** and modify the expression so that the next time it is evaluated,
  83497. ** the result is a copy of the cache register.
  83498. **
  83499. ** This routine is used for expressions that are used multiple
  83500. ** times. They are evaluated once and the results of the expression
  83501. ** are reused.
  83502. */
  83503. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  83504. Vdbe *v = pParse->pVdbe;
  83505. int iMem;
  83506. assert( target>0 );
  83507. assert( pExpr->op!=TK_REGISTER );
  83508. sqlite3ExprCode(pParse, pExpr, target);
  83509. iMem = ++pParse->nMem;
  83510. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  83511. exprToRegister(pExpr, iMem);
  83512. }
  83513. /*
  83514. ** Generate code that pushes the value of every element of the given
  83515. ** expression list into a sequence of registers beginning at target.
  83516. **
  83517. ** Return the number of elements evaluated.
  83518. **
  83519. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  83520. ** filled using OP_SCopy. OP_Copy must be used instead.
  83521. **
  83522. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  83523. ** factored out into initialization code.
  83524. **
  83525. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  83526. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  83527. ** in registers at srcReg, and so the value can be copied from there.
  83528. */
  83529. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  83530. Parse *pParse, /* Parsing context */
  83531. ExprList *pList, /* The expression list to be coded */
  83532. int target, /* Where to write results */
  83533. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  83534. u8 flags /* SQLITE_ECEL_* flags */
  83535. ){
  83536. struct ExprList_item *pItem;
  83537. int i, j, n;
  83538. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  83539. Vdbe *v = pParse->pVdbe;
  83540. assert( pList!=0 );
  83541. assert( target>0 );
  83542. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  83543. n = pList->nExpr;
  83544. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  83545. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  83546. Expr *pExpr = pItem->pExpr;
  83547. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
  83548. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  83549. }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  83550. sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
  83551. }else{
  83552. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  83553. if( inReg!=target+i ){
  83554. VdbeOp *pOp;
  83555. if( copyOp==OP_Copy
  83556. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  83557. && pOp->p1+pOp->p3+1==inReg
  83558. && pOp->p2+pOp->p3+1==target+i
  83559. ){
  83560. pOp->p3++;
  83561. }else{
  83562. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  83563. }
  83564. }
  83565. }
  83566. }
  83567. return n;
  83568. }
  83569. /*
  83570. ** Generate code for a BETWEEN operator.
  83571. **
  83572. ** x BETWEEN y AND z
  83573. **
  83574. ** The above is equivalent to
  83575. **
  83576. ** x>=y AND x<=z
  83577. **
  83578. ** Code it as such, taking care to do the common subexpression
  83579. ** elimination of x.
  83580. */
  83581. static void exprCodeBetween(
  83582. Parse *pParse, /* Parsing and code generating context */
  83583. Expr *pExpr, /* The BETWEEN expression */
  83584. int dest, /* Jump here if the jump is taken */
  83585. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  83586. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  83587. ){
  83588. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  83589. Expr compLeft; /* The x>=y term */
  83590. Expr compRight; /* The x<=z term */
  83591. Expr exprX; /* The x subexpression */
  83592. int regFree1 = 0; /* Temporary use register */
  83593. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  83594. exprX = *pExpr->pLeft;
  83595. exprAnd.op = TK_AND;
  83596. exprAnd.pLeft = &compLeft;
  83597. exprAnd.pRight = &compRight;
  83598. compLeft.op = TK_GE;
  83599. compLeft.pLeft = &exprX;
  83600. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  83601. compRight.op = TK_LE;
  83602. compRight.pLeft = &exprX;
  83603. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  83604. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  83605. if( jumpIfTrue ){
  83606. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  83607. }else{
  83608. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  83609. }
  83610. sqlite3ReleaseTempReg(pParse, regFree1);
  83611. /* Ensure adequate test coverage */
  83612. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  83613. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  83614. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  83615. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  83616. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  83617. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  83618. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  83619. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  83620. }
  83621. /*
  83622. ** Generate code for a boolean expression such that a jump is made
  83623. ** to the label "dest" if the expression is true but execution
  83624. ** continues straight thru if the expression is false.
  83625. **
  83626. ** If the expression evaluates to NULL (neither true nor false), then
  83627. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  83628. **
  83629. ** This code depends on the fact that certain token values (ex: TK_EQ)
  83630. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  83631. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  83632. ** the make process cause these values to align. Assert()s in the code
  83633. ** below verify that the numbers are aligned correctly.
  83634. */
  83635. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  83636. Vdbe *v = pParse->pVdbe;
  83637. int op = 0;
  83638. int regFree1 = 0;
  83639. int regFree2 = 0;
  83640. int r1, r2;
  83641. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  83642. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  83643. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  83644. op = pExpr->op;
  83645. switch( op ){
  83646. case TK_AND: {
  83647. int d2 = sqlite3VdbeMakeLabel(v);
  83648. testcase( jumpIfNull==0 );
  83649. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  83650. sqlite3ExprCachePush(pParse);
  83651. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  83652. sqlite3VdbeResolveLabel(v, d2);
  83653. sqlite3ExprCachePop(pParse);
  83654. break;
  83655. }
  83656. case TK_OR: {
  83657. testcase( jumpIfNull==0 );
  83658. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  83659. sqlite3ExprCachePush(pParse);
  83660. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  83661. sqlite3ExprCachePop(pParse);
  83662. break;
  83663. }
  83664. case TK_NOT: {
  83665. testcase( jumpIfNull==0 );
  83666. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  83667. break;
  83668. }
  83669. case TK_LT:
  83670. case TK_LE:
  83671. case TK_GT:
  83672. case TK_GE:
  83673. case TK_NE:
  83674. case TK_EQ: {
  83675. testcase( jumpIfNull==0 );
  83676. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83677. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  83678. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  83679. r1, r2, dest, jumpIfNull);
  83680. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  83681. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  83682. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  83683. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  83684. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  83685. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  83686. testcase( regFree1==0 );
  83687. testcase( regFree2==0 );
  83688. break;
  83689. }
  83690. case TK_IS:
  83691. case TK_ISNOT: {
  83692. testcase( op==TK_IS );
  83693. testcase( op==TK_ISNOT );
  83694. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83695. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  83696. op = (op==TK_IS) ? TK_EQ : TK_NE;
  83697. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  83698. r1, r2, dest, SQLITE_NULLEQ);
  83699. VdbeCoverageIf(v, op==TK_EQ);
  83700. VdbeCoverageIf(v, op==TK_NE);
  83701. testcase( regFree1==0 );
  83702. testcase( regFree2==0 );
  83703. break;
  83704. }
  83705. case TK_ISNULL:
  83706. case TK_NOTNULL: {
  83707. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  83708. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  83709. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83710. sqlite3VdbeAddOp2(v, op, r1, dest);
  83711. VdbeCoverageIf(v, op==TK_ISNULL);
  83712. VdbeCoverageIf(v, op==TK_NOTNULL);
  83713. testcase( regFree1==0 );
  83714. break;
  83715. }
  83716. case TK_BETWEEN: {
  83717. testcase( jumpIfNull==0 );
  83718. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  83719. break;
  83720. }
  83721. #ifndef SQLITE_OMIT_SUBQUERY
  83722. case TK_IN: {
  83723. int destIfFalse = sqlite3VdbeMakeLabel(v);
  83724. int destIfNull = jumpIfNull ? dest : destIfFalse;
  83725. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  83726. sqlite3VdbeGoto(v, dest);
  83727. sqlite3VdbeResolveLabel(v, destIfFalse);
  83728. break;
  83729. }
  83730. #endif
  83731. default: {
  83732. if( exprAlwaysTrue(pExpr) ){
  83733. sqlite3VdbeGoto(v, dest);
  83734. }else if( exprAlwaysFalse(pExpr) ){
  83735. /* No-op */
  83736. }else{
  83737. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  83738. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  83739. VdbeCoverage(v);
  83740. testcase( regFree1==0 );
  83741. testcase( jumpIfNull==0 );
  83742. }
  83743. break;
  83744. }
  83745. }
  83746. sqlite3ReleaseTempReg(pParse, regFree1);
  83747. sqlite3ReleaseTempReg(pParse, regFree2);
  83748. }
  83749. /*
  83750. ** Generate code for a boolean expression such that a jump is made
  83751. ** to the label "dest" if the expression is false but execution
  83752. ** continues straight thru if the expression is true.
  83753. **
  83754. ** If the expression evaluates to NULL (neither true nor false) then
  83755. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  83756. ** is 0.
  83757. */
  83758. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  83759. Vdbe *v = pParse->pVdbe;
  83760. int op = 0;
  83761. int regFree1 = 0;
  83762. int regFree2 = 0;
  83763. int r1, r2;
  83764. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  83765. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  83766. if( pExpr==0 ) return;
  83767. /* The value of pExpr->op and op are related as follows:
  83768. **
  83769. ** pExpr->op op
  83770. ** --------- ----------
  83771. ** TK_ISNULL OP_NotNull
  83772. ** TK_NOTNULL OP_IsNull
  83773. ** TK_NE OP_Eq
  83774. ** TK_EQ OP_Ne
  83775. ** TK_GT OP_Le
  83776. ** TK_LE OP_Gt
  83777. ** TK_GE OP_Lt
  83778. ** TK_LT OP_Ge
  83779. **
  83780. ** For other values of pExpr->op, op is undefined and unused.
  83781. ** The value of TK_ and OP_ constants are arranged such that we
  83782. ** can compute the mapping above using the following expression.
  83783. ** Assert()s verify that the computation is correct.
  83784. */
  83785. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  83786. /* Verify correct alignment of TK_ and OP_ constants
  83787. */
  83788. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  83789. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  83790. assert( pExpr->op!=TK_NE || op==OP_Eq );
  83791. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  83792. assert( pExpr->op!=TK_LT || op==OP_Ge );
  83793. assert( pExpr->op!=TK_LE || op==OP_Gt );
  83794. assert( pExpr->op!=TK_GT || op==OP_Le );
  83795. assert( pExpr->op!=TK_GE || op==OP_Lt );
  83796. switch( pExpr->op ){
  83797. case TK_AND: {
  83798. testcase( jumpIfNull==0 );
  83799. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  83800. sqlite3ExprCachePush(pParse);
  83801. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  83802. sqlite3ExprCachePop(pParse);
  83803. break;
  83804. }
  83805. case TK_OR: {
  83806. int d2 = sqlite3VdbeMakeLabel(v);
  83807. testcase( jumpIfNull==0 );
  83808. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  83809. sqlite3ExprCachePush(pParse);
  83810. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  83811. sqlite3VdbeResolveLabel(v, d2);
  83812. sqlite3ExprCachePop(pParse);
  83813. break;
  83814. }
  83815. case TK_NOT: {
  83816. testcase( jumpIfNull==0 );
  83817. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  83818. break;
  83819. }
  83820. case TK_LT:
  83821. case TK_LE:
  83822. case TK_GT:
  83823. case TK_GE:
  83824. case TK_NE:
  83825. case TK_EQ: {
  83826. testcase( jumpIfNull==0 );
  83827. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83828. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  83829. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  83830. r1, r2, dest, jumpIfNull);
  83831. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  83832. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  83833. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  83834. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  83835. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  83836. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  83837. testcase( regFree1==0 );
  83838. testcase( regFree2==0 );
  83839. break;
  83840. }
  83841. case TK_IS:
  83842. case TK_ISNOT: {
  83843. testcase( pExpr->op==TK_IS );
  83844. testcase( pExpr->op==TK_ISNOT );
  83845. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83846. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  83847. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  83848. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  83849. r1, r2, dest, SQLITE_NULLEQ);
  83850. VdbeCoverageIf(v, op==TK_EQ);
  83851. VdbeCoverageIf(v, op==TK_NE);
  83852. testcase( regFree1==0 );
  83853. testcase( regFree2==0 );
  83854. break;
  83855. }
  83856. case TK_ISNULL:
  83857. case TK_NOTNULL: {
  83858. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  83859. sqlite3VdbeAddOp2(v, op, r1, dest);
  83860. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  83861. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  83862. testcase( regFree1==0 );
  83863. break;
  83864. }
  83865. case TK_BETWEEN: {
  83866. testcase( jumpIfNull==0 );
  83867. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  83868. break;
  83869. }
  83870. #ifndef SQLITE_OMIT_SUBQUERY
  83871. case TK_IN: {
  83872. if( jumpIfNull ){
  83873. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  83874. }else{
  83875. int destIfNull = sqlite3VdbeMakeLabel(v);
  83876. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  83877. sqlite3VdbeResolveLabel(v, destIfNull);
  83878. }
  83879. break;
  83880. }
  83881. #endif
  83882. default: {
  83883. if( exprAlwaysFalse(pExpr) ){
  83884. sqlite3VdbeGoto(v, dest);
  83885. }else if( exprAlwaysTrue(pExpr) ){
  83886. /* no-op */
  83887. }else{
  83888. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  83889. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  83890. VdbeCoverage(v);
  83891. testcase( regFree1==0 );
  83892. testcase( jumpIfNull==0 );
  83893. }
  83894. break;
  83895. }
  83896. }
  83897. sqlite3ReleaseTempReg(pParse, regFree1);
  83898. sqlite3ReleaseTempReg(pParse, regFree2);
  83899. }
  83900. /*
  83901. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  83902. ** code generation, and that copy is deleted after code generation. This
  83903. ** ensures that the original pExpr is unchanged.
  83904. */
  83905. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  83906. sqlite3 *db = pParse->db;
  83907. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  83908. if( db->mallocFailed==0 ){
  83909. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  83910. }
  83911. sqlite3ExprDelete(db, pCopy);
  83912. }
  83913. /*
  83914. ** Do a deep comparison of two expression trees. Return 0 if the two
  83915. ** expressions are completely identical. Return 1 if they differ only
  83916. ** by a COLLATE operator at the top level. Return 2 if there are differences
  83917. ** other than the top-level COLLATE operator.
  83918. **
  83919. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  83920. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  83921. **
  83922. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  83923. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  83924. **
  83925. ** Sometimes this routine will return 2 even if the two expressions
  83926. ** really are equivalent. If we cannot prove that the expressions are
  83927. ** identical, we return 2 just to be safe. So if this routine
  83928. ** returns 2, then you do not really know for certain if the two
  83929. ** expressions are the same. But if you get a 0 or 1 return, then you
  83930. ** can be sure the expressions are the same. In the places where
  83931. ** this routine is used, it does not hurt to get an extra 2 - that
  83932. ** just might result in some slightly slower code. But returning
  83933. ** an incorrect 0 or 1 could lead to a malfunction.
  83934. */
  83935. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  83936. u32 combinedFlags;
  83937. if( pA==0 || pB==0 ){
  83938. return pB==pA ? 0 : 2;
  83939. }
  83940. combinedFlags = pA->flags | pB->flags;
  83941. if( combinedFlags & EP_IntValue ){
  83942. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  83943. return 0;
  83944. }
  83945. return 2;
  83946. }
  83947. if( pA->op!=pB->op ){
  83948. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  83949. return 1;
  83950. }
  83951. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  83952. return 1;
  83953. }
  83954. return 2;
  83955. }
  83956. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  83957. if( pA->op==TK_FUNCTION ){
  83958. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  83959. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  83960. return pA->op==TK_COLLATE ? 1 : 2;
  83961. }
  83962. }
  83963. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  83964. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  83965. if( combinedFlags & EP_xIsSelect ) return 2;
  83966. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  83967. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  83968. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  83969. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  83970. if( pA->iColumn!=pB->iColumn ) return 2;
  83971. if( pA->iTable!=pB->iTable
  83972. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  83973. }
  83974. }
  83975. return 0;
  83976. }
  83977. /*
  83978. ** Compare two ExprList objects. Return 0 if they are identical and
  83979. ** non-zero if they differ in any way.
  83980. **
  83981. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  83982. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  83983. **
  83984. ** This routine might return non-zero for equivalent ExprLists. The
  83985. ** only consequence will be disabled optimizations. But this routine
  83986. ** must never return 0 if the two ExprList objects are different, or
  83987. ** a malfunction will result.
  83988. **
  83989. ** Two NULL pointers are considered to be the same. But a NULL pointer
  83990. ** always differs from a non-NULL pointer.
  83991. */
  83992. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  83993. int i;
  83994. if( pA==0 && pB==0 ) return 0;
  83995. if( pA==0 || pB==0 ) return 1;
  83996. if( pA->nExpr!=pB->nExpr ) return 1;
  83997. for(i=0; i<pA->nExpr; i++){
  83998. Expr *pExprA = pA->a[i].pExpr;
  83999. Expr *pExprB = pB->a[i].pExpr;
  84000. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  84001. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  84002. }
  84003. return 0;
  84004. }
  84005. /*
  84006. ** Return true if we can prove the pE2 will always be true if pE1 is
  84007. ** true. Return false if we cannot complete the proof or if pE2 might
  84008. ** be false. Examples:
  84009. **
  84010. ** pE1: x==5 pE2: x==5 Result: true
  84011. ** pE1: x>0 pE2: x==5 Result: false
  84012. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  84013. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  84014. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  84015. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  84016. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  84017. **
  84018. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  84019. ** Expr.iTable<0 then assume a table number given by iTab.
  84020. **
  84021. ** When in doubt, return false. Returning true might give a performance
  84022. ** improvement. Returning false might cause a performance reduction, but
  84023. ** it will always give the correct answer and is hence always safe.
  84024. */
  84025. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  84026. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  84027. return 1;
  84028. }
  84029. if( pE2->op==TK_OR
  84030. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  84031. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  84032. ){
  84033. return 1;
  84034. }
  84035. if( pE2->op==TK_NOTNULL
  84036. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  84037. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  84038. ){
  84039. return 1;
  84040. }
  84041. return 0;
  84042. }
  84043. /*
  84044. ** An instance of the following structure is used by the tree walker
  84045. ** to count references to table columns in the arguments of an
  84046. ** aggregate function, in order to implement the
  84047. ** sqlite3FunctionThisSrc() routine.
  84048. */
  84049. struct SrcCount {
  84050. SrcList *pSrc; /* One particular FROM clause in a nested query */
  84051. int nThis; /* Number of references to columns in pSrcList */
  84052. int nOther; /* Number of references to columns in other FROM clauses */
  84053. };
  84054. /*
  84055. ** Count the number of references to columns.
  84056. */
  84057. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  84058. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  84059. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  84060. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  84061. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  84062. ** NEVER() will need to be removed. */
  84063. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  84064. int i;
  84065. struct SrcCount *p = pWalker->u.pSrcCount;
  84066. SrcList *pSrc = p->pSrc;
  84067. int nSrc = pSrc ? pSrc->nSrc : 0;
  84068. for(i=0; i<nSrc; i++){
  84069. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  84070. }
  84071. if( i<nSrc ){
  84072. p->nThis++;
  84073. }else{
  84074. p->nOther++;
  84075. }
  84076. }
  84077. return WRC_Continue;
  84078. }
  84079. /*
  84080. ** Determine if any of the arguments to the pExpr Function reference
  84081. ** pSrcList. Return true if they do. Also return true if the function
  84082. ** has no arguments or has only constant arguments. Return false if pExpr
  84083. ** references columns but not columns of tables found in pSrcList.
  84084. */
  84085. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  84086. Walker w;
  84087. struct SrcCount cnt;
  84088. assert( pExpr->op==TK_AGG_FUNCTION );
  84089. memset(&w, 0, sizeof(w));
  84090. w.xExprCallback = exprSrcCount;
  84091. w.u.pSrcCount = &cnt;
  84092. cnt.pSrc = pSrcList;
  84093. cnt.nThis = 0;
  84094. cnt.nOther = 0;
  84095. sqlite3WalkExprList(&w, pExpr->x.pList);
  84096. return cnt.nThis>0 || cnt.nOther==0;
  84097. }
  84098. /*
  84099. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  84100. ** the new element. Return a negative number if malloc fails.
  84101. */
  84102. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  84103. int i;
  84104. pInfo->aCol = sqlite3ArrayAllocate(
  84105. db,
  84106. pInfo->aCol,
  84107. sizeof(pInfo->aCol[0]),
  84108. &pInfo->nColumn,
  84109. &i
  84110. );
  84111. return i;
  84112. }
  84113. /*
  84114. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  84115. ** the new element. Return a negative number if malloc fails.
  84116. */
  84117. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  84118. int i;
  84119. pInfo->aFunc = sqlite3ArrayAllocate(
  84120. db,
  84121. pInfo->aFunc,
  84122. sizeof(pInfo->aFunc[0]),
  84123. &pInfo->nFunc,
  84124. &i
  84125. );
  84126. return i;
  84127. }
  84128. /*
  84129. ** This is the xExprCallback for a tree walker. It is used to
  84130. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  84131. ** for additional information.
  84132. */
  84133. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  84134. int i;
  84135. NameContext *pNC = pWalker->u.pNC;
  84136. Parse *pParse = pNC->pParse;
  84137. SrcList *pSrcList = pNC->pSrcList;
  84138. AggInfo *pAggInfo = pNC->pAggInfo;
  84139. switch( pExpr->op ){
  84140. case TK_AGG_COLUMN:
  84141. case TK_COLUMN: {
  84142. testcase( pExpr->op==TK_AGG_COLUMN );
  84143. testcase( pExpr->op==TK_COLUMN );
  84144. /* Check to see if the column is in one of the tables in the FROM
  84145. ** clause of the aggregate query */
  84146. if( ALWAYS(pSrcList!=0) ){
  84147. struct SrcList_item *pItem = pSrcList->a;
  84148. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  84149. struct AggInfo_col *pCol;
  84150. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  84151. if( pExpr->iTable==pItem->iCursor ){
  84152. /* If we reach this point, it means that pExpr refers to a table
  84153. ** that is in the FROM clause of the aggregate query.
  84154. **
  84155. ** Make an entry for the column in pAggInfo->aCol[] if there
  84156. ** is not an entry there already.
  84157. */
  84158. int k;
  84159. pCol = pAggInfo->aCol;
  84160. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  84161. if( pCol->iTable==pExpr->iTable &&
  84162. pCol->iColumn==pExpr->iColumn ){
  84163. break;
  84164. }
  84165. }
  84166. if( (k>=pAggInfo->nColumn)
  84167. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  84168. ){
  84169. pCol = &pAggInfo->aCol[k];
  84170. pCol->pTab = pExpr->pTab;
  84171. pCol->iTable = pExpr->iTable;
  84172. pCol->iColumn = pExpr->iColumn;
  84173. pCol->iMem = ++pParse->nMem;
  84174. pCol->iSorterColumn = -1;
  84175. pCol->pExpr = pExpr;
  84176. if( pAggInfo->pGroupBy ){
  84177. int j, n;
  84178. ExprList *pGB = pAggInfo->pGroupBy;
  84179. struct ExprList_item *pTerm = pGB->a;
  84180. n = pGB->nExpr;
  84181. for(j=0; j<n; j++, pTerm++){
  84182. Expr *pE = pTerm->pExpr;
  84183. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  84184. pE->iColumn==pExpr->iColumn ){
  84185. pCol->iSorterColumn = j;
  84186. break;
  84187. }
  84188. }
  84189. }
  84190. if( pCol->iSorterColumn<0 ){
  84191. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  84192. }
  84193. }
  84194. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  84195. ** because it was there before or because we just created it).
  84196. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  84197. ** pAggInfo->aCol[] entry.
  84198. */
  84199. ExprSetVVAProperty(pExpr, EP_NoReduce);
  84200. pExpr->pAggInfo = pAggInfo;
  84201. pExpr->op = TK_AGG_COLUMN;
  84202. pExpr->iAgg = (i16)k;
  84203. break;
  84204. } /* endif pExpr->iTable==pItem->iCursor */
  84205. } /* end loop over pSrcList */
  84206. }
  84207. return WRC_Prune;
  84208. }
  84209. case TK_AGG_FUNCTION: {
  84210. if( (pNC->ncFlags & NC_InAggFunc)==0
  84211. && pWalker->walkerDepth==pExpr->op2
  84212. ){
  84213. /* Check to see if pExpr is a duplicate of another aggregate
  84214. ** function that is already in the pAggInfo structure
  84215. */
  84216. struct AggInfo_func *pItem = pAggInfo->aFunc;
  84217. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  84218. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  84219. break;
  84220. }
  84221. }
  84222. if( i>=pAggInfo->nFunc ){
  84223. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  84224. */
  84225. u8 enc = ENC(pParse->db);
  84226. i = addAggInfoFunc(pParse->db, pAggInfo);
  84227. if( i>=0 ){
  84228. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  84229. pItem = &pAggInfo->aFunc[i];
  84230. pItem->pExpr = pExpr;
  84231. pItem->iMem = ++pParse->nMem;
  84232. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  84233. pItem->pFunc = sqlite3FindFunction(pParse->db,
  84234. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  84235. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  84236. if( pExpr->flags & EP_Distinct ){
  84237. pItem->iDistinct = pParse->nTab++;
  84238. }else{
  84239. pItem->iDistinct = -1;
  84240. }
  84241. }
  84242. }
  84243. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  84244. */
  84245. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  84246. ExprSetVVAProperty(pExpr, EP_NoReduce);
  84247. pExpr->iAgg = (i16)i;
  84248. pExpr->pAggInfo = pAggInfo;
  84249. return WRC_Prune;
  84250. }else{
  84251. return WRC_Continue;
  84252. }
  84253. }
  84254. }
  84255. return WRC_Continue;
  84256. }
  84257. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  84258. UNUSED_PARAMETER(pWalker);
  84259. UNUSED_PARAMETER(pSelect);
  84260. return WRC_Continue;
  84261. }
  84262. /*
  84263. ** Analyze the pExpr expression looking for aggregate functions and
  84264. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  84265. ** points to. Additional entries are made on the AggInfo object as
  84266. ** necessary.
  84267. **
  84268. ** This routine should only be called after the expression has been
  84269. ** analyzed by sqlite3ResolveExprNames().
  84270. */
  84271. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  84272. Walker w;
  84273. memset(&w, 0, sizeof(w));
  84274. w.xExprCallback = analyzeAggregate;
  84275. w.xSelectCallback = analyzeAggregatesInSelect;
  84276. w.u.pNC = pNC;
  84277. assert( pNC->pSrcList!=0 );
  84278. sqlite3WalkExpr(&w, pExpr);
  84279. }
  84280. /*
  84281. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  84282. ** expression list. Return the number of errors.
  84283. **
  84284. ** If an error is found, the analysis is cut short.
  84285. */
  84286. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  84287. struct ExprList_item *pItem;
  84288. int i;
  84289. if( pList ){
  84290. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  84291. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  84292. }
  84293. }
  84294. }
  84295. /*
  84296. ** Allocate a single new register for use to hold some intermediate result.
  84297. */
  84298. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  84299. if( pParse->nTempReg==0 ){
  84300. return ++pParse->nMem;
  84301. }
  84302. return pParse->aTempReg[--pParse->nTempReg];
  84303. }
  84304. /*
  84305. ** Deallocate a register, making available for reuse for some other
  84306. ** purpose.
  84307. **
  84308. ** If a register is currently being used by the column cache, then
  84309. ** the deallocation is deferred until the column cache line that uses
  84310. ** the register becomes stale.
  84311. */
  84312. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  84313. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  84314. int i;
  84315. struct yColCache *p;
  84316. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  84317. if( p->iReg==iReg ){
  84318. p->tempReg = 1;
  84319. return;
  84320. }
  84321. }
  84322. pParse->aTempReg[pParse->nTempReg++] = iReg;
  84323. }
  84324. }
  84325. /*
  84326. ** Allocate or deallocate a block of nReg consecutive registers
  84327. */
  84328. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  84329. int i, n;
  84330. i = pParse->iRangeReg;
  84331. n = pParse->nRangeReg;
  84332. if( nReg<=n ){
  84333. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  84334. pParse->iRangeReg += nReg;
  84335. pParse->nRangeReg -= nReg;
  84336. }else{
  84337. i = pParse->nMem+1;
  84338. pParse->nMem += nReg;
  84339. }
  84340. return i;
  84341. }
  84342. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  84343. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  84344. if( nReg>pParse->nRangeReg ){
  84345. pParse->nRangeReg = nReg;
  84346. pParse->iRangeReg = iReg;
  84347. }
  84348. }
  84349. /*
  84350. ** Mark all temporary registers as being unavailable for reuse.
  84351. */
  84352. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  84353. pParse->nTempReg = 0;
  84354. pParse->nRangeReg = 0;
  84355. }
  84356. /************** End of expr.c ************************************************/
  84357. /************** Begin file alter.c *******************************************/
  84358. /*
  84359. ** 2005 February 15
  84360. **
  84361. ** The author disclaims copyright to this source code. In place of
  84362. ** a legal notice, here is a blessing:
  84363. **
  84364. ** May you do good and not evil.
  84365. ** May you find forgiveness for yourself and forgive others.
  84366. ** May you share freely, never taking more than you give.
  84367. **
  84368. *************************************************************************
  84369. ** This file contains C code routines that used to generate VDBE code
  84370. ** that implements the ALTER TABLE command.
  84371. */
  84372. /* #include "sqliteInt.h" */
  84373. /*
  84374. ** The code in this file only exists if we are not omitting the
  84375. ** ALTER TABLE logic from the build.
  84376. */
  84377. #ifndef SQLITE_OMIT_ALTERTABLE
  84378. /*
  84379. ** This function is used by SQL generated to implement the
  84380. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  84381. ** CREATE INDEX command. The second is a table name. The table name in
  84382. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  84383. ** argument and the result returned. Examples:
  84384. **
  84385. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  84386. ** -> 'CREATE TABLE def(a, b, c)'
  84387. **
  84388. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  84389. ** -> 'CREATE INDEX i ON def(a, b, c)'
  84390. */
  84391. static void renameTableFunc(
  84392. sqlite3_context *context,
  84393. int NotUsed,
  84394. sqlite3_value **argv
  84395. ){
  84396. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  84397. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  84398. int token;
  84399. Token tname;
  84400. unsigned char const *zCsr = zSql;
  84401. int len = 0;
  84402. char *zRet;
  84403. sqlite3 *db = sqlite3_context_db_handle(context);
  84404. UNUSED_PARAMETER(NotUsed);
  84405. /* The principle used to locate the table name in the CREATE TABLE
  84406. ** statement is that the table name is the first non-space token that
  84407. ** is immediately followed by a TK_LP or TK_USING token.
  84408. */
  84409. if( zSql ){
  84410. do {
  84411. if( !*zCsr ){
  84412. /* Ran out of input before finding an opening bracket. Return NULL. */
  84413. return;
  84414. }
  84415. /* Store the token that zCsr points to in tname. */
  84416. tname.z = (char*)zCsr;
  84417. tname.n = len;
  84418. /* Advance zCsr to the next token. Store that token type in 'token',
  84419. ** and its length in 'len' (to be used next iteration of this loop).
  84420. */
  84421. do {
  84422. zCsr += len;
  84423. len = sqlite3GetToken(zCsr, &token);
  84424. } while( token==TK_SPACE );
  84425. assert( len>0 );
  84426. } while( token!=TK_LP && token!=TK_USING );
  84427. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  84428. zSql, zTableName, tname.z+tname.n);
  84429. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  84430. }
  84431. }
  84432. /*
  84433. ** This C function implements an SQL user function that is used by SQL code
  84434. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  84435. ** of any foreign key constraints that use the table being renamed as the
  84436. ** parent table. It is passed three arguments:
  84437. **
  84438. ** 1) The complete text of the CREATE TABLE statement being modified,
  84439. ** 2) The old name of the table being renamed, and
  84440. ** 3) The new name of the table being renamed.
  84441. **
  84442. ** It returns the new CREATE TABLE statement. For example:
  84443. **
  84444. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  84445. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  84446. */
  84447. #ifndef SQLITE_OMIT_FOREIGN_KEY
  84448. static void renameParentFunc(
  84449. sqlite3_context *context,
  84450. int NotUsed,
  84451. sqlite3_value **argv
  84452. ){
  84453. sqlite3 *db = sqlite3_context_db_handle(context);
  84454. char *zOutput = 0;
  84455. char *zResult;
  84456. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  84457. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  84458. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  84459. unsigned const char *z; /* Pointer to token */
  84460. int n; /* Length of token z */
  84461. int token; /* Type of token */
  84462. UNUSED_PARAMETER(NotUsed);
  84463. if( zInput==0 || zOld==0 ) return;
  84464. for(z=zInput; *z; z=z+n){
  84465. n = sqlite3GetToken(z, &token);
  84466. if( token==TK_REFERENCES ){
  84467. char *zParent;
  84468. do {
  84469. z += n;
  84470. n = sqlite3GetToken(z, &token);
  84471. }while( token==TK_SPACE );
  84472. if( token==TK_ILLEGAL ) break;
  84473. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  84474. if( zParent==0 ) break;
  84475. sqlite3Dequote(zParent);
  84476. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  84477. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  84478. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  84479. );
  84480. sqlite3DbFree(db, zOutput);
  84481. zOutput = zOut;
  84482. zInput = &z[n];
  84483. }
  84484. sqlite3DbFree(db, zParent);
  84485. }
  84486. }
  84487. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  84488. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  84489. sqlite3DbFree(db, zOutput);
  84490. }
  84491. #endif
  84492. #ifndef SQLITE_OMIT_TRIGGER
  84493. /* This function is used by SQL generated to implement the
  84494. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  84495. ** statement. The second is a table name. The table name in the CREATE
  84496. ** TRIGGER statement is replaced with the third argument and the result
  84497. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  84498. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  84499. */
  84500. static void renameTriggerFunc(
  84501. sqlite3_context *context,
  84502. int NotUsed,
  84503. sqlite3_value **argv
  84504. ){
  84505. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  84506. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  84507. int token;
  84508. Token tname;
  84509. int dist = 3;
  84510. unsigned char const *zCsr = zSql;
  84511. int len = 0;
  84512. char *zRet;
  84513. sqlite3 *db = sqlite3_context_db_handle(context);
  84514. UNUSED_PARAMETER(NotUsed);
  84515. /* The principle used to locate the table name in the CREATE TRIGGER
  84516. ** statement is that the table name is the first token that is immediately
  84517. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  84518. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  84519. */
  84520. if( zSql ){
  84521. do {
  84522. if( !*zCsr ){
  84523. /* Ran out of input before finding the table name. Return NULL. */
  84524. return;
  84525. }
  84526. /* Store the token that zCsr points to in tname. */
  84527. tname.z = (char*)zCsr;
  84528. tname.n = len;
  84529. /* Advance zCsr to the next token. Store that token type in 'token',
  84530. ** and its length in 'len' (to be used next iteration of this loop).
  84531. */
  84532. do {
  84533. zCsr += len;
  84534. len = sqlite3GetToken(zCsr, &token);
  84535. }while( token==TK_SPACE );
  84536. assert( len>0 );
  84537. /* Variable 'dist' stores the number of tokens read since the most
  84538. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  84539. ** token is read and 'dist' equals 2, the condition stated above
  84540. ** to be met.
  84541. **
  84542. ** Note that ON cannot be a database, table or column name, so
  84543. ** there is no need to worry about syntax like
  84544. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  84545. */
  84546. dist++;
  84547. if( token==TK_DOT || token==TK_ON ){
  84548. dist = 0;
  84549. }
  84550. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  84551. /* Variable tname now contains the token that is the old table-name
  84552. ** in the CREATE TRIGGER statement.
  84553. */
  84554. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  84555. zSql, zTableName, tname.z+tname.n);
  84556. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  84557. }
  84558. }
  84559. #endif /* !SQLITE_OMIT_TRIGGER */
  84560. /*
  84561. ** Register built-in functions used to help implement ALTER TABLE
  84562. */
  84563. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  84564. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  84565. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  84566. #ifndef SQLITE_OMIT_TRIGGER
  84567. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  84568. #endif
  84569. #ifndef SQLITE_OMIT_FOREIGN_KEY
  84570. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  84571. #endif
  84572. };
  84573. int i;
  84574. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  84575. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  84576. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  84577. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  84578. }
  84579. }
  84580. /*
  84581. ** This function is used to create the text of expressions of the form:
  84582. **
  84583. ** name=<constant1> OR name=<constant2> OR ...
  84584. **
  84585. ** If argument zWhere is NULL, then a pointer string containing the text
  84586. ** "name=<constant>" is returned, where <constant> is the quoted version
  84587. ** of the string passed as argument zConstant. The returned buffer is
  84588. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  84589. ** caller to ensure that it is eventually freed.
  84590. **
  84591. ** If argument zWhere is not NULL, then the string returned is
  84592. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  84593. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  84594. **
  84595. */
  84596. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  84597. char *zNew;
  84598. if( !zWhere ){
  84599. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  84600. }else{
  84601. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  84602. sqlite3DbFree(db, zWhere);
  84603. }
  84604. return zNew;
  84605. }
  84606. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  84607. /*
  84608. ** Generate the text of a WHERE expression which can be used to select all
  84609. ** tables that have foreign key constraints that refer to table pTab (i.e.
  84610. ** constraints for which pTab is the parent table) from the sqlite_master
  84611. ** table.
  84612. */
  84613. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  84614. FKey *p;
  84615. char *zWhere = 0;
  84616. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  84617. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  84618. }
  84619. return zWhere;
  84620. }
  84621. #endif
  84622. /*
  84623. ** Generate the text of a WHERE expression which can be used to select all
  84624. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  84625. ** table pTab has no temporary triggers, or is itself stored in the
  84626. ** temporary database, NULL is returned.
  84627. */
  84628. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  84629. Trigger *pTrig;
  84630. char *zWhere = 0;
  84631. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  84632. /* If the table is not located in the temp-db (in which case NULL is
  84633. ** returned, loop through the tables list of triggers. For each trigger
  84634. ** that is not part of the temp-db schema, add a clause to the WHERE
  84635. ** expression being built up in zWhere.
  84636. */
  84637. if( pTab->pSchema!=pTempSchema ){
  84638. sqlite3 *db = pParse->db;
  84639. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  84640. if( pTrig->pSchema==pTempSchema ){
  84641. zWhere = whereOrName(db, zWhere, pTrig->zName);
  84642. }
  84643. }
  84644. }
  84645. if( zWhere ){
  84646. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  84647. sqlite3DbFree(pParse->db, zWhere);
  84648. zWhere = zNew;
  84649. }
  84650. return zWhere;
  84651. }
  84652. /*
  84653. ** Generate code to drop and reload the internal representation of table
  84654. ** pTab from the database, including triggers and temporary triggers.
  84655. ** Argument zName is the name of the table in the database schema at
  84656. ** the time the generated code is executed. This can be different from
  84657. ** pTab->zName if this function is being called to code part of an
  84658. ** "ALTER TABLE RENAME TO" statement.
  84659. */
  84660. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  84661. Vdbe *v;
  84662. char *zWhere;
  84663. int iDb; /* Index of database containing pTab */
  84664. #ifndef SQLITE_OMIT_TRIGGER
  84665. Trigger *pTrig;
  84666. #endif
  84667. v = sqlite3GetVdbe(pParse);
  84668. if( NEVER(v==0) ) return;
  84669. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  84670. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  84671. assert( iDb>=0 );
  84672. #ifndef SQLITE_OMIT_TRIGGER
  84673. /* Drop any table triggers from the internal schema. */
  84674. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  84675. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  84676. assert( iTrigDb==iDb || iTrigDb==1 );
  84677. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  84678. }
  84679. #endif
  84680. /* Drop the table and index from the internal schema. */
  84681. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  84682. /* Reload the table, index and permanent trigger schemas. */
  84683. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  84684. if( !zWhere ) return;
  84685. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  84686. #ifndef SQLITE_OMIT_TRIGGER
  84687. /* Now, if the table is not stored in the temp database, reload any temp
  84688. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  84689. */
  84690. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  84691. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  84692. }
  84693. #endif
  84694. }
  84695. /*
  84696. ** Parameter zName is the name of a table that is about to be altered
  84697. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  84698. ** If the table is a system table, this function leaves an error message
  84699. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  84700. **
  84701. ** Or, if zName is not a system table, zero is returned.
  84702. */
  84703. static int isSystemTable(Parse *pParse, const char *zName){
  84704. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  84705. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  84706. return 1;
  84707. }
  84708. return 0;
  84709. }
  84710. /*
  84711. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  84712. ** command.
  84713. */
  84714. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  84715. Parse *pParse, /* Parser context. */
  84716. SrcList *pSrc, /* The table to rename. */
  84717. Token *pName /* The new table name. */
  84718. ){
  84719. int iDb; /* Database that contains the table */
  84720. char *zDb; /* Name of database iDb */
  84721. Table *pTab; /* Table being renamed */
  84722. char *zName = 0; /* NULL-terminated version of pName */
  84723. sqlite3 *db = pParse->db; /* Database connection */
  84724. int nTabName; /* Number of UTF-8 characters in zTabName */
  84725. const char *zTabName; /* Original name of the table */
  84726. Vdbe *v;
  84727. #ifndef SQLITE_OMIT_TRIGGER
  84728. char *zWhere = 0; /* Where clause to locate temp triggers */
  84729. #endif
  84730. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  84731. int savedDbFlags; /* Saved value of db->flags */
  84732. savedDbFlags = db->flags;
  84733. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  84734. assert( pSrc->nSrc==1 );
  84735. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  84736. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  84737. if( !pTab ) goto exit_rename_table;
  84738. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  84739. zDb = db->aDb[iDb].zName;
  84740. db->flags |= SQLITE_PreferBuiltin;
  84741. /* Get a NULL terminated version of the new table name. */
  84742. zName = sqlite3NameFromToken(db, pName);
  84743. if( !zName ) goto exit_rename_table;
  84744. /* Check that a table or index named 'zName' does not already exist
  84745. ** in database iDb. If so, this is an error.
  84746. */
  84747. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  84748. sqlite3ErrorMsg(pParse,
  84749. "there is already another table or index with this name: %s", zName);
  84750. goto exit_rename_table;
  84751. }
  84752. /* Make sure it is not a system table being altered, or a reserved name
  84753. ** that the table is being renamed to.
  84754. */
  84755. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  84756. goto exit_rename_table;
  84757. }
  84758. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  84759. exit_rename_table;
  84760. }
  84761. #ifndef SQLITE_OMIT_VIEW
  84762. if( pTab->pSelect ){
  84763. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  84764. goto exit_rename_table;
  84765. }
  84766. #endif
  84767. #ifndef SQLITE_OMIT_AUTHORIZATION
  84768. /* Invoke the authorization callback. */
  84769. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  84770. goto exit_rename_table;
  84771. }
  84772. #endif
  84773. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84774. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  84775. goto exit_rename_table;
  84776. }
  84777. if( IsVirtual(pTab) ){
  84778. pVTab = sqlite3GetVTable(db, pTab);
  84779. if( pVTab->pVtab->pModule->xRename==0 ){
  84780. pVTab = 0;
  84781. }
  84782. }
  84783. #endif
  84784. /* Begin a transaction for database iDb.
  84785. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  84786. ** schema). Open a statement transaction if the table is a virtual
  84787. ** table.
  84788. */
  84789. v = sqlite3GetVdbe(pParse);
  84790. if( v==0 ){
  84791. goto exit_rename_table;
  84792. }
  84793. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  84794. sqlite3ChangeCookie(pParse, iDb);
  84795. /* If this is a virtual table, invoke the xRename() function if
  84796. ** one is defined. The xRename() callback will modify the names
  84797. ** of any resources used by the v-table implementation (including other
  84798. ** SQLite tables) that are identified by the name of the virtual table.
  84799. */
  84800. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84801. if( pVTab ){
  84802. int i = ++pParse->nMem;
  84803. sqlite3VdbeLoadString(v, i, zName);
  84804. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  84805. sqlite3MayAbort(pParse);
  84806. }
  84807. #endif
  84808. /* figure out how many UTF-8 characters are in zName */
  84809. zTabName = pTab->zName;
  84810. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  84811. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  84812. if( db->flags&SQLITE_ForeignKeys ){
  84813. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  84814. ** statements corresponding to all child tables of foreign key constraints
  84815. ** for which the renamed table is the parent table. */
  84816. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  84817. sqlite3NestedParse(pParse,
  84818. "UPDATE \"%w\".%s SET "
  84819. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  84820. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  84821. sqlite3DbFree(db, zWhere);
  84822. }
  84823. }
  84824. #endif
  84825. /* Modify the sqlite_master table to use the new table name. */
  84826. sqlite3NestedParse(pParse,
  84827. "UPDATE %Q.%s SET "
  84828. #ifdef SQLITE_OMIT_TRIGGER
  84829. "sql = sqlite_rename_table(sql, %Q), "
  84830. #else
  84831. "sql = CASE "
  84832. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  84833. "ELSE sqlite_rename_table(sql, %Q) END, "
  84834. #endif
  84835. "tbl_name = %Q, "
  84836. "name = CASE "
  84837. "WHEN type='table' THEN %Q "
  84838. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  84839. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  84840. "ELSE name END "
  84841. "WHERE tbl_name=%Q COLLATE nocase AND "
  84842. "(type='table' OR type='index' OR type='trigger');",
  84843. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  84844. #ifndef SQLITE_OMIT_TRIGGER
  84845. zName,
  84846. #endif
  84847. zName, nTabName, zTabName
  84848. );
  84849. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84850. /* If the sqlite_sequence table exists in this database, then update
  84851. ** it with the new table name.
  84852. */
  84853. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  84854. sqlite3NestedParse(pParse,
  84855. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  84856. zDb, zName, pTab->zName);
  84857. }
  84858. #endif
  84859. #ifndef SQLITE_OMIT_TRIGGER
  84860. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  84861. ** table. Don't do this if the table being ALTERed is itself located in
  84862. ** the temp database.
  84863. */
  84864. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  84865. sqlite3NestedParse(pParse,
  84866. "UPDATE sqlite_temp_master SET "
  84867. "sql = sqlite_rename_trigger(sql, %Q), "
  84868. "tbl_name = %Q "
  84869. "WHERE %s;", zName, zName, zWhere);
  84870. sqlite3DbFree(db, zWhere);
  84871. }
  84872. #endif
  84873. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  84874. if( db->flags&SQLITE_ForeignKeys ){
  84875. FKey *p;
  84876. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  84877. Table *pFrom = p->pFrom;
  84878. if( pFrom!=pTab ){
  84879. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  84880. }
  84881. }
  84882. }
  84883. #endif
  84884. /* Drop and reload the internal table schema. */
  84885. reloadTableSchema(pParse, pTab, zName);
  84886. exit_rename_table:
  84887. sqlite3SrcListDelete(db, pSrc);
  84888. sqlite3DbFree(db, zName);
  84889. db->flags = savedDbFlags;
  84890. }
  84891. /*
  84892. ** Generate code to make sure the file format number is at least minFormat.
  84893. ** The generated code will increase the file format number if necessary.
  84894. */
  84895. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  84896. Vdbe *v;
  84897. v = sqlite3GetVdbe(pParse);
  84898. /* The VDBE should have been allocated before this routine is called.
  84899. ** If that allocation failed, we would have quit before reaching this
  84900. ** point */
  84901. if( ALWAYS(v) ){
  84902. int r1 = sqlite3GetTempReg(pParse);
  84903. int r2 = sqlite3GetTempReg(pParse);
  84904. int addr1;
  84905. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  84906. sqlite3VdbeUsesBtree(v, iDb);
  84907. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  84908. addr1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  84909. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
  84910. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  84911. sqlite3VdbeJumpHere(v, addr1);
  84912. sqlite3ReleaseTempReg(pParse, r1);
  84913. sqlite3ReleaseTempReg(pParse, r2);
  84914. }
  84915. }
  84916. /*
  84917. ** This function is called after an "ALTER TABLE ... ADD" statement
  84918. ** has been parsed. Argument pColDef contains the text of the new
  84919. ** column definition.
  84920. **
  84921. ** The Table structure pParse->pNewTable was extended to include
  84922. ** the new column during parsing.
  84923. */
  84924. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  84925. Table *pNew; /* Copy of pParse->pNewTable */
  84926. Table *pTab; /* Table being altered */
  84927. int iDb; /* Database number */
  84928. const char *zDb; /* Database name */
  84929. const char *zTab; /* Table name */
  84930. char *zCol; /* Null-terminated column definition */
  84931. Column *pCol; /* The new column */
  84932. Expr *pDflt; /* Default value for the new column */
  84933. sqlite3 *db; /* The database connection; */
  84934. db = pParse->db;
  84935. if( pParse->nErr || db->mallocFailed ) return;
  84936. pNew = pParse->pNewTable;
  84937. assert( pNew );
  84938. assert( sqlite3BtreeHoldsAllMutexes(db) );
  84939. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  84940. zDb = db->aDb[iDb].zName;
  84941. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  84942. pCol = &pNew->aCol[pNew->nCol-1];
  84943. pDflt = pCol->pDflt;
  84944. pTab = sqlite3FindTable(db, zTab, zDb);
  84945. assert( pTab );
  84946. #ifndef SQLITE_OMIT_AUTHORIZATION
  84947. /* Invoke the authorization callback. */
  84948. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  84949. return;
  84950. }
  84951. #endif
  84952. /* If the default value for the new column was specified with a
  84953. ** literal NULL, then set pDflt to 0. This simplifies checking
  84954. ** for an SQL NULL default below.
  84955. */
  84956. if( pDflt && pDflt->op==TK_NULL ){
  84957. pDflt = 0;
  84958. }
  84959. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  84960. ** If there is a NOT NULL constraint, then the default value for the
  84961. ** column must not be NULL.
  84962. */
  84963. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  84964. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  84965. return;
  84966. }
  84967. if( pNew->pIndex ){
  84968. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  84969. return;
  84970. }
  84971. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  84972. sqlite3ErrorMsg(pParse,
  84973. "Cannot add a REFERENCES column with non-NULL default value");
  84974. return;
  84975. }
  84976. if( pCol->notNull && !pDflt ){
  84977. sqlite3ErrorMsg(pParse,
  84978. "Cannot add a NOT NULL column with default value NULL");
  84979. return;
  84980. }
  84981. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  84982. ** can handle (i.e. not CURRENT_TIME etc.)
  84983. */
  84984. if( pDflt ){
  84985. sqlite3_value *pVal = 0;
  84986. int rc;
  84987. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  84988. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  84989. if( rc!=SQLITE_OK ){
  84990. db->mallocFailed = 1;
  84991. return;
  84992. }
  84993. if( !pVal ){
  84994. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  84995. return;
  84996. }
  84997. sqlite3ValueFree(pVal);
  84998. }
  84999. /* Modify the CREATE TABLE statement. */
  85000. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  85001. if( zCol ){
  85002. char *zEnd = &zCol[pColDef->n-1];
  85003. int savedDbFlags = db->flags;
  85004. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  85005. *zEnd-- = '\0';
  85006. }
  85007. db->flags |= SQLITE_PreferBuiltin;
  85008. sqlite3NestedParse(pParse,
  85009. "UPDATE \"%w\".%s SET "
  85010. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  85011. "WHERE type = 'table' AND name = %Q",
  85012. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  85013. zTab
  85014. );
  85015. sqlite3DbFree(db, zCol);
  85016. db->flags = savedDbFlags;
  85017. }
  85018. /* If the default value of the new column is NULL, then set the file
  85019. ** format to 2. If the default value of the new column is not NULL,
  85020. ** the file format becomes 3.
  85021. */
  85022. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  85023. /* Reload the schema of the modified table. */
  85024. reloadTableSchema(pParse, pTab, pTab->zName);
  85025. }
  85026. /*
  85027. ** This function is called by the parser after the table-name in
  85028. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  85029. ** pSrc is the full-name of the table being altered.
  85030. **
  85031. ** This routine makes a (partial) copy of the Table structure
  85032. ** for the table being altered and sets Parse.pNewTable to point
  85033. ** to it. Routines called by the parser as the column definition
  85034. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  85035. ** the copy. The copy of the Table structure is deleted by tokenize.c
  85036. ** after parsing is finished.
  85037. **
  85038. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  85039. ** coding the "ALTER TABLE ... ADD" statement.
  85040. */
  85041. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  85042. Table *pNew;
  85043. Table *pTab;
  85044. Vdbe *v;
  85045. int iDb;
  85046. int i;
  85047. int nAlloc;
  85048. sqlite3 *db = pParse->db;
  85049. /* Look up the table being altered. */
  85050. assert( pParse->pNewTable==0 );
  85051. assert( sqlite3BtreeHoldsAllMutexes(db) );
  85052. if( db->mallocFailed ) goto exit_begin_add_column;
  85053. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  85054. if( !pTab ) goto exit_begin_add_column;
  85055. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85056. if( IsVirtual(pTab) ){
  85057. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  85058. goto exit_begin_add_column;
  85059. }
  85060. #endif
  85061. /* Make sure this is not an attempt to ALTER a view. */
  85062. if( pTab->pSelect ){
  85063. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  85064. goto exit_begin_add_column;
  85065. }
  85066. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  85067. goto exit_begin_add_column;
  85068. }
  85069. assert( pTab->addColOffset>0 );
  85070. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85071. /* Put a copy of the Table struct in Parse.pNewTable for the
  85072. ** sqlite3AddColumn() function and friends to modify. But modify
  85073. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  85074. ** prefix, we insure that the name will not collide with an existing
  85075. ** table because user table are not allowed to have the "sqlite_"
  85076. ** prefix on their name.
  85077. */
  85078. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  85079. if( !pNew ) goto exit_begin_add_column;
  85080. pParse->pNewTable = pNew;
  85081. pNew->nRef = 1;
  85082. pNew->nCol = pTab->nCol;
  85083. assert( pNew->nCol>0 );
  85084. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  85085. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  85086. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  85087. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  85088. if( !pNew->aCol || !pNew->zName ){
  85089. db->mallocFailed = 1;
  85090. goto exit_begin_add_column;
  85091. }
  85092. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  85093. for(i=0; i<pNew->nCol; i++){
  85094. Column *pCol = &pNew->aCol[i];
  85095. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  85096. pCol->zColl = 0;
  85097. pCol->zType = 0;
  85098. pCol->pDflt = 0;
  85099. pCol->zDflt = 0;
  85100. }
  85101. pNew->pSchema = db->aDb[iDb].pSchema;
  85102. pNew->addColOffset = pTab->addColOffset;
  85103. pNew->nRef = 1;
  85104. /* Begin a transaction and increment the schema cookie. */
  85105. sqlite3BeginWriteOperation(pParse, 0, iDb);
  85106. v = sqlite3GetVdbe(pParse);
  85107. if( !v ) goto exit_begin_add_column;
  85108. sqlite3ChangeCookie(pParse, iDb);
  85109. exit_begin_add_column:
  85110. sqlite3SrcListDelete(db, pSrc);
  85111. return;
  85112. }
  85113. #endif /* SQLITE_ALTER_TABLE */
  85114. /************** End of alter.c ***********************************************/
  85115. /************** Begin file analyze.c *****************************************/
  85116. /*
  85117. ** 2005-07-08
  85118. **
  85119. ** The author disclaims copyright to this source code. In place of
  85120. ** a legal notice, here is a blessing:
  85121. **
  85122. ** May you do good and not evil.
  85123. ** May you find forgiveness for yourself and forgive others.
  85124. ** May you share freely, never taking more than you give.
  85125. **
  85126. *************************************************************************
  85127. ** This file contains code associated with the ANALYZE command.
  85128. **
  85129. ** The ANALYZE command gather statistics about the content of tables
  85130. ** and indices. These statistics are made available to the query planner
  85131. ** to help it make better decisions about how to perform queries.
  85132. **
  85133. ** The following system tables are or have been supported:
  85134. **
  85135. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  85136. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  85137. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  85138. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  85139. **
  85140. ** Additional tables might be added in future releases of SQLite.
  85141. ** The sqlite_stat2 table is not created or used unless the SQLite version
  85142. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  85143. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  85144. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  85145. ** created and used by SQLite versions 3.7.9 and later and with
  85146. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  85147. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  85148. ** version of sqlite_stat3 and is only available when compiled with
  85149. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  85150. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  85151. ** are both enabled, then STAT4 takes precedence.
  85152. **
  85153. ** For most applications, sqlite_stat1 provides all the statistics required
  85154. ** for the query planner to make good choices.
  85155. **
  85156. ** Format of sqlite_stat1:
  85157. **
  85158. ** There is normally one row per index, with the index identified by the
  85159. ** name in the idx column. The tbl column is the name of the table to
  85160. ** which the index belongs. In each such row, the stat column will be
  85161. ** a string consisting of a list of integers. The first integer in this
  85162. ** list is the number of rows in the index. (This is the same as the
  85163. ** number of rows in the table, except for partial indices.) The second
  85164. ** integer is the average number of rows in the index that have the same
  85165. ** value in the first column of the index. The third integer is the average
  85166. ** number of rows in the index that have the same value for the first two
  85167. ** columns. The N-th integer (for N>1) is the average number of rows in
  85168. ** the index which have the same value for the first N-1 columns. For
  85169. ** a K-column index, there will be K+1 integers in the stat column. If
  85170. ** the index is unique, then the last integer will be 1.
  85171. **
  85172. ** The list of integers in the stat column can optionally be followed
  85173. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  85174. ** must be separated from the last integer by a single space. If the
  85175. ** "unordered" keyword is present, then the query planner assumes that
  85176. ** the index is unordered and will not use the index for a range query.
  85177. **
  85178. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  85179. ** column contains a single integer which is the (estimated) number of
  85180. ** rows in the table identified by sqlite_stat1.tbl.
  85181. **
  85182. ** Format of sqlite_stat2:
  85183. **
  85184. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  85185. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  85186. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  85187. ** about the distribution of keys within an index. The index is identified by
  85188. ** the "idx" column and the "tbl" column is the name of the table to which
  85189. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  85190. ** table for each index.
  85191. **
  85192. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  85193. ** inclusive are samples of the left-most key value in the index taken at
  85194. ** evenly spaced points along the index. Let the number of samples be S
  85195. ** (10 in the standard build) and let C be the number of rows in the index.
  85196. ** Then the sampled rows are given by:
  85197. **
  85198. ** rownumber = (i*C*2 + C)/(S*2)
  85199. **
  85200. ** For i between 0 and S-1. Conceptually, the index space is divided into
  85201. ** S uniform buckets and the samples are the middle row from each bucket.
  85202. **
  85203. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  85204. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  85205. ** writes the sqlite_stat2 table. This version of SQLite only supports
  85206. ** sqlite_stat3.
  85207. **
  85208. ** Format for sqlite_stat3:
  85209. **
  85210. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  85211. ** sqlite_stat4 format will be described first. Further information
  85212. ** about sqlite_stat3 follows the sqlite_stat4 description.
  85213. **
  85214. ** Format for sqlite_stat4:
  85215. **
  85216. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  85217. ** to aid the query planner in choosing good indices based on the values
  85218. ** that indexed columns are compared against in the WHERE clauses of
  85219. ** queries.
  85220. **
  85221. ** The sqlite_stat4 table contains multiple entries for each index.
  85222. ** The idx column names the index and the tbl column is the table of the
  85223. ** index. If the idx and tbl columns are the same, then the sample is
  85224. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  85225. ** binary encoding of a key from the index. The nEq column is a
  85226. ** list of integers. The first integer is the approximate number
  85227. ** of entries in the index whose left-most column exactly matches
  85228. ** the left-most column of the sample. The second integer in nEq
  85229. ** is the approximate number of entries in the index where the
  85230. ** first two columns match the first two columns of the sample.
  85231. ** And so forth. nLt is another list of integers that show the approximate
  85232. ** number of entries that are strictly less than the sample. The first
  85233. ** integer in nLt contains the number of entries in the index where the
  85234. ** left-most column is less than the left-most column of the sample.
  85235. ** The K-th integer in the nLt entry is the number of index entries
  85236. ** where the first K columns are less than the first K columns of the
  85237. ** sample. The nDLt column is like nLt except that it contains the
  85238. ** number of distinct entries in the index that are less than the
  85239. ** sample.
  85240. **
  85241. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  85242. ** The ANALYZE command will typically generate sqlite_stat4 tables
  85243. ** that contain between 10 and 40 samples which are distributed across
  85244. ** the key space, though not uniformly, and which include samples with
  85245. ** large nEq values.
  85246. **
  85247. ** Format for sqlite_stat3 redux:
  85248. **
  85249. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  85250. ** looks at the left-most column of the index. The sqlite_stat3.sample
  85251. ** column contains the actual value of the left-most column instead
  85252. ** of a blob encoding of the complete index key as is found in
  85253. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  85254. ** all contain just a single integer which is the same as the first
  85255. ** integer in the equivalent columns in sqlite_stat4.
  85256. */
  85257. #ifndef SQLITE_OMIT_ANALYZE
  85258. /* #include "sqliteInt.h" */
  85259. #if defined(SQLITE_ENABLE_STAT4)
  85260. # define IsStat4 1
  85261. # define IsStat3 0
  85262. #elif defined(SQLITE_ENABLE_STAT3)
  85263. # define IsStat4 0
  85264. # define IsStat3 1
  85265. #else
  85266. # define IsStat4 0
  85267. # define IsStat3 0
  85268. # undef SQLITE_STAT4_SAMPLES
  85269. # define SQLITE_STAT4_SAMPLES 1
  85270. #endif
  85271. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  85272. /*
  85273. ** This routine generates code that opens the sqlite_statN tables.
  85274. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  85275. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  85276. ** appropriate compile-time options are provided.
  85277. **
  85278. ** If the sqlite_statN tables do not previously exist, it is created.
  85279. **
  85280. ** Argument zWhere may be a pointer to a buffer containing a table name,
  85281. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  85282. ** the sqlite_statN tables associated with the named table are deleted.
  85283. ** If zWhere==0, then code is generated to delete all stat table entries.
  85284. */
  85285. static void openStatTable(
  85286. Parse *pParse, /* Parsing context */
  85287. int iDb, /* The database we are looking in */
  85288. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  85289. const char *zWhere, /* Delete entries for this table or index */
  85290. const char *zWhereType /* Either "tbl" or "idx" */
  85291. ){
  85292. static const struct {
  85293. const char *zName;
  85294. const char *zCols;
  85295. } aTable[] = {
  85296. { "sqlite_stat1", "tbl,idx,stat" },
  85297. #if defined(SQLITE_ENABLE_STAT4)
  85298. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  85299. { "sqlite_stat3", 0 },
  85300. #elif defined(SQLITE_ENABLE_STAT3)
  85301. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  85302. { "sqlite_stat4", 0 },
  85303. #else
  85304. { "sqlite_stat3", 0 },
  85305. { "sqlite_stat4", 0 },
  85306. #endif
  85307. };
  85308. int i;
  85309. sqlite3 *db = pParse->db;
  85310. Db *pDb;
  85311. Vdbe *v = sqlite3GetVdbe(pParse);
  85312. int aRoot[ArraySize(aTable)];
  85313. u8 aCreateTbl[ArraySize(aTable)];
  85314. if( v==0 ) return;
  85315. assert( sqlite3BtreeHoldsAllMutexes(db) );
  85316. assert( sqlite3VdbeDb(v)==db );
  85317. pDb = &db->aDb[iDb];
  85318. /* Create new statistic tables if they do not exist, or clear them
  85319. ** if they do already exist.
  85320. */
  85321. for(i=0; i<ArraySize(aTable); i++){
  85322. const char *zTab = aTable[i].zName;
  85323. Table *pStat;
  85324. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  85325. if( aTable[i].zCols ){
  85326. /* The sqlite_statN table does not exist. Create it. Note that a
  85327. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  85328. ** of the new table in register pParse->regRoot. This is important
  85329. ** because the OpenWrite opcode below will be needing it. */
  85330. sqlite3NestedParse(pParse,
  85331. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  85332. );
  85333. aRoot[i] = pParse->regRoot;
  85334. aCreateTbl[i] = OPFLAG_P2ISREG;
  85335. }
  85336. }else{
  85337. /* The table already exists. If zWhere is not NULL, delete all entries
  85338. ** associated with the table zWhere. If zWhere is NULL, delete the
  85339. ** entire contents of the table. */
  85340. aRoot[i] = pStat->tnum;
  85341. aCreateTbl[i] = 0;
  85342. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  85343. if( zWhere ){
  85344. sqlite3NestedParse(pParse,
  85345. "DELETE FROM %Q.%s WHERE %s=%Q",
  85346. pDb->zName, zTab, zWhereType, zWhere
  85347. );
  85348. }else{
  85349. /* The sqlite_stat[134] table already exists. Delete all rows. */
  85350. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  85351. }
  85352. }
  85353. }
  85354. /* Open the sqlite_stat[134] tables for writing. */
  85355. for(i=0; aTable[i].zCols; i++){
  85356. assert( i<ArraySize(aTable) );
  85357. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  85358. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  85359. VdbeComment((v, aTable[i].zName));
  85360. }
  85361. }
  85362. /*
  85363. ** Recommended number of samples for sqlite_stat4
  85364. */
  85365. #ifndef SQLITE_STAT4_SAMPLES
  85366. # define SQLITE_STAT4_SAMPLES 24
  85367. #endif
  85368. /*
  85369. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  85370. ** share an instance of the following structure to hold their state
  85371. ** information.
  85372. */
  85373. typedef struct Stat4Accum Stat4Accum;
  85374. typedef struct Stat4Sample Stat4Sample;
  85375. struct Stat4Sample {
  85376. tRowcnt *anEq; /* sqlite_stat4.nEq */
  85377. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  85378. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85379. tRowcnt *anLt; /* sqlite_stat4.nLt */
  85380. union {
  85381. i64 iRowid; /* Rowid in main table of the key */
  85382. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  85383. } u;
  85384. u32 nRowid; /* Sizeof aRowid[] */
  85385. u8 isPSample; /* True if a periodic sample */
  85386. int iCol; /* If !isPSample, the reason for inclusion */
  85387. u32 iHash; /* Tiebreaker hash */
  85388. #endif
  85389. };
  85390. struct Stat4Accum {
  85391. tRowcnt nRow; /* Number of rows in the entire table */
  85392. tRowcnt nPSample; /* How often to do a periodic sample */
  85393. int nCol; /* Number of columns in index + pk/rowid */
  85394. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  85395. int mxSample; /* Maximum number of samples to accumulate */
  85396. Stat4Sample current; /* Current row as a Stat4Sample */
  85397. u32 iPrn; /* Pseudo-random number used for sampling */
  85398. Stat4Sample *aBest; /* Array of nCol best samples */
  85399. int iMin; /* Index in a[] of entry with minimum score */
  85400. int nSample; /* Current number of samples */
  85401. int iGet; /* Index of current sample accessed by stat_get() */
  85402. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  85403. sqlite3 *db; /* Database connection, for malloc() */
  85404. };
  85405. /* Reclaim memory used by a Stat4Sample
  85406. */
  85407. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85408. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  85409. assert( db!=0 );
  85410. if( p->nRowid ){
  85411. sqlite3DbFree(db, p->u.aRowid);
  85412. p->nRowid = 0;
  85413. }
  85414. }
  85415. #endif
  85416. /* Initialize the BLOB value of a ROWID
  85417. */
  85418. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85419. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  85420. assert( db!=0 );
  85421. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  85422. p->u.aRowid = sqlite3DbMallocRaw(db, n);
  85423. if( p->u.aRowid ){
  85424. p->nRowid = n;
  85425. memcpy(p->u.aRowid, pData, n);
  85426. }else{
  85427. p->nRowid = 0;
  85428. }
  85429. }
  85430. #endif
  85431. /* Initialize the INTEGER value of a ROWID.
  85432. */
  85433. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85434. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  85435. assert( db!=0 );
  85436. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  85437. p->nRowid = 0;
  85438. p->u.iRowid = iRowid;
  85439. }
  85440. #endif
  85441. /*
  85442. ** Copy the contents of object (*pFrom) into (*pTo).
  85443. */
  85444. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85445. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  85446. pTo->isPSample = pFrom->isPSample;
  85447. pTo->iCol = pFrom->iCol;
  85448. pTo->iHash = pFrom->iHash;
  85449. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  85450. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  85451. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  85452. if( pFrom->nRowid ){
  85453. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  85454. }else{
  85455. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  85456. }
  85457. }
  85458. #endif
  85459. /*
  85460. ** Reclaim all memory of a Stat4Accum structure.
  85461. */
  85462. static void stat4Destructor(void *pOld){
  85463. Stat4Accum *p = (Stat4Accum*)pOld;
  85464. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85465. int i;
  85466. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  85467. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  85468. sampleClear(p->db, &p->current);
  85469. #endif
  85470. sqlite3DbFree(p->db, p);
  85471. }
  85472. /*
  85473. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  85474. ** are:
  85475. ** N: The number of columns in the index including the rowid/pk (note 1)
  85476. ** K: The number of columns in the index excluding the rowid/pk.
  85477. ** C: The number of rows in the index (note 2)
  85478. **
  85479. ** Note 1: In the special case of the covering index that implements a
  85480. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  85481. ** total number of columns in the table.
  85482. **
  85483. ** Note 2: C is only used for STAT3 and STAT4.
  85484. **
  85485. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  85486. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  85487. ** PRIMARY KEY of the table. The covering index that implements the
  85488. ** original WITHOUT ROWID table as N==K as a special case.
  85489. **
  85490. ** This routine allocates the Stat4Accum object in heap memory. The return
  85491. ** value is a pointer to the Stat4Accum object. The datatype of the
  85492. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  85493. ** object.
  85494. */
  85495. static void statInit(
  85496. sqlite3_context *context,
  85497. int argc,
  85498. sqlite3_value **argv
  85499. ){
  85500. Stat4Accum *p;
  85501. int nCol; /* Number of columns in index being sampled */
  85502. int nKeyCol; /* Number of key columns */
  85503. int nColUp; /* nCol rounded up for alignment */
  85504. int n; /* Bytes of space to allocate */
  85505. sqlite3 *db; /* Database connection */
  85506. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85507. int mxSample = SQLITE_STAT4_SAMPLES;
  85508. #endif
  85509. /* Decode the three function arguments */
  85510. UNUSED_PARAMETER(argc);
  85511. nCol = sqlite3_value_int(argv[0]);
  85512. assert( nCol>0 );
  85513. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  85514. nKeyCol = sqlite3_value_int(argv[1]);
  85515. assert( nKeyCol<=nCol );
  85516. assert( nKeyCol>0 );
  85517. /* Allocate the space required for the Stat4Accum object */
  85518. n = sizeof(*p)
  85519. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  85520. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  85521. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85522. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  85523. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  85524. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  85525. #endif
  85526. ;
  85527. db = sqlite3_context_db_handle(context);
  85528. p = sqlite3DbMallocZero(db, n);
  85529. if( p==0 ){
  85530. sqlite3_result_error_nomem(context);
  85531. return;
  85532. }
  85533. p->db = db;
  85534. p->nRow = 0;
  85535. p->nCol = nCol;
  85536. p->nKeyCol = nKeyCol;
  85537. p->current.anDLt = (tRowcnt*)&p[1];
  85538. p->current.anEq = &p->current.anDLt[nColUp];
  85539. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85540. {
  85541. u8 *pSpace; /* Allocated space not yet assigned */
  85542. int i; /* Used to iterate through p->aSample[] */
  85543. p->iGet = -1;
  85544. p->mxSample = mxSample;
  85545. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  85546. p->current.anLt = &p->current.anEq[nColUp];
  85547. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  85548. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  85549. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  85550. p->aBest = &p->a[mxSample];
  85551. pSpace = (u8*)(&p->a[mxSample+nCol]);
  85552. for(i=0; i<(mxSample+nCol); i++){
  85553. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  85554. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  85555. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  85556. }
  85557. assert( (pSpace - (u8*)p)==n );
  85558. for(i=0; i<nCol; i++){
  85559. p->aBest[i].iCol = i;
  85560. }
  85561. }
  85562. #endif
  85563. /* Return a pointer to the allocated object to the caller. Note that
  85564. ** only the pointer (the 2nd parameter) matters. The size of the object
  85565. ** (given by the 3rd parameter) is never used and can be any positive
  85566. ** value. */
  85567. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  85568. }
  85569. static const FuncDef statInitFuncdef = {
  85570. 2+IsStat34, /* nArg */
  85571. SQLITE_UTF8, /* funcFlags */
  85572. 0, /* pUserData */
  85573. 0, /* pNext */
  85574. statInit, /* xFunc */
  85575. 0, /* xStep */
  85576. 0, /* xFinalize */
  85577. "stat_init", /* zName */
  85578. 0, /* pHash */
  85579. 0 /* pDestructor */
  85580. };
  85581. #ifdef SQLITE_ENABLE_STAT4
  85582. /*
  85583. ** pNew and pOld are both candidate non-periodic samples selected for
  85584. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  85585. ** considering only any trailing columns and the sample hash value, this
  85586. ** function returns true if sample pNew is to be preferred over pOld.
  85587. ** In other words, if we assume that the cardinalities of the selected
  85588. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  85589. **
  85590. ** This function assumes that for each argument sample, the contents of
  85591. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  85592. */
  85593. static int sampleIsBetterPost(
  85594. Stat4Accum *pAccum,
  85595. Stat4Sample *pNew,
  85596. Stat4Sample *pOld
  85597. ){
  85598. int nCol = pAccum->nCol;
  85599. int i;
  85600. assert( pNew->iCol==pOld->iCol );
  85601. for(i=pNew->iCol+1; i<nCol; i++){
  85602. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  85603. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  85604. }
  85605. if( pNew->iHash>pOld->iHash ) return 1;
  85606. return 0;
  85607. }
  85608. #endif
  85609. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85610. /*
  85611. ** Return true if pNew is to be preferred over pOld.
  85612. **
  85613. ** This function assumes that for each argument sample, the contents of
  85614. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  85615. */
  85616. static int sampleIsBetter(
  85617. Stat4Accum *pAccum,
  85618. Stat4Sample *pNew,
  85619. Stat4Sample *pOld
  85620. ){
  85621. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  85622. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  85623. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  85624. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  85625. if( (nEqNew>nEqOld) ) return 1;
  85626. #ifdef SQLITE_ENABLE_STAT4
  85627. if( nEqNew==nEqOld ){
  85628. if( pNew->iCol<pOld->iCol ) return 1;
  85629. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  85630. }
  85631. return 0;
  85632. #else
  85633. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  85634. #endif
  85635. }
  85636. /*
  85637. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  85638. ** remove the least desirable sample from p->a[] to make room.
  85639. */
  85640. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  85641. Stat4Sample *pSample = 0;
  85642. int i;
  85643. assert( IsStat4 || nEqZero==0 );
  85644. #ifdef SQLITE_ENABLE_STAT4
  85645. if( pNew->isPSample==0 ){
  85646. Stat4Sample *pUpgrade = 0;
  85647. assert( pNew->anEq[pNew->iCol]>0 );
  85648. /* This sample is being added because the prefix that ends in column
  85649. ** iCol occurs many times in the table. However, if we have already
  85650. ** added a sample that shares this prefix, there is no need to add
  85651. ** this one. Instead, upgrade the priority of the highest priority
  85652. ** existing sample that shares this prefix. */
  85653. for(i=p->nSample-1; i>=0; i--){
  85654. Stat4Sample *pOld = &p->a[i];
  85655. if( pOld->anEq[pNew->iCol]==0 ){
  85656. if( pOld->isPSample ) return;
  85657. assert( pOld->iCol>pNew->iCol );
  85658. assert( sampleIsBetter(p, pNew, pOld) );
  85659. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  85660. pUpgrade = pOld;
  85661. }
  85662. }
  85663. }
  85664. if( pUpgrade ){
  85665. pUpgrade->iCol = pNew->iCol;
  85666. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  85667. goto find_new_min;
  85668. }
  85669. }
  85670. #endif
  85671. /* If necessary, remove sample iMin to make room for the new sample. */
  85672. if( p->nSample>=p->mxSample ){
  85673. Stat4Sample *pMin = &p->a[p->iMin];
  85674. tRowcnt *anEq = pMin->anEq;
  85675. tRowcnt *anLt = pMin->anLt;
  85676. tRowcnt *anDLt = pMin->anDLt;
  85677. sampleClear(p->db, pMin);
  85678. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  85679. pSample = &p->a[p->nSample-1];
  85680. pSample->nRowid = 0;
  85681. pSample->anEq = anEq;
  85682. pSample->anDLt = anDLt;
  85683. pSample->anLt = anLt;
  85684. p->nSample = p->mxSample-1;
  85685. }
  85686. /* The "rows less-than" for the rowid column must be greater than that
  85687. ** for the last sample in the p->a[] array. Otherwise, the samples would
  85688. ** be out of order. */
  85689. #ifdef SQLITE_ENABLE_STAT4
  85690. assert( p->nSample==0
  85691. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  85692. #endif
  85693. /* Insert the new sample */
  85694. pSample = &p->a[p->nSample];
  85695. sampleCopy(p, pSample, pNew);
  85696. p->nSample++;
  85697. /* Zero the first nEqZero entries in the anEq[] array. */
  85698. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  85699. #ifdef SQLITE_ENABLE_STAT4
  85700. find_new_min:
  85701. #endif
  85702. if( p->nSample>=p->mxSample ){
  85703. int iMin = -1;
  85704. for(i=0; i<p->mxSample; i++){
  85705. if( p->a[i].isPSample ) continue;
  85706. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  85707. iMin = i;
  85708. }
  85709. }
  85710. assert( iMin>=0 );
  85711. p->iMin = iMin;
  85712. }
  85713. }
  85714. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  85715. /*
  85716. ** Field iChng of the index being scanned has changed. So at this point
  85717. ** p->current contains a sample that reflects the previous row of the
  85718. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  85719. ** correct at this point.
  85720. */
  85721. static void samplePushPrevious(Stat4Accum *p, int iChng){
  85722. #ifdef SQLITE_ENABLE_STAT4
  85723. int i;
  85724. /* Check if any samples from the aBest[] array should be pushed
  85725. ** into IndexSample.a[] at this point. */
  85726. for(i=(p->nCol-2); i>=iChng; i--){
  85727. Stat4Sample *pBest = &p->aBest[i];
  85728. pBest->anEq[i] = p->current.anEq[i];
  85729. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  85730. sampleInsert(p, pBest, i);
  85731. }
  85732. }
  85733. /* Update the anEq[] fields of any samples already collected. */
  85734. for(i=p->nSample-1; i>=0; i--){
  85735. int j;
  85736. for(j=iChng; j<p->nCol; j++){
  85737. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  85738. }
  85739. }
  85740. #endif
  85741. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  85742. if( iChng==0 ){
  85743. tRowcnt nLt = p->current.anLt[0];
  85744. tRowcnt nEq = p->current.anEq[0];
  85745. /* Check if this is to be a periodic sample. If so, add it. */
  85746. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  85747. p->current.isPSample = 1;
  85748. sampleInsert(p, &p->current, 0);
  85749. p->current.isPSample = 0;
  85750. }else
  85751. /* Or if it is a non-periodic sample. Add it in this case too. */
  85752. if( p->nSample<p->mxSample
  85753. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  85754. ){
  85755. sampleInsert(p, &p->current, 0);
  85756. }
  85757. }
  85758. #endif
  85759. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  85760. UNUSED_PARAMETER( p );
  85761. UNUSED_PARAMETER( iChng );
  85762. #endif
  85763. }
  85764. /*
  85765. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  85766. ** Arguments:
  85767. **
  85768. ** P Pointer to the Stat4Accum object created by stat_init()
  85769. ** C Index of left-most column to differ from previous row
  85770. ** R Rowid for the current row. Might be a key record for
  85771. ** WITHOUT ROWID tables.
  85772. **
  85773. ** This SQL function always returns NULL. It's purpose it to accumulate
  85774. ** statistical data and/or samples in the Stat4Accum object about the
  85775. ** index being analyzed. The stat_get() SQL function will later be used to
  85776. ** extract relevant information for constructing the sqlite_statN tables.
  85777. **
  85778. ** The R parameter is only used for STAT3 and STAT4
  85779. */
  85780. static void statPush(
  85781. sqlite3_context *context,
  85782. int argc,
  85783. sqlite3_value **argv
  85784. ){
  85785. int i;
  85786. /* The three function arguments */
  85787. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  85788. int iChng = sqlite3_value_int(argv[1]);
  85789. UNUSED_PARAMETER( argc );
  85790. UNUSED_PARAMETER( context );
  85791. assert( p->nCol>0 );
  85792. assert( iChng<p->nCol );
  85793. if( p->nRow==0 ){
  85794. /* This is the first call to this function. Do initialization. */
  85795. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  85796. }else{
  85797. /* Second and subsequent calls get processed here */
  85798. samplePushPrevious(p, iChng);
  85799. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  85800. ** to the current row of the index. */
  85801. for(i=0; i<iChng; i++){
  85802. p->current.anEq[i]++;
  85803. }
  85804. for(i=iChng; i<p->nCol; i++){
  85805. p->current.anDLt[i]++;
  85806. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85807. p->current.anLt[i] += p->current.anEq[i];
  85808. #endif
  85809. p->current.anEq[i] = 1;
  85810. }
  85811. }
  85812. p->nRow++;
  85813. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85814. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  85815. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  85816. }else{
  85817. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  85818. sqlite3_value_blob(argv[2]));
  85819. }
  85820. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  85821. #endif
  85822. #ifdef SQLITE_ENABLE_STAT4
  85823. {
  85824. tRowcnt nLt = p->current.anLt[p->nCol-1];
  85825. /* Check if this is to be a periodic sample. If so, add it. */
  85826. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  85827. p->current.isPSample = 1;
  85828. p->current.iCol = 0;
  85829. sampleInsert(p, &p->current, p->nCol-1);
  85830. p->current.isPSample = 0;
  85831. }
  85832. /* Update the aBest[] array. */
  85833. for(i=0; i<(p->nCol-1); i++){
  85834. p->current.iCol = i;
  85835. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  85836. sampleCopy(p, &p->aBest[i], &p->current);
  85837. }
  85838. }
  85839. }
  85840. #endif
  85841. }
  85842. static const FuncDef statPushFuncdef = {
  85843. 2+IsStat34, /* nArg */
  85844. SQLITE_UTF8, /* funcFlags */
  85845. 0, /* pUserData */
  85846. 0, /* pNext */
  85847. statPush, /* xFunc */
  85848. 0, /* xStep */
  85849. 0, /* xFinalize */
  85850. "stat_push", /* zName */
  85851. 0, /* pHash */
  85852. 0 /* pDestructor */
  85853. };
  85854. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  85855. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  85856. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  85857. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  85858. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  85859. /*
  85860. ** Implementation of the stat_get(P,J) SQL function. This routine is
  85861. ** used to query statistical information that has been gathered into
  85862. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  85863. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  85864. ** The content to returned is determined by the parameter J
  85865. ** which is one of the STAT_GET_xxxx values defined above.
  85866. **
  85867. ** If neither STAT3 nor STAT4 are enabled, then J is always
  85868. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  85869. ** a one-parameter function, stat_get(P), that always returns the
  85870. ** stat1 table entry information.
  85871. */
  85872. static void statGet(
  85873. sqlite3_context *context,
  85874. int argc,
  85875. sqlite3_value **argv
  85876. ){
  85877. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  85878. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85879. /* STAT3 and STAT4 have a parameter on this routine. */
  85880. int eCall = sqlite3_value_int(argv[1]);
  85881. assert( argc==2 );
  85882. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  85883. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  85884. || eCall==STAT_GET_NDLT
  85885. );
  85886. if( eCall==STAT_GET_STAT1 )
  85887. #else
  85888. assert( argc==1 );
  85889. #endif
  85890. {
  85891. /* Return the value to store in the "stat" column of the sqlite_stat1
  85892. ** table for this index.
  85893. **
  85894. ** The value is a string composed of a list of integers describing
  85895. ** the index. The first integer in the list is the total number of
  85896. ** entries in the index. There is one additional integer in the list
  85897. ** for each indexed column. This additional integer is an estimate of
  85898. ** the number of rows matched by a stabbing query on the index using
  85899. ** a key with the corresponding number of fields. In other words,
  85900. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  85901. ** "100 10 2", then SQLite estimates that:
  85902. **
  85903. ** * the index contains 100 rows,
  85904. ** * "WHERE a=?" matches 10 rows, and
  85905. ** * "WHERE a=? AND b=?" matches 2 rows.
  85906. **
  85907. ** If D is the count of distinct values and K is the total number of
  85908. ** rows, then each estimate is computed as:
  85909. **
  85910. ** I = (K+D-1)/D
  85911. */
  85912. char *z;
  85913. int i;
  85914. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  85915. if( zRet==0 ){
  85916. sqlite3_result_error_nomem(context);
  85917. return;
  85918. }
  85919. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  85920. z = zRet + sqlite3Strlen30(zRet);
  85921. for(i=0; i<p->nKeyCol; i++){
  85922. u64 nDistinct = p->current.anDLt[i] + 1;
  85923. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  85924. sqlite3_snprintf(24, z, " %llu", iVal);
  85925. z += sqlite3Strlen30(z);
  85926. assert( p->current.anEq[i] );
  85927. }
  85928. assert( z[0]=='\0' && z>zRet );
  85929. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  85930. }
  85931. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85932. else if( eCall==STAT_GET_ROWID ){
  85933. if( p->iGet<0 ){
  85934. samplePushPrevious(p, 0);
  85935. p->iGet = 0;
  85936. }
  85937. if( p->iGet<p->nSample ){
  85938. Stat4Sample *pS = p->a + p->iGet;
  85939. if( pS->nRowid==0 ){
  85940. sqlite3_result_int64(context, pS->u.iRowid);
  85941. }else{
  85942. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  85943. SQLITE_TRANSIENT);
  85944. }
  85945. }
  85946. }else{
  85947. tRowcnt *aCnt = 0;
  85948. assert( p->iGet<p->nSample );
  85949. switch( eCall ){
  85950. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  85951. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  85952. default: {
  85953. aCnt = p->a[p->iGet].anDLt;
  85954. p->iGet++;
  85955. break;
  85956. }
  85957. }
  85958. if( IsStat3 ){
  85959. sqlite3_result_int64(context, (i64)aCnt[0]);
  85960. }else{
  85961. char *zRet = sqlite3MallocZero(p->nCol * 25);
  85962. if( zRet==0 ){
  85963. sqlite3_result_error_nomem(context);
  85964. }else{
  85965. int i;
  85966. char *z = zRet;
  85967. for(i=0; i<p->nCol; i++){
  85968. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  85969. z += sqlite3Strlen30(z);
  85970. }
  85971. assert( z[0]=='\0' && z>zRet );
  85972. z[-1] = '\0';
  85973. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  85974. }
  85975. }
  85976. }
  85977. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  85978. #ifndef SQLITE_DEBUG
  85979. UNUSED_PARAMETER( argc );
  85980. #endif
  85981. }
  85982. static const FuncDef statGetFuncdef = {
  85983. 1+IsStat34, /* nArg */
  85984. SQLITE_UTF8, /* funcFlags */
  85985. 0, /* pUserData */
  85986. 0, /* pNext */
  85987. statGet, /* xFunc */
  85988. 0, /* xStep */
  85989. 0, /* xFinalize */
  85990. "stat_get", /* zName */
  85991. 0, /* pHash */
  85992. 0 /* pDestructor */
  85993. };
  85994. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  85995. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  85996. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85997. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  85998. #elif SQLITE_DEBUG
  85999. assert( iParam==STAT_GET_STAT1 );
  86000. #else
  86001. UNUSED_PARAMETER( iParam );
  86002. #endif
  86003. sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4, regOut);
  86004. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  86005. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  86006. }
  86007. /*
  86008. ** Generate code to do an analysis of all indices associated with
  86009. ** a single table.
  86010. */
  86011. static void analyzeOneTable(
  86012. Parse *pParse, /* Parser context */
  86013. Table *pTab, /* Table whose indices are to be analyzed */
  86014. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  86015. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  86016. int iMem, /* Available memory locations begin here */
  86017. int iTab /* Next available cursor */
  86018. ){
  86019. sqlite3 *db = pParse->db; /* Database handle */
  86020. Index *pIdx; /* An index to being analyzed */
  86021. int iIdxCur; /* Cursor open on index being analyzed */
  86022. int iTabCur; /* Table cursor */
  86023. Vdbe *v; /* The virtual machine being built up */
  86024. int i; /* Loop counter */
  86025. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  86026. int iDb; /* Index of database containing pTab */
  86027. u8 needTableCnt = 1; /* True to count the table */
  86028. int regNewRowid = iMem++; /* Rowid for the inserted record */
  86029. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  86030. int regChng = iMem++; /* Index of changed index field */
  86031. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86032. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  86033. #endif
  86034. int regTemp = iMem++; /* Temporary use register */
  86035. int regTabname = iMem++; /* Register containing table name */
  86036. int regIdxname = iMem++; /* Register containing index name */
  86037. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  86038. int regPrev = iMem; /* MUST BE LAST (see below) */
  86039. pParse->nMem = MAX(pParse->nMem, iMem);
  86040. v = sqlite3GetVdbe(pParse);
  86041. if( v==0 || NEVER(pTab==0) ){
  86042. return;
  86043. }
  86044. if( pTab->tnum==0 ){
  86045. /* Do not gather statistics on views or virtual tables */
  86046. return;
  86047. }
  86048. if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
  86049. /* Do not gather statistics on system tables */
  86050. return;
  86051. }
  86052. assert( sqlite3BtreeHoldsAllMutexes(db) );
  86053. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  86054. assert( iDb>=0 );
  86055. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86056. #ifndef SQLITE_OMIT_AUTHORIZATION
  86057. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  86058. db->aDb[iDb].zName ) ){
  86059. return;
  86060. }
  86061. #endif
  86062. /* Establish a read-lock on the table at the shared-cache level.
  86063. ** Open a read-only cursor on the table. Also allocate a cursor number
  86064. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  86065. ** this time though. */
  86066. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  86067. iTabCur = iTab++;
  86068. iIdxCur = iTab++;
  86069. pParse->nTab = MAX(pParse->nTab, iTab);
  86070. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  86071. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  86072. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  86073. int nCol; /* Number of columns in pIdx. "N" */
  86074. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  86075. int addrNextRow; /* Address of "next_row:" */
  86076. const char *zIdxName; /* Name of the index */
  86077. int nColTest; /* Number of columns to test for changes */
  86078. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  86079. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  86080. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  86081. nCol = pIdx->nKeyCol;
  86082. zIdxName = pTab->zName;
  86083. nColTest = nCol - 1;
  86084. }else{
  86085. nCol = pIdx->nColumn;
  86086. zIdxName = pIdx->zName;
  86087. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  86088. }
  86089. /* Populate the register containing the index name. */
  86090. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  86091. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  86092. /*
  86093. ** Pseudo-code for loop that calls stat_push():
  86094. **
  86095. ** Rewind csr
  86096. ** if eof(csr) goto end_of_scan;
  86097. ** regChng = 0
  86098. ** goto chng_addr_0;
  86099. **
  86100. ** next_row:
  86101. ** regChng = 0
  86102. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  86103. ** regChng = 1
  86104. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  86105. ** ...
  86106. ** regChng = N
  86107. ** goto chng_addr_N
  86108. **
  86109. ** chng_addr_0:
  86110. ** regPrev(0) = idx(0)
  86111. ** chng_addr_1:
  86112. ** regPrev(1) = idx(1)
  86113. ** ...
  86114. **
  86115. ** endDistinctTest:
  86116. ** regRowid = idx(rowid)
  86117. ** stat_push(P, regChng, regRowid)
  86118. ** Next csr
  86119. ** if !eof(csr) goto next_row;
  86120. **
  86121. ** end_of_scan:
  86122. */
  86123. /* Make sure there are enough memory cells allocated to accommodate
  86124. ** the regPrev array and a trailing rowid (the rowid slot is required
  86125. ** when building a record to insert into the sample column of
  86126. ** the sqlite_stat4 table. */
  86127. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  86128. /* Open a read-only cursor on the index being analyzed. */
  86129. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  86130. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  86131. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  86132. VdbeComment((v, "%s", pIdx->zName));
  86133. /* Invoke the stat_init() function. The arguments are:
  86134. **
  86135. ** (1) the number of columns in the index including the rowid
  86136. ** (or for a WITHOUT ROWID table, the number of PK columns),
  86137. ** (2) the number of columns in the key without the rowid/pk
  86138. ** (3) the number of rows in the index,
  86139. **
  86140. **
  86141. ** The third argument is only used for STAT3 and STAT4
  86142. */
  86143. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86144. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  86145. #endif
  86146. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  86147. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  86148. sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4+1, regStat4);
  86149. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  86150. sqlite3VdbeChangeP5(v, 2+IsStat34);
  86151. /* Implementation of the following:
  86152. **
  86153. ** Rewind csr
  86154. ** if eof(csr) goto end_of_scan;
  86155. ** regChng = 0
  86156. ** goto next_push_0;
  86157. **
  86158. */
  86159. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  86160. VdbeCoverage(v);
  86161. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  86162. addrNextRow = sqlite3VdbeCurrentAddr(v);
  86163. if( nColTest>0 ){
  86164. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  86165. int *aGotoChng; /* Array of jump instruction addresses */
  86166. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
  86167. if( aGotoChng==0 ) continue;
  86168. /*
  86169. ** next_row:
  86170. ** regChng = 0
  86171. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  86172. ** regChng = 1
  86173. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  86174. ** ...
  86175. ** regChng = N
  86176. ** goto endDistinctTest
  86177. */
  86178. sqlite3VdbeAddOp0(v, OP_Goto);
  86179. addrNextRow = sqlite3VdbeCurrentAddr(v);
  86180. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  86181. /* For a single-column UNIQUE index, once we have found a non-NULL
  86182. ** row, we know that all the rest will be distinct, so skip
  86183. ** subsequent distinctness tests. */
  86184. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  86185. VdbeCoverage(v);
  86186. }
  86187. for(i=0; i<nColTest; i++){
  86188. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  86189. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  86190. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  86191. aGotoChng[i] =
  86192. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  86193. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  86194. VdbeCoverage(v);
  86195. }
  86196. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  86197. sqlite3VdbeGoto(v, endDistinctTest);
  86198. /*
  86199. ** chng_addr_0:
  86200. ** regPrev(0) = idx(0)
  86201. ** chng_addr_1:
  86202. ** regPrev(1) = idx(1)
  86203. ** ...
  86204. */
  86205. sqlite3VdbeJumpHere(v, addrNextRow-1);
  86206. for(i=0; i<nColTest; i++){
  86207. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  86208. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  86209. }
  86210. sqlite3VdbeResolveLabel(v, endDistinctTest);
  86211. sqlite3DbFree(db, aGotoChng);
  86212. }
  86213. /*
  86214. ** chng_addr_N:
  86215. ** regRowid = idx(rowid) // STAT34 only
  86216. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  86217. ** Next csr
  86218. ** if !eof(csr) goto next_row;
  86219. */
  86220. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86221. assert( regRowid==(regStat4+2) );
  86222. if( HasRowid(pTab) ){
  86223. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  86224. }else{
  86225. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  86226. int j, k, regKey;
  86227. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  86228. for(j=0; j<pPk->nKeyCol; j++){
  86229. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  86230. assert( k>=0 && k<pTab->nCol );
  86231. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  86232. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  86233. }
  86234. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  86235. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  86236. }
  86237. #endif
  86238. assert( regChng==(regStat4+1) );
  86239. sqlite3VdbeAddOp3(v, OP_Function0, 1, regStat4, regTemp);
  86240. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  86241. sqlite3VdbeChangeP5(v, 2+IsStat34);
  86242. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  86243. /* Add the entry to the stat1 table. */
  86244. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  86245. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  86246. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  86247. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  86248. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  86249. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  86250. /* Add the entries to the stat3 or stat4 table. */
  86251. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86252. {
  86253. int regEq = regStat1;
  86254. int regLt = regStat1+1;
  86255. int regDLt = regStat1+2;
  86256. int regSample = regStat1+3;
  86257. int regCol = regStat1+4;
  86258. int regSampleRowid = regCol + nCol;
  86259. int addrNext;
  86260. int addrIsNull;
  86261. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  86262. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  86263. addrNext = sqlite3VdbeCurrentAddr(v);
  86264. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  86265. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  86266. VdbeCoverage(v);
  86267. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  86268. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  86269. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  86270. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  86271. /* We know that the regSampleRowid row exists because it was read by
  86272. ** the previous loop. Thus the not-found jump of seekOp will never
  86273. ** be taken */
  86274. VdbeCoverageNeverTaken(v);
  86275. #ifdef SQLITE_ENABLE_STAT3
  86276. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  86277. #else
  86278. for(i=0; i<nCol; i++){
  86279. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  86280. }
  86281. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  86282. #endif
  86283. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  86284. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  86285. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  86286. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  86287. sqlite3VdbeJumpHere(v, addrIsNull);
  86288. }
  86289. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  86290. /* End of analysis */
  86291. sqlite3VdbeJumpHere(v, addrRewind);
  86292. }
  86293. /* Create a single sqlite_stat1 entry containing NULL as the index
  86294. ** name and the row count as the content.
  86295. */
  86296. if( pOnlyIdx==0 && needTableCnt ){
  86297. VdbeComment((v, "%s", pTab->zName));
  86298. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  86299. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  86300. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  86301. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  86302. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  86303. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  86304. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  86305. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  86306. sqlite3VdbeJumpHere(v, jZeroRows);
  86307. }
  86308. }
  86309. /*
  86310. ** Generate code that will cause the most recent index analysis to
  86311. ** be loaded into internal hash tables where is can be used.
  86312. */
  86313. static void loadAnalysis(Parse *pParse, int iDb){
  86314. Vdbe *v = sqlite3GetVdbe(pParse);
  86315. if( v ){
  86316. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  86317. }
  86318. }
  86319. /*
  86320. ** Generate code that will do an analysis of an entire database
  86321. */
  86322. static void analyzeDatabase(Parse *pParse, int iDb){
  86323. sqlite3 *db = pParse->db;
  86324. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  86325. HashElem *k;
  86326. int iStatCur;
  86327. int iMem;
  86328. int iTab;
  86329. sqlite3BeginWriteOperation(pParse, 0, iDb);
  86330. iStatCur = pParse->nTab;
  86331. pParse->nTab += 3;
  86332. openStatTable(pParse, iDb, iStatCur, 0, 0);
  86333. iMem = pParse->nMem+1;
  86334. iTab = pParse->nTab;
  86335. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86336. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  86337. Table *pTab = (Table*)sqliteHashData(k);
  86338. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  86339. }
  86340. loadAnalysis(pParse, iDb);
  86341. }
  86342. /*
  86343. ** Generate code that will do an analysis of a single table in
  86344. ** a database. If pOnlyIdx is not NULL then it is a single index
  86345. ** in pTab that should be analyzed.
  86346. */
  86347. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  86348. int iDb;
  86349. int iStatCur;
  86350. assert( pTab!=0 );
  86351. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  86352. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  86353. sqlite3BeginWriteOperation(pParse, 0, iDb);
  86354. iStatCur = pParse->nTab;
  86355. pParse->nTab += 3;
  86356. if( pOnlyIdx ){
  86357. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  86358. }else{
  86359. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  86360. }
  86361. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  86362. loadAnalysis(pParse, iDb);
  86363. }
  86364. /*
  86365. ** Generate code for the ANALYZE command. The parser calls this routine
  86366. ** when it recognizes an ANALYZE command.
  86367. **
  86368. ** ANALYZE -- 1
  86369. ** ANALYZE <database> -- 2
  86370. ** ANALYZE ?<database>.?<tablename> -- 3
  86371. **
  86372. ** Form 1 causes all indices in all attached databases to be analyzed.
  86373. ** Form 2 analyzes all indices the single database named.
  86374. ** Form 3 analyzes all indices associated with the named table.
  86375. */
  86376. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  86377. sqlite3 *db = pParse->db;
  86378. int iDb;
  86379. int i;
  86380. char *z, *zDb;
  86381. Table *pTab;
  86382. Index *pIdx;
  86383. Token *pTableName;
  86384. Vdbe *v;
  86385. /* Read the database schema. If an error occurs, leave an error message
  86386. ** and code in pParse and return NULL. */
  86387. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  86388. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  86389. return;
  86390. }
  86391. assert( pName2!=0 || pName1==0 );
  86392. if( pName1==0 ){
  86393. /* Form 1: Analyze everything */
  86394. for(i=0; i<db->nDb; i++){
  86395. if( i==1 ) continue; /* Do not analyze the TEMP database */
  86396. analyzeDatabase(pParse, i);
  86397. }
  86398. }else if( pName2->n==0 ){
  86399. /* Form 2: Analyze the database or table named */
  86400. iDb = sqlite3FindDb(db, pName1);
  86401. if( iDb>=0 ){
  86402. analyzeDatabase(pParse, iDb);
  86403. }else{
  86404. z = sqlite3NameFromToken(db, pName1);
  86405. if( z ){
  86406. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  86407. analyzeTable(pParse, pIdx->pTable, pIdx);
  86408. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  86409. analyzeTable(pParse, pTab, 0);
  86410. }
  86411. sqlite3DbFree(db, z);
  86412. }
  86413. }
  86414. }else{
  86415. /* Form 3: Analyze the fully qualified table name */
  86416. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  86417. if( iDb>=0 ){
  86418. zDb = db->aDb[iDb].zName;
  86419. z = sqlite3NameFromToken(db, pTableName);
  86420. if( z ){
  86421. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  86422. analyzeTable(pParse, pIdx->pTable, pIdx);
  86423. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  86424. analyzeTable(pParse, pTab, 0);
  86425. }
  86426. sqlite3DbFree(db, z);
  86427. }
  86428. }
  86429. }
  86430. v = sqlite3GetVdbe(pParse);
  86431. if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
  86432. }
  86433. /*
  86434. ** Used to pass information from the analyzer reader through to the
  86435. ** callback routine.
  86436. */
  86437. typedef struct analysisInfo analysisInfo;
  86438. struct analysisInfo {
  86439. sqlite3 *db;
  86440. const char *zDatabase;
  86441. };
  86442. /*
  86443. ** The first argument points to a nul-terminated string containing a
  86444. ** list of space separated integers. Read the first nOut of these into
  86445. ** the array aOut[].
  86446. */
  86447. static void decodeIntArray(
  86448. char *zIntArray, /* String containing int array to decode */
  86449. int nOut, /* Number of slots in aOut[] */
  86450. tRowcnt *aOut, /* Store integers here */
  86451. LogEst *aLog, /* Or, if aOut==0, here */
  86452. Index *pIndex /* Handle extra flags for this index, if not NULL */
  86453. ){
  86454. char *z = zIntArray;
  86455. int c;
  86456. int i;
  86457. tRowcnt v;
  86458. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86459. if( z==0 ) z = "";
  86460. #else
  86461. assert( z!=0 );
  86462. #endif
  86463. for(i=0; *z && i<nOut; i++){
  86464. v = 0;
  86465. while( (c=z[0])>='0' && c<='9' ){
  86466. v = v*10 + c - '0';
  86467. z++;
  86468. }
  86469. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86470. if( aOut ) aOut[i] = v;
  86471. if( aLog ) aLog[i] = sqlite3LogEst(v);
  86472. #else
  86473. assert( aOut==0 );
  86474. UNUSED_PARAMETER(aOut);
  86475. assert( aLog!=0 );
  86476. aLog[i] = sqlite3LogEst(v);
  86477. #endif
  86478. if( *z==' ' ) z++;
  86479. }
  86480. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  86481. assert( pIndex!=0 ); {
  86482. #else
  86483. if( pIndex ){
  86484. #endif
  86485. pIndex->bUnordered = 0;
  86486. pIndex->noSkipScan = 0;
  86487. while( z[0] ){
  86488. if( sqlite3_strglob("unordered*", z)==0 ){
  86489. pIndex->bUnordered = 1;
  86490. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  86491. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  86492. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  86493. pIndex->noSkipScan = 1;
  86494. }
  86495. #ifdef SQLITE_ENABLE_COSTMULT
  86496. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  86497. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  86498. }
  86499. #endif
  86500. while( z[0]!=0 && z[0]!=' ' ) z++;
  86501. while( z[0]==' ' ) z++;
  86502. }
  86503. }
  86504. }
  86505. /*
  86506. ** This callback is invoked once for each index when reading the
  86507. ** sqlite_stat1 table.
  86508. **
  86509. ** argv[0] = name of the table
  86510. ** argv[1] = name of the index (might be NULL)
  86511. ** argv[2] = results of analysis - on integer for each column
  86512. **
  86513. ** Entries for which argv[1]==NULL simply record the number of rows in
  86514. ** the table.
  86515. */
  86516. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  86517. analysisInfo *pInfo = (analysisInfo*)pData;
  86518. Index *pIndex;
  86519. Table *pTable;
  86520. const char *z;
  86521. assert( argc==3 );
  86522. UNUSED_PARAMETER2(NotUsed, argc);
  86523. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  86524. return 0;
  86525. }
  86526. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  86527. if( pTable==0 ){
  86528. return 0;
  86529. }
  86530. if( argv[1]==0 ){
  86531. pIndex = 0;
  86532. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  86533. pIndex = sqlite3PrimaryKeyIndex(pTable);
  86534. }else{
  86535. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  86536. }
  86537. z = argv[2];
  86538. if( pIndex ){
  86539. tRowcnt *aiRowEst = 0;
  86540. int nCol = pIndex->nKeyCol+1;
  86541. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86542. /* Index.aiRowEst may already be set here if there are duplicate
  86543. ** sqlite_stat1 entries for this index. In that case just clobber
  86544. ** the old data with the new instead of allocating a new array. */
  86545. if( pIndex->aiRowEst==0 ){
  86546. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  86547. if( pIndex->aiRowEst==0 ) pInfo->db->mallocFailed = 1;
  86548. }
  86549. aiRowEst = pIndex->aiRowEst;
  86550. #endif
  86551. pIndex->bUnordered = 0;
  86552. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  86553. if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  86554. }else{
  86555. Index fakeIdx;
  86556. fakeIdx.szIdxRow = pTable->szTabRow;
  86557. #ifdef SQLITE_ENABLE_COSTMULT
  86558. fakeIdx.pTable = pTable;
  86559. #endif
  86560. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  86561. pTable->szTabRow = fakeIdx.szIdxRow;
  86562. }
  86563. return 0;
  86564. }
  86565. /*
  86566. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  86567. ** and its contents.
  86568. */
  86569. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  86570. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86571. if( pIdx->aSample ){
  86572. int j;
  86573. for(j=0; j<pIdx->nSample; j++){
  86574. IndexSample *p = &pIdx->aSample[j];
  86575. sqlite3DbFree(db, p->p);
  86576. }
  86577. sqlite3DbFree(db, pIdx->aSample);
  86578. }
  86579. if( db && db->pnBytesFreed==0 ){
  86580. pIdx->nSample = 0;
  86581. pIdx->aSample = 0;
  86582. }
  86583. #else
  86584. UNUSED_PARAMETER(db);
  86585. UNUSED_PARAMETER(pIdx);
  86586. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  86587. }
  86588. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86589. /*
  86590. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  86591. ** stored in pIdx->aSample[].
  86592. */
  86593. static void initAvgEq(Index *pIdx){
  86594. if( pIdx ){
  86595. IndexSample *aSample = pIdx->aSample;
  86596. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  86597. int iCol;
  86598. int nCol = 1;
  86599. if( pIdx->nSampleCol>1 ){
  86600. /* If this is stat4 data, then calculate aAvgEq[] values for all
  86601. ** sample columns except the last. The last is always set to 1, as
  86602. ** once the trailing PK fields are considered all index keys are
  86603. ** unique. */
  86604. nCol = pIdx->nSampleCol-1;
  86605. pIdx->aAvgEq[nCol] = 1;
  86606. }
  86607. for(iCol=0; iCol<nCol; iCol++){
  86608. int nSample = pIdx->nSample;
  86609. int i; /* Used to iterate through samples */
  86610. tRowcnt sumEq = 0; /* Sum of the nEq values */
  86611. tRowcnt avgEq = 0;
  86612. tRowcnt nRow; /* Number of rows in index */
  86613. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  86614. i64 nDist100; /* Number of distinct values in index */
  86615. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  86616. nRow = pFinal->anLt[iCol];
  86617. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  86618. nSample--;
  86619. }else{
  86620. nRow = pIdx->aiRowEst[0];
  86621. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  86622. }
  86623. pIdx->nRowEst0 = nRow;
  86624. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  86625. ** occur in the stat4 table for this index. Set sumEq to the sum of
  86626. ** the nEq values for column iCol for the same set (adding the value
  86627. ** only once where there exist duplicate prefixes). */
  86628. for(i=0; i<nSample; i++){
  86629. if( i==(pIdx->nSample-1)
  86630. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  86631. ){
  86632. sumEq += aSample[i].anEq[iCol];
  86633. nSum100 += 100;
  86634. }
  86635. }
  86636. if( nDist100>nSum100 ){
  86637. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  86638. }
  86639. if( avgEq==0 ) avgEq = 1;
  86640. pIdx->aAvgEq[iCol] = avgEq;
  86641. }
  86642. }
  86643. }
  86644. /*
  86645. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  86646. ** is supplied instead, find the PRIMARY KEY index for that table.
  86647. */
  86648. static Index *findIndexOrPrimaryKey(
  86649. sqlite3 *db,
  86650. const char *zName,
  86651. const char *zDb
  86652. ){
  86653. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  86654. if( pIdx==0 ){
  86655. Table *pTab = sqlite3FindTable(db, zName, zDb);
  86656. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  86657. }
  86658. return pIdx;
  86659. }
  86660. /*
  86661. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  86662. ** into the relevant Index.aSample[] arrays.
  86663. **
  86664. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  86665. ** data equivalent to the following (statements are different for stat3,
  86666. ** see the caller of this function for details):
  86667. **
  86668. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  86669. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  86670. **
  86671. ** where %Q is replaced with the database name before the SQL is executed.
  86672. */
  86673. static int loadStatTbl(
  86674. sqlite3 *db, /* Database handle */
  86675. int bStat3, /* Assume single column records only */
  86676. const char *zSql1, /* SQL statement 1 (see above) */
  86677. const char *zSql2, /* SQL statement 2 (see above) */
  86678. const char *zDb /* Database name (e.g. "main") */
  86679. ){
  86680. int rc; /* Result codes from subroutines */
  86681. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  86682. char *zSql; /* Text of the SQL statement */
  86683. Index *pPrevIdx = 0; /* Previous index in the loop */
  86684. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  86685. assert( db->lookaside.bEnabled==0 );
  86686. zSql = sqlite3MPrintf(db, zSql1, zDb);
  86687. if( !zSql ){
  86688. return SQLITE_NOMEM;
  86689. }
  86690. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  86691. sqlite3DbFree(db, zSql);
  86692. if( rc ) return rc;
  86693. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  86694. int nIdxCol = 1; /* Number of columns in stat4 records */
  86695. char *zIndex; /* Index name */
  86696. Index *pIdx; /* Pointer to the index object */
  86697. int nSample; /* Number of samples */
  86698. int nByte; /* Bytes of space required */
  86699. int i; /* Bytes of space required */
  86700. tRowcnt *pSpace;
  86701. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  86702. if( zIndex==0 ) continue;
  86703. nSample = sqlite3_column_int(pStmt, 1);
  86704. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  86705. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  86706. /* Index.nSample is non-zero at this point if data has already been
  86707. ** loaded from the stat4 table. In this case ignore stat3 data. */
  86708. if( pIdx==0 || pIdx->nSample ) continue;
  86709. if( bStat3==0 ){
  86710. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  86711. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  86712. nIdxCol = pIdx->nKeyCol;
  86713. }else{
  86714. nIdxCol = pIdx->nColumn;
  86715. }
  86716. }
  86717. pIdx->nSampleCol = nIdxCol;
  86718. nByte = sizeof(IndexSample) * nSample;
  86719. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  86720. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  86721. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  86722. if( pIdx->aSample==0 ){
  86723. sqlite3_finalize(pStmt);
  86724. return SQLITE_NOMEM;
  86725. }
  86726. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  86727. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  86728. for(i=0; i<nSample; i++){
  86729. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  86730. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  86731. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  86732. }
  86733. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  86734. }
  86735. rc = sqlite3_finalize(pStmt);
  86736. if( rc ) return rc;
  86737. zSql = sqlite3MPrintf(db, zSql2, zDb);
  86738. if( !zSql ){
  86739. return SQLITE_NOMEM;
  86740. }
  86741. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  86742. sqlite3DbFree(db, zSql);
  86743. if( rc ) return rc;
  86744. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  86745. char *zIndex; /* Index name */
  86746. Index *pIdx; /* Pointer to the index object */
  86747. int nCol = 1; /* Number of columns in index */
  86748. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  86749. if( zIndex==0 ) continue;
  86750. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  86751. if( pIdx==0 ) continue;
  86752. /* This next condition is true if data has already been loaded from
  86753. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  86754. nCol = pIdx->nSampleCol;
  86755. if( bStat3 && nCol>1 ) continue;
  86756. if( pIdx!=pPrevIdx ){
  86757. initAvgEq(pPrevIdx);
  86758. pPrevIdx = pIdx;
  86759. }
  86760. pSample = &pIdx->aSample[pIdx->nSample];
  86761. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  86762. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  86763. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  86764. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  86765. ** This is in case the sample record is corrupted. In that case, the
  86766. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  86767. ** end of the allocated buffer before it realizes it is dealing with
  86768. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  86769. ** a buffer overread. */
  86770. pSample->n = sqlite3_column_bytes(pStmt, 4);
  86771. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  86772. if( pSample->p==0 ){
  86773. sqlite3_finalize(pStmt);
  86774. return SQLITE_NOMEM;
  86775. }
  86776. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  86777. pIdx->nSample++;
  86778. }
  86779. rc = sqlite3_finalize(pStmt);
  86780. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  86781. return rc;
  86782. }
  86783. /*
  86784. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  86785. ** the Index.aSample[] arrays of all indices.
  86786. */
  86787. static int loadStat4(sqlite3 *db, const char *zDb){
  86788. int rc = SQLITE_OK; /* Result codes from subroutines */
  86789. assert( db->lookaside.bEnabled==0 );
  86790. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  86791. rc = loadStatTbl(db, 0,
  86792. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  86793. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  86794. zDb
  86795. );
  86796. }
  86797. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  86798. rc = loadStatTbl(db, 1,
  86799. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  86800. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  86801. zDb
  86802. );
  86803. }
  86804. return rc;
  86805. }
  86806. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  86807. /*
  86808. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  86809. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  86810. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  86811. ** Index.aSample[] arrays.
  86812. **
  86813. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  86814. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  86815. ** during compilation and the sqlite_stat3/4 table is present, no data is
  86816. ** read from it.
  86817. **
  86818. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  86819. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  86820. ** returned. However, in this case, data is read from the sqlite_stat1
  86821. ** table (if it is present) before returning.
  86822. **
  86823. ** If an OOM error occurs, this function always sets db->mallocFailed.
  86824. ** This means if the caller does not care about other errors, the return
  86825. ** code may be ignored.
  86826. */
  86827. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  86828. analysisInfo sInfo;
  86829. HashElem *i;
  86830. char *zSql;
  86831. int rc;
  86832. assert( iDb>=0 && iDb<db->nDb );
  86833. assert( db->aDb[iDb].pBt!=0 );
  86834. /* Clear any prior statistics */
  86835. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86836. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  86837. Index *pIdx = sqliteHashData(i);
  86838. sqlite3DefaultRowEst(pIdx);
  86839. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86840. sqlite3DeleteIndexSamples(db, pIdx);
  86841. pIdx->aSample = 0;
  86842. #endif
  86843. }
  86844. /* Check to make sure the sqlite_stat1 table exists */
  86845. sInfo.db = db;
  86846. sInfo.zDatabase = db->aDb[iDb].zName;
  86847. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  86848. return SQLITE_ERROR;
  86849. }
  86850. /* Load new statistics out of the sqlite_stat1 table */
  86851. zSql = sqlite3MPrintf(db,
  86852. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  86853. if( zSql==0 ){
  86854. rc = SQLITE_NOMEM;
  86855. }else{
  86856. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  86857. sqlite3DbFree(db, zSql);
  86858. }
  86859. /* Load the statistics from the sqlite_stat4 table. */
  86860. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86861. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  86862. int lookasideEnabled = db->lookaside.bEnabled;
  86863. db->lookaside.bEnabled = 0;
  86864. rc = loadStat4(db, sInfo.zDatabase);
  86865. db->lookaside.bEnabled = lookasideEnabled;
  86866. }
  86867. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  86868. Index *pIdx = sqliteHashData(i);
  86869. sqlite3_free(pIdx->aiRowEst);
  86870. pIdx->aiRowEst = 0;
  86871. }
  86872. #endif
  86873. if( rc==SQLITE_NOMEM ){
  86874. db->mallocFailed = 1;
  86875. }
  86876. return rc;
  86877. }
  86878. #endif /* SQLITE_OMIT_ANALYZE */
  86879. /************** End of analyze.c *********************************************/
  86880. /************** Begin file attach.c ******************************************/
  86881. /*
  86882. ** 2003 April 6
  86883. **
  86884. ** The author disclaims copyright to this source code. In place of
  86885. ** a legal notice, here is a blessing:
  86886. **
  86887. ** May you do good and not evil.
  86888. ** May you find forgiveness for yourself and forgive others.
  86889. ** May you share freely, never taking more than you give.
  86890. **
  86891. *************************************************************************
  86892. ** This file contains code used to implement the ATTACH and DETACH commands.
  86893. */
  86894. /* #include "sqliteInt.h" */
  86895. #ifndef SQLITE_OMIT_ATTACH
  86896. /*
  86897. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  86898. ** is slightly different from resolving a normal SQL expression, because simple
  86899. ** identifiers are treated as strings, not possible column names or aliases.
  86900. **
  86901. ** i.e. if the parser sees:
  86902. **
  86903. ** ATTACH DATABASE abc AS def
  86904. **
  86905. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  86906. ** looking for columns of the same name.
  86907. **
  86908. ** This only applies to the root node of pExpr, so the statement:
  86909. **
  86910. ** ATTACH DATABASE abc||def AS 'db2'
  86911. **
  86912. ** will fail because neither abc or def can be resolved.
  86913. */
  86914. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  86915. {
  86916. int rc = SQLITE_OK;
  86917. if( pExpr ){
  86918. if( pExpr->op!=TK_ID ){
  86919. rc = sqlite3ResolveExprNames(pName, pExpr);
  86920. }else{
  86921. pExpr->op = TK_STRING;
  86922. }
  86923. }
  86924. return rc;
  86925. }
  86926. /*
  86927. ** An SQL user-function registered to do the work of an ATTACH statement. The
  86928. ** three arguments to the function come directly from an attach statement:
  86929. **
  86930. ** ATTACH DATABASE x AS y KEY z
  86931. **
  86932. ** SELECT sqlite_attach(x, y, z)
  86933. **
  86934. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  86935. ** third argument.
  86936. */
  86937. static void attachFunc(
  86938. sqlite3_context *context,
  86939. int NotUsed,
  86940. sqlite3_value **argv
  86941. ){
  86942. int i;
  86943. int rc = 0;
  86944. sqlite3 *db = sqlite3_context_db_handle(context);
  86945. const char *zName;
  86946. const char *zFile;
  86947. char *zPath = 0;
  86948. char *zErr = 0;
  86949. unsigned int flags;
  86950. Db *aNew;
  86951. char *zErrDyn = 0;
  86952. sqlite3_vfs *pVfs;
  86953. UNUSED_PARAMETER(NotUsed);
  86954. zFile = (const char *)sqlite3_value_text(argv[0]);
  86955. zName = (const char *)sqlite3_value_text(argv[1]);
  86956. if( zFile==0 ) zFile = "";
  86957. if( zName==0 ) zName = "";
  86958. /* Check for the following errors:
  86959. **
  86960. ** * Too many attached databases,
  86961. ** * Transaction currently open
  86962. ** * Specified database name already being used.
  86963. */
  86964. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  86965. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  86966. db->aLimit[SQLITE_LIMIT_ATTACHED]
  86967. );
  86968. goto attach_error;
  86969. }
  86970. if( !db->autoCommit ){
  86971. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  86972. goto attach_error;
  86973. }
  86974. for(i=0; i<db->nDb; i++){
  86975. char *z = db->aDb[i].zName;
  86976. assert( z && zName );
  86977. if( sqlite3StrICmp(z, zName)==0 ){
  86978. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  86979. goto attach_error;
  86980. }
  86981. }
  86982. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  86983. ** hash tables.
  86984. */
  86985. if( db->aDb==db->aDbStatic ){
  86986. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  86987. if( aNew==0 ) return;
  86988. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  86989. }else{
  86990. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  86991. if( aNew==0 ) return;
  86992. }
  86993. db->aDb = aNew;
  86994. aNew = &db->aDb[db->nDb];
  86995. memset(aNew, 0, sizeof(*aNew));
  86996. /* Open the database file. If the btree is successfully opened, use
  86997. ** it to obtain the database schema. At this point the schema may
  86998. ** or may not be initialized.
  86999. */
  87000. flags = db->openFlags;
  87001. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  87002. if( rc!=SQLITE_OK ){
  87003. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  87004. sqlite3_result_error(context, zErr, -1);
  87005. sqlite3_free(zErr);
  87006. return;
  87007. }
  87008. assert( pVfs );
  87009. flags |= SQLITE_OPEN_MAIN_DB;
  87010. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  87011. sqlite3_free( zPath );
  87012. db->nDb++;
  87013. if( rc==SQLITE_CONSTRAINT ){
  87014. rc = SQLITE_ERROR;
  87015. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  87016. }else if( rc==SQLITE_OK ){
  87017. Pager *pPager;
  87018. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  87019. if( !aNew->pSchema ){
  87020. rc = SQLITE_NOMEM;
  87021. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  87022. zErrDyn = sqlite3MPrintf(db,
  87023. "attached databases must use the same text encoding as main database");
  87024. rc = SQLITE_ERROR;
  87025. }
  87026. sqlite3BtreeEnter(aNew->pBt);
  87027. pPager = sqlite3BtreePager(aNew->pBt);
  87028. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  87029. sqlite3BtreeSecureDelete(aNew->pBt,
  87030. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  87031. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87032. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  87033. #endif
  87034. sqlite3BtreeLeave(aNew->pBt);
  87035. }
  87036. aNew->safety_level = 3;
  87037. aNew->zName = sqlite3DbStrDup(db, zName);
  87038. if( rc==SQLITE_OK && aNew->zName==0 ){
  87039. rc = SQLITE_NOMEM;
  87040. }
  87041. #ifdef SQLITE_HAS_CODEC
  87042. if( rc==SQLITE_OK ){
  87043. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  87044. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  87045. int nKey;
  87046. char *zKey;
  87047. int t = sqlite3_value_type(argv[2]);
  87048. switch( t ){
  87049. case SQLITE_INTEGER:
  87050. case SQLITE_FLOAT:
  87051. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  87052. rc = SQLITE_ERROR;
  87053. break;
  87054. case SQLITE_TEXT:
  87055. case SQLITE_BLOB:
  87056. nKey = sqlite3_value_bytes(argv[2]);
  87057. zKey = (char *)sqlite3_value_blob(argv[2]);
  87058. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  87059. break;
  87060. case SQLITE_NULL:
  87061. /* No key specified. Use the key from the main database */
  87062. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  87063. if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  87064. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  87065. }
  87066. break;
  87067. }
  87068. }
  87069. #endif
  87070. /* If the file was opened successfully, read the schema for the new database.
  87071. ** If this fails, or if opening the file failed, then close the file and
  87072. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  87073. ** we found it.
  87074. */
  87075. if( rc==SQLITE_OK ){
  87076. sqlite3BtreeEnterAll(db);
  87077. rc = sqlite3Init(db, &zErrDyn);
  87078. sqlite3BtreeLeaveAll(db);
  87079. }
  87080. #ifdef SQLITE_USER_AUTHENTICATION
  87081. if( rc==SQLITE_OK ){
  87082. u8 newAuth = 0;
  87083. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  87084. if( newAuth<db->auth.authLevel ){
  87085. rc = SQLITE_AUTH_USER;
  87086. }
  87087. }
  87088. #endif
  87089. if( rc ){
  87090. int iDb = db->nDb - 1;
  87091. assert( iDb>=2 );
  87092. if( db->aDb[iDb].pBt ){
  87093. sqlite3BtreeClose(db->aDb[iDb].pBt);
  87094. db->aDb[iDb].pBt = 0;
  87095. db->aDb[iDb].pSchema = 0;
  87096. }
  87097. sqlite3ResetAllSchemasOfConnection(db);
  87098. db->nDb = iDb;
  87099. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  87100. db->mallocFailed = 1;
  87101. sqlite3DbFree(db, zErrDyn);
  87102. zErrDyn = sqlite3MPrintf(db, "out of memory");
  87103. }else if( zErrDyn==0 ){
  87104. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  87105. }
  87106. goto attach_error;
  87107. }
  87108. return;
  87109. attach_error:
  87110. /* Return an error if we get here */
  87111. if( zErrDyn ){
  87112. sqlite3_result_error(context, zErrDyn, -1);
  87113. sqlite3DbFree(db, zErrDyn);
  87114. }
  87115. if( rc ) sqlite3_result_error_code(context, rc);
  87116. }
  87117. /*
  87118. ** An SQL user-function registered to do the work of an DETACH statement. The
  87119. ** three arguments to the function come directly from a detach statement:
  87120. **
  87121. ** DETACH DATABASE x
  87122. **
  87123. ** SELECT sqlite_detach(x)
  87124. */
  87125. static void detachFunc(
  87126. sqlite3_context *context,
  87127. int NotUsed,
  87128. sqlite3_value **argv
  87129. ){
  87130. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  87131. sqlite3 *db = sqlite3_context_db_handle(context);
  87132. int i;
  87133. Db *pDb = 0;
  87134. char zErr[128];
  87135. UNUSED_PARAMETER(NotUsed);
  87136. if( zName==0 ) zName = "";
  87137. for(i=0; i<db->nDb; i++){
  87138. pDb = &db->aDb[i];
  87139. if( pDb->pBt==0 ) continue;
  87140. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  87141. }
  87142. if( i>=db->nDb ){
  87143. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  87144. goto detach_error;
  87145. }
  87146. if( i<2 ){
  87147. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  87148. goto detach_error;
  87149. }
  87150. if( !db->autoCommit ){
  87151. sqlite3_snprintf(sizeof(zErr), zErr,
  87152. "cannot DETACH database within transaction");
  87153. goto detach_error;
  87154. }
  87155. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  87156. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  87157. goto detach_error;
  87158. }
  87159. sqlite3BtreeClose(pDb->pBt);
  87160. pDb->pBt = 0;
  87161. pDb->pSchema = 0;
  87162. sqlite3CollapseDatabaseArray(db);
  87163. return;
  87164. detach_error:
  87165. sqlite3_result_error(context, zErr, -1);
  87166. }
  87167. /*
  87168. ** This procedure generates VDBE code for a single invocation of either the
  87169. ** sqlite_detach() or sqlite_attach() SQL user functions.
  87170. */
  87171. static void codeAttach(
  87172. Parse *pParse, /* The parser context */
  87173. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  87174. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  87175. Expr *pAuthArg, /* Expression to pass to authorization callback */
  87176. Expr *pFilename, /* Name of database file */
  87177. Expr *pDbname, /* Name of the database to use internally */
  87178. Expr *pKey /* Database key for encryption extension */
  87179. ){
  87180. int rc;
  87181. NameContext sName;
  87182. Vdbe *v;
  87183. sqlite3* db = pParse->db;
  87184. int regArgs;
  87185. memset(&sName, 0, sizeof(NameContext));
  87186. sName.pParse = pParse;
  87187. if(
  87188. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  87189. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  87190. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  87191. ){
  87192. goto attach_end;
  87193. }
  87194. #ifndef SQLITE_OMIT_AUTHORIZATION
  87195. if( pAuthArg ){
  87196. char *zAuthArg;
  87197. if( pAuthArg->op==TK_STRING ){
  87198. zAuthArg = pAuthArg->u.zToken;
  87199. }else{
  87200. zAuthArg = 0;
  87201. }
  87202. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  87203. if(rc!=SQLITE_OK ){
  87204. goto attach_end;
  87205. }
  87206. }
  87207. #endif /* SQLITE_OMIT_AUTHORIZATION */
  87208. v = sqlite3GetVdbe(pParse);
  87209. regArgs = sqlite3GetTempRange(pParse, 4);
  87210. sqlite3ExprCode(pParse, pFilename, regArgs);
  87211. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  87212. sqlite3ExprCode(pParse, pKey, regArgs+2);
  87213. assert( v || db->mallocFailed );
  87214. if( v ){
  87215. sqlite3VdbeAddOp3(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3);
  87216. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  87217. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  87218. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  87219. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  87220. ** statement only). For DETACH, set it to false (expire all existing
  87221. ** statements).
  87222. */
  87223. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  87224. }
  87225. attach_end:
  87226. sqlite3ExprDelete(db, pFilename);
  87227. sqlite3ExprDelete(db, pDbname);
  87228. sqlite3ExprDelete(db, pKey);
  87229. }
  87230. /*
  87231. ** Called by the parser to compile a DETACH statement.
  87232. **
  87233. ** DETACH pDbname
  87234. */
  87235. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  87236. static const FuncDef detach_func = {
  87237. 1, /* nArg */
  87238. SQLITE_UTF8, /* funcFlags */
  87239. 0, /* pUserData */
  87240. 0, /* pNext */
  87241. detachFunc, /* xFunc */
  87242. 0, /* xStep */
  87243. 0, /* xFinalize */
  87244. "sqlite_detach", /* zName */
  87245. 0, /* pHash */
  87246. 0 /* pDestructor */
  87247. };
  87248. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  87249. }
  87250. /*
  87251. ** Called by the parser to compile an ATTACH statement.
  87252. **
  87253. ** ATTACH p AS pDbname KEY pKey
  87254. */
  87255. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  87256. static const FuncDef attach_func = {
  87257. 3, /* nArg */
  87258. SQLITE_UTF8, /* funcFlags */
  87259. 0, /* pUserData */
  87260. 0, /* pNext */
  87261. attachFunc, /* xFunc */
  87262. 0, /* xStep */
  87263. 0, /* xFinalize */
  87264. "sqlite_attach", /* zName */
  87265. 0, /* pHash */
  87266. 0 /* pDestructor */
  87267. };
  87268. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  87269. }
  87270. #endif /* SQLITE_OMIT_ATTACH */
  87271. /*
  87272. ** Initialize a DbFixer structure. This routine must be called prior
  87273. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  87274. */
  87275. SQLITE_PRIVATE void sqlite3FixInit(
  87276. DbFixer *pFix, /* The fixer to be initialized */
  87277. Parse *pParse, /* Error messages will be written here */
  87278. int iDb, /* This is the database that must be used */
  87279. const char *zType, /* "view", "trigger", or "index" */
  87280. const Token *pName /* Name of the view, trigger, or index */
  87281. ){
  87282. sqlite3 *db;
  87283. db = pParse->db;
  87284. assert( db->nDb>iDb );
  87285. pFix->pParse = pParse;
  87286. pFix->zDb = db->aDb[iDb].zName;
  87287. pFix->pSchema = db->aDb[iDb].pSchema;
  87288. pFix->zType = zType;
  87289. pFix->pName = pName;
  87290. pFix->bVarOnly = (iDb==1);
  87291. }
  87292. /*
  87293. ** The following set of routines walk through the parse tree and assign
  87294. ** a specific database to all table references where the database name
  87295. ** was left unspecified in the original SQL statement. The pFix structure
  87296. ** must have been initialized by a prior call to sqlite3FixInit().
  87297. **
  87298. ** These routines are used to make sure that an index, trigger, or
  87299. ** view in one database does not refer to objects in a different database.
  87300. ** (Exception: indices, triggers, and views in the TEMP database are
  87301. ** allowed to refer to anything.) If a reference is explicitly made
  87302. ** to an object in a different database, an error message is added to
  87303. ** pParse->zErrMsg and these routines return non-zero. If everything
  87304. ** checks out, these routines return 0.
  87305. */
  87306. SQLITE_PRIVATE int sqlite3FixSrcList(
  87307. DbFixer *pFix, /* Context of the fixation */
  87308. SrcList *pList /* The Source list to check and modify */
  87309. ){
  87310. int i;
  87311. const char *zDb;
  87312. struct SrcList_item *pItem;
  87313. if( NEVER(pList==0) ) return 0;
  87314. zDb = pFix->zDb;
  87315. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  87316. if( pFix->bVarOnly==0 ){
  87317. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  87318. sqlite3ErrorMsg(pFix->pParse,
  87319. "%s %T cannot reference objects in database %s",
  87320. pFix->zType, pFix->pName, pItem->zDatabase);
  87321. return 1;
  87322. }
  87323. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  87324. pItem->zDatabase = 0;
  87325. pItem->pSchema = pFix->pSchema;
  87326. }
  87327. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  87328. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  87329. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  87330. #endif
  87331. }
  87332. return 0;
  87333. }
  87334. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  87335. SQLITE_PRIVATE int sqlite3FixSelect(
  87336. DbFixer *pFix, /* Context of the fixation */
  87337. Select *pSelect /* The SELECT statement to be fixed to one database */
  87338. ){
  87339. while( pSelect ){
  87340. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  87341. return 1;
  87342. }
  87343. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  87344. return 1;
  87345. }
  87346. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  87347. return 1;
  87348. }
  87349. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  87350. return 1;
  87351. }
  87352. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  87353. return 1;
  87354. }
  87355. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  87356. return 1;
  87357. }
  87358. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  87359. return 1;
  87360. }
  87361. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  87362. return 1;
  87363. }
  87364. pSelect = pSelect->pPrior;
  87365. }
  87366. return 0;
  87367. }
  87368. SQLITE_PRIVATE int sqlite3FixExpr(
  87369. DbFixer *pFix, /* Context of the fixation */
  87370. Expr *pExpr /* The expression to be fixed to one database */
  87371. ){
  87372. while( pExpr ){
  87373. if( pExpr->op==TK_VARIABLE ){
  87374. if( pFix->pParse->db->init.busy ){
  87375. pExpr->op = TK_NULL;
  87376. }else{
  87377. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  87378. return 1;
  87379. }
  87380. }
  87381. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  87382. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  87383. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  87384. }else{
  87385. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  87386. }
  87387. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  87388. return 1;
  87389. }
  87390. pExpr = pExpr->pLeft;
  87391. }
  87392. return 0;
  87393. }
  87394. SQLITE_PRIVATE int sqlite3FixExprList(
  87395. DbFixer *pFix, /* Context of the fixation */
  87396. ExprList *pList /* The expression to be fixed to one database */
  87397. ){
  87398. int i;
  87399. struct ExprList_item *pItem;
  87400. if( pList==0 ) return 0;
  87401. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  87402. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  87403. return 1;
  87404. }
  87405. }
  87406. return 0;
  87407. }
  87408. #endif
  87409. #ifndef SQLITE_OMIT_TRIGGER
  87410. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  87411. DbFixer *pFix, /* Context of the fixation */
  87412. TriggerStep *pStep /* The trigger step be fixed to one database */
  87413. ){
  87414. while( pStep ){
  87415. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  87416. return 1;
  87417. }
  87418. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  87419. return 1;
  87420. }
  87421. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  87422. return 1;
  87423. }
  87424. pStep = pStep->pNext;
  87425. }
  87426. return 0;
  87427. }
  87428. #endif
  87429. /************** End of attach.c **********************************************/
  87430. /************** Begin file auth.c ********************************************/
  87431. /*
  87432. ** 2003 January 11
  87433. **
  87434. ** The author disclaims copyright to this source code. In place of
  87435. ** a legal notice, here is a blessing:
  87436. **
  87437. ** May you do good and not evil.
  87438. ** May you find forgiveness for yourself and forgive others.
  87439. ** May you share freely, never taking more than you give.
  87440. **
  87441. *************************************************************************
  87442. ** This file contains code used to implement the sqlite3_set_authorizer()
  87443. ** API. This facility is an optional feature of the library. Embedded
  87444. ** systems that do not need this facility may omit it by recompiling
  87445. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  87446. */
  87447. /* #include "sqliteInt.h" */
  87448. /*
  87449. ** All of the code in this file may be omitted by defining a single
  87450. ** macro.
  87451. */
  87452. #ifndef SQLITE_OMIT_AUTHORIZATION
  87453. /*
  87454. ** Set or clear the access authorization function.
  87455. **
  87456. ** The access authorization function is be called during the compilation
  87457. ** phase to verify that the user has read and/or write access permission on
  87458. ** various fields of the database. The first argument to the auth function
  87459. ** is a copy of the 3rd argument to this routine. The second argument
  87460. ** to the auth function is one of these constants:
  87461. **
  87462. ** SQLITE_CREATE_INDEX
  87463. ** SQLITE_CREATE_TABLE
  87464. ** SQLITE_CREATE_TEMP_INDEX
  87465. ** SQLITE_CREATE_TEMP_TABLE
  87466. ** SQLITE_CREATE_TEMP_TRIGGER
  87467. ** SQLITE_CREATE_TEMP_VIEW
  87468. ** SQLITE_CREATE_TRIGGER
  87469. ** SQLITE_CREATE_VIEW
  87470. ** SQLITE_DELETE
  87471. ** SQLITE_DROP_INDEX
  87472. ** SQLITE_DROP_TABLE
  87473. ** SQLITE_DROP_TEMP_INDEX
  87474. ** SQLITE_DROP_TEMP_TABLE
  87475. ** SQLITE_DROP_TEMP_TRIGGER
  87476. ** SQLITE_DROP_TEMP_VIEW
  87477. ** SQLITE_DROP_TRIGGER
  87478. ** SQLITE_DROP_VIEW
  87479. ** SQLITE_INSERT
  87480. ** SQLITE_PRAGMA
  87481. ** SQLITE_READ
  87482. ** SQLITE_SELECT
  87483. ** SQLITE_TRANSACTION
  87484. ** SQLITE_UPDATE
  87485. **
  87486. ** The third and fourth arguments to the auth function are the name of
  87487. ** the table and the column that are being accessed. The auth function
  87488. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  87489. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  87490. ** means that the SQL statement will never-run - the sqlite3_exec() call
  87491. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  87492. ** should run but attempts to read the specified column will return NULL
  87493. ** and attempts to write the column will be ignored.
  87494. **
  87495. ** Setting the auth function to NULL disables this hook. The default
  87496. ** setting of the auth function is NULL.
  87497. */
  87498. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  87499. sqlite3 *db,
  87500. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  87501. void *pArg
  87502. ){
  87503. #ifdef SQLITE_ENABLE_API_ARMOR
  87504. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  87505. #endif
  87506. sqlite3_mutex_enter(db->mutex);
  87507. db->xAuth = (sqlite3_xauth)xAuth;
  87508. db->pAuthArg = pArg;
  87509. sqlite3ExpirePreparedStatements(db);
  87510. sqlite3_mutex_leave(db->mutex);
  87511. return SQLITE_OK;
  87512. }
  87513. /*
  87514. ** Write an error message into pParse->zErrMsg that explains that the
  87515. ** user-supplied authorization function returned an illegal value.
  87516. */
  87517. static void sqliteAuthBadReturnCode(Parse *pParse){
  87518. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  87519. pParse->rc = SQLITE_ERROR;
  87520. }
  87521. /*
  87522. ** Invoke the authorization callback for permission to read column zCol from
  87523. ** table zTab in database zDb. This function assumes that an authorization
  87524. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  87525. **
  87526. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  87527. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  87528. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  87529. */
  87530. SQLITE_PRIVATE int sqlite3AuthReadCol(
  87531. Parse *pParse, /* The parser context */
  87532. const char *zTab, /* Table name */
  87533. const char *zCol, /* Column name */
  87534. int iDb /* Index of containing database. */
  87535. ){
  87536. sqlite3 *db = pParse->db; /* Database handle */
  87537. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  87538. int rc; /* Auth callback return code */
  87539. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  87540. #ifdef SQLITE_USER_AUTHENTICATION
  87541. ,db->auth.zAuthUser
  87542. #endif
  87543. );
  87544. if( rc==SQLITE_DENY ){
  87545. if( db->nDb>2 || iDb!=0 ){
  87546. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  87547. }else{
  87548. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  87549. }
  87550. pParse->rc = SQLITE_AUTH;
  87551. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  87552. sqliteAuthBadReturnCode(pParse);
  87553. }
  87554. return rc;
  87555. }
  87556. /*
  87557. ** The pExpr should be a TK_COLUMN expression. The table referred to
  87558. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  87559. ** Check to see if it is OK to read this particular column.
  87560. **
  87561. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  87562. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  87563. ** then generate an error.
  87564. */
  87565. SQLITE_PRIVATE void sqlite3AuthRead(
  87566. Parse *pParse, /* The parser context */
  87567. Expr *pExpr, /* The expression to check authorization on */
  87568. Schema *pSchema, /* The schema of the expression */
  87569. SrcList *pTabList /* All table that pExpr might refer to */
  87570. ){
  87571. sqlite3 *db = pParse->db;
  87572. Table *pTab = 0; /* The table being read */
  87573. const char *zCol; /* Name of the column of the table */
  87574. int iSrc; /* Index in pTabList->a[] of table being read */
  87575. int iDb; /* The index of the database the expression refers to */
  87576. int iCol; /* Index of column in table */
  87577. if( db->xAuth==0 ) return;
  87578. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  87579. if( iDb<0 ){
  87580. /* An attempt to read a column out of a subquery or other
  87581. ** temporary table. */
  87582. return;
  87583. }
  87584. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  87585. if( pExpr->op==TK_TRIGGER ){
  87586. pTab = pParse->pTriggerTab;
  87587. }else{
  87588. assert( pTabList );
  87589. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  87590. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  87591. pTab = pTabList->a[iSrc].pTab;
  87592. break;
  87593. }
  87594. }
  87595. }
  87596. iCol = pExpr->iColumn;
  87597. if( NEVER(pTab==0) ) return;
  87598. if( iCol>=0 ){
  87599. assert( iCol<pTab->nCol );
  87600. zCol = pTab->aCol[iCol].zName;
  87601. }else if( pTab->iPKey>=0 ){
  87602. assert( pTab->iPKey<pTab->nCol );
  87603. zCol = pTab->aCol[pTab->iPKey].zName;
  87604. }else{
  87605. zCol = "ROWID";
  87606. }
  87607. assert( iDb>=0 && iDb<db->nDb );
  87608. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  87609. pExpr->op = TK_NULL;
  87610. }
  87611. }
  87612. /*
  87613. ** Do an authorization check using the code and arguments given. Return
  87614. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  87615. ** is returned, then the error count and error message in pParse are
  87616. ** modified appropriately.
  87617. */
  87618. SQLITE_PRIVATE int sqlite3AuthCheck(
  87619. Parse *pParse,
  87620. int code,
  87621. const char *zArg1,
  87622. const char *zArg2,
  87623. const char *zArg3
  87624. ){
  87625. sqlite3 *db = pParse->db;
  87626. int rc;
  87627. /* Don't do any authorization checks if the database is initialising
  87628. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  87629. */
  87630. if( db->init.busy || IN_DECLARE_VTAB ){
  87631. return SQLITE_OK;
  87632. }
  87633. if( db->xAuth==0 ){
  87634. return SQLITE_OK;
  87635. }
  87636. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  87637. #ifdef SQLITE_USER_AUTHENTICATION
  87638. ,db->auth.zAuthUser
  87639. #endif
  87640. );
  87641. if( rc==SQLITE_DENY ){
  87642. sqlite3ErrorMsg(pParse, "not authorized");
  87643. pParse->rc = SQLITE_AUTH;
  87644. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  87645. rc = SQLITE_DENY;
  87646. sqliteAuthBadReturnCode(pParse);
  87647. }
  87648. return rc;
  87649. }
  87650. /*
  87651. ** Push an authorization context. After this routine is called, the
  87652. ** zArg3 argument to authorization callbacks will be zContext until
  87653. ** popped. Or if pParse==0, this routine is a no-op.
  87654. */
  87655. SQLITE_PRIVATE void sqlite3AuthContextPush(
  87656. Parse *pParse,
  87657. AuthContext *pContext,
  87658. const char *zContext
  87659. ){
  87660. assert( pParse );
  87661. pContext->pParse = pParse;
  87662. pContext->zAuthContext = pParse->zAuthContext;
  87663. pParse->zAuthContext = zContext;
  87664. }
  87665. /*
  87666. ** Pop an authorization context that was previously pushed
  87667. ** by sqlite3AuthContextPush
  87668. */
  87669. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  87670. if( pContext->pParse ){
  87671. pContext->pParse->zAuthContext = pContext->zAuthContext;
  87672. pContext->pParse = 0;
  87673. }
  87674. }
  87675. #endif /* SQLITE_OMIT_AUTHORIZATION */
  87676. /************** End of auth.c ************************************************/
  87677. /************** Begin file build.c *******************************************/
  87678. /*
  87679. ** 2001 September 15
  87680. **
  87681. ** The author disclaims copyright to this source code. In place of
  87682. ** a legal notice, here is a blessing:
  87683. **
  87684. ** May you do good and not evil.
  87685. ** May you find forgiveness for yourself and forgive others.
  87686. ** May you share freely, never taking more than you give.
  87687. **
  87688. *************************************************************************
  87689. ** This file contains C code routines that are called by the SQLite parser
  87690. ** when syntax rules are reduced. The routines in this file handle the
  87691. ** following kinds of SQL syntax:
  87692. **
  87693. ** CREATE TABLE
  87694. ** DROP TABLE
  87695. ** CREATE INDEX
  87696. ** DROP INDEX
  87697. ** creating ID lists
  87698. ** BEGIN TRANSACTION
  87699. ** COMMIT
  87700. ** ROLLBACK
  87701. */
  87702. /* #include "sqliteInt.h" */
  87703. /*
  87704. ** This routine is called when a new SQL statement is beginning to
  87705. ** be parsed. Initialize the pParse structure as needed.
  87706. */
  87707. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  87708. pParse->explain = (u8)explainFlag;
  87709. pParse->nVar = 0;
  87710. }
  87711. #ifndef SQLITE_OMIT_SHARED_CACHE
  87712. /*
  87713. ** The TableLock structure is only used by the sqlite3TableLock() and
  87714. ** codeTableLocks() functions.
  87715. */
  87716. struct TableLock {
  87717. int iDb; /* The database containing the table to be locked */
  87718. int iTab; /* The root page of the table to be locked */
  87719. u8 isWriteLock; /* True for write lock. False for a read lock */
  87720. const char *zName; /* Name of the table */
  87721. };
  87722. /*
  87723. ** Record the fact that we want to lock a table at run-time.
  87724. **
  87725. ** The table to be locked has root page iTab and is found in database iDb.
  87726. ** A read or a write lock can be taken depending on isWritelock.
  87727. **
  87728. ** This routine just records the fact that the lock is desired. The
  87729. ** code to make the lock occur is generated by a later call to
  87730. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  87731. */
  87732. SQLITE_PRIVATE void sqlite3TableLock(
  87733. Parse *pParse, /* Parsing context */
  87734. int iDb, /* Index of the database containing the table to lock */
  87735. int iTab, /* Root page number of the table to be locked */
  87736. u8 isWriteLock, /* True for a write lock */
  87737. const char *zName /* Name of the table to be locked */
  87738. ){
  87739. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  87740. int i;
  87741. int nBytes;
  87742. TableLock *p;
  87743. assert( iDb>=0 );
  87744. for(i=0; i<pToplevel->nTableLock; i++){
  87745. p = &pToplevel->aTableLock[i];
  87746. if( p->iDb==iDb && p->iTab==iTab ){
  87747. p->isWriteLock = (p->isWriteLock || isWriteLock);
  87748. return;
  87749. }
  87750. }
  87751. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  87752. pToplevel->aTableLock =
  87753. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  87754. if( pToplevel->aTableLock ){
  87755. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  87756. p->iDb = iDb;
  87757. p->iTab = iTab;
  87758. p->isWriteLock = isWriteLock;
  87759. p->zName = zName;
  87760. }else{
  87761. pToplevel->nTableLock = 0;
  87762. pToplevel->db->mallocFailed = 1;
  87763. }
  87764. }
  87765. /*
  87766. ** Code an OP_TableLock instruction for each table locked by the
  87767. ** statement (configured by calls to sqlite3TableLock()).
  87768. */
  87769. static void codeTableLocks(Parse *pParse){
  87770. int i;
  87771. Vdbe *pVdbe;
  87772. pVdbe = sqlite3GetVdbe(pParse);
  87773. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  87774. for(i=0; i<pParse->nTableLock; i++){
  87775. TableLock *p = &pParse->aTableLock[i];
  87776. int p1 = p->iDb;
  87777. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  87778. p->zName, P4_STATIC);
  87779. }
  87780. }
  87781. #else
  87782. #define codeTableLocks(x)
  87783. #endif
  87784. /*
  87785. ** Return TRUE if the given yDbMask object is empty - if it contains no
  87786. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  87787. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  87788. */
  87789. #if SQLITE_MAX_ATTACHED>30
  87790. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  87791. int i;
  87792. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  87793. return 1;
  87794. }
  87795. #endif
  87796. /*
  87797. ** This routine is called after a single SQL statement has been
  87798. ** parsed and a VDBE program to execute that statement has been
  87799. ** prepared. This routine puts the finishing touches on the
  87800. ** VDBE program and resets the pParse structure for the next
  87801. ** parse.
  87802. **
  87803. ** Note that if an error occurred, it might be the case that
  87804. ** no VDBE code was generated.
  87805. */
  87806. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  87807. sqlite3 *db;
  87808. Vdbe *v;
  87809. assert( pParse->pToplevel==0 );
  87810. db = pParse->db;
  87811. if( pParse->nested ) return;
  87812. if( db->mallocFailed || pParse->nErr ){
  87813. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  87814. return;
  87815. }
  87816. /* Begin by generating some termination code at the end of the
  87817. ** vdbe program
  87818. */
  87819. v = sqlite3GetVdbe(pParse);
  87820. assert( !pParse->isMultiWrite
  87821. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  87822. if( v ){
  87823. while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
  87824. sqlite3VdbeAddOp0(v, OP_Halt);
  87825. #if SQLITE_USER_AUTHENTICATION
  87826. if( pParse->nTableLock>0 && db->init.busy==0 ){
  87827. sqlite3UserAuthInit(db);
  87828. if( db->auth.authLevel<UAUTH_User ){
  87829. pParse->rc = SQLITE_AUTH_USER;
  87830. sqlite3ErrorMsg(pParse, "user not authenticated");
  87831. return;
  87832. }
  87833. }
  87834. #endif
  87835. /* The cookie mask contains one bit for each database file open.
  87836. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  87837. ** set for each database that is used. Generate code to start a
  87838. ** transaction on each used database and to verify the schema cookie
  87839. ** on each used database.
  87840. */
  87841. if( db->mallocFailed==0
  87842. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  87843. ){
  87844. int iDb, i;
  87845. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  87846. sqlite3VdbeJumpHere(v, 0);
  87847. for(iDb=0; iDb<db->nDb; iDb++){
  87848. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  87849. sqlite3VdbeUsesBtree(v, iDb);
  87850. sqlite3VdbeAddOp4Int(v,
  87851. OP_Transaction, /* Opcode */
  87852. iDb, /* P1 */
  87853. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  87854. pParse->cookieValue[iDb], /* P3 */
  87855. db->aDb[iDb].pSchema->iGeneration /* P4 */
  87856. );
  87857. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  87858. VdbeComment((v,
  87859. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  87860. }
  87861. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87862. for(i=0; i<pParse->nVtabLock; i++){
  87863. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  87864. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  87865. }
  87866. pParse->nVtabLock = 0;
  87867. #endif
  87868. /* Once all the cookies have been verified and transactions opened,
  87869. ** obtain the required table-locks. This is a no-op unless the
  87870. ** shared-cache feature is enabled.
  87871. */
  87872. codeTableLocks(pParse);
  87873. /* Initialize any AUTOINCREMENT data structures required.
  87874. */
  87875. sqlite3AutoincrementBegin(pParse);
  87876. /* Code constant expressions that where factored out of inner loops */
  87877. if( pParse->pConstExpr ){
  87878. ExprList *pEL = pParse->pConstExpr;
  87879. pParse->okConstFactor = 0;
  87880. for(i=0; i<pEL->nExpr; i++){
  87881. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  87882. }
  87883. }
  87884. /* Finally, jump back to the beginning of the executable code. */
  87885. sqlite3VdbeGoto(v, 1);
  87886. }
  87887. }
  87888. /* Get the VDBE program ready for execution
  87889. */
  87890. if( v && pParse->nErr==0 && !db->mallocFailed ){
  87891. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  87892. /* A minimum of one cursor is required if autoincrement is used
  87893. * See ticket [a696379c1f08866] */
  87894. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  87895. sqlite3VdbeMakeReady(v, pParse);
  87896. pParse->rc = SQLITE_DONE;
  87897. pParse->colNamesSet = 0;
  87898. }else{
  87899. pParse->rc = SQLITE_ERROR;
  87900. }
  87901. pParse->nTab = 0;
  87902. pParse->nMem = 0;
  87903. pParse->nSet = 0;
  87904. pParse->nVar = 0;
  87905. DbMaskZero(pParse->cookieMask);
  87906. }
  87907. /*
  87908. ** Run the parser and code generator recursively in order to generate
  87909. ** code for the SQL statement given onto the end of the pParse context
  87910. ** currently under construction. When the parser is run recursively
  87911. ** this way, the final OP_Halt is not appended and other initialization
  87912. ** and finalization steps are omitted because those are handling by the
  87913. ** outermost parser.
  87914. **
  87915. ** Not everything is nestable. This facility is designed to permit
  87916. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  87917. ** care if you decide to try to use this routine for some other purposes.
  87918. */
  87919. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  87920. va_list ap;
  87921. char *zSql;
  87922. char *zErrMsg = 0;
  87923. sqlite3 *db = pParse->db;
  87924. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  87925. char saveBuf[SAVE_SZ];
  87926. if( pParse->nErr ) return;
  87927. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  87928. va_start(ap, zFormat);
  87929. zSql = sqlite3VMPrintf(db, zFormat, ap);
  87930. va_end(ap);
  87931. if( zSql==0 ){
  87932. return; /* A malloc must have failed */
  87933. }
  87934. pParse->nested++;
  87935. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  87936. memset(&pParse->nVar, 0, SAVE_SZ);
  87937. sqlite3RunParser(pParse, zSql, &zErrMsg);
  87938. sqlite3DbFree(db, zErrMsg);
  87939. sqlite3DbFree(db, zSql);
  87940. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  87941. pParse->nested--;
  87942. }
  87943. #if SQLITE_USER_AUTHENTICATION
  87944. /*
  87945. ** Return TRUE if zTable is the name of the system table that stores the
  87946. ** list of users and their access credentials.
  87947. */
  87948. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  87949. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  87950. }
  87951. #endif
  87952. /*
  87953. ** Locate the in-memory structure that describes a particular database
  87954. ** table given the name of that table and (optionally) the name of the
  87955. ** database containing the table. Return NULL if not found.
  87956. **
  87957. ** If zDatabase is 0, all databases are searched for the table and the
  87958. ** first matching table is returned. (No checking for duplicate table
  87959. ** names is done.) The search order is TEMP first, then MAIN, then any
  87960. ** auxiliary databases added using the ATTACH command.
  87961. **
  87962. ** See also sqlite3LocateTable().
  87963. */
  87964. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  87965. Table *p = 0;
  87966. int i;
  87967. /* All mutexes are required for schema access. Make sure we hold them. */
  87968. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  87969. #if SQLITE_USER_AUTHENTICATION
  87970. /* Only the admin user is allowed to know that the sqlite_user table
  87971. ** exists */
  87972. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  87973. return 0;
  87974. }
  87975. #endif
  87976. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  87977. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  87978. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  87979. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  87980. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  87981. if( p ) break;
  87982. }
  87983. return p;
  87984. }
  87985. /*
  87986. ** Locate the in-memory structure that describes a particular database
  87987. ** table given the name of that table and (optionally) the name of the
  87988. ** database containing the table. Return NULL if not found. Also leave an
  87989. ** error message in pParse->zErrMsg.
  87990. **
  87991. ** The difference between this routine and sqlite3FindTable() is that this
  87992. ** routine leaves an error message in pParse->zErrMsg where
  87993. ** sqlite3FindTable() does not.
  87994. */
  87995. SQLITE_PRIVATE Table *sqlite3LocateTable(
  87996. Parse *pParse, /* context in which to report errors */
  87997. int isView, /* True if looking for a VIEW rather than a TABLE */
  87998. const char *zName, /* Name of the table we are looking for */
  87999. const char *zDbase /* Name of the database. Might be NULL */
  88000. ){
  88001. Table *p;
  88002. /* Read the database schema. If an error occurs, leave an error message
  88003. ** and code in pParse and return NULL. */
  88004. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  88005. return 0;
  88006. }
  88007. p = sqlite3FindTable(pParse->db, zName, zDbase);
  88008. if( p==0 ){
  88009. const char *zMsg = isView ? "no such view" : "no such table";
  88010. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88011. if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
  88012. /* If zName is the not the name of a table in the schema created using
  88013. ** CREATE, then check to see if it is the name of an virtual table that
  88014. ** can be an eponymous virtual table. */
  88015. Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
  88016. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  88017. return pMod->pEpoTab;
  88018. }
  88019. }
  88020. #endif
  88021. if( zDbase ){
  88022. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  88023. }else{
  88024. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  88025. }
  88026. pParse->checkSchema = 1;
  88027. }
  88028. return p;
  88029. }
  88030. /*
  88031. ** Locate the table identified by *p.
  88032. **
  88033. ** This is a wrapper around sqlite3LocateTable(). The difference between
  88034. ** sqlite3LocateTable() and this function is that this function restricts
  88035. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  88036. ** non-NULL if it is part of a view or trigger program definition. See
  88037. ** sqlite3FixSrcList() for details.
  88038. */
  88039. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  88040. Parse *pParse,
  88041. int isView,
  88042. struct SrcList_item *p
  88043. ){
  88044. const char *zDb;
  88045. assert( p->pSchema==0 || p->zDatabase==0 );
  88046. if( p->pSchema ){
  88047. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  88048. zDb = pParse->db->aDb[iDb].zName;
  88049. }else{
  88050. zDb = p->zDatabase;
  88051. }
  88052. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  88053. }
  88054. /*
  88055. ** Locate the in-memory structure that describes
  88056. ** a particular index given the name of that index
  88057. ** and the name of the database that contains the index.
  88058. ** Return NULL if not found.
  88059. **
  88060. ** If zDatabase is 0, all databases are searched for the
  88061. ** table and the first matching index is returned. (No checking
  88062. ** for duplicate index names is done.) The search order is
  88063. ** TEMP first, then MAIN, then any auxiliary databases added
  88064. ** using the ATTACH command.
  88065. */
  88066. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  88067. Index *p = 0;
  88068. int i;
  88069. /* All mutexes are required for schema access. Make sure we hold them. */
  88070. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  88071. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  88072. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  88073. Schema *pSchema = db->aDb[j].pSchema;
  88074. assert( pSchema );
  88075. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  88076. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  88077. p = sqlite3HashFind(&pSchema->idxHash, zName);
  88078. if( p ) break;
  88079. }
  88080. return p;
  88081. }
  88082. /*
  88083. ** Reclaim the memory used by an index
  88084. */
  88085. static void freeIndex(sqlite3 *db, Index *p){
  88086. #ifndef SQLITE_OMIT_ANALYZE
  88087. sqlite3DeleteIndexSamples(db, p);
  88088. #endif
  88089. sqlite3ExprDelete(db, p->pPartIdxWhere);
  88090. sqlite3ExprListDelete(db, p->aColExpr);
  88091. sqlite3DbFree(db, p->zColAff);
  88092. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  88093. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  88094. sqlite3_free(p->aiRowEst);
  88095. #endif
  88096. sqlite3DbFree(db, p);
  88097. }
  88098. /*
  88099. ** For the index called zIdxName which is found in the database iDb,
  88100. ** unlike that index from its Table then remove the index from
  88101. ** the index hash table and free all memory structures associated
  88102. ** with the index.
  88103. */
  88104. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  88105. Index *pIndex;
  88106. Hash *pHash;
  88107. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88108. pHash = &db->aDb[iDb].pSchema->idxHash;
  88109. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  88110. if( ALWAYS(pIndex) ){
  88111. if( pIndex->pTable->pIndex==pIndex ){
  88112. pIndex->pTable->pIndex = pIndex->pNext;
  88113. }else{
  88114. Index *p;
  88115. /* Justification of ALWAYS(); The index must be on the list of
  88116. ** indices. */
  88117. p = pIndex->pTable->pIndex;
  88118. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  88119. if( ALWAYS(p && p->pNext==pIndex) ){
  88120. p->pNext = pIndex->pNext;
  88121. }
  88122. }
  88123. freeIndex(db, pIndex);
  88124. }
  88125. db->flags |= SQLITE_InternChanges;
  88126. }
  88127. /*
  88128. ** Look through the list of open database files in db->aDb[] and if
  88129. ** any have been closed, remove them from the list. Reallocate the
  88130. ** db->aDb[] structure to a smaller size, if possible.
  88131. **
  88132. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  88133. ** are never candidates for being collapsed.
  88134. */
  88135. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  88136. int i, j;
  88137. for(i=j=2; i<db->nDb; i++){
  88138. struct Db *pDb = &db->aDb[i];
  88139. if( pDb->pBt==0 ){
  88140. sqlite3DbFree(db, pDb->zName);
  88141. pDb->zName = 0;
  88142. continue;
  88143. }
  88144. if( j<i ){
  88145. db->aDb[j] = db->aDb[i];
  88146. }
  88147. j++;
  88148. }
  88149. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  88150. db->nDb = j;
  88151. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  88152. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  88153. sqlite3DbFree(db, db->aDb);
  88154. db->aDb = db->aDbStatic;
  88155. }
  88156. }
  88157. /*
  88158. ** Reset the schema for the database at index iDb. Also reset the
  88159. ** TEMP schema.
  88160. */
  88161. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  88162. Db *pDb;
  88163. assert( iDb<db->nDb );
  88164. /* Case 1: Reset the single schema identified by iDb */
  88165. pDb = &db->aDb[iDb];
  88166. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88167. assert( pDb->pSchema!=0 );
  88168. sqlite3SchemaClear(pDb->pSchema);
  88169. /* If any database other than TEMP is reset, then also reset TEMP
  88170. ** since TEMP might be holding triggers that reference tables in the
  88171. ** other database.
  88172. */
  88173. if( iDb!=1 ){
  88174. pDb = &db->aDb[1];
  88175. assert( pDb->pSchema!=0 );
  88176. sqlite3SchemaClear(pDb->pSchema);
  88177. }
  88178. return;
  88179. }
  88180. /*
  88181. ** Erase all schema information from all attached databases (including
  88182. ** "main" and "temp") for a single database connection.
  88183. */
  88184. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  88185. int i;
  88186. sqlite3BtreeEnterAll(db);
  88187. for(i=0; i<db->nDb; i++){
  88188. Db *pDb = &db->aDb[i];
  88189. if( pDb->pSchema ){
  88190. sqlite3SchemaClear(pDb->pSchema);
  88191. }
  88192. }
  88193. db->flags &= ~SQLITE_InternChanges;
  88194. sqlite3VtabUnlockList(db);
  88195. sqlite3BtreeLeaveAll(db);
  88196. sqlite3CollapseDatabaseArray(db);
  88197. }
  88198. /*
  88199. ** This routine is called when a commit occurs.
  88200. */
  88201. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  88202. db->flags &= ~SQLITE_InternChanges;
  88203. }
  88204. /*
  88205. ** Delete memory allocated for the column names of a table or view (the
  88206. ** Table.aCol[] array).
  88207. */
  88208. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  88209. int i;
  88210. Column *pCol;
  88211. assert( pTable!=0 );
  88212. if( (pCol = pTable->aCol)!=0 ){
  88213. for(i=0; i<pTable->nCol; i++, pCol++){
  88214. sqlite3DbFree(db, pCol->zName);
  88215. sqlite3ExprDelete(db, pCol->pDflt);
  88216. sqlite3DbFree(db, pCol->zDflt);
  88217. sqlite3DbFree(db, pCol->zType);
  88218. sqlite3DbFree(db, pCol->zColl);
  88219. }
  88220. sqlite3DbFree(db, pTable->aCol);
  88221. }
  88222. }
  88223. /*
  88224. ** Remove the memory data structures associated with the given
  88225. ** Table. No changes are made to disk by this routine.
  88226. **
  88227. ** This routine just deletes the data structure. It does not unlink
  88228. ** the table data structure from the hash table. But it does destroy
  88229. ** memory structures of the indices and foreign keys associated with
  88230. ** the table.
  88231. **
  88232. ** The db parameter is optional. It is needed if the Table object
  88233. ** contains lookaside memory. (Table objects in the schema do not use
  88234. ** lookaside memory, but some ephemeral Table objects do.) Or the
  88235. ** db parameter can be used with db->pnBytesFreed to measure the memory
  88236. ** used by the Table object.
  88237. */
  88238. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  88239. Index *pIndex, *pNext;
  88240. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  88241. assert( !pTable || pTable->nRef>0 );
  88242. /* Do not delete the table until the reference count reaches zero. */
  88243. if( !pTable ) return;
  88244. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  88245. /* Record the number of outstanding lookaside allocations in schema Tables
  88246. ** prior to doing any free() operations. Since schema Tables do not use
  88247. ** lookaside, this number should not change. */
  88248. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  88249. db->lookaside.nOut : 0 );
  88250. /* Delete all indices associated with this table. */
  88251. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  88252. pNext = pIndex->pNext;
  88253. assert( pIndex->pSchema==pTable->pSchema );
  88254. if( !db || db->pnBytesFreed==0 ){
  88255. char *zName = pIndex->zName;
  88256. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  88257. &pIndex->pSchema->idxHash, zName, 0
  88258. );
  88259. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  88260. assert( pOld==pIndex || pOld==0 );
  88261. }
  88262. freeIndex(db, pIndex);
  88263. }
  88264. /* Delete any foreign keys attached to this table. */
  88265. sqlite3FkDelete(db, pTable);
  88266. /* Delete the Table structure itself.
  88267. */
  88268. sqlite3DeleteColumnNames(db, pTable);
  88269. sqlite3DbFree(db, pTable->zName);
  88270. sqlite3DbFree(db, pTable->zColAff);
  88271. sqlite3SelectDelete(db, pTable->pSelect);
  88272. sqlite3ExprListDelete(db, pTable->pCheck);
  88273. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88274. sqlite3VtabClear(db, pTable);
  88275. #endif
  88276. sqlite3DbFree(db, pTable);
  88277. /* Verify that no lookaside memory was used by schema tables */
  88278. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  88279. }
  88280. /*
  88281. ** Unlink the given table from the hash tables and the delete the
  88282. ** table structure with all its indices and foreign keys.
  88283. */
  88284. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  88285. Table *p;
  88286. Db *pDb;
  88287. assert( db!=0 );
  88288. assert( iDb>=0 && iDb<db->nDb );
  88289. assert( zTabName );
  88290. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88291. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  88292. pDb = &db->aDb[iDb];
  88293. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  88294. sqlite3DeleteTable(db, p);
  88295. db->flags |= SQLITE_InternChanges;
  88296. }
  88297. /*
  88298. ** Given a token, return a string that consists of the text of that
  88299. ** token. Space to hold the returned string
  88300. ** is obtained from sqliteMalloc() and must be freed by the calling
  88301. ** function.
  88302. **
  88303. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  88304. ** surround the body of the token are removed.
  88305. **
  88306. ** Tokens are often just pointers into the original SQL text and so
  88307. ** are not \000 terminated and are not persistent. The returned string
  88308. ** is \000 terminated and is persistent.
  88309. */
  88310. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  88311. char *zName;
  88312. if( pName ){
  88313. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  88314. sqlite3Dequote(zName);
  88315. }else{
  88316. zName = 0;
  88317. }
  88318. return zName;
  88319. }
  88320. /*
  88321. ** Open the sqlite_master table stored in database number iDb for
  88322. ** writing. The table is opened using cursor 0.
  88323. */
  88324. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  88325. Vdbe *v = sqlite3GetVdbe(p);
  88326. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  88327. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  88328. if( p->nTab==0 ){
  88329. p->nTab = 1;
  88330. }
  88331. }
  88332. /*
  88333. ** Parameter zName points to a nul-terminated buffer containing the name
  88334. ** of a database ("main", "temp" or the name of an attached db). This
  88335. ** function returns the index of the named database in db->aDb[], or
  88336. ** -1 if the named db cannot be found.
  88337. */
  88338. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  88339. int i = -1; /* Database number */
  88340. if( zName ){
  88341. Db *pDb;
  88342. int n = sqlite3Strlen30(zName);
  88343. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  88344. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  88345. 0==sqlite3StrICmp(pDb->zName, zName) ){
  88346. break;
  88347. }
  88348. }
  88349. }
  88350. return i;
  88351. }
  88352. /*
  88353. ** The token *pName contains the name of a database (either "main" or
  88354. ** "temp" or the name of an attached db). This routine returns the
  88355. ** index of the named database in db->aDb[], or -1 if the named db
  88356. ** does not exist.
  88357. */
  88358. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  88359. int i; /* Database number */
  88360. char *zName; /* Name we are searching for */
  88361. zName = sqlite3NameFromToken(db, pName);
  88362. i = sqlite3FindDbName(db, zName);
  88363. sqlite3DbFree(db, zName);
  88364. return i;
  88365. }
  88366. /* The table or view or trigger name is passed to this routine via tokens
  88367. ** pName1 and pName2. If the table name was fully qualified, for example:
  88368. **
  88369. ** CREATE TABLE xxx.yyy (...);
  88370. **
  88371. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  88372. ** the table name is not fully qualified, i.e.:
  88373. **
  88374. ** CREATE TABLE yyy(...);
  88375. **
  88376. ** Then pName1 is set to "yyy" and pName2 is "".
  88377. **
  88378. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  88379. ** pName2) that stores the unqualified table name. The index of the
  88380. ** database "xxx" is returned.
  88381. */
  88382. SQLITE_PRIVATE int sqlite3TwoPartName(
  88383. Parse *pParse, /* Parsing and code generating context */
  88384. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  88385. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  88386. Token **pUnqual /* Write the unqualified object name here */
  88387. ){
  88388. int iDb; /* Database holding the object */
  88389. sqlite3 *db = pParse->db;
  88390. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  88391. if( db->init.busy ) {
  88392. sqlite3ErrorMsg(pParse, "corrupt database");
  88393. return -1;
  88394. }
  88395. *pUnqual = pName2;
  88396. iDb = sqlite3FindDb(db, pName1);
  88397. if( iDb<0 ){
  88398. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  88399. return -1;
  88400. }
  88401. }else{
  88402. assert( db->init.iDb==0 || db->init.busy );
  88403. iDb = db->init.iDb;
  88404. *pUnqual = pName1;
  88405. }
  88406. return iDb;
  88407. }
  88408. /*
  88409. ** This routine is used to check if the UTF-8 string zName is a legal
  88410. ** unqualified name for a new schema object (table, index, view or
  88411. ** trigger). All names are legal except those that begin with the string
  88412. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  88413. ** is reserved for internal use.
  88414. */
  88415. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  88416. if( !pParse->db->init.busy && pParse->nested==0
  88417. && (pParse->db->flags & SQLITE_WriteSchema)==0
  88418. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  88419. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  88420. return SQLITE_ERROR;
  88421. }
  88422. return SQLITE_OK;
  88423. }
  88424. /*
  88425. ** Return the PRIMARY KEY index of a table
  88426. */
  88427. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  88428. Index *p;
  88429. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  88430. return p;
  88431. }
  88432. /*
  88433. ** Return the column of index pIdx that corresponds to table
  88434. ** column iCol. Return -1 if not found.
  88435. */
  88436. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  88437. int i;
  88438. for(i=0; i<pIdx->nColumn; i++){
  88439. if( iCol==pIdx->aiColumn[i] ) return i;
  88440. }
  88441. return -1;
  88442. }
  88443. /*
  88444. ** Begin constructing a new table representation in memory. This is
  88445. ** the first of several action routines that get called in response
  88446. ** to a CREATE TABLE statement. In particular, this routine is called
  88447. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  88448. ** flag is true if the table should be stored in the auxiliary database
  88449. ** file instead of in the main database file. This is normally the case
  88450. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  88451. ** CREATE and TABLE.
  88452. **
  88453. ** The new table record is initialized and put in pParse->pNewTable.
  88454. ** As more of the CREATE TABLE statement is parsed, additional action
  88455. ** routines will be called to add more information to this record.
  88456. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  88457. ** is called to complete the construction of the new table record.
  88458. */
  88459. SQLITE_PRIVATE void sqlite3StartTable(
  88460. Parse *pParse, /* Parser context */
  88461. Token *pName1, /* First part of the name of the table or view */
  88462. Token *pName2, /* Second part of the name of the table or view */
  88463. int isTemp, /* True if this is a TEMP table */
  88464. int isView, /* True if this is a VIEW */
  88465. int isVirtual, /* True if this is a VIRTUAL table */
  88466. int noErr /* Do nothing if table already exists */
  88467. ){
  88468. Table *pTable;
  88469. char *zName = 0; /* The name of the new table */
  88470. sqlite3 *db = pParse->db;
  88471. Vdbe *v;
  88472. int iDb; /* Database number to create the table in */
  88473. Token *pName; /* Unqualified name of the table to create */
  88474. /* The table or view name to create is passed to this routine via tokens
  88475. ** pName1 and pName2. If the table name was fully qualified, for example:
  88476. **
  88477. ** CREATE TABLE xxx.yyy (...);
  88478. **
  88479. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  88480. ** the table name is not fully qualified, i.e.:
  88481. **
  88482. ** CREATE TABLE yyy(...);
  88483. **
  88484. ** Then pName1 is set to "yyy" and pName2 is "".
  88485. **
  88486. ** The call below sets the pName pointer to point at the token (pName1 or
  88487. ** pName2) that stores the unqualified table name. The variable iDb is
  88488. ** set to the index of the database that the table or view is to be
  88489. ** created in.
  88490. */
  88491. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  88492. if( iDb<0 ) return;
  88493. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  88494. /* If creating a temp table, the name may not be qualified. Unless
  88495. ** the database name is "temp" anyway. */
  88496. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  88497. return;
  88498. }
  88499. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  88500. pParse->sNameToken = *pName;
  88501. zName = sqlite3NameFromToken(db, pName);
  88502. if( zName==0 ) return;
  88503. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  88504. goto begin_table_error;
  88505. }
  88506. if( db->init.iDb==1 ) isTemp = 1;
  88507. #ifndef SQLITE_OMIT_AUTHORIZATION
  88508. assert( (isTemp & 1)==isTemp );
  88509. {
  88510. int code;
  88511. char *zDb = db->aDb[iDb].zName;
  88512. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  88513. goto begin_table_error;
  88514. }
  88515. if( isView ){
  88516. if( !OMIT_TEMPDB && isTemp ){
  88517. code = SQLITE_CREATE_TEMP_VIEW;
  88518. }else{
  88519. code = SQLITE_CREATE_VIEW;
  88520. }
  88521. }else{
  88522. if( !OMIT_TEMPDB && isTemp ){
  88523. code = SQLITE_CREATE_TEMP_TABLE;
  88524. }else{
  88525. code = SQLITE_CREATE_TABLE;
  88526. }
  88527. }
  88528. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  88529. goto begin_table_error;
  88530. }
  88531. }
  88532. #endif
  88533. /* Make sure the new table name does not collide with an existing
  88534. ** index or table name in the same database. Issue an error message if
  88535. ** it does. The exception is if the statement being parsed was passed
  88536. ** to an sqlite3_declare_vtab() call. In that case only the column names
  88537. ** and types will be used, so there is no need to test for namespace
  88538. ** collisions.
  88539. */
  88540. if( !IN_DECLARE_VTAB ){
  88541. char *zDb = db->aDb[iDb].zName;
  88542. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  88543. goto begin_table_error;
  88544. }
  88545. pTable = sqlite3FindTable(db, zName, zDb);
  88546. if( pTable ){
  88547. if( !noErr ){
  88548. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  88549. }else{
  88550. assert( !db->init.busy || CORRUPT_DB );
  88551. sqlite3CodeVerifySchema(pParse, iDb);
  88552. }
  88553. goto begin_table_error;
  88554. }
  88555. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  88556. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  88557. goto begin_table_error;
  88558. }
  88559. }
  88560. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  88561. if( pTable==0 ){
  88562. db->mallocFailed = 1;
  88563. pParse->rc = SQLITE_NOMEM;
  88564. pParse->nErr++;
  88565. goto begin_table_error;
  88566. }
  88567. pTable->zName = zName;
  88568. pTable->iPKey = -1;
  88569. pTable->pSchema = db->aDb[iDb].pSchema;
  88570. pTable->nRef = 1;
  88571. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  88572. assert( pParse->pNewTable==0 );
  88573. pParse->pNewTable = pTable;
  88574. /* If this is the magic sqlite_sequence table used by autoincrement,
  88575. ** then record a pointer to this table in the main database structure
  88576. ** so that INSERT can find the table easily.
  88577. */
  88578. #ifndef SQLITE_OMIT_AUTOINCREMENT
  88579. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  88580. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88581. pTable->pSchema->pSeqTab = pTable;
  88582. }
  88583. #endif
  88584. /* Begin generating the code that will insert the table record into
  88585. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  88586. ** and allocate the record number for the table entry now. Before any
  88587. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  88588. ** indices to be created and the table record must come before the
  88589. ** indices. Hence, the record number for the table must be allocated
  88590. ** now.
  88591. */
  88592. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  88593. int addr1;
  88594. int fileFormat;
  88595. int reg1, reg2, reg3;
  88596. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  88597. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  88598. sqlite3BeginWriteOperation(pParse, 1, iDb);
  88599. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88600. if( isVirtual ){
  88601. sqlite3VdbeAddOp0(v, OP_VBegin);
  88602. }
  88603. #endif
  88604. /* If the file format and encoding in the database have not been set,
  88605. ** set them now.
  88606. */
  88607. reg1 = pParse->regRowid = ++pParse->nMem;
  88608. reg2 = pParse->regRoot = ++pParse->nMem;
  88609. reg3 = ++pParse->nMem;
  88610. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  88611. sqlite3VdbeUsesBtree(v, iDb);
  88612. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  88613. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  88614. 1 : SQLITE_MAX_FILE_FORMAT;
  88615. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  88616. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  88617. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  88618. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  88619. sqlite3VdbeJumpHere(v, addr1);
  88620. /* This just creates a place-holder record in the sqlite_master table.
  88621. ** The record created does not contain anything yet. It will be replaced
  88622. ** by the real entry in code generated at sqlite3EndTable().
  88623. **
  88624. ** The rowid for the new entry is left in register pParse->regRowid.
  88625. ** The root page number of the new table is left in reg pParse->regRoot.
  88626. ** The rowid and root page number values are needed by the code that
  88627. ** sqlite3EndTable will generate.
  88628. */
  88629. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  88630. if( isView || isVirtual ){
  88631. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  88632. }else
  88633. #endif
  88634. {
  88635. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  88636. }
  88637. sqlite3OpenMasterTable(pParse, iDb);
  88638. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  88639. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  88640. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  88641. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  88642. sqlite3VdbeAddOp0(v, OP_Close);
  88643. }
  88644. /* Normal (non-error) return. */
  88645. return;
  88646. /* If an error occurs, we jump here */
  88647. begin_table_error:
  88648. sqlite3DbFree(db, zName);
  88649. return;
  88650. }
  88651. /* Set properties of a table column based on the (magical)
  88652. ** name of the column.
  88653. */
  88654. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  88655. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  88656. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  88657. pCol->colFlags |= COLFLAG_HIDDEN;
  88658. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  88659. pTab->tabFlags |= TF_OOOHidden;
  88660. }
  88661. }
  88662. #endif
  88663. /*
  88664. ** Add a new column to the table currently being constructed.
  88665. **
  88666. ** The parser calls this routine once for each column declaration
  88667. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  88668. ** first to get things going. Then this routine is called for each
  88669. ** column.
  88670. */
  88671. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  88672. Table *p;
  88673. int i;
  88674. char *z;
  88675. Column *pCol;
  88676. sqlite3 *db = pParse->db;
  88677. if( (p = pParse->pNewTable)==0 ) return;
  88678. #if SQLITE_MAX_COLUMN
  88679. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  88680. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  88681. return;
  88682. }
  88683. #endif
  88684. z = sqlite3NameFromToken(db, pName);
  88685. if( z==0 ) return;
  88686. for(i=0; i<p->nCol; i++){
  88687. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  88688. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  88689. sqlite3DbFree(db, z);
  88690. return;
  88691. }
  88692. }
  88693. if( (p->nCol & 0x7)==0 ){
  88694. Column *aNew;
  88695. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  88696. if( aNew==0 ){
  88697. sqlite3DbFree(db, z);
  88698. return;
  88699. }
  88700. p->aCol = aNew;
  88701. }
  88702. pCol = &p->aCol[p->nCol];
  88703. memset(pCol, 0, sizeof(p->aCol[0]));
  88704. pCol->zName = z;
  88705. sqlite3ColumnPropertiesFromName(p, pCol);
  88706. /* If there is no type specified, columns have the default affinity
  88707. ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
  88708. ** be called next to set pCol->affinity correctly.
  88709. */
  88710. pCol->affinity = SQLITE_AFF_BLOB;
  88711. pCol->szEst = 1;
  88712. p->nCol++;
  88713. }
  88714. /*
  88715. ** This routine is called by the parser while in the middle of
  88716. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  88717. ** been seen on a column. This routine sets the notNull flag on
  88718. ** the column currently under construction.
  88719. */
  88720. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  88721. Table *p;
  88722. p = pParse->pNewTable;
  88723. if( p==0 || NEVER(p->nCol<1) ) return;
  88724. p->aCol[p->nCol-1].notNull = (u8)onError;
  88725. }
  88726. /*
  88727. ** Scan the column type name zType (length nType) and return the
  88728. ** associated affinity type.
  88729. **
  88730. ** This routine does a case-independent search of zType for the
  88731. ** substrings in the following table. If one of the substrings is
  88732. ** found, the corresponding affinity is returned. If zType contains
  88733. ** more than one of the substrings, entries toward the top of
  88734. ** the table take priority. For example, if zType is 'BLOBINT',
  88735. ** SQLITE_AFF_INTEGER is returned.
  88736. **
  88737. ** Substring | Affinity
  88738. ** --------------------------------
  88739. ** 'INT' | SQLITE_AFF_INTEGER
  88740. ** 'CHAR' | SQLITE_AFF_TEXT
  88741. ** 'CLOB' | SQLITE_AFF_TEXT
  88742. ** 'TEXT' | SQLITE_AFF_TEXT
  88743. ** 'BLOB' | SQLITE_AFF_BLOB
  88744. ** 'REAL' | SQLITE_AFF_REAL
  88745. ** 'FLOA' | SQLITE_AFF_REAL
  88746. ** 'DOUB' | SQLITE_AFF_REAL
  88747. **
  88748. ** If none of the substrings in the above table are found,
  88749. ** SQLITE_AFF_NUMERIC is returned.
  88750. */
  88751. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  88752. u32 h = 0;
  88753. char aff = SQLITE_AFF_NUMERIC;
  88754. const char *zChar = 0;
  88755. if( zIn==0 ) return aff;
  88756. while( zIn[0] ){
  88757. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  88758. zIn++;
  88759. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  88760. aff = SQLITE_AFF_TEXT;
  88761. zChar = zIn;
  88762. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  88763. aff = SQLITE_AFF_TEXT;
  88764. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  88765. aff = SQLITE_AFF_TEXT;
  88766. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  88767. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  88768. aff = SQLITE_AFF_BLOB;
  88769. if( zIn[0]=='(' ) zChar = zIn;
  88770. #ifndef SQLITE_OMIT_FLOATING_POINT
  88771. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  88772. && aff==SQLITE_AFF_NUMERIC ){
  88773. aff = SQLITE_AFF_REAL;
  88774. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  88775. && aff==SQLITE_AFF_NUMERIC ){
  88776. aff = SQLITE_AFF_REAL;
  88777. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  88778. && aff==SQLITE_AFF_NUMERIC ){
  88779. aff = SQLITE_AFF_REAL;
  88780. #endif
  88781. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  88782. aff = SQLITE_AFF_INTEGER;
  88783. break;
  88784. }
  88785. }
  88786. /* If pszEst is not NULL, store an estimate of the field size. The
  88787. ** estimate is scaled so that the size of an integer is 1. */
  88788. if( pszEst ){
  88789. *pszEst = 1; /* default size is approx 4 bytes */
  88790. if( aff<SQLITE_AFF_NUMERIC ){
  88791. if( zChar ){
  88792. while( zChar[0] ){
  88793. if( sqlite3Isdigit(zChar[0]) ){
  88794. int v = 0;
  88795. sqlite3GetInt32(zChar, &v);
  88796. v = v/4 + 1;
  88797. if( v>255 ) v = 255;
  88798. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  88799. break;
  88800. }
  88801. zChar++;
  88802. }
  88803. }else{
  88804. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  88805. }
  88806. }
  88807. }
  88808. return aff;
  88809. }
  88810. /*
  88811. ** This routine is called by the parser while in the middle of
  88812. ** parsing a CREATE TABLE statement. The pFirst token is the first
  88813. ** token in the sequence of tokens that describe the type of the
  88814. ** column currently under construction. pLast is the last token
  88815. ** in the sequence. Use this information to construct a string
  88816. ** that contains the typename of the column and store that string
  88817. ** in zType.
  88818. */
  88819. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  88820. Table *p;
  88821. Column *pCol;
  88822. p = pParse->pNewTable;
  88823. if( p==0 || NEVER(p->nCol<1) ) return;
  88824. pCol = &p->aCol[p->nCol-1];
  88825. assert( pCol->zType==0 || CORRUPT_DB );
  88826. sqlite3DbFree(pParse->db, pCol->zType);
  88827. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  88828. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  88829. }
  88830. /*
  88831. ** The expression is the default value for the most recently added column
  88832. ** of the table currently under construction.
  88833. **
  88834. ** Default value expressions must be constant. Raise an exception if this
  88835. ** is not the case.
  88836. **
  88837. ** This routine is called by the parser while in the middle of
  88838. ** parsing a CREATE TABLE statement.
  88839. */
  88840. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  88841. Table *p;
  88842. Column *pCol;
  88843. sqlite3 *db = pParse->db;
  88844. p = pParse->pNewTable;
  88845. if( p!=0 ){
  88846. pCol = &(p->aCol[p->nCol-1]);
  88847. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  88848. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  88849. pCol->zName);
  88850. }else{
  88851. /* A copy of pExpr is used instead of the original, as pExpr contains
  88852. ** tokens that point to volatile memory. The 'span' of the expression
  88853. ** is required by pragma table_info.
  88854. */
  88855. sqlite3ExprDelete(db, pCol->pDflt);
  88856. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  88857. sqlite3DbFree(db, pCol->zDflt);
  88858. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  88859. (int)(pSpan->zEnd - pSpan->zStart));
  88860. }
  88861. }
  88862. sqlite3ExprDelete(db, pSpan->pExpr);
  88863. }
  88864. /*
  88865. ** Backwards Compatibility Hack:
  88866. **
  88867. ** Historical versions of SQLite accepted strings as column names in
  88868. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  88869. **
  88870. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  88871. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  88872. **
  88873. ** This is goofy. But to preserve backwards compatibility we continue to
  88874. ** accept it. This routine does the necessary conversion. It converts
  88875. ** the expression given in its argument from a TK_STRING into a TK_ID
  88876. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  88877. ** If the epxression is anything other than TK_STRING, the expression is
  88878. ** unchanged.
  88879. */
  88880. static void sqlite3StringToId(Expr *p){
  88881. if( p->op==TK_STRING ){
  88882. p->op = TK_ID;
  88883. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  88884. p->pLeft->op = TK_ID;
  88885. }
  88886. }
  88887. /*
  88888. ** Designate the PRIMARY KEY for the table. pList is a list of names
  88889. ** of columns that form the primary key. If pList is NULL, then the
  88890. ** most recently added column of the table is the primary key.
  88891. **
  88892. ** A table can have at most one primary key. If the table already has
  88893. ** a primary key (and this is the second primary key) then create an
  88894. ** error.
  88895. **
  88896. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  88897. ** then we will try to use that column as the rowid. Set the Table.iPKey
  88898. ** field of the table under construction to be the index of the
  88899. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  88900. ** no INTEGER PRIMARY KEY.
  88901. **
  88902. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  88903. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  88904. */
  88905. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  88906. Parse *pParse, /* Parsing context */
  88907. ExprList *pList, /* List of field names to be indexed */
  88908. int onError, /* What to do with a uniqueness conflict */
  88909. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  88910. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  88911. ){
  88912. Table *pTab = pParse->pNewTable;
  88913. char *zType = 0;
  88914. int iCol = -1, i;
  88915. int nTerm;
  88916. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  88917. if( pTab->tabFlags & TF_HasPrimaryKey ){
  88918. sqlite3ErrorMsg(pParse,
  88919. "table \"%s\" has more than one primary key", pTab->zName);
  88920. goto primary_key_exit;
  88921. }
  88922. pTab->tabFlags |= TF_HasPrimaryKey;
  88923. if( pList==0 ){
  88924. iCol = pTab->nCol - 1;
  88925. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  88926. zType = pTab->aCol[iCol].zType;
  88927. nTerm = 1;
  88928. }else{
  88929. nTerm = pList->nExpr;
  88930. for(i=0; i<nTerm; i++){
  88931. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  88932. assert( pCExpr!=0 );
  88933. sqlite3StringToId(pCExpr);
  88934. if( pCExpr->op==TK_ID ){
  88935. const char *zCName = pCExpr->u.zToken;
  88936. for(iCol=0; iCol<pTab->nCol; iCol++){
  88937. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  88938. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  88939. zType = pTab->aCol[iCol].zType;
  88940. break;
  88941. }
  88942. }
  88943. }
  88944. }
  88945. }
  88946. if( nTerm==1
  88947. && zType && sqlite3StrICmp(zType, "INTEGER")==0
  88948. && sortOrder!=SQLITE_SO_DESC
  88949. ){
  88950. pTab->iPKey = iCol;
  88951. pTab->keyConf = (u8)onError;
  88952. assert( autoInc==0 || autoInc==1 );
  88953. pTab->tabFlags |= autoInc*TF_Autoincrement;
  88954. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  88955. }else if( autoInc ){
  88956. #ifndef SQLITE_OMIT_AUTOINCREMENT
  88957. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  88958. "INTEGER PRIMARY KEY");
  88959. #endif
  88960. }else{
  88961. Index *p;
  88962. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  88963. 0, sortOrder, 0);
  88964. if( p ){
  88965. p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  88966. }
  88967. pList = 0;
  88968. }
  88969. primary_key_exit:
  88970. sqlite3ExprListDelete(pParse->db, pList);
  88971. return;
  88972. }
  88973. /*
  88974. ** Add a new CHECK constraint to the table currently under construction.
  88975. */
  88976. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  88977. Parse *pParse, /* Parsing context */
  88978. Expr *pCheckExpr /* The check expression */
  88979. ){
  88980. #ifndef SQLITE_OMIT_CHECK
  88981. Table *pTab = pParse->pNewTable;
  88982. sqlite3 *db = pParse->db;
  88983. if( pTab && !IN_DECLARE_VTAB
  88984. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  88985. ){
  88986. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  88987. if( pParse->constraintName.n ){
  88988. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  88989. }
  88990. }else
  88991. #endif
  88992. {
  88993. sqlite3ExprDelete(pParse->db, pCheckExpr);
  88994. }
  88995. }
  88996. /*
  88997. ** Set the collation function of the most recently parsed table column
  88998. ** to the CollSeq given.
  88999. */
  89000. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  89001. Table *p;
  89002. int i;
  89003. char *zColl; /* Dequoted name of collation sequence */
  89004. sqlite3 *db;
  89005. if( (p = pParse->pNewTable)==0 ) return;
  89006. i = p->nCol-1;
  89007. db = pParse->db;
  89008. zColl = sqlite3NameFromToken(db, pToken);
  89009. if( !zColl ) return;
  89010. if( sqlite3LocateCollSeq(pParse, zColl) ){
  89011. Index *pIdx;
  89012. sqlite3DbFree(db, p->aCol[i].zColl);
  89013. p->aCol[i].zColl = zColl;
  89014. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  89015. ** then an index may have been created on this column before the
  89016. ** collation type was added. Correct this if it is the case.
  89017. */
  89018. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  89019. assert( pIdx->nKeyCol==1 );
  89020. if( pIdx->aiColumn[0]==i ){
  89021. pIdx->azColl[0] = p->aCol[i].zColl;
  89022. }
  89023. }
  89024. }else{
  89025. sqlite3DbFree(db, zColl);
  89026. }
  89027. }
  89028. /*
  89029. ** This function returns the collation sequence for database native text
  89030. ** encoding identified by the string zName, length nName.
  89031. **
  89032. ** If the requested collation sequence is not available, or not available
  89033. ** in the database native encoding, the collation factory is invoked to
  89034. ** request it. If the collation factory does not supply such a sequence,
  89035. ** and the sequence is available in another text encoding, then that is
  89036. ** returned instead.
  89037. **
  89038. ** If no versions of the requested collations sequence are available, or
  89039. ** another error occurs, NULL is returned and an error message written into
  89040. ** pParse.
  89041. **
  89042. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  89043. ** invokes the collation factory if the named collation cannot be found
  89044. ** and generates an error message.
  89045. **
  89046. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  89047. */
  89048. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  89049. sqlite3 *db = pParse->db;
  89050. u8 enc = ENC(db);
  89051. u8 initbusy = db->init.busy;
  89052. CollSeq *pColl;
  89053. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  89054. if( !initbusy && (!pColl || !pColl->xCmp) ){
  89055. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  89056. }
  89057. return pColl;
  89058. }
  89059. /*
  89060. ** Generate code that will increment the schema cookie.
  89061. **
  89062. ** The schema cookie is used to determine when the schema for the
  89063. ** database changes. After each schema change, the cookie value
  89064. ** changes. When a process first reads the schema it records the
  89065. ** cookie. Thereafter, whenever it goes to access the database,
  89066. ** it checks the cookie to make sure the schema has not changed
  89067. ** since it was last read.
  89068. **
  89069. ** This plan is not completely bullet-proof. It is possible for
  89070. ** the schema to change multiple times and for the cookie to be
  89071. ** set back to prior value. But schema changes are infrequent
  89072. ** and the probability of hitting the same cookie value is only
  89073. ** 1 chance in 2^32. So we're safe enough.
  89074. */
  89075. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  89076. int r1 = sqlite3GetTempReg(pParse);
  89077. sqlite3 *db = pParse->db;
  89078. Vdbe *v = pParse->pVdbe;
  89079. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89080. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  89081. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  89082. sqlite3ReleaseTempReg(pParse, r1);
  89083. }
  89084. /*
  89085. ** Measure the number of characters needed to output the given
  89086. ** identifier. The number returned includes any quotes used
  89087. ** but does not include the null terminator.
  89088. **
  89089. ** The estimate is conservative. It might be larger that what is
  89090. ** really needed.
  89091. */
  89092. static int identLength(const char *z){
  89093. int n;
  89094. for(n=0; *z; n++, z++){
  89095. if( *z=='"' ){ n++; }
  89096. }
  89097. return n + 2;
  89098. }
  89099. /*
  89100. ** The first parameter is a pointer to an output buffer. The second
  89101. ** parameter is a pointer to an integer that contains the offset at
  89102. ** which to write into the output buffer. This function copies the
  89103. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  89104. ** to the specified offset in the buffer and updates *pIdx to refer
  89105. ** to the first byte after the last byte written before returning.
  89106. **
  89107. ** If the string zSignedIdent consists entirely of alpha-numeric
  89108. ** characters, does not begin with a digit and is not an SQL keyword,
  89109. ** then it is copied to the output buffer exactly as it is. Otherwise,
  89110. ** it is quoted using double-quotes.
  89111. */
  89112. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  89113. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  89114. int i, j, needQuote;
  89115. i = *pIdx;
  89116. for(j=0; zIdent[j]; j++){
  89117. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  89118. }
  89119. needQuote = sqlite3Isdigit(zIdent[0])
  89120. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  89121. || zIdent[j]!=0
  89122. || j==0;
  89123. if( needQuote ) z[i++] = '"';
  89124. for(j=0; zIdent[j]; j++){
  89125. z[i++] = zIdent[j];
  89126. if( zIdent[j]=='"' ) z[i++] = '"';
  89127. }
  89128. if( needQuote ) z[i++] = '"';
  89129. z[i] = 0;
  89130. *pIdx = i;
  89131. }
  89132. /*
  89133. ** Generate a CREATE TABLE statement appropriate for the given
  89134. ** table. Memory to hold the text of the statement is obtained
  89135. ** from sqliteMalloc() and must be freed by the calling function.
  89136. */
  89137. static char *createTableStmt(sqlite3 *db, Table *p){
  89138. int i, k, n;
  89139. char *zStmt;
  89140. char *zSep, *zSep2, *zEnd;
  89141. Column *pCol;
  89142. n = 0;
  89143. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  89144. n += identLength(pCol->zName) + 5;
  89145. }
  89146. n += identLength(p->zName);
  89147. if( n<50 ){
  89148. zSep = "";
  89149. zSep2 = ",";
  89150. zEnd = ")";
  89151. }else{
  89152. zSep = "\n ";
  89153. zSep2 = ",\n ";
  89154. zEnd = "\n)";
  89155. }
  89156. n += 35 + 6*p->nCol;
  89157. zStmt = sqlite3DbMallocRaw(0, n);
  89158. if( zStmt==0 ){
  89159. db->mallocFailed = 1;
  89160. return 0;
  89161. }
  89162. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  89163. k = sqlite3Strlen30(zStmt);
  89164. identPut(zStmt, &k, p->zName);
  89165. zStmt[k++] = '(';
  89166. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  89167. static const char * const azType[] = {
  89168. /* SQLITE_AFF_BLOB */ "",
  89169. /* SQLITE_AFF_TEXT */ " TEXT",
  89170. /* SQLITE_AFF_NUMERIC */ " NUM",
  89171. /* SQLITE_AFF_INTEGER */ " INT",
  89172. /* SQLITE_AFF_REAL */ " REAL"
  89173. };
  89174. int len;
  89175. const char *zType;
  89176. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  89177. k += sqlite3Strlen30(&zStmt[k]);
  89178. zSep = zSep2;
  89179. identPut(zStmt, &k, pCol->zName);
  89180. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  89181. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  89182. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  89183. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  89184. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  89185. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  89186. testcase( pCol->affinity==SQLITE_AFF_REAL );
  89187. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  89188. len = sqlite3Strlen30(zType);
  89189. assert( pCol->affinity==SQLITE_AFF_BLOB
  89190. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  89191. memcpy(&zStmt[k], zType, len);
  89192. k += len;
  89193. assert( k<=n );
  89194. }
  89195. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  89196. return zStmt;
  89197. }
  89198. /*
  89199. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  89200. ** on success and SQLITE_NOMEM on an OOM error.
  89201. */
  89202. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  89203. char *zExtra;
  89204. int nByte;
  89205. if( pIdx->nColumn>=N ) return SQLITE_OK;
  89206. assert( pIdx->isResized==0 );
  89207. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  89208. zExtra = sqlite3DbMallocZero(db, nByte);
  89209. if( zExtra==0 ) return SQLITE_NOMEM;
  89210. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  89211. pIdx->azColl = (const char**)zExtra;
  89212. zExtra += sizeof(char*)*N;
  89213. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  89214. pIdx->aiColumn = (i16*)zExtra;
  89215. zExtra += sizeof(i16)*N;
  89216. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  89217. pIdx->aSortOrder = (u8*)zExtra;
  89218. pIdx->nColumn = N;
  89219. pIdx->isResized = 1;
  89220. return SQLITE_OK;
  89221. }
  89222. /*
  89223. ** Estimate the total row width for a table.
  89224. */
  89225. static void estimateTableWidth(Table *pTab){
  89226. unsigned wTable = 0;
  89227. const Column *pTabCol;
  89228. int i;
  89229. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  89230. wTable += pTabCol->szEst;
  89231. }
  89232. if( pTab->iPKey<0 ) wTable++;
  89233. pTab->szTabRow = sqlite3LogEst(wTable*4);
  89234. }
  89235. /*
  89236. ** Estimate the average size of a row for an index.
  89237. */
  89238. static void estimateIndexWidth(Index *pIdx){
  89239. unsigned wIndex = 0;
  89240. int i;
  89241. const Column *aCol = pIdx->pTable->aCol;
  89242. for(i=0; i<pIdx->nColumn; i++){
  89243. i16 x = pIdx->aiColumn[i];
  89244. assert( x<pIdx->pTable->nCol );
  89245. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  89246. }
  89247. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  89248. }
  89249. /* Return true if value x is found any of the first nCol entries of aiCol[]
  89250. */
  89251. static int hasColumn(const i16 *aiCol, int nCol, int x){
  89252. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  89253. return 0;
  89254. }
  89255. /*
  89256. ** This routine runs at the end of parsing a CREATE TABLE statement that
  89257. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  89258. ** internal schema data structures and the generated VDBE code so that they
  89259. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  89260. ** Changes include:
  89261. **
  89262. ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
  89263. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  89264. ** data storage is a covering index btree.
  89265. ** (2) Bypass the creation of the sqlite_master table entry
  89266. ** for the PRIMARY KEY as the primary key index is now
  89267. ** identified by the sqlite_master table entry of the table itself.
  89268. ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
  89269. ** schema to the rootpage from the main table.
  89270. ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  89271. ** (5) Add all table columns to the PRIMARY KEY Index object
  89272. ** so that the PRIMARY KEY is a covering index. The surplus
  89273. ** columns are part of KeyInfo.nXField and are not used for
  89274. ** sorting or lookup or uniqueness checks.
  89275. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  89276. ** indices with the PRIMARY KEY columns.
  89277. */
  89278. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  89279. Index *pIdx;
  89280. Index *pPk;
  89281. int nPk;
  89282. int i, j;
  89283. sqlite3 *db = pParse->db;
  89284. Vdbe *v = pParse->pVdbe;
  89285. /* Convert the OP_CreateTable opcode that would normally create the
  89286. ** root-page for the table into an OP_CreateIndex opcode. The index
  89287. ** created will become the PRIMARY KEY index.
  89288. */
  89289. if( pParse->addrCrTab ){
  89290. assert( v );
  89291. sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
  89292. }
  89293. /* Locate the PRIMARY KEY index. Or, if this table was originally
  89294. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  89295. */
  89296. if( pTab->iPKey>=0 ){
  89297. ExprList *pList;
  89298. Token ipkToken;
  89299. ipkToken.z = pTab->aCol[pTab->iPKey].zName;
  89300. ipkToken.n = sqlite3Strlen30(ipkToken.z);
  89301. pList = sqlite3ExprListAppend(pParse, 0,
  89302. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  89303. if( pList==0 ) return;
  89304. pList->a[0].sortOrder = pParse->iPkSortOrder;
  89305. assert( pParse->pNewTable==pTab );
  89306. pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
  89307. if( pPk==0 ) return;
  89308. pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  89309. pTab->iPKey = -1;
  89310. }else{
  89311. pPk = sqlite3PrimaryKeyIndex(pTab);
  89312. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  89313. ** table entry. This is only required if currently generating VDBE
  89314. ** code for a CREATE TABLE (not when parsing one as part of reading
  89315. ** a database schema). */
  89316. if( v ){
  89317. assert( db->init.busy==0 );
  89318. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  89319. }
  89320. /*
  89321. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  89322. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  89323. ** code assumes the PRIMARY KEY contains no repeated columns.
  89324. */
  89325. for(i=j=1; i<pPk->nKeyCol; i++){
  89326. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  89327. pPk->nColumn--;
  89328. }else{
  89329. pPk->aiColumn[j++] = pPk->aiColumn[i];
  89330. }
  89331. }
  89332. pPk->nKeyCol = j;
  89333. }
  89334. pPk->isCovering = 1;
  89335. assert( pPk!=0 );
  89336. nPk = pPk->nKeyCol;
  89337. /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
  89338. ** do not enforce this for imposter tables.) */
  89339. if( !db->init.imposterTable ){
  89340. for(i=0; i<nPk; i++){
  89341. pTab->aCol[pPk->aiColumn[i]].notNull = OE_Abort;
  89342. }
  89343. pPk->uniqNotNull = 1;
  89344. }
  89345. /* The root page of the PRIMARY KEY is the table root page */
  89346. pPk->tnum = pTab->tnum;
  89347. /* Update the in-memory representation of all UNIQUE indices by converting
  89348. ** the final rowid column into one or more columns of the PRIMARY KEY.
  89349. */
  89350. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  89351. int n;
  89352. if( IsPrimaryKeyIndex(pIdx) ) continue;
  89353. for(i=n=0; i<nPk; i++){
  89354. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  89355. }
  89356. if( n==0 ){
  89357. /* This index is a superset of the primary key */
  89358. pIdx->nColumn = pIdx->nKeyCol;
  89359. continue;
  89360. }
  89361. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  89362. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  89363. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  89364. pIdx->aiColumn[j] = pPk->aiColumn[i];
  89365. pIdx->azColl[j] = pPk->azColl[i];
  89366. j++;
  89367. }
  89368. }
  89369. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  89370. assert( pIdx->nColumn>=j );
  89371. }
  89372. /* Add all table columns to the PRIMARY KEY index
  89373. */
  89374. if( nPk<pTab->nCol ){
  89375. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  89376. for(i=0, j=nPk; i<pTab->nCol; i++){
  89377. if( !hasColumn(pPk->aiColumn, j, i) ){
  89378. assert( j<pPk->nColumn );
  89379. pPk->aiColumn[j] = i;
  89380. pPk->azColl[j] = sqlite3StrBINARY;
  89381. j++;
  89382. }
  89383. }
  89384. assert( pPk->nColumn==j );
  89385. assert( pTab->nCol==j );
  89386. }else{
  89387. pPk->nColumn = pTab->nCol;
  89388. }
  89389. }
  89390. /*
  89391. ** This routine is called to report the final ")" that terminates
  89392. ** a CREATE TABLE statement.
  89393. **
  89394. ** The table structure that other action routines have been building
  89395. ** is added to the internal hash tables, assuming no errors have
  89396. ** occurred.
  89397. **
  89398. ** An entry for the table is made in the master table on disk, unless
  89399. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  89400. ** it means we are reading the sqlite_master table because we just
  89401. ** connected to the database or because the sqlite_master table has
  89402. ** recently changed, so the entry for this table already exists in
  89403. ** the sqlite_master table. We do not want to create it again.
  89404. **
  89405. ** If the pSelect argument is not NULL, it means that this routine
  89406. ** was called to create a table generated from a
  89407. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  89408. ** the new table will match the result set of the SELECT.
  89409. */
  89410. SQLITE_PRIVATE void sqlite3EndTable(
  89411. Parse *pParse, /* Parse context */
  89412. Token *pCons, /* The ',' token after the last column defn. */
  89413. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  89414. u8 tabOpts, /* Extra table options. Usually 0. */
  89415. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  89416. ){
  89417. Table *p; /* The new table */
  89418. sqlite3 *db = pParse->db; /* The database connection */
  89419. int iDb; /* Database in which the table lives */
  89420. Index *pIdx; /* An implied index of the table */
  89421. if( pEnd==0 && pSelect==0 ){
  89422. return;
  89423. }
  89424. assert( !db->mallocFailed );
  89425. p = pParse->pNewTable;
  89426. if( p==0 ) return;
  89427. assert( !db->init.busy || !pSelect );
  89428. /* If the db->init.busy is 1 it means we are reading the SQL off the
  89429. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  89430. ** So do not write to the disk again. Extract the root page number
  89431. ** for the table from the db->init.newTnum field. (The page number
  89432. ** should have been put there by the sqliteOpenCb routine.)
  89433. */
  89434. if( db->init.busy ){
  89435. p->tnum = db->init.newTnum;
  89436. }
  89437. /* Special processing for WITHOUT ROWID Tables */
  89438. if( tabOpts & TF_WithoutRowid ){
  89439. if( (p->tabFlags & TF_Autoincrement) ){
  89440. sqlite3ErrorMsg(pParse,
  89441. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  89442. return;
  89443. }
  89444. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  89445. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  89446. }else{
  89447. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  89448. convertToWithoutRowidTable(pParse, p);
  89449. }
  89450. }
  89451. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  89452. #ifndef SQLITE_OMIT_CHECK
  89453. /* Resolve names in all CHECK constraint expressions.
  89454. */
  89455. if( p->pCheck ){
  89456. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  89457. }
  89458. #endif /* !defined(SQLITE_OMIT_CHECK) */
  89459. /* Estimate the average row size for the table and for all implied indices */
  89460. estimateTableWidth(p);
  89461. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  89462. estimateIndexWidth(pIdx);
  89463. }
  89464. /* If not initializing, then create a record for the new table
  89465. ** in the SQLITE_MASTER table of the database.
  89466. **
  89467. ** If this is a TEMPORARY table, write the entry into the auxiliary
  89468. ** file instead of into the main database file.
  89469. */
  89470. if( !db->init.busy ){
  89471. int n;
  89472. Vdbe *v;
  89473. char *zType; /* "view" or "table" */
  89474. char *zType2; /* "VIEW" or "TABLE" */
  89475. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  89476. v = sqlite3GetVdbe(pParse);
  89477. if( NEVER(v==0) ) return;
  89478. sqlite3VdbeAddOp1(v, OP_Close, 0);
  89479. /*
  89480. ** Initialize zType for the new view or table.
  89481. */
  89482. if( p->pSelect==0 ){
  89483. /* A regular table */
  89484. zType = "table";
  89485. zType2 = "TABLE";
  89486. #ifndef SQLITE_OMIT_VIEW
  89487. }else{
  89488. /* A view */
  89489. zType = "view";
  89490. zType2 = "VIEW";
  89491. #endif
  89492. }
  89493. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  89494. ** statement to populate the new table. The root-page number for the
  89495. ** new table is in register pParse->regRoot.
  89496. **
  89497. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  89498. ** suitable state to query for the column names and types to be used
  89499. ** by the new table.
  89500. **
  89501. ** A shared-cache write-lock is not required to write to the new table,
  89502. ** as a schema-lock must have already been obtained to create it. Since
  89503. ** a schema-lock excludes all other database users, the write-lock would
  89504. ** be redundant.
  89505. */
  89506. if( pSelect ){
  89507. SelectDest dest; /* Where the SELECT should store results */
  89508. int regYield; /* Register holding co-routine entry-point */
  89509. int addrTop; /* Top of the co-routine */
  89510. int regRec; /* A record to be insert into the new table */
  89511. int regRowid; /* Rowid of the next row to insert */
  89512. int addrInsLoop; /* Top of the loop for inserting rows */
  89513. Table *pSelTab; /* A table that describes the SELECT results */
  89514. regYield = ++pParse->nMem;
  89515. regRec = ++pParse->nMem;
  89516. regRowid = ++pParse->nMem;
  89517. assert(pParse->nTab==1);
  89518. sqlite3MayAbort(pParse);
  89519. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  89520. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  89521. pParse->nTab = 2;
  89522. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  89523. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  89524. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  89525. sqlite3Select(pParse, pSelect, &dest);
  89526. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  89527. sqlite3VdbeJumpHere(v, addrTop - 1);
  89528. if( pParse->nErr ) return;
  89529. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  89530. if( pSelTab==0 ) return;
  89531. assert( p->aCol==0 );
  89532. p->nCol = pSelTab->nCol;
  89533. p->aCol = pSelTab->aCol;
  89534. pSelTab->nCol = 0;
  89535. pSelTab->aCol = 0;
  89536. sqlite3DeleteTable(db, pSelTab);
  89537. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  89538. VdbeCoverage(v);
  89539. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  89540. sqlite3TableAffinity(v, p, 0);
  89541. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  89542. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  89543. sqlite3VdbeGoto(v, addrInsLoop);
  89544. sqlite3VdbeJumpHere(v, addrInsLoop);
  89545. sqlite3VdbeAddOp1(v, OP_Close, 1);
  89546. }
  89547. /* Compute the complete text of the CREATE statement */
  89548. if( pSelect ){
  89549. zStmt = createTableStmt(db, p);
  89550. }else{
  89551. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  89552. n = (int)(pEnd2->z - pParse->sNameToken.z);
  89553. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  89554. zStmt = sqlite3MPrintf(db,
  89555. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  89556. );
  89557. }
  89558. /* A slot for the record has already been allocated in the
  89559. ** SQLITE_MASTER table. We just need to update that slot with all
  89560. ** the information we've collected.
  89561. */
  89562. sqlite3NestedParse(pParse,
  89563. "UPDATE %Q.%s "
  89564. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  89565. "WHERE rowid=#%d",
  89566. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  89567. zType,
  89568. p->zName,
  89569. p->zName,
  89570. pParse->regRoot,
  89571. zStmt,
  89572. pParse->regRowid
  89573. );
  89574. sqlite3DbFree(db, zStmt);
  89575. sqlite3ChangeCookie(pParse, iDb);
  89576. #ifndef SQLITE_OMIT_AUTOINCREMENT
  89577. /* Check to see if we need to create an sqlite_sequence table for
  89578. ** keeping track of autoincrement keys.
  89579. */
  89580. if( p->tabFlags & TF_Autoincrement ){
  89581. Db *pDb = &db->aDb[iDb];
  89582. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89583. if( pDb->pSchema->pSeqTab==0 ){
  89584. sqlite3NestedParse(pParse,
  89585. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  89586. pDb->zName
  89587. );
  89588. }
  89589. }
  89590. #endif
  89591. /* Reparse everything to update our internal data structures */
  89592. sqlite3VdbeAddParseSchemaOp(v, iDb,
  89593. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  89594. }
  89595. /* Add the table to the in-memory representation of the database.
  89596. */
  89597. if( db->init.busy ){
  89598. Table *pOld;
  89599. Schema *pSchema = p->pSchema;
  89600. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89601. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  89602. if( pOld ){
  89603. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  89604. db->mallocFailed = 1;
  89605. return;
  89606. }
  89607. pParse->pNewTable = 0;
  89608. db->flags |= SQLITE_InternChanges;
  89609. #ifndef SQLITE_OMIT_ALTERTABLE
  89610. if( !p->pSelect ){
  89611. const char *zName = (const char *)pParse->sNameToken.z;
  89612. int nName;
  89613. assert( !pSelect && pCons && pEnd );
  89614. if( pCons->z==0 ){
  89615. pCons = pEnd;
  89616. }
  89617. nName = (int)((const char *)pCons->z - zName);
  89618. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  89619. }
  89620. #endif
  89621. }
  89622. }
  89623. #ifndef SQLITE_OMIT_VIEW
  89624. /*
  89625. ** The parser calls this routine in order to create a new VIEW
  89626. */
  89627. SQLITE_PRIVATE void sqlite3CreateView(
  89628. Parse *pParse, /* The parsing context */
  89629. Token *pBegin, /* The CREATE token that begins the statement */
  89630. Token *pName1, /* The token that holds the name of the view */
  89631. Token *pName2, /* The token that holds the name of the view */
  89632. ExprList *pCNames, /* Optional list of view column names */
  89633. Select *pSelect, /* A SELECT statement that will become the new view */
  89634. int isTemp, /* TRUE for a TEMPORARY view */
  89635. int noErr /* Suppress error messages if VIEW already exists */
  89636. ){
  89637. Table *p;
  89638. int n;
  89639. const char *z;
  89640. Token sEnd;
  89641. DbFixer sFix;
  89642. Token *pName = 0;
  89643. int iDb;
  89644. sqlite3 *db = pParse->db;
  89645. if( pParse->nVar>0 ){
  89646. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  89647. goto create_view_fail;
  89648. }
  89649. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  89650. p = pParse->pNewTable;
  89651. if( p==0 || pParse->nErr ) goto create_view_fail;
  89652. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  89653. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  89654. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  89655. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  89656. /* Make a copy of the entire SELECT statement that defines the view.
  89657. ** This will force all the Expr.token.z values to be dynamically
  89658. ** allocated rather than point to the input string - which means that
  89659. ** they will persist after the current sqlite3_exec() call returns.
  89660. */
  89661. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  89662. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  89663. if( db->mallocFailed ) goto create_view_fail;
  89664. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  89665. ** the end.
  89666. */
  89667. sEnd = pParse->sLastToken;
  89668. assert( sEnd.z[0]!=0 );
  89669. if( sEnd.z[0]!=';' ){
  89670. sEnd.z += sEnd.n;
  89671. }
  89672. sEnd.n = 0;
  89673. n = (int)(sEnd.z - pBegin->z);
  89674. assert( n>0 );
  89675. z = pBegin->z;
  89676. while( sqlite3Isspace(z[n-1]) ){ n--; }
  89677. sEnd.z = &z[n-1];
  89678. sEnd.n = 1;
  89679. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  89680. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  89681. create_view_fail:
  89682. sqlite3SelectDelete(db, pSelect);
  89683. sqlite3ExprListDelete(db, pCNames);
  89684. return;
  89685. }
  89686. #endif /* SQLITE_OMIT_VIEW */
  89687. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  89688. /*
  89689. ** The Table structure pTable is really a VIEW. Fill in the names of
  89690. ** the columns of the view in the pTable structure. Return the number
  89691. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  89692. */
  89693. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  89694. Table *pSelTab; /* A fake table from which we get the result set */
  89695. Select *pSel; /* Copy of the SELECT that implements the view */
  89696. int nErr = 0; /* Number of errors encountered */
  89697. int n; /* Temporarily holds the number of cursors assigned */
  89698. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  89699. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  89700. u8 bEnabledLA; /* Saved db->lookaside.bEnabled state */
  89701. assert( pTable );
  89702. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89703. if( sqlite3VtabCallConnect(pParse, pTable) ){
  89704. return SQLITE_ERROR;
  89705. }
  89706. if( IsVirtual(pTable) ) return 0;
  89707. #endif
  89708. #ifndef SQLITE_OMIT_VIEW
  89709. /* A positive nCol means the columns names for this view are
  89710. ** already known.
  89711. */
  89712. if( pTable->nCol>0 ) return 0;
  89713. /* A negative nCol is a special marker meaning that we are currently
  89714. ** trying to compute the column names. If we enter this routine with
  89715. ** a negative nCol, it means two or more views form a loop, like this:
  89716. **
  89717. ** CREATE VIEW one AS SELECT * FROM two;
  89718. ** CREATE VIEW two AS SELECT * FROM one;
  89719. **
  89720. ** Actually, the error above is now caught prior to reaching this point.
  89721. ** But the following test is still important as it does come up
  89722. ** in the following:
  89723. **
  89724. ** CREATE TABLE main.ex1(a);
  89725. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  89726. ** SELECT * FROM temp.ex1;
  89727. */
  89728. if( pTable->nCol<0 ){
  89729. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  89730. return 1;
  89731. }
  89732. assert( pTable->nCol>=0 );
  89733. /* If we get this far, it means we need to compute the table names.
  89734. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  89735. ** "*" elements in the results set of the view and will assign cursors
  89736. ** to the elements of the FROM clause. But we do not want these changes
  89737. ** to be permanent. So the computation is done on a copy of the SELECT
  89738. ** statement that defines the view.
  89739. */
  89740. assert( pTable->pSelect );
  89741. bEnabledLA = db->lookaside.bEnabled;
  89742. if( pTable->pCheck ){
  89743. db->lookaside.bEnabled = 0;
  89744. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  89745. &pTable->nCol, &pTable->aCol);
  89746. }else{
  89747. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  89748. if( pSel ){
  89749. n = pParse->nTab;
  89750. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  89751. pTable->nCol = -1;
  89752. db->lookaside.bEnabled = 0;
  89753. #ifndef SQLITE_OMIT_AUTHORIZATION
  89754. xAuth = db->xAuth;
  89755. db->xAuth = 0;
  89756. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  89757. db->xAuth = xAuth;
  89758. #else
  89759. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  89760. #endif
  89761. pParse->nTab = n;
  89762. if( pSelTab ){
  89763. assert( pTable->aCol==0 );
  89764. pTable->nCol = pSelTab->nCol;
  89765. pTable->aCol = pSelTab->aCol;
  89766. pSelTab->nCol = 0;
  89767. pSelTab->aCol = 0;
  89768. sqlite3DeleteTable(db, pSelTab);
  89769. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  89770. }else{
  89771. pTable->nCol = 0;
  89772. nErr++;
  89773. }
  89774. sqlite3SelectDelete(db, pSel);
  89775. } else {
  89776. nErr++;
  89777. }
  89778. }
  89779. db->lookaside.bEnabled = bEnabledLA;
  89780. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  89781. #endif /* SQLITE_OMIT_VIEW */
  89782. return nErr;
  89783. }
  89784. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  89785. #ifndef SQLITE_OMIT_VIEW
  89786. /*
  89787. ** Clear the column names from every VIEW in database idx.
  89788. */
  89789. static void sqliteViewResetAll(sqlite3 *db, int idx){
  89790. HashElem *i;
  89791. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  89792. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  89793. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  89794. Table *pTab = sqliteHashData(i);
  89795. if( pTab->pSelect ){
  89796. sqlite3DeleteColumnNames(db, pTab);
  89797. pTab->aCol = 0;
  89798. pTab->nCol = 0;
  89799. }
  89800. }
  89801. DbClearProperty(db, idx, DB_UnresetViews);
  89802. }
  89803. #else
  89804. # define sqliteViewResetAll(A,B)
  89805. #endif /* SQLITE_OMIT_VIEW */
  89806. /*
  89807. ** This function is called by the VDBE to adjust the internal schema
  89808. ** used by SQLite when the btree layer moves a table root page. The
  89809. ** root-page of a table or index in database iDb has changed from iFrom
  89810. ** to iTo.
  89811. **
  89812. ** Ticket #1728: The symbol table might still contain information
  89813. ** on tables and/or indices that are the process of being deleted.
  89814. ** If you are unlucky, one of those deleted indices or tables might
  89815. ** have the same rootpage number as the real table or index that is
  89816. ** being moved. So we cannot stop searching after the first match
  89817. ** because the first match might be for one of the deleted indices
  89818. ** or tables and not the table/index that is actually being moved.
  89819. ** We must continue looping until all tables and indices with
  89820. ** rootpage==iFrom have been converted to have a rootpage of iTo
  89821. ** in order to be certain that we got the right one.
  89822. */
  89823. #ifndef SQLITE_OMIT_AUTOVACUUM
  89824. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  89825. HashElem *pElem;
  89826. Hash *pHash;
  89827. Db *pDb;
  89828. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89829. pDb = &db->aDb[iDb];
  89830. pHash = &pDb->pSchema->tblHash;
  89831. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  89832. Table *pTab = sqliteHashData(pElem);
  89833. if( pTab->tnum==iFrom ){
  89834. pTab->tnum = iTo;
  89835. }
  89836. }
  89837. pHash = &pDb->pSchema->idxHash;
  89838. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  89839. Index *pIdx = sqliteHashData(pElem);
  89840. if( pIdx->tnum==iFrom ){
  89841. pIdx->tnum = iTo;
  89842. }
  89843. }
  89844. }
  89845. #endif
  89846. /*
  89847. ** Write code to erase the table with root-page iTable from database iDb.
  89848. ** Also write code to modify the sqlite_master table and internal schema
  89849. ** if a root-page of another table is moved by the btree-layer whilst
  89850. ** erasing iTable (this can happen with an auto-vacuum database).
  89851. */
  89852. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  89853. Vdbe *v = sqlite3GetVdbe(pParse);
  89854. int r1 = sqlite3GetTempReg(pParse);
  89855. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  89856. sqlite3MayAbort(pParse);
  89857. #ifndef SQLITE_OMIT_AUTOVACUUM
  89858. /* OP_Destroy stores an in integer r1. If this integer
  89859. ** is non-zero, then it is the root page number of a table moved to
  89860. ** location iTable. The following code modifies the sqlite_master table to
  89861. ** reflect this.
  89862. **
  89863. ** The "#NNN" in the SQL is a special constant that means whatever value
  89864. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  89865. ** token for additional information.
  89866. */
  89867. sqlite3NestedParse(pParse,
  89868. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  89869. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  89870. #endif
  89871. sqlite3ReleaseTempReg(pParse, r1);
  89872. }
  89873. /*
  89874. ** Write VDBE code to erase table pTab and all associated indices on disk.
  89875. ** Code to update the sqlite_master tables and internal schema definitions
  89876. ** in case a root-page belonging to another table is moved by the btree layer
  89877. ** is also added (this can happen with an auto-vacuum database).
  89878. */
  89879. static void destroyTable(Parse *pParse, Table *pTab){
  89880. #ifdef SQLITE_OMIT_AUTOVACUUM
  89881. Index *pIdx;
  89882. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  89883. destroyRootPage(pParse, pTab->tnum, iDb);
  89884. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  89885. destroyRootPage(pParse, pIdx->tnum, iDb);
  89886. }
  89887. #else
  89888. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  89889. ** is not defined), then it is important to call OP_Destroy on the
  89890. ** table and index root-pages in order, starting with the numerically
  89891. ** largest root-page number. This guarantees that none of the root-pages
  89892. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  89893. ** following were coded:
  89894. **
  89895. ** OP_Destroy 4 0
  89896. ** ...
  89897. ** OP_Destroy 5 0
  89898. **
  89899. ** and root page 5 happened to be the largest root-page number in the
  89900. ** database, then root page 5 would be moved to page 4 by the
  89901. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  89902. ** a free-list page.
  89903. */
  89904. int iTab = pTab->tnum;
  89905. int iDestroyed = 0;
  89906. while( 1 ){
  89907. Index *pIdx;
  89908. int iLargest = 0;
  89909. if( iDestroyed==0 || iTab<iDestroyed ){
  89910. iLargest = iTab;
  89911. }
  89912. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  89913. int iIdx = pIdx->tnum;
  89914. assert( pIdx->pSchema==pTab->pSchema );
  89915. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  89916. iLargest = iIdx;
  89917. }
  89918. }
  89919. if( iLargest==0 ){
  89920. return;
  89921. }else{
  89922. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  89923. assert( iDb>=0 && iDb<pParse->db->nDb );
  89924. destroyRootPage(pParse, iLargest, iDb);
  89925. iDestroyed = iLargest;
  89926. }
  89927. }
  89928. #endif
  89929. }
  89930. /*
  89931. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  89932. ** after a DROP INDEX or DROP TABLE command.
  89933. */
  89934. static void sqlite3ClearStatTables(
  89935. Parse *pParse, /* The parsing context */
  89936. int iDb, /* The database number */
  89937. const char *zType, /* "idx" or "tbl" */
  89938. const char *zName /* Name of index or table */
  89939. ){
  89940. int i;
  89941. const char *zDbName = pParse->db->aDb[iDb].zName;
  89942. for(i=1; i<=4; i++){
  89943. char zTab[24];
  89944. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  89945. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  89946. sqlite3NestedParse(pParse,
  89947. "DELETE FROM %Q.%s WHERE %s=%Q",
  89948. zDbName, zTab, zType, zName
  89949. );
  89950. }
  89951. }
  89952. }
  89953. /*
  89954. ** Generate code to drop a table.
  89955. */
  89956. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  89957. Vdbe *v;
  89958. sqlite3 *db = pParse->db;
  89959. Trigger *pTrigger;
  89960. Db *pDb = &db->aDb[iDb];
  89961. v = sqlite3GetVdbe(pParse);
  89962. assert( v!=0 );
  89963. sqlite3BeginWriteOperation(pParse, 1, iDb);
  89964. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89965. if( IsVirtual(pTab) ){
  89966. sqlite3VdbeAddOp0(v, OP_VBegin);
  89967. }
  89968. #endif
  89969. /* Drop all triggers associated with the table being dropped. Code
  89970. ** is generated to remove entries from sqlite_master and/or
  89971. ** sqlite_temp_master if required.
  89972. */
  89973. pTrigger = sqlite3TriggerList(pParse, pTab);
  89974. while( pTrigger ){
  89975. assert( pTrigger->pSchema==pTab->pSchema ||
  89976. pTrigger->pSchema==db->aDb[1].pSchema );
  89977. sqlite3DropTriggerPtr(pParse, pTrigger);
  89978. pTrigger = pTrigger->pNext;
  89979. }
  89980. #ifndef SQLITE_OMIT_AUTOINCREMENT
  89981. /* Remove any entries of the sqlite_sequence table associated with
  89982. ** the table being dropped. This is done before the table is dropped
  89983. ** at the btree level, in case the sqlite_sequence table needs to
  89984. ** move as a result of the drop (can happen in auto-vacuum mode).
  89985. */
  89986. if( pTab->tabFlags & TF_Autoincrement ){
  89987. sqlite3NestedParse(pParse,
  89988. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  89989. pDb->zName, pTab->zName
  89990. );
  89991. }
  89992. #endif
  89993. /* Drop all SQLITE_MASTER table and index entries that refer to the
  89994. ** table. The program name loops through the master table and deletes
  89995. ** every row that refers to a table of the same name as the one being
  89996. ** dropped. Triggers are handled separately because a trigger can be
  89997. ** created in the temp database that refers to a table in another
  89998. ** database.
  89999. */
  90000. sqlite3NestedParse(pParse,
  90001. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  90002. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  90003. if( !isView && !IsVirtual(pTab) ){
  90004. destroyTable(pParse, pTab);
  90005. }
  90006. /* Remove the table entry from SQLite's internal schema and modify
  90007. ** the schema cookie.
  90008. */
  90009. if( IsVirtual(pTab) ){
  90010. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  90011. }
  90012. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  90013. sqlite3ChangeCookie(pParse, iDb);
  90014. sqliteViewResetAll(db, iDb);
  90015. }
  90016. /*
  90017. ** This routine is called to do the work of a DROP TABLE statement.
  90018. ** pName is the name of the table to be dropped.
  90019. */
  90020. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  90021. Table *pTab;
  90022. Vdbe *v;
  90023. sqlite3 *db = pParse->db;
  90024. int iDb;
  90025. if( db->mallocFailed ){
  90026. goto exit_drop_table;
  90027. }
  90028. assert( pParse->nErr==0 );
  90029. assert( pName->nSrc==1 );
  90030. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  90031. if( noErr ) db->suppressErr++;
  90032. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  90033. if( noErr ) db->suppressErr--;
  90034. if( pTab==0 ){
  90035. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  90036. goto exit_drop_table;
  90037. }
  90038. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90039. assert( iDb>=0 && iDb<db->nDb );
  90040. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  90041. ** it is initialized.
  90042. */
  90043. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  90044. goto exit_drop_table;
  90045. }
  90046. #ifndef SQLITE_OMIT_AUTHORIZATION
  90047. {
  90048. int code;
  90049. const char *zTab = SCHEMA_TABLE(iDb);
  90050. const char *zDb = db->aDb[iDb].zName;
  90051. const char *zArg2 = 0;
  90052. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  90053. goto exit_drop_table;
  90054. }
  90055. if( isView ){
  90056. if( !OMIT_TEMPDB && iDb==1 ){
  90057. code = SQLITE_DROP_TEMP_VIEW;
  90058. }else{
  90059. code = SQLITE_DROP_VIEW;
  90060. }
  90061. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90062. }else if( IsVirtual(pTab) ){
  90063. code = SQLITE_DROP_VTABLE;
  90064. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  90065. #endif
  90066. }else{
  90067. if( !OMIT_TEMPDB && iDb==1 ){
  90068. code = SQLITE_DROP_TEMP_TABLE;
  90069. }else{
  90070. code = SQLITE_DROP_TABLE;
  90071. }
  90072. }
  90073. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  90074. goto exit_drop_table;
  90075. }
  90076. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  90077. goto exit_drop_table;
  90078. }
  90079. }
  90080. #endif
  90081. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  90082. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  90083. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  90084. goto exit_drop_table;
  90085. }
  90086. #ifndef SQLITE_OMIT_VIEW
  90087. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  90088. ** on a table.
  90089. */
  90090. if( isView && pTab->pSelect==0 ){
  90091. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  90092. goto exit_drop_table;
  90093. }
  90094. if( !isView && pTab->pSelect ){
  90095. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  90096. goto exit_drop_table;
  90097. }
  90098. #endif
  90099. /* Generate code to remove the table from the master table
  90100. ** on disk.
  90101. */
  90102. v = sqlite3GetVdbe(pParse);
  90103. if( v ){
  90104. sqlite3BeginWriteOperation(pParse, 1, iDb);
  90105. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  90106. sqlite3FkDropTable(pParse, pName, pTab);
  90107. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  90108. }
  90109. exit_drop_table:
  90110. sqlite3SrcListDelete(db, pName);
  90111. }
  90112. /*
  90113. ** This routine is called to create a new foreign key on the table
  90114. ** currently under construction. pFromCol determines which columns
  90115. ** in the current table point to the foreign key. If pFromCol==0 then
  90116. ** connect the key to the last column inserted. pTo is the name of
  90117. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  90118. ** of tables in the parent pTo table. flags contains all
  90119. ** information about the conflict resolution algorithms specified
  90120. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  90121. **
  90122. ** An FKey structure is created and added to the table currently
  90123. ** under construction in the pParse->pNewTable field.
  90124. **
  90125. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  90126. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  90127. */
  90128. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  90129. Parse *pParse, /* Parsing context */
  90130. ExprList *pFromCol, /* Columns in this table that point to other table */
  90131. Token *pTo, /* Name of the other table */
  90132. ExprList *pToCol, /* Columns in the other table */
  90133. int flags /* Conflict resolution algorithms. */
  90134. ){
  90135. sqlite3 *db = pParse->db;
  90136. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90137. FKey *pFKey = 0;
  90138. FKey *pNextTo;
  90139. Table *p = pParse->pNewTable;
  90140. int nByte;
  90141. int i;
  90142. int nCol;
  90143. char *z;
  90144. assert( pTo!=0 );
  90145. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  90146. if( pFromCol==0 ){
  90147. int iCol = p->nCol-1;
  90148. if( NEVER(iCol<0) ) goto fk_end;
  90149. if( pToCol && pToCol->nExpr!=1 ){
  90150. sqlite3ErrorMsg(pParse, "foreign key on %s"
  90151. " should reference only one column of table %T",
  90152. p->aCol[iCol].zName, pTo);
  90153. goto fk_end;
  90154. }
  90155. nCol = 1;
  90156. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  90157. sqlite3ErrorMsg(pParse,
  90158. "number of columns in foreign key does not match the number of "
  90159. "columns in the referenced table");
  90160. goto fk_end;
  90161. }else{
  90162. nCol = pFromCol->nExpr;
  90163. }
  90164. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  90165. if( pToCol ){
  90166. for(i=0; i<pToCol->nExpr; i++){
  90167. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  90168. }
  90169. }
  90170. pFKey = sqlite3DbMallocZero(db, nByte );
  90171. if( pFKey==0 ){
  90172. goto fk_end;
  90173. }
  90174. pFKey->pFrom = p;
  90175. pFKey->pNextFrom = p->pFKey;
  90176. z = (char*)&pFKey->aCol[nCol];
  90177. pFKey->zTo = z;
  90178. memcpy(z, pTo->z, pTo->n);
  90179. z[pTo->n] = 0;
  90180. sqlite3Dequote(z);
  90181. z += pTo->n+1;
  90182. pFKey->nCol = nCol;
  90183. if( pFromCol==0 ){
  90184. pFKey->aCol[0].iFrom = p->nCol-1;
  90185. }else{
  90186. for(i=0; i<nCol; i++){
  90187. int j;
  90188. for(j=0; j<p->nCol; j++){
  90189. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  90190. pFKey->aCol[i].iFrom = j;
  90191. break;
  90192. }
  90193. }
  90194. if( j>=p->nCol ){
  90195. sqlite3ErrorMsg(pParse,
  90196. "unknown column \"%s\" in foreign key definition",
  90197. pFromCol->a[i].zName);
  90198. goto fk_end;
  90199. }
  90200. }
  90201. }
  90202. if( pToCol ){
  90203. for(i=0; i<nCol; i++){
  90204. int n = sqlite3Strlen30(pToCol->a[i].zName);
  90205. pFKey->aCol[i].zCol = z;
  90206. memcpy(z, pToCol->a[i].zName, n);
  90207. z[n] = 0;
  90208. z += n+1;
  90209. }
  90210. }
  90211. pFKey->isDeferred = 0;
  90212. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  90213. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  90214. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  90215. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  90216. pFKey->zTo, (void *)pFKey
  90217. );
  90218. if( pNextTo==pFKey ){
  90219. db->mallocFailed = 1;
  90220. goto fk_end;
  90221. }
  90222. if( pNextTo ){
  90223. assert( pNextTo->pPrevTo==0 );
  90224. pFKey->pNextTo = pNextTo;
  90225. pNextTo->pPrevTo = pFKey;
  90226. }
  90227. /* Link the foreign key to the table as the last step.
  90228. */
  90229. p->pFKey = pFKey;
  90230. pFKey = 0;
  90231. fk_end:
  90232. sqlite3DbFree(db, pFKey);
  90233. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  90234. sqlite3ExprListDelete(db, pFromCol);
  90235. sqlite3ExprListDelete(db, pToCol);
  90236. }
  90237. /*
  90238. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  90239. ** clause is seen as part of a foreign key definition. The isDeferred
  90240. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  90241. ** The behavior of the most recently created foreign key is adjusted
  90242. ** accordingly.
  90243. */
  90244. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  90245. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90246. Table *pTab;
  90247. FKey *pFKey;
  90248. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  90249. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  90250. pFKey->isDeferred = (u8)isDeferred;
  90251. #endif
  90252. }
  90253. /*
  90254. ** Generate code that will erase and refill index *pIdx. This is
  90255. ** used to initialize a newly created index or to recompute the
  90256. ** content of an index in response to a REINDEX command.
  90257. **
  90258. ** if memRootPage is not negative, it means that the index is newly
  90259. ** created. The register specified by memRootPage contains the
  90260. ** root page number of the index. If memRootPage is negative, then
  90261. ** the index already exists and must be cleared before being refilled and
  90262. ** the root page number of the index is taken from pIndex->tnum.
  90263. */
  90264. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  90265. Table *pTab = pIndex->pTable; /* The table that is indexed */
  90266. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  90267. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  90268. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  90269. int addr1; /* Address of top of loop */
  90270. int addr2; /* Address to jump to for next iteration */
  90271. int tnum; /* Root page of index */
  90272. int iPartIdxLabel; /* Jump to this label to skip a row */
  90273. Vdbe *v; /* Generate code into this virtual machine */
  90274. KeyInfo *pKey; /* KeyInfo for index */
  90275. int regRecord; /* Register holding assembled index record */
  90276. sqlite3 *db = pParse->db; /* The database connection */
  90277. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  90278. #ifndef SQLITE_OMIT_AUTHORIZATION
  90279. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  90280. db->aDb[iDb].zName ) ){
  90281. return;
  90282. }
  90283. #endif
  90284. /* Require a write-lock on the table to perform this operation */
  90285. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  90286. v = sqlite3GetVdbe(pParse);
  90287. if( v==0 ) return;
  90288. if( memRootPage>=0 ){
  90289. tnum = memRootPage;
  90290. }else{
  90291. tnum = pIndex->tnum;
  90292. }
  90293. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  90294. /* Open the sorter cursor if we are to use one. */
  90295. iSorter = pParse->nTab++;
  90296. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  90297. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  90298. /* Open the table. Loop through all rows of the table, inserting index
  90299. ** records into the sorter. */
  90300. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  90301. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  90302. regRecord = sqlite3GetTempReg(pParse);
  90303. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  90304. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  90305. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  90306. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  90307. sqlite3VdbeJumpHere(v, addr1);
  90308. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  90309. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  90310. (char *)pKey, P4_KEYINFO);
  90311. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  90312. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  90313. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  90314. if( IsUniqueIndex(pIndex) && pKey!=0 ){
  90315. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  90316. sqlite3VdbeGoto(v, j2);
  90317. addr2 = sqlite3VdbeCurrentAddr(v);
  90318. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  90319. pIndex->nKeyCol); VdbeCoverage(v);
  90320. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  90321. }else{
  90322. addr2 = sqlite3VdbeCurrentAddr(v);
  90323. }
  90324. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  90325. sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
  90326. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
  90327. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  90328. sqlite3ReleaseTempReg(pParse, regRecord);
  90329. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  90330. sqlite3VdbeJumpHere(v, addr1);
  90331. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  90332. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  90333. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  90334. }
  90335. /*
  90336. ** Allocate heap space to hold an Index object with nCol columns.
  90337. **
  90338. ** Increase the allocation size to provide an extra nExtra bytes
  90339. ** of 8-byte aligned space after the Index object and return a
  90340. ** pointer to this extra space in *ppExtra.
  90341. */
  90342. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  90343. sqlite3 *db, /* Database connection */
  90344. i16 nCol, /* Total number of columns in the index */
  90345. int nExtra, /* Number of bytes of extra space to alloc */
  90346. char **ppExtra /* Pointer to the "extra" space */
  90347. ){
  90348. Index *p; /* Allocated index object */
  90349. int nByte; /* Bytes of space for Index object + arrays */
  90350. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  90351. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  90352. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  90353. sizeof(i16)*nCol + /* Index.aiColumn */
  90354. sizeof(u8)*nCol); /* Index.aSortOrder */
  90355. p = sqlite3DbMallocZero(db, nByte + nExtra);
  90356. if( p ){
  90357. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  90358. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  90359. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  90360. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  90361. p->aSortOrder = (u8*)pExtra;
  90362. p->nColumn = nCol;
  90363. p->nKeyCol = nCol - 1;
  90364. *ppExtra = ((char*)p) + nByte;
  90365. }
  90366. return p;
  90367. }
  90368. /*
  90369. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  90370. ** and pTblList is the name of the table that is to be indexed. Both will
  90371. ** be NULL for a primary key or an index that is created to satisfy a
  90372. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  90373. ** as the table to be indexed. pParse->pNewTable is a table that is
  90374. ** currently being constructed by a CREATE TABLE statement.
  90375. **
  90376. ** pList is a list of columns to be indexed. pList will be NULL if this
  90377. ** is a primary key or unique-constraint on the most recent column added
  90378. ** to the table currently under construction.
  90379. **
  90380. ** If the index is created successfully, return a pointer to the new Index
  90381. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  90382. ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  90383. */
  90384. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  90385. Parse *pParse, /* All information about this parse */
  90386. Token *pName1, /* First part of index name. May be NULL */
  90387. Token *pName2, /* Second part of index name. May be NULL */
  90388. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  90389. ExprList *pList, /* A list of columns to be indexed */
  90390. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  90391. Token *pStart, /* The CREATE token that begins this statement */
  90392. Expr *pPIWhere, /* WHERE clause for partial indices */
  90393. int sortOrder, /* Sort order of primary key when pList==NULL */
  90394. int ifNotExist /* Omit error if index already exists */
  90395. ){
  90396. Index *pRet = 0; /* Pointer to return */
  90397. Table *pTab = 0; /* Table to be indexed */
  90398. Index *pIndex = 0; /* The index to be created */
  90399. char *zName = 0; /* Name of the index */
  90400. int nName; /* Number of characters in zName */
  90401. int i, j;
  90402. DbFixer sFix; /* For assigning database names to pTable */
  90403. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  90404. sqlite3 *db = pParse->db;
  90405. Db *pDb; /* The specific table containing the indexed database */
  90406. int iDb; /* Index of the database that is being written */
  90407. Token *pName = 0; /* Unqualified name of the index to create */
  90408. struct ExprList_item *pListItem; /* For looping over pList */
  90409. int nExtra = 0; /* Space allocated for zExtra[] */
  90410. int nExtraCol; /* Number of extra columns needed */
  90411. char *zExtra = 0; /* Extra space after the Index object */
  90412. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  90413. if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
  90414. goto exit_create_index;
  90415. }
  90416. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  90417. goto exit_create_index;
  90418. }
  90419. /*
  90420. ** Find the table that is to be indexed. Return early if not found.
  90421. */
  90422. if( pTblName!=0 ){
  90423. /* Use the two-part index name to determine the database
  90424. ** to search for the table. 'Fix' the table name to this db
  90425. ** before looking up the table.
  90426. */
  90427. assert( pName1 && pName2 );
  90428. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  90429. if( iDb<0 ) goto exit_create_index;
  90430. assert( pName && pName->z );
  90431. #ifndef SQLITE_OMIT_TEMPDB
  90432. /* If the index name was unqualified, check if the table
  90433. ** is a temp table. If so, set the database to 1. Do not do this
  90434. ** if initialising a database schema.
  90435. */
  90436. if( !db->init.busy ){
  90437. pTab = sqlite3SrcListLookup(pParse, pTblName);
  90438. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  90439. iDb = 1;
  90440. }
  90441. }
  90442. #endif
  90443. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  90444. if( sqlite3FixSrcList(&sFix, pTblName) ){
  90445. /* Because the parser constructs pTblName from a single identifier,
  90446. ** sqlite3FixSrcList can never fail. */
  90447. assert(0);
  90448. }
  90449. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  90450. assert( db->mallocFailed==0 || pTab==0 );
  90451. if( pTab==0 ) goto exit_create_index;
  90452. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  90453. sqlite3ErrorMsg(pParse,
  90454. "cannot create a TEMP index on non-TEMP table \"%s\"",
  90455. pTab->zName);
  90456. goto exit_create_index;
  90457. }
  90458. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  90459. }else{
  90460. assert( pName==0 );
  90461. assert( pStart==0 );
  90462. pTab = pParse->pNewTable;
  90463. if( !pTab ) goto exit_create_index;
  90464. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90465. }
  90466. pDb = &db->aDb[iDb];
  90467. assert( pTab!=0 );
  90468. assert( pParse->nErr==0 );
  90469. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  90470. && db->init.busy==0
  90471. #if SQLITE_USER_AUTHENTICATION
  90472. && sqlite3UserAuthTable(pTab->zName)==0
  90473. #endif
  90474. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  90475. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  90476. goto exit_create_index;
  90477. }
  90478. #ifndef SQLITE_OMIT_VIEW
  90479. if( pTab->pSelect ){
  90480. sqlite3ErrorMsg(pParse, "views may not be indexed");
  90481. goto exit_create_index;
  90482. }
  90483. #endif
  90484. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90485. if( IsVirtual(pTab) ){
  90486. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  90487. goto exit_create_index;
  90488. }
  90489. #endif
  90490. /*
  90491. ** Find the name of the index. Make sure there is not already another
  90492. ** index or table with the same name.
  90493. **
  90494. ** Exception: If we are reading the names of permanent indices from the
  90495. ** sqlite_master table (because some other process changed the schema) and
  90496. ** one of the index names collides with the name of a temporary table or
  90497. ** index, then we will continue to process this index.
  90498. **
  90499. ** If pName==0 it means that we are
  90500. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  90501. ** own name.
  90502. */
  90503. if( pName ){
  90504. zName = sqlite3NameFromToken(db, pName);
  90505. if( zName==0 ) goto exit_create_index;
  90506. assert( pName->z!=0 );
  90507. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  90508. goto exit_create_index;
  90509. }
  90510. if( !db->init.busy ){
  90511. if( sqlite3FindTable(db, zName, 0)!=0 ){
  90512. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  90513. goto exit_create_index;
  90514. }
  90515. }
  90516. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  90517. if( !ifNotExist ){
  90518. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  90519. }else{
  90520. assert( !db->init.busy );
  90521. sqlite3CodeVerifySchema(pParse, iDb);
  90522. }
  90523. goto exit_create_index;
  90524. }
  90525. }else{
  90526. int n;
  90527. Index *pLoop;
  90528. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  90529. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  90530. if( zName==0 ){
  90531. goto exit_create_index;
  90532. }
  90533. }
  90534. /* Check for authorization to create an index.
  90535. */
  90536. #ifndef SQLITE_OMIT_AUTHORIZATION
  90537. {
  90538. const char *zDb = pDb->zName;
  90539. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  90540. goto exit_create_index;
  90541. }
  90542. i = SQLITE_CREATE_INDEX;
  90543. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  90544. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  90545. goto exit_create_index;
  90546. }
  90547. }
  90548. #endif
  90549. /* If pList==0, it means this routine was called to make a primary
  90550. ** key out of the last column added to the table under construction.
  90551. ** So create a fake list to simulate this.
  90552. */
  90553. if( pList==0 ){
  90554. Token prevCol;
  90555. prevCol.z = pTab->aCol[pTab->nCol-1].zName;
  90556. prevCol.n = sqlite3Strlen30(prevCol.z);
  90557. pList = sqlite3ExprListAppend(pParse, 0,
  90558. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  90559. if( pList==0 ) goto exit_create_index;
  90560. assert( pList->nExpr==1 );
  90561. sqlite3ExprListSetSortOrder(pList, sortOrder);
  90562. }else{
  90563. sqlite3ExprListCheckLength(pParse, pList, "index");
  90564. }
  90565. /* Figure out how many bytes of space are required to store explicitly
  90566. ** specified collation sequence names.
  90567. */
  90568. for(i=0; i<pList->nExpr; i++){
  90569. Expr *pExpr = pList->a[i].pExpr;
  90570. assert( pExpr!=0 );
  90571. if( pExpr->op==TK_COLLATE ){
  90572. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  90573. }
  90574. }
  90575. /*
  90576. ** Allocate the index structure.
  90577. */
  90578. nName = sqlite3Strlen30(zName);
  90579. nExtraCol = pPk ? pPk->nKeyCol : 1;
  90580. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  90581. nName + nExtra + 1, &zExtra);
  90582. if( db->mallocFailed ){
  90583. goto exit_create_index;
  90584. }
  90585. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  90586. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  90587. pIndex->zName = zExtra;
  90588. zExtra += nName + 1;
  90589. memcpy(pIndex->zName, zName, nName+1);
  90590. pIndex->pTable = pTab;
  90591. pIndex->onError = (u8)onError;
  90592. pIndex->uniqNotNull = onError!=OE_None;
  90593. pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
  90594. pIndex->pSchema = db->aDb[iDb].pSchema;
  90595. pIndex->nKeyCol = pList->nExpr;
  90596. if( pPIWhere ){
  90597. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  90598. pIndex->pPartIdxWhere = pPIWhere;
  90599. pPIWhere = 0;
  90600. }
  90601. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  90602. /* Check to see if we should honor DESC requests on index columns
  90603. */
  90604. if( pDb->pSchema->file_format>=4 ){
  90605. sortOrderMask = -1; /* Honor DESC */
  90606. }else{
  90607. sortOrderMask = 0; /* Ignore DESC */
  90608. }
  90609. /* Analyze the list of expressions that form the terms of the index and
  90610. ** report any errors. In the common case where the expression is exactly
  90611. ** a table column, store that column in aiColumn[]. For general expressions,
  90612. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  90613. **
  90614. ** TODO: Issue a warning if two or more columns of the index are identical.
  90615. ** TODO: Issue a warning if the table primary key is used as part of the
  90616. ** index key.
  90617. */
  90618. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  90619. Expr *pCExpr; /* The i-th index expression */
  90620. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  90621. const char *zColl; /* Collation sequence name */
  90622. sqlite3StringToId(pListItem->pExpr);
  90623. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  90624. if( pParse->nErr ) goto exit_create_index;
  90625. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  90626. if( pCExpr->op!=TK_COLUMN ){
  90627. if( pTab==pParse->pNewTable ){
  90628. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  90629. "UNIQUE constraints");
  90630. goto exit_create_index;
  90631. }
  90632. if( pIndex->aColExpr==0 ){
  90633. ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
  90634. pIndex->aColExpr = pCopy;
  90635. if( !db->mallocFailed ){
  90636. assert( pCopy!=0 );
  90637. pListItem = &pCopy->a[i];
  90638. }
  90639. }
  90640. j = XN_EXPR;
  90641. pIndex->aiColumn[i] = XN_EXPR;
  90642. pIndex->uniqNotNull = 0;
  90643. }else{
  90644. j = pCExpr->iColumn;
  90645. assert( j<=0x7fff );
  90646. if( j<0 ){
  90647. j = pTab->iPKey;
  90648. }else if( pTab->aCol[j].notNull==0 ){
  90649. pIndex->uniqNotNull = 0;
  90650. }
  90651. pIndex->aiColumn[i] = (i16)j;
  90652. }
  90653. zColl = 0;
  90654. if( pListItem->pExpr->op==TK_COLLATE ){
  90655. int nColl;
  90656. zColl = pListItem->pExpr->u.zToken;
  90657. nColl = sqlite3Strlen30(zColl) + 1;
  90658. assert( nExtra>=nColl );
  90659. memcpy(zExtra, zColl, nColl);
  90660. zColl = zExtra;
  90661. zExtra += nColl;
  90662. nExtra -= nColl;
  90663. }else if( j>=0 ){
  90664. zColl = pTab->aCol[j].zColl;
  90665. }
  90666. if( !zColl ) zColl = sqlite3StrBINARY;
  90667. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  90668. goto exit_create_index;
  90669. }
  90670. pIndex->azColl[i] = zColl;
  90671. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  90672. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  90673. }
  90674. /* Append the table key to the end of the index. For WITHOUT ROWID
  90675. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  90676. ** normal tables (when pPk==0) this will be the rowid.
  90677. */
  90678. if( pPk ){
  90679. for(j=0; j<pPk->nKeyCol; j++){
  90680. int x = pPk->aiColumn[j];
  90681. assert( x>=0 );
  90682. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  90683. pIndex->nColumn--;
  90684. }else{
  90685. pIndex->aiColumn[i] = x;
  90686. pIndex->azColl[i] = pPk->azColl[j];
  90687. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  90688. i++;
  90689. }
  90690. }
  90691. assert( i==pIndex->nColumn );
  90692. }else{
  90693. pIndex->aiColumn[i] = XN_ROWID;
  90694. pIndex->azColl[i] = sqlite3StrBINARY;
  90695. }
  90696. sqlite3DefaultRowEst(pIndex);
  90697. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  90698. if( pTab==pParse->pNewTable ){
  90699. /* This routine has been called to create an automatic index as a
  90700. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  90701. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  90702. ** i.e. one of:
  90703. **
  90704. ** CREATE TABLE t(x PRIMARY KEY, y);
  90705. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  90706. **
  90707. ** Either way, check to see if the table already has such an index. If
  90708. ** so, don't bother creating this one. This only applies to
  90709. ** automatically created indices. Users can do as they wish with
  90710. ** explicit indices.
  90711. **
  90712. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  90713. ** (and thus suppressing the second one) even if they have different
  90714. ** sort orders.
  90715. **
  90716. ** If there are different collating sequences or if the columns of
  90717. ** the constraint occur in different orders, then the constraints are
  90718. ** considered distinct and both result in separate indices.
  90719. */
  90720. Index *pIdx;
  90721. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  90722. int k;
  90723. assert( IsUniqueIndex(pIdx) );
  90724. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  90725. assert( IsUniqueIndex(pIndex) );
  90726. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  90727. for(k=0; k<pIdx->nKeyCol; k++){
  90728. const char *z1;
  90729. const char *z2;
  90730. assert( pIdx->aiColumn[k]>=0 );
  90731. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  90732. z1 = pIdx->azColl[k];
  90733. z2 = pIndex->azColl[k];
  90734. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  90735. }
  90736. if( k==pIdx->nKeyCol ){
  90737. if( pIdx->onError!=pIndex->onError ){
  90738. /* This constraint creates the same index as a previous
  90739. ** constraint specified somewhere in the CREATE TABLE statement.
  90740. ** However the ON CONFLICT clauses are different. If both this
  90741. ** constraint and the previous equivalent constraint have explicit
  90742. ** ON CONFLICT clauses this is an error. Otherwise, use the
  90743. ** explicitly specified behavior for the index.
  90744. */
  90745. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  90746. sqlite3ErrorMsg(pParse,
  90747. "conflicting ON CONFLICT clauses specified", 0);
  90748. }
  90749. if( pIdx->onError==OE_Default ){
  90750. pIdx->onError = pIndex->onError;
  90751. }
  90752. }
  90753. pRet = pIdx;
  90754. goto exit_create_index;
  90755. }
  90756. }
  90757. }
  90758. /* Link the new Index structure to its table and to the other
  90759. ** in-memory database structures.
  90760. */
  90761. assert( pParse->nErr==0 );
  90762. if( db->init.busy ){
  90763. Index *p;
  90764. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  90765. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  90766. pIndex->zName, pIndex);
  90767. if( p ){
  90768. assert( p==pIndex ); /* Malloc must have failed */
  90769. db->mallocFailed = 1;
  90770. goto exit_create_index;
  90771. }
  90772. db->flags |= SQLITE_InternChanges;
  90773. if( pTblName!=0 ){
  90774. pIndex->tnum = db->init.newTnum;
  90775. }
  90776. }
  90777. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  90778. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  90779. ** emit code to allocate the index rootpage on disk and make an entry for
  90780. ** the index in the sqlite_master table and populate the index with
  90781. ** content. But, do not do this if we are simply reading the sqlite_master
  90782. ** table to parse the schema, or if this index is the PRIMARY KEY index
  90783. ** of a WITHOUT ROWID table.
  90784. **
  90785. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  90786. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  90787. ** has just been created, it contains no data and the index initialization
  90788. ** step can be skipped.
  90789. */
  90790. else if( HasRowid(pTab) || pTblName!=0 ){
  90791. Vdbe *v;
  90792. char *zStmt;
  90793. int iMem = ++pParse->nMem;
  90794. v = sqlite3GetVdbe(pParse);
  90795. if( v==0 ) goto exit_create_index;
  90796. sqlite3BeginWriteOperation(pParse, 1, iDb);
  90797. /* Create the rootpage for the index using CreateIndex. But before
  90798. ** doing so, code a Noop instruction and store its address in
  90799. ** Index.tnum. This is required in case this index is actually a
  90800. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  90801. ** that case the convertToWithoutRowidTable() routine will replace
  90802. ** the Noop with a Goto to jump over the VDBE code generated below. */
  90803. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  90804. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  90805. /* Gather the complete text of the CREATE INDEX statement into
  90806. ** the zStmt variable
  90807. */
  90808. if( pStart ){
  90809. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  90810. if( pName->z[n-1]==';' ) n--;
  90811. /* A named index with an explicit CREATE INDEX statement */
  90812. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  90813. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  90814. }else{
  90815. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  90816. /* zStmt = sqlite3MPrintf(""); */
  90817. zStmt = 0;
  90818. }
  90819. /* Add an entry in sqlite_master for this index
  90820. */
  90821. sqlite3NestedParse(pParse,
  90822. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  90823. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  90824. pIndex->zName,
  90825. pTab->zName,
  90826. iMem,
  90827. zStmt
  90828. );
  90829. sqlite3DbFree(db, zStmt);
  90830. /* Fill the index with data and reparse the schema. Code an OP_Expire
  90831. ** to invalidate all pre-compiled statements.
  90832. */
  90833. if( pTblName ){
  90834. sqlite3RefillIndex(pParse, pIndex, iMem);
  90835. sqlite3ChangeCookie(pParse, iDb);
  90836. sqlite3VdbeAddParseSchemaOp(v, iDb,
  90837. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  90838. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  90839. }
  90840. sqlite3VdbeJumpHere(v, pIndex->tnum);
  90841. }
  90842. /* When adding an index to the list of indices for a table, make
  90843. ** sure all indices labeled OE_Replace come after all those labeled
  90844. ** OE_Ignore. This is necessary for the correct constraint check
  90845. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  90846. ** UPDATE and INSERT statements.
  90847. */
  90848. if( db->init.busy || pTblName==0 ){
  90849. if( onError!=OE_Replace || pTab->pIndex==0
  90850. || pTab->pIndex->onError==OE_Replace){
  90851. pIndex->pNext = pTab->pIndex;
  90852. pTab->pIndex = pIndex;
  90853. }else{
  90854. Index *pOther = pTab->pIndex;
  90855. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  90856. pOther = pOther->pNext;
  90857. }
  90858. pIndex->pNext = pOther->pNext;
  90859. pOther->pNext = pIndex;
  90860. }
  90861. pRet = pIndex;
  90862. pIndex = 0;
  90863. }
  90864. /* Clean up before exiting */
  90865. exit_create_index:
  90866. if( pIndex ) freeIndex(db, pIndex);
  90867. sqlite3ExprDelete(db, pPIWhere);
  90868. sqlite3ExprListDelete(db, pList);
  90869. sqlite3SrcListDelete(db, pTblName);
  90870. sqlite3DbFree(db, zName);
  90871. return pRet;
  90872. }
  90873. /*
  90874. ** Fill the Index.aiRowEst[] array with default information - information
  90875. ** to be used when we have not run the ANALYZE command.
  90876. **
  90877. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  90878. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  90879. ** number of rows in the table that match any particular value of the
  90880. ** first column of the index. aiRowEst[2] is an estimate of the number
  90881. ** of rows that match any particular combination of the first 2 columns
  90882. ** of the index. And so forth. It must always be the case that
  90883. *
  90884. ** aiRowEst[N]<=aiRowEst[N-1]
  90885. ** aiRowEst[N]>=1
  90886. **
  90887. ** Apart from that, we have little to go on besides intuition as to
  90888. ** how aiRowEst[] should be initialized. The numbers generated here
  90889. ** are based on typical values found in actual indices.
  90890. */
  90891. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  90892. /* 10, 9, 8, 7, 6 */
  90893. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  90894. LogEst *a = pIdx->aiRowLogEst;
  90895. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  90896. int i;
  90897. /* Set the first entry (number of rows in the index) to the estimated
  90898. ** number of rows in the table. Or 10, if the estimated number of rows
  90899. ** in the table is less than that. */
  90900. a[0] = pIdx->pTable->nRowLogEst;
  90901. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  90902. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  90903. ** 6 and each subsequent value (if any) is 5. */
  90904. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  90905. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  90906. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  90907. }
  90908. assert( 0==sqlite3LogEst(1) );
  90909. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  90910. }
  90911. /*
  90912. ** This routine will drop an existing named index. This routine
  90913. ** implements the DROP INDEX statement.
  90914. */
  90915. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  90916. Index *pIndex;
  90917. Vdbe *v;
  90918. sqlite3 *db = pParse->db;
  90919. int iDb;
  90920. assert( pParse->nErr==0 ); /* Never called with prior errors */
  90921. if( db->mallocFailed ){
  90922. goto exit_drop_index;
  90923. }
  90924. assert( pName->nSrc==1 );
  90925. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  90926. goto exit_drop_index;
  90927. }
  90928. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  90929. if( pIndex==0 ){
  90930. if( !ifExists ){
  90931. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  90932. }else{
  90933. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  90934. }
  90935. pParse->checkSchema = 1;
  90936. goto exit_drop_index;
  90937. }
  90938. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  90939. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  90940. "or PRIMARY KEY constraint cannot be dropped", 0);
  90941. goto exit_drop_index;
  90942. }
  90943. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  90944. #ifndef SQLITE_OMIT_AUTHORIZATION
  90945. {
  90946. int code = SQLITE_DROP_INDEX;
  90947. Table *pTab = pIndex->pTable;
  90948. const char *zDb = db->aDb[iDb].zName;
  90949. const char *zTab = SCHEMA_TABLE(iDb);
  90950. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  90951. goto exit_drop_index;
  90952. }
  90953. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  90954. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  90955. goto exit_drop_index;
  90956. }
  90957. }
  90958. #endif
  90959. /* Generate code to remove the index and from the master table */
  90960. v = sqlite3GetVdbe(pParse);
  90961. if( v ){
  90962. sqlite3BeginWriteOperation(pParse, 1, iDb);
  90963. sqlite3NestedParse(pParse,
  90964. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  90965. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  90966. );
  90967. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  90968. sqlite3ChangeCookie(pParse, iDb);
  90969. destroyRootPage(pParse, pIndex->tnum, iDb);
  90970. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  90971. }
  90972. exit_drop_index:
  90973. sqlite3SrcListDelete(db, pName);
  90974. }
  90975. /*
  90976. ** pArray is a pointer to an array of objects. Each object in the
  90977. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  90978. ** to extend the array so that there is space for a new object at the end.
  90979. **
  90980. ** When this function is called, *pnEntry contains the current size of
  90981. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  90982. ** in total).
  90983. **
  90984. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  90985. ** space allocated for the new object is zeroed, *pnEntry updated to
  90986. ** reflect the new size of the array and a pointer to the new allocation
  90987. ** returned. *pIdx is set to the index of the new array entry in this case.
  90988. **
  90989. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  90990. ** unchanged and a copy of pArray returned.
  90991. */
  90992. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  90993. sqlite3 *db, /* Connection to notify of malloc failures */
  90994. void *pArray, /* Array of objects. Might be reallocated */
  90995. int szEntry, /* Size of each object in the array */
  90996. int *pnEntry, /* Number of objects currently in use */
  90997. int *pIdx /* Write the index of a new slot here */
  90998. ){
  90999. char *z;
  91000. int n = *pnEntry;
  91001. if( (n & (n-1))==0 ){
  91002. int sz = (n==0) ? 1 : 2*n;
  91003. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  91004. if( pNew==0 ){
  91005. *pIdx = -1;
  91006. return pArray;
  91007. }
  91008. pArray = pNew;
  91009. }
  91010. z = (char*)pArray;
  91011. memset(&z[n * szEntry], 0, szEntry);
  91012. *pIdx = n;
  91013. ++*pnEntry;
  91014. return pArray;
  91015. }
  91016. /*
  91017. ** Append a new element to the given IdList. Create a new IdList if
  91018. ** need be.
  91019. **
  91020. ** A new IdList is returned, or NULL if malloc() fails.
  91021. */
  91022. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  91023. int i;
  91024. if( pList==0 ){
  91025. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  91026. if( pList==0 ) return 0;
  91027. }
  91028. pList->a = sqlite3ArrayAllocate(
  91029. db,
  91030. pList->a,
  91031. sizeof(pList->a[0]),
  91032. &pList->nId,
  91033. &i
  91034. );
  91035. if( i<0 ){
  91036. sqlite3IdListDelete(db, pList);
  91037. return 0;
  91038. }
  91039. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  91040. return pList;
  91041. }
  91042. /*
  91043. ** Delete an IdList.
  91044. */
  91045. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  91046. int i;
  91047. if( pList==0 ) return;
  91048. for(i=0; i<pList->nId; i++){
  91049. sqlite3DbFree(db, pList->a[i].zName);
  91050. }
  91051. sqlite3DbFree(db, pList->a);
  91052. sqlite3DbFree(db, pList);
  91053. }
  91054. /*
  91055. ** Return the index in pList of the identifier named zId. Return -1
  91056. ** if not found.
  91057. */
  91058. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  91059. int i;
  91060. if( pList==0 ) return -1;
  91061. for(i=0; i<pList->nId; i++){
  91062. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  91063. }
  91064. return -1;
  91065. }
  91066. /*
  91067. ** Expand the space allocated for the given SrcList object by
  91068. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  91069. ** New slots are zeroed.
  91070. **
  91071. ** For example, suppose a SrcList initially contains two entries: A,B.
  91072. ** To append 3 new entries onto the end, do this:
  91073. **
  91074. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  91075. **
  91076. ** After the call above it would contain: A, B, nil, nil, nil.
  91077. ** If the iStart argument had been 1 instead of 2, then the result
  91078. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  91079. ** the iStart value would be 0. The result then would
  91080. ** be: nil, nil, nil, A, B.
  91081. **
  91082. ** If a memory allocation fails the SrcList is unchanged. The
  91083. ** db->mallocFailed flag will be set to true.
  91084. */
  91085. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  91086. sqlite3 *db, /* Database connection to notify of OOM errors */
  91087. SrcList *pSrc, /* The SrcList to be enlarged */
  91088. int nExtra, /* Number of new slots to add to pSrc->a[] */
  91089. int iStart /* Index in pSrc->a[] of first new slot */
  91090. ){
  91091. int i;
  91092. /* Sanity checking on calling parameters */
  91093. assert( iStart>=0 );
  91094. assert( nExtra>=1 );
  91095. assert( pSrc!=0 );
  91096. assert( iStart<=pSrc->nSrc );
  91097. /* Allocate additional space if needed */
  91098. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  91099. SrcList *pNew;
  91100. int nAlloc = pSrc->nSrc+nExtra;
  91101. int nGot;
  91102. pNew = sqlite3DbRealloc(db, pSrc,
  91103. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  91104. if( pNew==0 ){
  91105. assert( db->mallocFailed );
  91106. return pSrc;
  91107. }
  91108. pSrc = pNew;
  91109. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  91110. pSrc->nAlloc = nGot;
  91111. }
  91112. /* Move existing slots that come after the newly inserted slots
  91113. ** out of the way */
  91114. for(i=pSrc->nSrc-1; i>=iStart; i--){
  91115. pSrc->a[i+nExtra] = pSrc->a[i];
  91116. }
  91117. pSrc->nSrc += nExtra;
  91118. /* Zero the newly allocated slots */
  91119. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  91120. for(i=iStart; i<iStart+nExtra; i++){
  91121. pSrc->a[i].iCursor = -1;
  91122. }
  91123. /* Return a pointer to the enlarged SrcList */
  91124. return pSrc;
  91125. }
  91126. /*
  91127. ** Append a new table name to the given SrcList. Create a new SrcList if
  91128. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  91129. **
  91130. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  91131. ** SrcList might be the same as the SrcList that was input or it might be
  91132. ** a new one. If an OOM error does occurs, then the prior value of pList
  91133. ** that is input to this routine is automatically freed.
  91134. **
  91135. ** If pDatabase is not null, it means that the table has an optional
  91136. ** database name prefix. Like this: "database.table". The pDatabase
  91137. ** points to the table name and the pTable points to the database name.
  91138. ** The SrcList.a[].zName field is filled with the table name which might
  91139. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  91140. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  91141. ** or with NULL if no database is specified.
  91142. **
  91143. ** In other words, if call like this:
  91144. **
  91145. ** sqlite3SrcListAppend(D,A,B,0);
  91146. **
  91147. ** Then B is a table name and the database name is unspecified. If called
  91148. ** like this:
  91149. **
  91150. ** sqlite3SrcListAppend(D,A,B,C);
  91151. **
  91152. ** Then C is the table name and B is the database name. If C is defined
  91153. ** then so is B. In other words, we never have a case where:
  91154. **
  91155. ** sqlite3SrcListAppend(D,A,0,C);
  91156. **
  91157. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  91158. ** before being added to the SrcList.
  91159. */
  91160. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  91161. sqlite3 *db, /* Connection to notify of malloc failures */
  91162. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  91163. Token *pTable, /* Table to append */
  91164. Token *pDatabase /* Database of the table */
  91165. ){
  91166. struct SrcList_item *pItem;
  91167. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  91168. if( pList==0 ){
  91169. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  91170. if( pList==0 ) return 0;
  91171. pList->nAlloc = 1;
  91172. }
  91173. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  91174. if( db->mallocFailed ){
  91175. sqlite3SrcListDelete(db, pList);
  91176. return 0;
  91177. }
  91178. pItem = &pList->a[pList->nSrc-1];
  91179. if( pDatabase && pDatabase->z==0 ){
  91180. pDatabase = 0;
  91181. }
  91182. if( pDatabase ){
  91183. Token *pTemp = pDatabase;
  91184. pDatabase = pTable;
  91185. pTable = pTemp;
  91186. }
  91187. pItem->zName = sqlite3NameFromToken(db, pTable);
  91188. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  91189. return pList;
  91190. }
  91191. /*
  91192. ** Assign VdbeCursor index numbers to all tables in a SrcList
  91193. */
  91194. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  91195. int i;
  91196. struct SrcList_item *pItem;
  91197. assert(pList || pParse->db->mallocFailed );
  91198. if( pList ){
  91199. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  91200. if( pItem->iCursor>=0 ) break;
  91201. pItem->iCursor = pParse->nTab++;
  91202. if( pItem->pSelect ){
  91203. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  91204. }
  91205. }
  91206. }
  91207. }
  91208. /*
  91209. ** Delete an entire SrcList including all its substructure.
  91210. */
  91211. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  91212. int i;
  91213. struct SrcList_item *pItem;
  91214. if( pList==0 ) return;
  91215. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  91216. sqlite3DbFree(db, pItem->zDatabase);
  91217. sqlite3DbFree(db, pItem->zName);
  91218. sqlite3DbFree(db, pItem->zAlias);
  91219. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  91220. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  91221. sqlite3DeleteTable(db, pItem->pTab);
  91222. sqlite3SelectDelete(db, pItem->pSelect);
  91223. sqlite3ExprDelete(db, pItem->pOn);
  91224. sqlite3IdListDelete(db, pItem->pUsing);
  91225. }
  91226. sqlite3DbFree(db, pList);
  91227. }
  91228. /*
  91229. ** This routine is called by the parser to add a new term to the
  91230. ** end of a growing FROM clause. The "p" parameter is the part of
  91231. ** the FROM clause that has already been constructed. "p" is NULL
  91232. ** if this is the first term of the FROM clause. pTable and pDatabase
  91233. ** are the name of the table and database named in the FROM clause term.
  91234. ** pDatabase is NULL if the database name qualifier is missing - the
  91235. ** usual case. If the term has an alias, then pAlias points to the
  91236. ** alias token. If the term is a subquery, then pSubquery is the
  91237. ** SELECT statement that the subquery encodes. The pTable and
  91238. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  91239. ** parameters are the content of the ON and USING clauses.
  91240. **
  91241. ** Return a new SrcList which encodes is the FROM with the new
  91242. ** term added.
  91243. */
  91244. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  91245. Parse *pParse, /* Parsing context */
  91246. SrcList *p, /* The left part of the FROM clause already seen */
  91247. Token *pTable, /* Name of the table to add to the FROM clause */
  91248. Token *pDatabase, /* Name of the database containing pTable */
  91249. Token *pAlias, /* The right-hand side of the AS subexpression */
  91250. Select *pSubquery, /* A subquery used in place of a table name */
  91251. Expr *pOn, /* The ON clause of a join */
  91252. IdList *pUsing /* The USING clause of a join */
  91253. ){
  91254. struct SrcList_item *pItem;
  91255. sqlite3 *db = pParse->db;
  91256. if( !p && (pOn || pUsing) ){
  91257. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  91258. (pOn ? "ON" : "USING")
  91259. );
  91260. goto append_from_error;
  91261. }
  91262. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  91263. if( p==0 || NEVER(p->nSrc==0) ){
  91264. goto append_from_error;
  91265. }
  91266. pItem = &p->a[p->nSrc-1];
  91267. assert( pAlias!=0 );
  91268. if( pAlias->n ){
  91269. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  91270. }
  91271. pItem->pSelect = pSubquery;
  91272. pItem->pOn = pOn;
  91273. pItem->pUsing = pUsing;
  91274. return p;
  91275. append_from_error:
  91276. assert( p==0 );
  91277. sqlite3ExprDelete(db, pOn);
  91278. sqlite3IdListDelete(db, pUsing);
  91279. sqlite3SelectDelete(db, pSubquery);
  91280. return 0;
  91281. }
  91282. /*
  91283. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  91284. ** element of the source-list passed as the second argument.
  91285. */
  91286. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  91287. assert( pIndexedBy!=0 );
  91288. if( p && ALWAYS(p->nSrc>0) ){
  91289. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  91290. assert( pItem->fg.notIndexed==0 );
  91291. assert( pItem->fg.isIndexedBy==0 );
  91292. assert( pItem->fg.isTabFunc==0 );
  91293. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  91294. /* A "NOT INDEXED" clause was supplied. See parse.y
  91295. ** construct "indexed_opt" for details. */
  91296. pItem->fg.notIndexed = 1;
  91297. }else{
  91298. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  91299. pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
  91300. }
  91301. }
  91302. }
  91303. /*
  91304. ** Add the list of function arguments to the SrcList entry for a
  91305. ** table-valued-function.
  91306. */
  91307. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  91308. if( p ){
  91309. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  91310. assert( pItem->fg.notIndexed==0 );
  91311. assert( pItem->fg.isIndexedBy==0 );
  91312. assert( pItem->fg.isTabFunc==0 );
  91313. pItem->u1.pFuncArg = pList;
  91314. pItem->fg.isTabFunc = 1;
  91315. }else{
  91316. sqlite3ExprListDelete(pParse->db, pList);
  91317. }
  91318. }
  91319. /*
  91320. ** When building up a FROM clause in the parser, the join operator
  91321. ** is initially attached to the left operand. But the code generator
  91322. ** expects the join operator to be on the right operand. This routine
  91323. ** Shifts all join operators from left to right for an entire FROM
  91324. ** clause.
  91325. **
  91326. ** Example: Suppose the join is like this:
  91327. **
  91328. ** A natural cross join B
  91329. **
  91330. ** The operator is "natural cross join". The A and B operands are stored
  91331. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  91332. ** operator with A. This routine shifts that operator over to B.
  91333. */
  91334. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  91335. if( p ){
  91336. int i;
  91337. for(i=p->nSrc-1; i>0; i--){
  91338. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  91339. }
  91340. p->a[0].fg.jointype = 0;
  91341. }
  91342. }
  91343. /*
  91344. ** Begin a transaction
  91345. */
  91346. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  91347. sqlite3 *db;
  91348. Vdbe *v;
  91349. int i;
  91350. assert( pParse!=0 );
  91351. db = pParse->db;
  91352. assert( db!=0 );
  91353. /* if( db->aDb[0].pBt==0 ) return; */
  91354. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  91355. return;
  91356. }
  91357. v = sqlite3GetVdbe(pParse);
  91358. if( !v ) return;
  91359. if( type!=TK_DEFERRED ){
  91360. for(i=0; i<db->nDb; i++){
  91361. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  91362. sqlite3VdbeUsesBtree(v, i);
  91363. }
  91364. }
  91365. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  91366. }
  91367. /*
  91368. ** Commit a transaction
  91369. */
  91370. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  91371. Vdbe *v;
  91372. assert( pParse!=0 );
  91373. assert( pParse->db!=0 );
  91374. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  91375. return;
  91376. }
  91377. v = sqlite3GetVdbe(pParse);
  91378. if( v ){
  91379. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  91380. }
  91381. }
  91382. /*
  91383. ** Rollback a transaction
  91384. */
  91385. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  91386. Vdbe *v;
  91387. assert( pParse!=0 );
  91388. assert( pParse->db!=0 );
  91389. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  91390. return;
  91391. }
  91392. v = sqlite3GetVdbe(pParse);
  91393. if( v ){
  91394. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  91395. }
  91396. }
  91397. /*
  91398. ** This function is called by the parser when it parses a command to create,
  91399. ** release or rollback an SQL savepoint.
  91400. */
  91401. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  91402. char *zName = sqlite3NameFromToken(pParse->db, pName);
  91403. if( zName ){
  91404. Vdbe *v = sqlite3GetVdbe(pParse);
  91405. #ifndef SQLITE_OMIT_AUTHORIZATION
  91406. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  91407. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  91408. #endif
  91409. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  91410. sqlite3DbFree(pParse->db, zName);
  91411. return;
  91412. }
  91413. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  91414. }
  91415. }
  91416. /*
  91417. ** Make sure the TEMP database is open and available for use. Return
  91418. ** the number of errors. Leave any error messages in the pParse structure.
  91419. */
  91420. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  91421. sqlite3 *db = pParse->db;
  91422. if( db->aDb[1].pBt==0 && !pParse->explain ){
  91423. int rc;
  91424. Btree *pBt;
  91425. static const int flags =
  91426. SQLITE_OPEN_READWRITE |
  91427. SQLITE_OPEN_CREATE |
  91428. SQLITE_OPEN_EXCLUSIVE |
  91429. SQLITE_OPEN_DELETEONCLOSE |
  91430. SQLITE_OPEN_TEMP_DB;
  91431. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  91432. if( rc!=SQLITE_OK ){
  91433. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  91434. "file for storing temporary tables");
  91435. pParse->rc = rc;
  91436. return 1;
  91437. }
  91438. db->aDb[1].pBt = pBt;
  91439. assert( db->aDb[1].pSchema );
  91440. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  91441. db->mallocFailed = 1;
  91442. return 1;
  91443. }
  91444. }
  91445. return 0;
  91446. }
  91447. /*
  91448. ** Record the fact that the schema cookie will need to be verified
  91449. ** for database iDb. The code to actually verify the schema cookie
  91450. ** will occur at the end of the top-level VDBE and will be generated
  91451. ** later, by sqlite3FinishCoding().
  91452. */
  91453. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  91454. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91455. sqlite3 *db = pToplevel->db;
  91456. assert( iDb>=0 && iDb<db->nDb );
  91457. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  91458. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  91459. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  91460. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  91461. DbMaskSet(pToplevel->cookieMask, iDb);
  91462. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  91463. if( !OMIT_TEMPDB && iDb==1 ){
  91464. sqlite3OpenTempDatabase(pToplevel);
  91465. }
  91466. }
  91467. }
  91468. /*
  91469. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  91470. ** attached database. Otherwise, invoke it for the database named zDb only.
  91471. */
  91472. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  91473. sqlite3 *db = pParse->db;
  91474. int i;
  91475. for(i=0; i<db->nDb; i++){
  91476. Db *pDb = &db->aDb[i];
  91477. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  91478. sqlite3CodeVerifySchema(pParse, i);
  91479. }
  91480. }
  91481. }
  91482. /*
  91483. ** Generate VDBE code that prepares for doing an operation that
  91484. ** might change the database.
  91485. **
  91486. ** This routine starts a new transaction if we are not already within
  91487. ** a transaction. If we are already within a transaction, then a checkpoint
  91488. ** is set if the setStatement parameter is true. A checkpoint should
  91489. ** be set for operations that might fail (due to a constraint) part of
  91490. ** the way through and which will need to undo some writes without having to
  91491. ** rollback the whole transaction. For operations where all constraints
  91492. ** can be checked before any changes are made to the database, it is never
  91493. ** necessary to undo a write and the checkpoint should not be set.
  91494. */
  91495. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  91496. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91497. sqlite3CodeVerifySchema(pParse, iDb);
  91498. DbMaskSet(pToplevel->writeMask, iDb);
  91499. pToplevel->isMultiWrite |= setStatement;
  91500. }
  91501. /*
  91502. ** Indicate that the statement currently under construction might write
  91503. ** more than one entry (example: deleting one row then inserting another,
  91504. ** inserting multiple rows in a table, or inserting a row and index entries.)
  91505. ** If an abort occurs after some of these writes have completed, then it will
  91506. ** be necessary to undo the completed writes.
  91507. */
  91508. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  91509. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91510. pToplevel->isMultiWrite = 1;
  91511. }
  91512. /*
  91513. ** The code generator calls this routine if is discovers that it is
  91514. ** possible to abort a statement prior to completion. In order to
  91515. ** perform this abort without corrupting the database, we need to make
  91516. ** sure that the statement is protected by a statement transaction.
  91517. **
  91518. ** Technically, we only need to set the mayAbort flag if the
  91519. ** isMultiWrite flag was previously set. There is a time dependency
  91520. ** such that the abort must occur after the multiwrite. This makes
  91521. ** some statements involving the REPLACE conflict resolution algorithm
  91522. ** go a little faster. But taking advantage of this time dependency
  91523. ** makes it more difficult to prove that the code is correct (in
  91524. ** particular, it prevents us from writing an effective
  91525. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  91526. ** to take the safe route and skip the optimization.
  91527. */
  91528. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  91529. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91530. pToplevel->mayAbort = 1;
  91531. }
  91532. /*
  91533. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  91534. ** error. The onError parameter determines which (if any) of the statement
  91535. ** and/or current transaction is rolled back.
  91536. */
  91537. SQLITE_PRIVATE void sqlite3HaltConstraint(
  91538. Parse *pParse, /* Parsing context */
  91539. int errCode, /* extended error code */
  91540. int onError, /* Constraint type */
  91541. char *p4, /* Error message */
  91542. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  91543. u8 p5Errmsg /* P5_ErrMsg type */
  91544. ){
  91545. Vdbe *v = sqlite3GetVdbe(pParse);
  91546. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  91547. if( onError==OE_Abort ){
  91548. sqlite3MayAbort(pParse);
  91549. }
  91550. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  91551. if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
  91552. }
  91553. /*
  91554. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  91555. */
  91556. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  91557. Parse *pParse, /* Parsing context */
  91558. int onError, /* Constraint type */
  91559. Index *pIdx /* The index that triggers the constraint */
  91560. ){
  91561. char *zErr;
  91562. int j;
  91563. StrAccum errMsg;
  91564. Table *pTab = pIdx->pTable;
  91565. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  91566. if( pIdx->aColExpr ){
  91567. sqlite3XPrintf(&errMsg, 0, "index '%q'", pIdx->zName);
  91568. }else{
  91569. for(j=0; j<pIdx->nKeyCol; j++){
  91570. char *zCol;
  91571. assert( pIdx->aiColumn[j]>=0 );
  91572. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  91573. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  91574. sqlite3XPrintf(&errMsg, 0, "%s.%s", pTab->zName, zCol);
  91575. }
  91576. }
  91577. zErr = sqlite3StrAccumFinish(&errMsg);
  91578. sqlite3HaltConstraint(pParse,
  91579. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  91580. : SQLITE_CONSTRAINT_UNIQUE,
  91581. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  91582. }
  91583. /*
  91584. ** Code an OP_Halt due to non-unique rowid.
  91585. */
  91586. SQLITE_PRIVATE void sqlite3RowidConstraint(
  91587. Parse *pParse, /* Parsing context */
  91588. int onError, /* Conflict resolution algorithm */
  91589. Table *pTab /* The table with the non-unique rowid */
  91590. ){
  91591. char *zMsg;
  91592. int rc;
  91593. if( pTab->iPKey>=0 ){
  91594. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  91595. pTab->aCol[pTab->iPKey].zName);
  91596. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  91597. }else{
  91598. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  91599. rc = SQLITE_CONSTRAINT_ROWID;
  91600. }
  91601. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  91602. P5_ConstraintUnique);
  91603. }
  91604. /*
  91605. ** Check to see if pIndex uses the collating sequence pColl. Return
  91606. ** true if it does and false if it does not.
  91607. */
  91608. #ifndef SQLITE_OMIT_REINDEX
  91609. static int collationMatch(const char *zColl, Index *pIndex){
  91610. int i;
  91611. assert( zColl!=0 );
  91612. for(i=0; i<pIndex->nColumn; i++){
  91613. const char *z = pIndex->azColl[i];
  91614. assert( z!=0 || pIndex->aiColumn[i]<0 );
  91615. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  91616. return 1;
  91617. }
  91618. }
  91619. return 0;
  91620. }
  91621. #endif
  91622. /*
  91623. ** Recompute all indices of pTab that use the collating sequence pColl.
  91624. ** If pColl==0 then recompute all indices of pTab.
  91625. */
  91626. #ifndef SQLITE_OMIT_REINDEX
  91627. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  91628. Index *pIndex; /* An index associated with pTab */
  91629. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  91630. if( zColl==0 || collationMatch(zColl, pIndex) ){
  91631. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  91632. sqlite3BeginWriteOperation(pParse, 0, iDb);
  91633. sqlite3RefillIndex(pParse, pIndex, -1);
  91634. }
  91635. }
  91636. }
  91637. #endif
  91638. /*
  91639. ** Recompute all indices of all tables in all databases where the
  91640. ** indices use the collating sequence pColl. If pColl==0 then recompute
  91641. ** all indices everywhere.
  91642. */
  91643. #ifndef SQLITE_OMIT_REINDEX
  91644. static void reindexDatabases(Parse *pParse, char const *zColl){
  91645. Db *pDb; /* A single database */
  91646. int iDb; /* The database index number */
  91647. sqlite3 *db = pParse->db; /* The database connection */
  91648. HashElem *k; /* For looping over tables in pDb */
  91649. Table *pTab; /* A table in the database */
  91650. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  91651. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  91652. assert( pDb!=0 );
  91653. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  91654. pTab = (Table*)sqliteHashData(k);
  91655. reindexTable(pParse, pTab, zColl);
  91656. }
  91657. }
  91658. }
  91659. #endif
  91660. /*
  91661. ** Generate code for the REINDEX command.
  91662. **
  91663. ** REINDEX -- 1
  91664. ** REINDEX <collation> -- 2
  91665. ** REINDEX ?<database>.?<tablename> -- 3
  91666. ** REINDEX ?<database>.?<indexname> -- 4
  91667. **
  91668. ** Form 1 causes all indices in all attached databases to be rebuilt.
  91669. ** Form 2 rebuilds all indices in all databases that use the named
  91670. ** collating function. Forms 3 and 4 rebuild the named index or all
  91671. ** indices associated with the named table.
  91672. */
  91673. #ifndef SQLITE_OMIT_REINDEX
  91674. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  91675. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  91676. char *z; /* Name of a table or index */
  91677. const char *zDb; /* Name of the database */
  91678. Table *pTab; /* A table in the database */
  91679. Index *pIndex; /* An index associated with pTab */
  91680. int iDb; /* The database index number */
  91681. sqlite3 *db = pParse->db; /* The database connection */
  91682. Token *pObjName; /* Name of the table or index to be reindexed */
  91683. /* Read the database schema. If an error occurs, leave an error message
  91684. ** and code in pParse and return NULL. */
  91685. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  91686. return;
  91687. }
  91688. if( pName1==0 ){
  91689. reindexDatabases(pParse, 0);
  91690. return;
  91691. }else if( NEVER(pName2==0) || pName2->z==0 ){
  91692. char *zColl;
  91693. assert( pName1->z );
  91694. zColl = sqlite3NameFromToken(pParse->db, pName1);
  91695. if( !zColl ) return;
  91696. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  91697. if( pColl ){
  91698. reindexDatabases(pParse, zColl);
  91699. sqlite3DbFree(db, zColl);
  91700. return;
  91701. }
  91702. sqlite3DbFree(db, zColl);
  91703. }
  91704. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  91705. if( iDb<0 ) return;
  91706. z = sqlite3NameFromToken(db, pObjName);
  91707. if( z==0 ) return;
  91708. zDb = db->aDb[iDb].zName;
  91709. pTab = sqlite3FindTable(db, z, zDb);
  91710. if( pTab ){
  91711. reindexTable(pParse, pTab, 0);
  91712. sqlite3DbFree(db, z);
  91713. return;
  91714. }
  91715. pIndex = sqlite3FindIndex(db, z, zDb);
  91716. sqlite3DbFree(db, z);
  91717. if( pIndex ){
  91718. sqlite3BeginWriteOperation(pParse, 0, iDb);
  91719. sqlite3RefillIndex(pParse, pIndex, -1);
  91720. return;
  91721. }
  91722. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  91723. }
  91724. #endif
  91725. /*
  91726. ** Return a KeyInfo structure that is appropriate for the given Index.
  91727. **
  91728. ** The KeyInfo structure for an index is cached in the Index object.
  91729. ** So there might be multiple references to the returned pointer. The
  91730. ** caller should not try to modify the KeyInfo object.
  91731. **
  91732. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  91733. ** when it has finished using it.
  91734. */
  91735. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  91736. int i;
  91737. int nCol = pIdx->nColumn;
  91738. int nKey = pIdx->nKeyCol;
  91739. KeyInfo *pKey;
  91740. if( pParse->nErr ) return 0;
  91741. if( pIdx->uniqNotNull ){
  91742. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  91743. }else{
  91744. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  91745. }
  91746. if( pKey ){
  91747. assert( sqlite3KeyInfoIsWriteable(pKey) );
  91748. for(i=0; i<nCol; i++){
  91749. const char *zColl = pIdx->azColl[i];
  91750. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  91751. sqlite3LocateCollSeq(pParse, zColl);
  91752. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  91753. }
  91754. if( pParse->nErr ){
  91755. sqlite3KeyInfoUnref(pKey);
  91756. pKey = 0;
  91757. }
  91758. }
  91759. return pKey;
  91760. }
  91761. #ifndef SQLITE_OMIT_CTE
  91762. /*
  91763. ** This routine is invoked once per CTE by the parser while parsing a
  91764. ** WITH clause.
  91765. */
  91766. SQLITE_PRIVATE With *sqlite3WithAdd(
  91767. Parse *pParse, /* Parsing context */
  91768. With *pWith, /* Existing WITH clause, or NULL */
  91769. Token *pName, /* Name of the common-table */
  91770. ExprList *pArglist, /* Optional column name list for the table */
  91771. Select *pQuery /* Query used to initialize the table */
  91772. ){
  91773. sqlite3 *db = pParse->db;
  91774. With *pNew;
  91775. char *zName;
  91776. /* Check that the CTE name is unique within this WITH clause. If
  91777. ** not, store an error in the Parse structure. */
  91778. zName = sqlite3NameFromToken(pParse->db, pName);
  91779. if( zName && pWith ){
  91780. int i;
  91781. for(i=0; i<pWith->nCte; i++){
  91782. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  91783. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  91784. }
  91785. }
  91786. }
  91787. if( pWith ){
  91788. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  91789. pNew = sqlite3DbRealloc(db, pWith, nByte);
  91790. }else{
  91791. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  91792. }
  91793. assert( zName!=0 || pNew==0 );
  91794. assert( db->mallocFailed==0 || pNew==0 );
  91795. if( pNew==0 ){
  91796. sqlite3ExprListDelete(db, pArglist);
  91797. sqlite3SelectDelete(db, pQuery);
  91798. sqlite3DbFree(db, zName);
  91799. pNew = pWith;
  91800. }else{
  91801. pNew->a[pNew->nCte].pSelect = pQuery;
  91802. pNew->a[pNew->nCte].pCols = pArglist;
  91803. pNew->a[pNew->nCte].zName = zName;
  91804. pNew->a[pNew->nCte].zCteErr = 0;
  91805. pNew->nCte++;
  91806. }
  91807. return pNew;
  91808. }
  91809. /*
  91810. ** Free the contents of the With object passed as the second argument.
  91811. */
  91812. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  91813. if( pWith ){
  91814. int i;
  91815. for(i=0; i<pWith->nCte; i++){
  91816. struct Cte *pCte = &pWith->a[i];
  91817. sqlite3ExprListDelete(db, pCte->pCols);
  91818. sqlite3SelectDelete(db, pCte->pSelect);
  91819. sqlite3DbFree(db, pCte->zName);
  91820. }
  91821. sqlite3DbFree(db, pWith);
  91822. }
  91823. }
  91824. #endif /* !defined(SQLITE_OMIT_CTE) */
  91825. /************** End of build.c ***********************************************/
  91826. /************** Begin file callback.c ****************************************/
  91827. /*
  91828. ** 2005 May 23
  91829. **
  91830. ** The author disclaims copyright to this source code. In place of
  91831. ** a legal notice, here is a blessing:
  91832. **
  91833. ** May you do good and not evil.
  91834. ** May you find forgiveness for yourself and forgive others.
  91835. ** May you share freely, never taking more than you give.
  91836. **
  91837. *************************************************************************
  91838. **
  91839. ** This file contains functions used to access the internal hash tables
  91840. ** of user defined functions and collation sequences.
  91841. */
  91842. /* #include "sqliteInt.h" */
  91843. /*
  91844. ** Invoke the 'collation needed' callback to request a collation sequence
  91845. ** in the encoding enc of name zName, length nName.
  91846. */
  91847. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  91848. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  91849. if( db->xCollNeeded ){
  91850. char *zExternal = sqlite3DbStrDup(db, zName);
  91851. if( !zExternal ) return;
  91852. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  91853. sqlite3DbFree(db, zExternal);
  91854. }
  91855. #ifndef SQLITE_OMIT_UTF16
  91856. if( db->xCollNeeded16 ){
  91857. char const *zExternal;
  91858. sqlite3_value *pTmp = sqlite3ValueNew(db);
  91859. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  91860. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  91861. if( zExternal ){
  91862. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  91863. }
  91864. sqlite3ValueFree(pTmp);
  91865. }
  91866. #endif
  91867. }
  91868. /*
  91869. ** This routine is called if the collation factory fails to deliver a
  91870. ** collation function in the best encoding but there may be other versions
  91871. ** of this collation function (for other text encodings) available. Use one
  91872. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  91873. ** possible.
  91874. */
  91875. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  91876. CollSeq *pColl2;
  91877. char *z = pColl->zName;
  91878. int i;
  91879. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  91880. for(i=0; i<3; i++){
  91881. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  91882. if( pColl2->xCmp!=0 ){
  91883. memcpy(pColl, pColl2, sizeof(CollSeq));
  91884. pColl->xDel = 0; /* Do not copy the destructor */
  91885. return SQLITE_OK;
  91886. }
  91887. }
  91888. return SQLITE_ERROR;
  91889. }
  91890. /*
  91891. ** This function is responsible for invoking the collation factory callback
  91892. ** or substituting a collation sequence of a different encoding when the
  91893. ** requested collation sequence is not available in the desired encoding.
  91894. **
  91895. ** If it is not NULL, then pColl must point to the database native encoding
  91896. ** collation sequence with name zName, length nName.
  91897. **
  91898. ** The return value is either the collation sequence to be used in database
  91899. ** db for collation type name zName, length nName, or NULL, if no collation
  91900. ** sequence can be found. If no collation is found, leave an error message.
  91901. **
  91902. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  91903. */
  91904. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  91905. Parse *pParse, /* Parsing context */
  91906. u8 enc, /* The desired encoding for the collating sequence */
  91907. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  91908. const char *zName /* Collating sequence name */
  91909. ){
  91910. CollSeq *p;
  91911. sqlite3 *db = pParse->db;
  91912. p = pColl;
  91913. if( !p ){
  91914. p = sqlite3FindCollSeq(db, enc, zName, 0);
  91915. }
  91916. if( !p || !p->xCmp ){
  91917. /* No collation sequence of this type for this encoding is registered.
  91918. ** Call the collation factory to see if it can supply us with one.
  91919. */
  91920. callCollNeeded(db, enc, zName);
  91921. p = sqlite3FindCollSeq(db, enc, zName, 0);
  91922. }
  91923. if( p && !p->xCmp && synthCollSeq(db, p) ){
  91924. p = 0;
  91925. }
  91926. assert( !p || p->xCmp );
  91927. if( p==0 ){
  91928. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  91929. }
  91930. return p;
  91931. }
  91932. /*
  91933. ** This routine is called on a collation sequence before it is used to
  91934. ** check that it is defined. An undefined collation sequence exists when
  91935. ** a database is loaded that contains references to collation sequences
  91936. ** that have not been defined by sqlite3_create_collation() etc.
  91937. **
  91938. ** If required, this routine calls the 'collation needed' callback to
  91939. ** request a definition of the collating sequence. If this doesn't work,
  91940. ** an equivalent collating sequence that uses a text encoding different
  91941. ** from the main database is substituted, if one is available.
  91942. */
  91943. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  91944. if( pColl ){
  91945. const char *zName = pColl->zName;
  91946. sqlite3 *db = pParse->db;
  91947. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  91948. if( !p ){
  91949. return SQLITE_ERROR;
  91950. }
  91951. assert( p==pColl );
  91952. }
  91953. return SQLITE_OK;
  91954. }
  91955. /*
  91956. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  91957. ** specified by zName and nName is not found and parameter 'create' is
  91958. ** true, then create a new entry. Otherwise return NULL.
  91959. **
  91960. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  91961. ** array of three CollSeq structures. The first is the collation sequence
  91962. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  91963. **
  91964. ** Stored immediately after the three collation sequences is a copy of
  91965. ** the collation sequence name. A pointer to this string is stored in
  91966. ** each collation sequence structure.
  91967. */
  91968. static CollSeq *findCollSeqEntry(
  91969. sqlite3 *db, /* Database connection */
  91970. const char *zName, /* Name of the collating sequence */
  91971. int create /* Create a new entry if true */
  91972. ){
  91973. CollSeq *pColl;
  91974. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  91975. if( 0==pColl && create ){
  91976. int nName = sqlite3Strlen30(zName);
  91977. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  91978. if( pColl ){
  91979. CollSeq *pDel = 0;
  91980. pColl[0].zName = (char*)&pColl[3];
  91981. pColl[0].enc = SQLITE_UTF8;
  91982. pColl[1].zName = (char*)&pColl[3];
  91983. pColl[1].enc = SQLITE_UTF16LE;
  91984. pColl[2].zName = (char*)&pColl[3];
  91985. pColl[2].enc = SQLITE_UTF16BE;
  91986. memcpy(pColl[0].zName, zName, nName);
  91987. pColl[0].zName[nName] = 0;
  91988. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  91989. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  91990. ** return the pColl pointer to be deleted (because it wasn't added
  91991. ** to the hash table).
  91992. */
  91993. assert( pDel==0 || pDel==pColl );
  91994. if( pDel!=0 ){
  91995. db->mallocFailed = 1;
  91996. sqlite3DbFree(db, pDel);
  91997. pColl = 0;
  91998. }
  91999. }
  92000. }
  92001. return pColl;
  92002. }
  92003. /*
  92004. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  92005. ** Return the CollSeq* pointer for the collation sequence named zName
  92006. ** for the encoding 'enc' from the database 'db'.
  92007. **
  92008. ** If the entry specified is not found and 'create' is true, then create a
  92009. ** new entry. Otherwise return NULL.
  92010. **
  92011. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  92012. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  92013. ** if necessary and generates an error message if the collating sequence
  92014. ** cannot be found.
  92015. **
  92016. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  92017. */
  92018. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  92019. sqlite3 *db,
  92020. u8 enc,
  92021. const char *zName,
  92022. int create
  92023. ){
  92024. CollSeq *pColl;
  92025. if( zName ){
  92026. pColl = findCollSeqEntry(db, zName, create);
  92027. }else{
  92028. pColl = db->pDfltColl;
  92029. }
  92030. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  92031. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  92032. if( pColl ) pColl += enc-1;
  92033. return pColl;
  92034. }
  92035. /* During the search for the best function definition, this procedure
  92036. ** is called to test how well the function passed as the first argument
  92037. ** matches the request for a function with nArg arguments in a system
  92038. ** that uses encoding enc. The value returned indicates how well the
  92039. ** request is matched. A higher value indicates a better match.
  92040. **
  92041. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  92042. ** is also -1. In other words, we are searching for a function that
  92043. ** takes a variable number of arguments.
  92044. **
  92045. ** If nArg is -2 that means that we are searching for any function
  92046. ** regardless of the number of arguments it uses, so return a positive
  92047. ** match score for any
  92048. **
  92049. ** The returned value is always between 0 and 6, as follows:
  92050. **
  92051. ** 0: Not a match.
  92052. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  92053. ** 2: UTF16 byte order change required and function takes any number of args.
  92054. ** 3: encoding matches and function takes any number of arguments
  92055. ** 4: UTF8/16 conversion required - argument count matches exactly
  92056. ** 5: UTF16 byte order conversion required - argument count matches exactly
  92057. ** 6: Perfect match: encoding and argument count match exactly.
  92058. **
  92059. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  92060. ** a perfect match and any function with both xStep and xFunc NULL is
  92061. ** a non-match.
  92062. */
  92063. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  92064. static int matchQuality(
  92065. FuncDef *p, /* The function we are evaluating for match quality */
  92066. int nArg, /* Desired number of arguments. (-1)==any */
  92067. u8 enc /* Desired text encoding */
  92068. ){
  92069. int match;
  92070. /* nArg of -2 is a special case */
  92071. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  92072. /* Wrong number of arguments means "no match" */
  92073. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  92074. /* Give a better score to a function with a specific number of arguments
  92075. ** than to function that accepts any number of arguments. */
  92076. if( p->nArg==nArg ){
  92077. match = 4;
  92078. }else{
  92079. match = 1;
  92080. }
  92081. /* Bonus points if the text encoding matches */
  92082. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  92083. match += 2; /* Exact encoding match */
  92084. }else if( (enc & p->funcFlags & 2)!=0 ){
  92085. match += 1; /* Both are UTF16, but with different byte orders */
  92086. }
  92087. return match;
  92088. }
  92089. /*
  92090. ** Search a FuncDefHash for a function with the given name. Return
  92091. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  92092. */
  92093. static FuncDef *functionSearch(
  92094. FuncDefHash *pHash, /* Hash table to search */
  92095. int h, /* Hash of the name */
  92096. const char *zFunc, /* Name of function */
  92097. int nFunc /* Number of bytes in zFunc */
  92098. ){
  92099. FuncDef *p;
  92100. for(p=pHash->a[h]; p; p=p->pHash){
  92101. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  92102. return p;
  92103. }
  92104. }
  92105. return 0;
  92106. }
  92107. /*
  92108. ** Insert a new FuncDef into a FuncDefHash hash table.
  92109. */
  92110. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  92111. FuncDefHash *pHash, /* The hash table into which to insert */
  92112. FuncDef *pDef /* The function definition to insert */
  92113. ){
  92114. FuncDef *pOther;
  92115. int nName = sqlite3Strlen30(pDef->zName);
  92116. u8 c1 = (u8)pDef->zName[0];
  92117. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  92118. pOther = functionSearch(pHash, h, pDef->zName, nName);
  92119. if( pOther ){
  92120. assert( pOther!=pDef && pOther->pNext!=pDef );
  92121. pDef->pNext = pOther->pNext;
  92122. pOther->pNext = pDef;
  92123. }else{
  92124. pDef->pNext = 0;
  92125. pDef->pHash = pHash->a[h];
  92126. pHash->a[h] = pDef;
  92127. }
  92128. }
  92129. /*
  92130. ** Locate a user function given a name, a number of arguments and a flag
  92131. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  92132. ** pointer to the FuncDef structure that defines that function, or return
  92133. ** NULL if the function does not exist.
  92134. **
  92135. ** If the createFlag argument is true, then a new (blank) FuncDef
  92136. ** structure is created and liked into the "db" structure if a
  92137. ** no matching function previously existed.
  92138. **
  92139. ** If nArg is -2, then the first valid function found is returned. A
  92140. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  92141. ** case is used to see if zName is a valid function name for some number
  92142. ** of arguments. If nArg is -2, then createFlag must be 0.
  92143. **
  92144. ** If createFlag is false, then a function with the required name and
  92145. ** number of arguments may be returned even if the eTextRep flag does not
  92146. ** match that requested.
  92147. */
  92148. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  92149. sqlite3 *db, /* An open database */
  92150. const char *zName, /* Name of the function. Not null-terminated */
  92151. int nName, /* Number of characters in the name */
  92152. int nArg, /* Number of arguments. -1 means any number */
  92153. u8 enc, /* Preferred text encoding */
  92154. u8 createFlag /* Create new entry if true and does not otherwise exist */
  92155. ){
  92156. FuncDef *p; /* Iterator variable */
  92157. FuncDef *pBest = 0; /* Best match found so far */
  92158. int bestScore = 0; /* Score of best match */
  92159. int h; /* Hash value */
  92160. assert( nArg>=(-2) );
  92161. assert( nArg>=(-1) || createFlag==0 );
  92162. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  92163. /* First search for a match amongst the application-defined functions.
  92164. */
  92165. p = functionSearch(&db->aFunc, h, zName, nName);
  92166. while( p ){
  92167. int score = matchQuality(p, nArg, enc);
  92168. if( score>bestScore ){
  92169. pBest = p;
  92170. bestScore = score;
  92171. }
  92172. p = p->pNext;
  92173. }
  92174. /* If no match is found, search the built-in functions.
  92175. **
  92176. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  92177. ** functions even if a prior app-defined function was found. And give
  92178. ** priority to built-in functions.
  92179. **
  92180. ** Except, if createFlag is true, that means that we are trying to
  92181. ** install a new function. Whatever FuncDef structure is returned it will
  92182. ** have fields overwritten with new information appropriate for the
  92183. ** new function. But the FuncDefs for built-in functions are read-only.
  92184. ** So we must not search for built-ins when creating a new function.
  92185. */
  92186. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  92187. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  92188. bestScore = 0;
  92189. p = functionSearch(pHash, h, zName, nName);
  92190. while( p ){
  92191. int score = matchQuality(p, nArg, enc);
  92192. if( score>bestScore ){
  92193. pBest = p;
  92194. bestScore = score;
  92195. }
  92196. p = p->pNext;
  92197. }
  92198. }
  92199. /* If the createFlag parameter is true and the search did not reveal an
  92200. ** exact match for the name, number of arguments and encoding, then add a
  92201. ** new entry to the hash table and return it.
  92202. */
  92203. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  92204. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  92205. pBest->zName = (char *)&pBest[1];
  92206. pBest->nArg = (u16)nArg;
  92207. pBest->funcFlags = enc;
  92208. memcpy(pBest->zName, zName, nName);
  92209. pBest->zName[nName] = 0;
  92210. sqlite3FuncDefInsert(&db->aFunc, pBest);
  92211. }
  92212. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  92213. return pBest;
  92214. }
  92215. return 0;
  92216. }
  92217. /*
  92218. ** Free all resources held by the schema structure. The void* argument points
  92219. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  92220. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  92221. ** of the schema hash tables).
  92222. **
  92223. ** The Schema.cache_size variable is not cleared.
  92224. */
  92225. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  92226. Hash temp1;
  92227. Hash temp2;
  92228. HashElem *pElem;
  92229. Schema *pSchema = (Schema *)p;
  92230. temp1 = pSchema->tblHash;
  92231. temp2 = pSchema->trigHash;
  92232. sqlite3HashInit(&pSchema->trigHash);
  92233. sqlite3HashClear(&pSchema->idxHash);
  92234. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  92235. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  92236. }
  92237. sqlite3HashClear(&temp2);
  92238. sqlite3HashInit(&pSchema->tblHash);
  92239. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  92240. Table *pTab = sqliteHashData(pElem);
  92241. sqlite3DeleteTable(0, pTab);
  92242. }
  92243. sqlite3HashClear(&temp1);
  92244. sqlite3HashClear(&pSchema->fkeyHash);
  92245. pSchema->pSeqTab = 0;
  92246. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  92247. pSchema->iGeneration++;
  92248. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  92249. }
  92250. }
  92251. /*
  92252. ** Find and return the schema associated with a BTree. Create
  92253. ** a new one if necessary.
  92254. */
  92255. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  92256. Schema * p;
  92257. if( pBt ){
  92258. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  92259. }else{
  92260. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  92261. }
  92262. if( !p ){
  92263. db->mallocFailed = 1;
  92264. }else if ( 0==p->file_format ){
  92265. sqlite3HashInit(&p->tblHash);
  92266. sqlite3HashInit(&p->idxHash);
  92267. sqlite3HashInit(&p->trigHash);
  92268. sqlite3HashInit(&p->fkeyHash);
  92269. p->enc = SQLITE_UTF8;
  92270. }
  92271. return p;
  92272. }
  92273. /************** End of callback.c ********************************************/
  92274. /************** Begin file delete.c ******************************************/
  92275. /*
  92276. ** 2001 September 15
  92277. **
  92278. ** The author disclaims copyright to this source code. In place of
  92279. ** a legal notice, here is a blessing:
  92280. **
  92281. ** May you do good and not evil.
  92282. ** May you find forgiveness for yourself and forgive others.
  92283. ** May you share freely, never taking more than you give.
  92284. **
  92285. *************************************************************************
  92286. ** This file contains C code routines that are called by the parser
  92287. ** in order to generate code for DELETE FROM statements.
  92288. */
  92289. /* #include "sqliteInt.h" */
  92290. /*
  92291. ** While a SrcList can in general represent multiple tables and subqueries
  92292. ** (as in the FROM clause of a SELECT statement) in this case it contains
  92293. ** the name of a single table, as one might find in an INSERT, DELETE,
  92294. ** or UPDATE statement. Look up that table in the symbol table and
  92295. ** return a pointer. Set an error message and return NULL if the table
  92296. ** name is not found or if any other error occurs.
  92297. **
  92298. ** The following fields are initialized appropriate in pSrc:
  92299. **
  92300. ** pSrc->a[0].pTab Pointer to the Table object
  92301. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  92302. **
  92303. */
  92304. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  92305. struct SrcList_item *pItem = pSrc->a;
  92306. Table *pTab;
  92307. assert( pItem && pSrc->nSrc==1 );
  92308. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  92309. sqlite3DeleteTable(pParse->db, pItem->pTab);
  92310. pItem->pTab = pTab;
  92311. if( pTab ){
  92312. pTab->nRef++;
  92313. }
  92314. if( sqlite3IndexedByLookup(pParse, pItem) ){
  92315. pTab = 0;
  92316. }
  92317. return pTab;
  92318. }
  92319. /*
  92320. ** Check to make sure the given table is writable. If it is not
  92321. ** writable, generate an error message and return 1. If it is
  92322. ** writable return 0;
  92323. */
  92324. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  92325. /* A table is not writable under the following circumstances:
  92326. **
  92327. ** 1) It is a virtual table and no implementation of the xUpdate method
  92328. ** has been provided, or
  92329. ** 2) It is a system table (i.e. sqlite_master), this call is not
  92330. ** part of a nested parse and writable_schema pragma has not
  92331. ** been specified.
  92332. **
  92333. ** In either case leave an error message in pParse and return non-zero.
  92334. */
  92335. if( ( IsVirtual(pTab)
  92336. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  92337. || ( (pTab->tabFlags & TF_Readonly)!=0
  92338. && (pParse->db->flags & SQLITE_WriteSchema)==0
  92339. && pParse->nested==0 )
  92340. ){
  92341. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  92342. return 1;
  92343. }
  92344. #ifndef SQLITE_OMIT_VIEW
  92345. if( !viewOk && pTab->pSelect ){
  92346. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  92347. return 1;
  92348. }
  92349. #endif
  92350. return 0;
  92351. }
  92352. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  92353. /*
  92354. ** Evaluate a view and store its result in an ephemeral table. The
  92355. ** pWhere argument is an optional WHERE clause that restricts the
  92356. ** set of rows in the view that are to be added to the ephemeral table.
  92357. */
  92358. SQLITE_PRIVATE void sqlite3MaterializeView(
  92359. Parse *pParse, /* Parsing context */
  92360. Table *pView, /* View definition */
  92361. Expr *pWhere, /* Optional WHERE clause to be added */
  92362. int iCur /* Cursor number for ephemeral table */
  92363. ){
  92364. SelectDest dest;
  92365. Select *pSel;
  92366. SrcList *pFrom;
  92367. sqlite3 *db = pParse->db;
  92368. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  92369. pWhere = sqlite3ExprDup(db, pWhere, 0);
  92370. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  92371. if( pFrom ){
  92372. assert( pFrom->nSrc==1 );
  92373. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  92374. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  92375. assert( pFrom->a[0].pOn==0 );
  92376. assert( pFrom->a[0].pUsing==0 );
  92377. }
  92378. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
  92379. SF_IncludeHidden, 0, 0);
  92380. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  92381. sqlite3Select(pParse, pSel, &dest);
  92382. sqlite3SelectDelete(db, pSel);
  92383. }
  92384. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  92385. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  92386. /*
  92387. ** Generate an expression tree to implement the WHERE, ORDER BY,
  92388. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  92389. **
  92390. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  92391. ** \__________________________/
  92392. ** pLimitWhere (pInClause)
  92393. */
  92394. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  92395. Parse *pParse, /* The parser context */
  92396. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  92397. Expr *pWhere, /* The WHERE clause. May be null */
  92398. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  92399. Expr *pLimit, /* The LIMIT clause. May be null */
  92400. Expr *pOffset, /* The OFFSET clause. May be null */
  92401. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  92402. ){
  92403. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  92404. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  92405. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  92406. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  92407. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  92408. Select *pSelect = NULL; /* Complete SELECT tree */
  92409. /* Check that there isn't an ORDER BY without a LIMIT clause.
  92410. */
  92411. if( pOrderBy && (pLimit == 0) ) {
  92412. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  92413. goto limit_where_cleanup_2;
  92414. }
  92415. /* We only need to generate a select expression if there
  92416. ** is a limit/offset term to enforce.
  92417. */
  92418. if( pLimit == 0 ) {
  92419. /* if pLimit is null, pOffset will always be null as well. */
  92420. assert( pOffset == 0 );
  92421. return pWhere;
  92422. }
  92423. /* Generate a select expression tree to enforce the limit/offset
  92424. ** term for the DELETE or UPDATE statement. For example:
  92425. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  92426. ** becomes:
  92427. ** DELETE FROM table_a WHERE rowid IN (
  92428. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  92429. ** );
  92430. */
  92431. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  92432. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  92433. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  92434. if( pEList == 0 ) goto limit_where_cleanup_2;
  92435. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  92436. ** and the SELECT subtree. */
  92437. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  92438. if( pSelectSrc == 0 ) {
  92439. sqlite3ExprListDelete(pParse->db, pEList);
  92440. goto limit_where_cleanup_2;
  92441. }
  92442. /* generate the SELECT expression tree. */
  92443. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  92444. pOrderBy,0,pLimit,pOffset);
  92445. if( pSelect == 0 ) return 0;
  92446. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  92447. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  92448. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  92449. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  92450. if( pInClause == 0 ) goto limit_where_cleanup_1;
  92451. pInClause->x.pSelect = pSelect;
  92452. pInClause->flags |= EP_xIsSelect;
  92453. sqlite3ExprSetHeightAndFlags(pParse, pInClause);
  92454. return pInClause;
  92455. /* something went wrong. clean up anything allocated. */
  92456. limit_where_cleanup_1:
  92457. sqlite3SelectDelete(pParse->db, pSelect);
  92458. return 0;
  92459. limit_where_cleanup_2:
  92460. sqlite3ExprDelete(pParse->db, pWhere);
  92461. sqlite3ExprListDelete(pParse->db, pOrderBy);
  92462. sqlite3ExprDelete(pParse->db, pLimit);
  92463. sqlite3ExprDelete(pParse->db, pOffset);
  92464. return 0;
  92465. }
  92466. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  92467. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  92468. /*
  92469. ** Generate code for a DELETE FROM statement.
  92470. **
  92471. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  92472. ** \________/ \________________/
  92473. ** pTabList pWhere
  92474. */
  92475. SQLITE_PRIVATE void sqlite3DeleteFrom(
  92476. Parse *pParse, /* The parser context */
  92477. SrcList *pTabList, /* The table from which we should delete things */
  92478. Expr *pWhere /* The WHERE clause. May be null */
  92479. ){
  92480. Vdbe *v; /* The virtual database engine */
  92481. Table *pTab; /* The table from which records will be deleted */
  92482. const char *zDb; /* Name of database holding pTab */
  92483. int i; /* Loop counter */
  92484. WhereInfo *pWInfo; /* Information about the WHERE clause */
  92485. Index *pIdx; /* For looping over indices of the table */
  92486. int iTabCur; /* Cursor number for the table */
  92487. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  92488. int iIdxCur = 0; /* Cursor number of the first index */
  92489. int nIdx; /* Number of indices */
  92490. sqlite3 *db; /* Main database structure */
  92491. AuthContext sContext; /* Authorization context */
  92492. NameContext sNC; /* Name context to resolve expressions in */
  92493. int iDb; /* Database number */
  92494. int memCnt = -1; /* Memory cell used for change counting */
  92495. int rcauth; /* Value returned by authorization callback */
  92496. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  92497. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  92498. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  92499. Index *pPk; /* The PRIMARY KEY index on the table */
  92500. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  92501. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  92502. int iKey; /* Memory cell holding key of row to be deleted */
  92503. i16 nKey; /* Number of memory cells in the row key */
  92504. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  92505. int iRowSet = 0; /* Register for rowset of rows to delete */
  92506. int addrBypass = 0; /* Address of jump over the delete logic */
  92507. int addrLoop = 0; /* Top of the delete loop */
  92508. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  92509. #ifndef SQLITE_OMIT_TRIGGER
  92510. int isView; /* True if attempting to delete from a view */
  92511. Trigger *pTrigger; /* List of table triggers, if required */
  92512. int bComplex; /* True if there are either triggers or FKs */
  92513. #endif
  92514. memset(&sContext, 0, sizeof(sContext));
  92515. db = pParse->db;
  92516. if( pParse->nErr || db->mallocFailed ){
  92517. goto delete_from_cleanup;
  92518. }
  92519. assert( pTabList->nSrc==1 );
  92520. /* Locate the table which we want to delete. This table has to be
  92521. ** put in an SrcList structure because some of the subroutines we
  92522. ** will be calling are designed to work with multiple tables and expect
  92523. ** an SrcList* parameter instead of just a Table* parameter.
  92524. */
  92525. pTab = sqlite3SrcListLookup(pParse, pTabList);
  92526. if( pTab==0 ) goto delete_from_cleanup;
  92527. /* Figure out if we have any triggers and if the table being
  92528. ** deleted from is a view
  92529. */
  92530. #ifndef SQLITE_OMIT_TRIGGER
  92531. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  92532. isView = pTab->pSelect!=0;
  92533. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  92534. #else
  92535. # define pTrigger 0
  92536. # define isView 0
  92537. # define bComplex 0
  92538. #endif
  92539. #ifdef SQLITE_OMIT_VIEW
  92540. # undef isView
  92541. # define isView 0
  92542. #endif
  92543. /* If pTab is really a view, make sure it has been initialized.
  92544. */
  92545. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  92546. goto delete_from_cleanup;
  92547. }
  92548. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  92549. goto delete_from_cleanup;
  92550. }
  92551. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  92552. assert( iDb<db->nDb );
  92553. zDb = db->aDb[iDb].zName;
  92554. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  92555. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  92556. if( rcauth==SQLITE_DENY ){
  92557. goto delete_from_cleanup;
  92558. }
  92559. assert(!isView || pTrigger);
  92560. /* Assign cursor numbers to the table and all its indices.
  92561. */
  92562. assert( pTabList->nSrc==1 );
  92563. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  92564. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  92565. pParse->nTab++;
  92566. }
  92567. /* Start the view context
  92568. */
  92569. if( isView ){
  92570. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  92571. }
  92572. /* Begin generating code.
  92573. */
  92574. v = sqlite3GetVdbe(pParse);
  92575. if( v==0 ){
  92576. goto delete_from_cleanup;
  92577. }
  92578. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  92579. sqlite3BeginWriteOperation(pParse, 1, iDb);
  92580. /* If we are trying to delete from a view, realize that view into
  92581. ** an ephemeral table.
  92582. */
  92583. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  92584. if( isView ){
  92585. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  92586. iDataCur = iIdxCur = iTabCur;
  92587. }
  92588. #endif
  92589. /* Resolve the column names in the WHERE clause.
  92590. */
  92591. memset(&sNC, 0, sizeof(sNC));
  92592. sNC.pParse = pParse;
  92593. sNC.pSrcList = pTabList;
  92594. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  92595. goto delete_from_cleanup;
  92596. }
  92597. /* Initialize the counter of the number of rows deleted, if
  92598. ** we are counting rows.
  92599. */
  92600. if( db->flags & SQLITE_CountRows ){
  92601. memCnt = ++pParse->nMem;
  92602. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  92603. }
  92604. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  92605. /* Special case: A DELETE without a WHERE clause deletes everything.
  92606. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  92607. ** this optimization caused the row change count (the value returned by
  92608. ** API function sqlite3_count_changes) to be set incorrectly. */
  92609. if( rcauth==SQLITE_OK
  92610. && pWhere==0
  92611. && !bComplex
  92612. && !IsVirtual(pTab)
  92613. ){
  92614. assert( !isView );
  92615. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  92616. if( HasRowid(pTab) ){
  92617. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  92618. pTab->zName, P4_STATIC);
  92619. }
  92620. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  92621. assert( pIdx->pSchema==pTab->pSchema );
  92622. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  92623. }
  92624. }else
  92625. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  92626. {
  92627. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
  92628. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  92629. if( HasRowid(pTab) ){
  92630. /* For a rowid table, initialize the RowSet to an empty set */
  92631. pPk = 0;
  92632. nPk = 1;
  92633. iRowSet = ++pParse->nMem;
  92634. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  92635. }else{
  92636. /* For a WITHOUT ROWID table, create an ephemeral table used to
  92637. ** hold all primary keys for rows to be deleted. */
  92638. pPk = sqlite3PrimaryKeyIndex(pTab);
  92639. assert( pPk!=0 );
  92640. nPk = pPk->nKeyCol;
  92641. iPk = pParse->nMem+1;
  92642. pParse->nMem += nPk;
  92643. iEphCur = pParse->nTab++;
  92644. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  92645. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  92646. }
  92647. /* Construct a query to find the rowid or primary key for every row
  92648. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  92649. ** to indicate the strategy used to implement this delete:
  92650. **
  92651. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  92652. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  92653. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  92654. */
  92655. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  92656. if( pWInfo==0 ) goto delete_from_cleanup;
  92657. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  92658. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  92659. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  92660. /* Keep track of the number of rows to be deleted */
  92661. if( db->flags & SQLITE_CountRows ){
  92662. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  92663. }
  92664. /* Extract the rowid or primary key for the current row */
  92665. if( pPk ){
  92666. for(i=0; i<nPk; i++){
  92667. assert( pPk->aiColumn[i]>=0 );
  92668. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  92669. pPk->aiColumn[i], iPk+i);
  92670. }
  92671. iKey = iPk;
  92672. }else{
  92673. iKey = pParse->nMem + 1;
  92674. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  92675. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  92676. }
  92677. if( eOnePass!=ONEPASS_OFF ){
  92678. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  92679. ** one, so just keep it in its register(s) and fall through to the
  92680. ** delete code. */
  92681. nKey = nPk; /* OP_Found will use an unpacked key */
  92682. aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
  92683. if( aToOpen==0 ){
  92684. sqlite3WhereEnd(pWInfo);
  92685. goto delete_from_cleanup;
  92686. }
  92687. memset(aToOpen, 1, nIdx+1);
  92688. aToOpen[nIdx+1] = 0;
  92689. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  92690. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  92691. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  92692. }else{
  92693. if( pPk ){
  92694. /* Add the PK key for this row to the temporary table */
  92695. iKey = ++pParse->nMem;
  92696. nKey = 0; /* Zero tells OP_Found to use a composite key */
  92697. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  92698. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  92699. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
  92700. }else{
  92701. /* Add the rowid of the row to be deleted to the RowSet */
  92702. nKey = 1; /* OP_Seek always uses a single rowid */
  92703. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  92704. }
  92705. }
  92706. /* If this DELETE cannot use the ONEPASS strategy, this is the
  92707. ** end of the WHERE loop */
  92708. if( eOnePass!=ONEPASS_OFF ){
  92709. addrBypass = sqlite3VdbeMakeLabel(v);
  92710. }else{
  92711. sqlite3WhereEnd(pWInfo);
  92712. }
  92713. /* Unless this is a view, open cursors for the table we are
  92714. ** deleting from and all its indices. If this is a view, then the
  92715. ** only effect this statement has is to fire the INSTEAD OF
  92716. ** triggers.
  92717. */
  92718. if( !isView ){
  92719. int iAddrOnce = 0;
  92720. u8 p5 = (eOnePass==ONEPASS_OFF ? 0 : OPFLAG_FORDELETE);
  92721. if( eOnePass==ONEPASS_MULTI ){
  92722. iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  92723. }
  92724. testcase( IsVirtual(pTab) );
  92725. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, p5, iTabCur,
  92726. aToOpen, &iDataCur, &iIdxCur);
  92727. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  92728. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  92729. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  92730. }
  92731. /* Set up a loop over the rowids/primary-keys that were found in the
  92732. ** where-clause loop above.
  92733. */
  92734. if( eOnePass!=ONEPASS_OFF ){
  92735. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  92736. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  92737. assert( pPk!=0 || pTab->pSelect!=0 );
  92738. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  92739. VdbeCoverage(v);
  92740. }
  92741. }else if( pPk ){
  92742. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  92743. sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
  92744. assert( nKey==0 ); /* OP_Found will use a composite key */
  92745. }else{
  92746. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  92747. VdbeCoverage(v);
  92748. assert( nKey==1 );
  92749. }
  92750. /* Delete the row */
  92751. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92752. if( IsVirtual(pTab) ){
  92753. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  92754. sqlite3VtabMakeWritable(pParse, pTab);
  92755. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  92756. sqlite3VdbeChangeP5(v, OE_Abort);
  92757. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  92758. sqlite3MayAbort(pParse);
  92759. if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
  92760. pParse->isMultiWrite = 0;
  92761. }
  92762. }else
  92763. #endif
  92764. {
  92765. int count = (pParse->nested==0); /* True to count changes */
  92766. int iIdxNoSeek = -1;
  92767. if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
  92768. iIdxNoSeek = aiCurOnePass[1];
  92769. }
  92770. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  92771. iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
  92772. }
  92773. /* End of the loop over all rowids/primary-keys. */
  92774. if( eOnePass!=ONEPASS_OFF ){
  92775. sqlite3VdbeResolveLabel(v, addrBypass);
  92776. sqlite3WhereEnd(pWInfo);
  92777. }else if( pPk ){
  92778. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  92779. sqlite3VdbeJumpHere(v, addrLoop);
  92780. }else{
  92781. sqlite3VdbeGoto(v, addrLoop);
  92782. sqlite3VdbeJumpHere(v, addrLoop);
  92783. }
  92784. /* Close the cursors open on the table and its indexes. */
  92785. if( !isView && !IsVirtual(pTab) ){
  92786. if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  92787. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  92788. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
  92789. }
  92790. }
  92791. } /* End non-truncate path */
  92792. /* Update the sqlite_sequence table by storing the content of the
  92793. ** maximum rowid counter values recorded while inserting into
  92794. ** autoincrement tables.
  92795. */
  92796. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  92797. sqlite3AutoincrementEnd(pParse);
  92798. }
  92799. /* Return the number of rows that were deleted. If this routine is
  92800. ** generating code because of a call to sqlite3NestedParse(), do not
  92801. ** invoke the callback function.
  92802. */
  92803. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  92804. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  92805. sqlite3VdbeSetNumCols(v, 1);
  92806. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  92807. }
  92808. delete_from_cleanup:
  92809. sqlite3AuthContextPop(&sContext);
  92810. sqlite3SrcListDelete(db, pTabList);
  92811. sqlite3ExprDelete(db, pWhere);
  92812. sqlite3DbFree(db, aToOpen);
  92813. return;
  92814. }
  92815. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  92816. ** they may interfere with compilation of other functions in this file
  92817. ** (or in another file, if this file becomes part of the amalgamation). */
  92818. #ifdef isView
  92819. #undef isView
  92820. #endif
  92821. #ifdef pTrigger
  92822. #undef pTrigger
  92823. #endif
  92824. /*
  92825. ** This routine generates VDBE code that causes a single row of a
  92826. ** single table to be deleted. Both the original table entry and
  92827. ** all indices are removed.
  92828. **
  92829. ** Preconditions:
  92830. **
  92831. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  92832. ** store for the table. (This will be either the table itself,
  92833. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  92834. ** of a WITHOUT ROWID table.)
  92835. **
  92836. ** 2. Read/write cursors for all indices of pTab must be open as
  92837. ** cursor number iIdxCur+i for the i-th index.
  92838. **
  92839. ** 3. The primary key for the row to be deleted must be stored in a
  92840. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  92841. ** that a search record formed from OP_MakeRecord is contained in the
  92842. ** single memory location iPk.
  92843. **
  92844. ** eMode:
  92845. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  92846. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  92847. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  92848. ** then this function must seek iDataCur to the entry identified by iPk
  92849. ** and nPk before reading from it.
  92850. **
  92851. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  92852. ** of a ONEPASS delete that affects multiple rows. In this case, if
  92853. ** iIdxNoSeek is a valid cursor number (>=0), then its position should
  92854. ** be preserved following the delete operation. Or, if iIdxNoSeek is not
  92855. ** a valid cursor number, the position of iDataCur should be preserved
  92856. ** instead.
  92857. **
  92858. ** iIdxNoSeek:
  92859. ** If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
  92860. ** index cursor (from within array of cursors starting at iIdxCur) that
  92861. ** already points to the index entry to be deleted.
  92862. */
  92863. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  92864. Parse *pParse, /* Parsing context */
  92865. Table *pTab, /* Table containing the row to be deleted */
  92866. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  92867. int iDataCur, /* Cursor from which column data is extracted */
  92868. int iIdxCur, /* First index cursor */
  92869. int iPk, /* First memory cell containing the PRIMARY KEY */
  92870. i16 nPk, /* Number of PRIMARY KEY memory cells */
  92871. u8 count, /* If non-zero, increment the row change counter */
  92872. u8 onconf, /* Default ON CONFLICT policy for triggers */
  92873. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  92874. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  92875. ){
  92876. Vdbe *v = pParse->pVdbe; /* Vdbe */
  92877. int iOld = 0; /* First register in OLD.* array */
  92878. int iLabel; /* Label resolved to end of generated code */
  92879. u8 opSeek; /* Seek opcode */
  92880. /* Vdbe is guaranteed to have been allocated by this stage. */
  92881. assert( v );
  92882. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  92883. iDataCur, iIdxCur, iPk, (int)nPk));
  92884. /* Seek cursor iCur to the row to delete. If this row no longer exists
  92885. ** (this can happen if a trigger program has already deleted it), do
  92886. ** not attempt to delete it or fire any DELETE triggers. */
  92887. iLabel = sqlite3VdbeMakeLabel(v);
  92888. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  92889. if( eMode==ONEPASS_OFF ){
  92890. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  92891. VdbeCoverageIf(v, opSeek==OP_NotExists);
  92892. VdbeCoverageIf(v, opSeek==OP_NotFound);
  92893. }
  92894. /* If there are any triggers to fire, allocate a range of registers to
  92895. ** use for the old.* references in the triggers. */
  92896. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  92897. u32 mask; /* Mask of OLD.* columns in use */
  92898. int iCol; /* Iterator used while populating OLD.* */
  92899. int addrStart; /* Start of BEFORE trigger programs */
  92900. /* TODO: Could use temporary registers here. Also could attempt to
  92901. ** avoid copying the contents of the rowid register. */
  92902. mask = sqlite3TriggerColmask(
  92903. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  92904. );
  92905. mask |= sqlite3FkOldmask(pParse, pTab);
  92906. iOld = pParse->nMem+1;
  92907. pParse->nMem += (1 + pTab->nCol);
  92908. /* Populate the OLD.* pseudo-table register array. These values will be
  92909. ** used by any BEFORE and AFTER triggers that exist. */
  92910. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  92911. for(iCol=0; iCol<pTab->nCol; iCol++){
  92912. testcase( mask!=0xffffffff && iCol==31 );
  92913. testcase( mask!=0xffffffff && iCol==32 );
  92914. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  92915. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  92916. }
  92917. }
  92918. /* Invoke BEFORE DELETE trigger programs. */
  92919. addrStart = sqlite3VdbeCurrentAddr(v);
  92920. sqlite3CodeRowTrigger(pParse, pTrigger,
  92921. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  92922. );
  92923. /* If any BEFORE triggers were coded, then seek the cursor to the
  92924. ** row to be deleted again. It may be that the BEFORE triggers moved
  92925. ** the cursor or of already deleted the row that the cursor was
  92926. ** pointing to.
  92927. */
  92928. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  92929. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  92930. VdbeCoverageIf(v, opSeek==OP_NotExists);
  92931. VdbeCoverageIf(v, opSeek==OP_NotFound);
  92932. }
  92933. /* Do FK processing. This call checks that any FK constraints that
  92934. ** refer to this table (i.e. constraints attached to other tables)
  92935. ** are not violated by deleting this row. */
  92936. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  92937. }
  92938. /* Delete the index and table entries. Skip this step if pTab is really
  92939. ** a view (in which case the only effect of the DELETE statement is to
  92940. ** fire the INSTEAD OF triggers). */
  92941. if( pTab->pSelect==0 ){
  92942. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  92943. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  92944. if( count ){
  92945. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  92946. }
  92947. if( iIdxNoSeek>=0 ){
  92948. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  92949. }
  92950. sqlite3VdbeChangeP5(v, eMode==ONEPASS_MULTI);
  92951. }
  92952. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  92953. ** handle rows (possibly in other tables) that refer via a foreign key
  92954. ** to the row just deleted. */
  92955. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  92956. /* Invoke AFTER DELETE trigger programs. */
  92957. sqlite3CodeRowTrigger(pParse, pTrigger,
  92958. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  92959. );
  92960. /* Jump here if the row had already been deleted before any BEFORE
  92961. ** trigger programs were invoked. Or if a trigger program throws a
  92962. ** RAISE(IGNORE) exception. */
  92963. sqlite3VdbeResolveLabel(v, iLabel);
  92964. VdbeModuleComment((v, "END: GenRowDel()"));
  92965. }
  92966. /*
  92967. ** This routine generates VDBE code that causes the deletion of all
  92968. ** index entries associated with a single row of a single table, pTab
  92969. **
  92970. ** Preconditions:
  92971. **
  92972. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  92973. ** btree for the table pTab. (This will be either the table itself
  92974. ** for rowid tables or to the primary key index for WITHOUT ROWID
  92975. ** tables.)
  92976. **
  92977. ** 2. Read/write cursors for all indices of pTab must be open as
  92978. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  92979. ** index is the 0-th index.)
  92980. **
  92981. ** 3. The "iDataCur" cursor must be already be positioned on the row
  92982. ** that is to be deleted.
  92983. */
  92984. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  92985. Parse *pParse, /* Parsing and code generating context */
  92986. Table *pTab, /* Table containing the row to be deleted */
  92987. int iDataCur, /* Cursor of table holding data. */
  92988. int iIdxCur, /* First index cursor */
  92989. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  92990. int iIdxNoSeek /* Do not delete from this cursor */
  92991. ){
  92992. int i; /* Index loop counter */
  92993. int r1 = -1; /* Register holding an index key */
  92994. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  92995. Index *pIdx; /* Current index */
  92996. Index *pPrior = 0; /* Prior index */
  92997. Vdbe *v; /* The prepared statement under construction */
  92998. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  92999. v = pParse->pVdbe;
  93000. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  93001. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  93002. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  93003. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  93004. if( pIdx==pPk ) continue;
  93005. if( iIdxCur+i==iIdxNoSeek ) continue;
  93006. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  93007. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  93008. &iPartIdxLabel, pPrior, r1);
  93009. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  93010. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  93011. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  93012. pPrior = pIdx;
  93013. }
  93014. }
  93015. /*
  93016. ** Generate code that will assemble an index key and stores it in register
  93017. ** regOut. The key with be for index pIdx which is an index on pTab.
  93018. ** iCur is the index of a cursor open on the pTab table and pointing to
  93019. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  93020. ** iCur must be the cursor of the PRIMARY KEY index.
  93021. **
  93022. ** Return a register number which is the first in a block of
  93023. ** registers that holds the elements of the index key. The
  93024. ** block of registers has already been deallocated by the time
  93025. ** this routine returns.
  93026. **
  93027. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  93028. ** to that label if pIdx is a partial index that should be skipped.
  93029. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  93030. ** A partial index should be skipped if its WHERE clause evaluates
  93031. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  93032. ** will be set to zero which is an empty label that is ignored by
  93033. ** sqlite3ResolvePartIdxLabel().
  93034. **
  93035. ** The pPrior and regPrior parameters are used to implement a cache to
  93036. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  93037. ** a pointer to a different index for which an index key has just been
  93038. ** computed into register regPrior. If the current pIdx index is generating
  93039. ** its key into the same sequence of registers and if pPrior and pIdx share
  93040. ** a column in common, then the register corresponding to that column already
  93041. ** holds the correct value and the loading of that register is skipped.
  93042. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  93043. ** on a table with multiple indices, and especially with the ROWID or
  93044. ** PRIMARY KEY columns of the index.
  93045. */
  93046. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  93047. Parse *pParse, /* Parsing context */
  93048. Index *pIdx, /* The index for which to generate a key */
  93049. int iDataCur, /* Cursor number from which to take column data */
  93050. int regOut, /* Put the new key into this register if not 0 */
  93051. int prefixOnly, /* Compute only a unique prefix of the key */
  93052. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  93053. Index *pPrior, /* Previously generated index key */
  93054. int regPrior /* Register holding previous generated key */
  93055. ){
  93056. Vdbe *v = pParse->pVdbe;
  93057. int j;
  93058. int regBase;
  93059. int nCol;
  93060. if( piPartIdxLabel ){
  93061. if( pIdx->pPartIdxWhere ){
  93062. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  93063. pParse->iSelfTab = iDataCur;
  93064. sqlite3ExprCachePush(pParse);
  93065. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  93066. SQLITE_JUMPIFNULL);
  93067. }else{
  93068. *piPartIdxLabel = 0;
  93069. }
  93070. }
  93071. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  93072. regBase = sqlite3GetTempRange(pParse, nCol);
  93073. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  93074. for(j=0; j<nCol; j++){
  93075. if( pPrior
  93076. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  93077. && pPrior->aiColumn[j]!=XN_EXPR
  93078. ){
  93079. /* This column was already computed by the previous index */
  93080. continue;
  93081. }
  93082. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  93083. /* If the column affinity is REAL but the number is an integer, then it
  93084. ** might be stored in the table as an integer (using a compact
  93085. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  93086. ** But we are getting ready to store this value back into an index, where
  93087. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  93088. ** opcode if it is present */
  93089. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  93090. }
  93091. if( regOut ){
  93092. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  93093. }
  93094. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  93095. return regBase;
  93096. }
  93097. /*
  93098. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  93099. ** because it was a partial index, then this routine should be called to
  93100. ** resolve that label.
  93101. */
  93102. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  93103. if( iLabel ){
  93104. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  93105. sqlite3ExprCachePop(pParse);
  93106. }
  93107. }
  93108. /************** End of delete.c **********************************************/
  93109. /************** Begin file func.c ********************************************/
  93110. /*
  93111. ** 2002 February 23
  93112. **
  93113. ** The author disclaims copyright to this source code. In place of
  93114. ** a legal notice, here is a blessing:
  93115. **
  93116. ** May you do good and not evil.
  93117. ** May you find forgiveness for yourself and forgive others.
  93118. ** May you share freely, never taking more than you give.
  93119. **
  93120. *************************************************************************
  93121. ** This file contains the C-language implementations for many of the SQL
  93122. ** functions of SQLite. (Some function, and in particular the date and
  93123. ** time functions, are implemented separately.)
  93124. */
  93125. /* #include "sqliteInt.h" */
  93126. /* #include <stdlib.h> */
  93127. /* #include <assert.h> */
  93128. /* #include "vdbeInt.h" */
  93129. /*
  93130. ** Return the collating function associated with a function.
  93131. */
  93132. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  93133. VdbeOp *pOp;
  93134. assert( context->pVdbe!=0 );
  93135. pOp = &context->pVdbe->aOp[context->iOp-1];
  93136. assert( pOp->opcode==OP_CollSeq );
  93137. assert( pOp->p4type==P4_COLLSEQ );
  93138. return pOp->p4.pColl;
  93139. }
  93140. /*
  93141. ** Indicate that the accumulator load should be skipped on this
  93142. ** iteration of the aggregate loop.
  93143. */
  93144. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  93145. context->skipFlag = 1;
  93146. }
  93147. /*
  93148. ** Implementation of the non-aggregate min() and max() functions
  93149. */
  93150. static void minmaxFunc(
  93151. sqlite3_context *context,
  93152. int argc,
  93153. sqlite3_value **argv
  93154. ){
  93155. int i;
  93156. int mask; /* 0 for min() or 0xffffffff for max() */
  93157. int iBest;
  93158. CollSeq *pColl;
  93159. assert( argc>1 );
  93160. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  93161. pColl = sqlite3GetFuncCollSeq(context);
  93162. assert( pColl );
  93163. assert( mask==-1 || mask==0 );
  93164. iBest = 0;
  93165. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  93166. for(i=1; i<argc; i++){
  93167. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  93168. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  93169. testcase( mask==0 );
  93170. iBest = i;
  93171. }
  93172. }
  93173. sqlite3_result_value(context, argv[iBest]);
  93174. }
  93175. /*
  93176. ** Return the type of the argument.
  93177. */
  93178. static void typeofFunc(
  93179. sqlite3_context *context,
  93180. int NotUsed,
  93181. sqlite3_value **argv
  93182. ){
  93183. const char *z = 0;
  93184. UNUSED_PARAMETER(NotUsed);
  93185. switch( sqlite3_value_type(argv[0]) ){
  93186. case SQLITE_INTEGER: z = "integer"; break;
  93187. case SQLITE_TEXT: z = "text"; break;
  93188. case SQLITE_FLOAT: z = "real"; break;
  93189. case SQLITE_BLOB: z = "blob"; break;
  93190. default: z = "null"; break;
  93191. }
  93192. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  93193. }
  93194. /*
  93195. ** Implementation of the length() function
  93196. */
  93197. static void lengthFunc(
  93198. sqlite3_context *context,
  93199. int argc,
  93200. sqlite3_value **argv
  93201. ){
  93202. int len;
  93203. assert( argc==1 );
  93204. UNUSED_PARAMETER(argc);
  93205. switch( sqlite3_value_type(argv[0]) ){
  93206. case SQLITE_BLOB:
  93207. case SQLITE_INTEGER:
  93208. case SQLITE_FLOAT: {
  93209. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  93210. break;
  93211. }
  93212. case SQLITE_TEXT: {
  93213. const unsigned char *z = sqlite3_value_text(argv[0]);
  93214. if( z==0 ) return;
  93215. len = 0;
  93216. while( *z ){
  93217. len++;
  93218. SQLITE_SKIP_UTF8(z);
  93219. }
  93220. sqlite3_result_int(context, len);
  93221. break;
  93222. }
  93223. default: {
  93224. sqlite3_result_null(context);
  93225. break;
  93226. }
  93227. }
  93228. }
  93229. /*
  93230. ** Implementation of the abs() function.
  93231. **
  93232. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  93233. ** the numeric argument X.
  93234. */
  93235. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  93236. assert( argc==1 );
  93237. UNUSED_PARAMETER(argc);
  93238. switch( sqlite3_value_type(argv[0]) ){
  93239. case SQLITE_INTEGER: {
  93240. i64 iVal = sqlite3_value_int64(argv[0]);
  93241. if( iVal<0 ){
  93242. if( iVal==SMALLEST_INT64 ){
  93243. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  93244. ** then abs(X) throws an integer overflow error since there is no
  93245. ** equivalent positive 64-bit two complement value. */
  93246. sqlite3_result_error(context, "integer overflow", -1);
  93247. return;
  93248. }
  93249. iVal = -iVal;
  93250. }
  93251. sqlite3_result_int64(context, iVal);
  93252. break;
  93253. }
  93254. case SQLITE_NULL: {
  93255. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  93256. sqlite3_result_null(context);
  93257. break;
  93258. }
  93259. default: {
  93260. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  93261. ** something that can be converted into a number, we have:
  93262. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  93263. ** that cannot be converted to a numeric value.
  93264. */
  93265. double rVal = sqlite3_value_double(argv[0]);
  93266. if( rVal<0 ) rVal = -rVal;
  93267. sqlite3_result_double(context, rVal);
  93268. break;
  93269. }
  93270. }
  93271. }
  93272. /*
  93273. ** Implementation of the instr() function.
  93274. **
  93275. ** instr(haystack,needle) finds the first occurrence of needle
  93276. ** in haystack and returns the number of previous characters plus 1,
  93277. ** or 0 if needle does not occur within haystack.
  93278. **
  93279. ** If both haystack and needle are BLOBs, then the result is one more than
  93280. ** the number of bytes in haystack prior to the first occurrence of needle,
  93281. ** or 0 if needle never occurs in haystack.
  93282. */
  93283. static void instrFunc(
  93284. sqlite3_context *context,
  93285. int argc,
  93286. sqlite3_value **argv
  93287. ){
  93288. const unsigned char *zHaystack;
  93289. const unsigned char *zNeedle;
  93290. int nHaystack;
  93291. int nNeedle;
  93292. int typeHaystack, typeNeedle;
  93293. int N = 1;
  93294. int isText;
  93295. UNUSED_PARAMETER(argc);
  93296. typeHaystack = sqlite3_value_type(argv[0]);
  93297. typeNeedle = sqlite3_value_type(argv[1]);
  93298. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  93299. nHaystack = sqlite3_value_bytes(argv[0]);
  93300. nNeedle = sqlite3_value_bytes(argv[1]);
  93301. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  93302. zHaystack = sqlite3_value_blob(argv[0]);
  93303. zNeedle = sqlite3_value_blob(argv[1]);
  93304. isText = 0;
  93305. }else{
  93306. zHaystack = sqlite3_value_text(argv[0]);
  93307. zNeedle = sqlite3_value_text(argv[1]);
  93308. isText = 1;
  93309. }
  93310. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  93311. N++;
  93312. do{
  93313. nHaystack--;
  93314. zHaystack++;
  93315. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  93316. }
  93317. if( nNeedle>nHaystack ) N = 0;
  93318. sqlite3_result_int(context, N);
  93319. }
  93320. /*
  93321. ** Implementation of the printf() function.
  93322. */
  93323. static void printfFunc(
  93324. sqlite3_context *context,
  93325. int argc,
  93326. sqlite3_value **argv
  93327. ){
  93328. PrintfArguments x;
  93329. StrAccum str;
  93330. const char *zFormat;
  93331. int n;
  93332. sqlite3 *db = sqlite3_context_db_handle(context);
  93333. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  93334. x.nArg = argc-1;
  93335. x.nUsed = 0;
  93336. x.apArg = argv+1;
  93337. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  93338. sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
  93339. n = str.nChar;
  93340. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  93341. SQLITE_DYNAMIC);
  93342. }
  93343. }
  93344. /*
  93345. ** Implementation of the substr() function.
  93346. **
  93347. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  93348. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  93349. ** of x. If x is text, then we actually count UTF-8 characters.
  93350. ** If x is a blob, then we count bytes.
  93351. **
  93352. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  93353. **
  93354. ** If p2 is negative, return the p2 characters preceding p1.
  93355. */
  93356. static void substrFunc(
  93357. sqlite3_context *context,
  93358. int argc,
  93359. sqlite3_value **argv
  93360. ){
  93361. const unsigned char *z;
  93362. const unsigned char *z2;
  93363. int len;
  93364. int p0type;
  93365. i64 p1, p2;
  93366. int negP2 = 0;
  93367. assert( argc==3 || argc==2 );
  93368. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  93369. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  93370. ){
  93371. return;
  93372. }
  93373. p0type = sqlite3_value_type(argv[0]);
  93374. p1 = sqlite3_value_int(argv[1]);
  93375. if( p0type==SQLITE_BLOB ){
  93376. len = sqlite3_value_bytes(argv[0]);
  93377. z = sqlite3_value_blob(argv[0]);
  93378. if( z==0 ) return;
  93379. assert( len==sqlite3_value_bytes(argv[0]) );
  93380. }else{
  93381. z = sqlite3_value_text(argv[0]);
  93382. if( z==0 ) return;
  93383. len = 0;
  93384. if( p1<0 ){
  93385. for(z2=z; *z2; len++){
  93386. SQLITE_SKIP_UTF8(z2);
  93387. }
  93388. }
  93389. }
  93390. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  93391. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  93392. ** as substr(X,1,N) - it returns the first N characters of X. This
  93393. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  93394. ** from 2009-02-02 for compatibility of applications that exploited the
  93395. ** old buggy behavior. */
  93396. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  93397. #endif
  93398. if( argc==3 ){
  93399. p2 = sqlite3_value_int(argv[2]);
  93400. if( p2<0 ){
  93401. p2 = -p2;
  93402. negP2 = 1;
  93403. }
  93404. }else{
  93405. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  93406. }
  93407. if( p1<0 ){
  93408. p1 += len;
  93409. if( p1<0 ){
  93410. p2 += p1;
  93411. if( p2<0 ) p2 = 0;
  93412. p1 = 0;
  93413. }
  93414. }else if( p1>0 ){
  93415. p1--;
  93416. }else if( p2>0 ){
  93417. p2--;
  93418. }
  93419. if( negP2 ){
  93420. p1 -= p2;
  93421. if( p1<0 ){
  93422. p2 += p1;
  93423. p1 = 0;
  93424. }
  93425. }
  93426. assert( p1>=0 && p2>=0 );
  93427. if( p0type!=SQLITE_BLOB ){
  93428. while( *z && p1 ){
  93429. SQLITE_SKIP_UTF8(z);
  93430. p1--;
  93431. }
  93432. for(z2=z; *z2 && p2; p2--){
  93433. SQLITE_SKIP_UTF8(z2);
  93434. }
  93435. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  93436. SQLITE_UTF8);
  93437. }else{
  93438. if( p1+p2>len ){
  93439. p2 = len-p1;
  93440. if( p2<0 ) p2 = 0;
  93441. }
  93442. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  93443. }
  93444. }
  93445. /*
  93446. ** Implementation of the round() function
  93447. */
  93448. #ifndef SQLITE_OMIT_FLOATING_POINT
  93449. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  93450. int n = 0;
  93451. double r;
  93452. char *zBuf;
  93453. assert( argc==1 || argc==2 );
  93454. if( argc==2 ){
  93455. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  93456. n = sqlite3_value_int(argv[1]);
  93457. if( n>30 ) n = 30;
  93458. if( n<0 ) n = 0;
  93459. }
  93460. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  93461. r = sqlite3_value_double(argv[0]);
  93462. /* If Y==0 and X will fit in a 64-bit int,
  93463. ** handle the rounding directly,
  93464. ** otherwise use printf.
  93465. */
  93466. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  93467. r = (double)((sqlite_int64)(r+0.5));
  93468. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  93469. r = -(double)((sqlite_int64)((-r)+0.5));
  93470. }else{
  93471. zBuf = sqlite3_mprintf("%.*f",n,r);
  93472. if( zBuf==0 ){
  93473. sqlite3_result_error_nomem(context);
  93474. return;
  93475. }
  93476. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  93477. sqlite3_free(zBuf);
  93478. }
  93479. sqlite3_result_double(context, r);
  93480. }
  93481. #endif
  93482. /*
  93483. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  93484. ** allocation fails, call sqlite3_result_error_nomem() to notify
  93485. ** the database handle that malloc() has failed and return NULL.
  93486. ** If nByte is larger than the maximum string or blob length, then
  93487. ** raise an SQLITE_TOOBIG exception and return NULL.
  93488. */
  93489. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  93490. char *z;
  93491. sqlite3 *db = sqlite3_context_db_handle(context);
  93492. assert( nByte>0 );
  93493. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  93494. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  93495. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  93496. sqlite3_result_error_toobig(context);
  93497. z = 0;
  93498. }else{
  93499. z = sqlite3Malloc(nByte);
  93500. if( !z ){
  93501. sqlite3_result_error_nomem(context);
  93502. }
  93503. }
  93504. return z;
  93505. }
  93506. /*
  93507. ** Implementation of the upper() and lower() SQL functions.
  93508. */
  93509. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  93510. char *z1;
  93511. const char *z2;
  93512. int i, n;
  93513. UNUSED_PARAMETER(argc);
  93514. z2 = (char*)sqlite3_value_text(argv[0]);
  93515. n = sqlite3_value_bytes(argv[0]);
  93516. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  93517. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  93518. if( z2 ){
  93519. z1 = contextMalloc(context, ((i64)n)+1);
  93520. if( z1 ){
  93521. for(i=0; i<n; i++){
  93522. z1[i] = (char)sqlite3Toupper(z2[i]);
  93523. }
  93524. sqlite3_result_text(context, z1, n, sqlite3_free);
  93525. }
  93526. }
  93527. }
  93528. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  93529. char *z1;
  93530. const char *z2;
  93531. int i, n;
  93532. UNUSED_PARAMETER(argc);
  93533. z2 = (char*)sqlite3_value_text(argv[0]);
  93534. n = sqlite3_value_bytes(argv[0]);
  93535. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  93536. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  93537. if( z2 ){
  93538. z1 = contextMalloc(context, ((i64)n)+1);
  93539. if( z1 ){
  93540. for(i=0; i<n; i++){
  93541. z1[i] = sqlite3Tolower(z2[i]);
  93542. }
  93543. sqlite3_result_text(context, z1, n, sqlite3_free);
  93544. }
  93545. }
  93546. }
  93547. /*
  93548. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  93549. ** as VDBE code so that unused argument values do not have to be computed.
  93550. ** However, we still need some kind of function implementation for this
  93551. ** routines in the function table. The noopFunc macro provides this.
  93552. ** noopFunc will never be called so it doesn't matter what the implementation
  93553. ** is. We might as well use the "version()" function as a substitute.
  93554. */
  93555. #define noopFunc versionFunc /* Substitute function - never called */
  93556. /*
  93557. ** Implementation of random(). Return a random integer.
  93558. */
  93559. static void randomFunc(
  93560. sqlite3_context *context,
  93561. int NotUsed,
  93562. sqlite3_value **NotUsed2
  93563. ){
  93564. sqlite_int64 r;
  93565. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93566. sqlite3_randomness(sizeof(r), &r);
  93567. if( r<0 ){
  93568. /* We need to prevent a random number of 0x8000000000000000
  93569. ** (or -9223372036854775808) since when you do abs() of that
  93570. ** number of you get the same value back again. To do this
  93571. ** in a way that is testable, mask the sign bit off of negative
  93572. ** values, resulting in a positive value. Then take the
  93573. ** 2s complement of that positive value. The end result can
  93574. ** therefore be no less than -9223372036854775807.
  93575. */
  93576. r = -(r & LARGEST_INT64);
  93577. }
  93578. sqlite3_result_int64(context, r);
  93579. }
  93580. /*
  93581. ** Implementation of randomblob(N). Return a random blob
  93582. ** that is N bytes long.
  93583. */
  93584. static void randomBlob(
  93585. sqlite3_context *context,
  93586. int argc,
  93587. sqlite3_value **argv
  93588. ){
  93589. int n;
  93590. unsigned char *p;
  93591. assert( argc==1 );
  93592. UNUSED_PARAMETER(argc);
  93593. n = sqlite3_value_int(argv[0]);
  93594. if( n<1 ){
  93595. n = 1;
  93596. }
  93597. p = contextMalloc(context, n);
  93598. if( p ){
  93599. sqlite3_randomness(n, p);
  93600. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  93601. }
  93602. }
  93603. /*
  93604. ** Implementation of the last_insert_rowid() SQL function. The return
  93605. ** value is the same as the sqlite3_last_insert_rowid() API function.
  93606. */
  93607. static void last_insert_rowid(
  93608. sqlite3_context *context,
  93609. int NotUsed,
  93610. sqlite3_value **NotUsed2
  93611. ){
  93612. sqlite3 *db = sqlite3_context_db_handle(context);
  93613. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93614. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  93615. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  93616. ** function. */
  93617. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  93618. }
  93619. /*
  93620. ** Implementation of the changes() SQL function.
  93621. **
  93622. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  93623. ** around the sqlite3_changes() C/C++ function and hence follows the same
  93624. ** rules for counting changes.
  93625. */
  93626. static void changes(
  93627. sqlite3_context *context,
  93628. int NotUsed,
  93629. sqlite3_value **NotUsed2
  93630. ){
  93631. sqlite3 *db = sqlite3_context_db_handle(context);
  93632. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93633. sqlite3_result_int(context, sqlite3_changes(db));
  93634. }
  93635. /*
  93636. ** Implementation of the total_changes() SQL function. The return value is
  93637. ** the same as the sqlite3_total_changes() API function.
  93638. */
  93639. static void total_changes(
  93640. sqlite3_context *context,
  93641. int NotUsed,
  93642. sqlite3_value **NotUsed2
  93643. ){
  93644. sqlite3 *db = sqlite3_context_db_handle(context);
  93645. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93646. /* IMP: R-52756-41993 This function is a wrapper around the
  93647. ** sqlite3_total_changes() C/C++ interface. */
  93648. sqlite3_result_int(context, sqlite3_total_changes(db));
  93649. }
  93650. /*
  93651. ** A structure defining how to do GLOB-style comparisons.
  93652. */
  93653. struct compareInfo {
  93654. u8 matchAll;
  93655. u8 matchOne;
  93656. u8 matchSet;
  93657. u8 noCase;
  93658. };
  93659. /*
  93660. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  93661. ** character is exactly one byte in size. Also, provde the Utf8Read()
  93662. ** macro for fast reading of the next character in the common case where
  93663. ** the next character is ASCII.
  93664. */
  93665. #if defined(SQLITE_EBCDIC)
  93666. # define sqlite3Utf8Read(A) (*((*A)++))
  93667. # define Utf8Read(A) (*(A++))
  93668. #else
  93669. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  93670. #endif
  93671. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  93672. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  93673. ** case. Thus 'a' LIKE 'A' would be true. */
  93674. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  93675. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  93676. ** is case sensitive causing 'a' LIKE 'A' to be false */
  93677. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  93678. /*
  93679. ** Compare two UTF-8 strings for equality where the first string can
  93680. ** potentially be a "glob" or "like" expression. Return true (1) if they
  93681. ** are the same and false (0) if they are different.
  93682. **
  93683. ** Globbing rules:
  93684. **
  93685. ** '*' Matches any sequence of zero or more characters.
  93686. **
  93687. ** '?' Matches exactly one character.
  93688. **
  93689. ** [...] Matches one character from the enclosed list of
  93690. ** characters.
  93691. **
  93692. ** [^...] Matches one character not in the enclosed list.
  93693. **
  93694. ** With the [...] and [^...] matching, a ']' character can be included
  93695. ** in the list by making it the first character after '[' or '^'. A
  93696. ** range of characters can be specified using '-'. Example:
  93697. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  93698. ** it the last character in the list.
  93699. **
  93700. ** Like matching rules:
  93701. **
  93702. ** '%' Matches any sequence of zero or more characters
  93703. **
  93704. *** '_' Matches any one character
  93705. **
  93706. ** Ec Where E is the "esc" character and c is any other
  93707. ** character, including '%', '_', and esc, match exactly c.
  93708. **
  93709. ** The comments within this routine usually assume glob matching.
  93710. **
  93711. ** This routine is usually quick, but can be N**2 in the worst case.
  93712. */
  93713. static int patternCompare(
  93714. const u8 *zPattern, /* The glob pattern */
  93715. const u8 *zString, /* The string to compare against the glob */
  93716. const struct compareInfo *pInfo, /* Information about how to do the compare */
  93717. u32 esc /* The escape character */
  93718. ){
  93719. u32 c, c2; /* Next pattern and input string chars */
  93720. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  93721. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  93722. u32 matchOther; /* "[" or the escape character */
  93723. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  93724. const u8 *zEscaped = 0; /* One past the last escaped input char */
  93725. /* The GLOB operator does not have an ESCAPE clause. And LIKE does not
  93726. ** have the matchSet operator. So we either have to look for one or
  93727. ** the other, never both. Hence the single variable matchOther is used
  93728. ** to store the one we have to look for.
  93729. */
  93730. matchOther = esc ? esc : pInfo->matchSet;
  93731. while( (c = Utf8Read(zPattern))!=0 ){
  93732. if( c==matchAll ){ /* Match "*" */
  93733. /* Skip over multiple "*" characters in the pattern. If there
  93734. ** are also "?" characters, skip those as well, but consume a
  93735. ** single character of the input string for each "?" skipped */
  93736. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  93737. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  93738. return 0;
  93739. }
  93740. }
  93741. if( c==0 ){
  93742. return 1; /* "*" at the end of the pattern matches */
  93743. }else if( c==matchOther ){
  93744. if( esc ){
  93745. c = sqlite3Utf8Read(&zPattern);
  93746. if( c==0 ) return 0;
  93747. }else{
  93748. /* "[...]" immediately follows the "*". We have to do a slow
  93749. ** recursive search in this case, but it is an unusual case. */
  93750. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  93751. while( *zString
  93752. && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  93753. SQLITE_SKIP_UTF8(zString);
  93754. }
  93755. return *zString!=0;
  93756. }
  93757. }
  93758. /* At this point variable c contains the first character of the
  93759. ** pattern string past the "*". Search in the input string for the
  93760. ** first matching character and recursively contine the match from
  93761. ** that point.
  93762. **
  93763. ** For a case-insensitive search, set variable cx to be the same as
  93764. ** c but in the other case and search the input string for either
  93765. ** c or cx.
  93766. */
  93767. if( c<=0x80 ){
  93768. u32 cx;
  93769. if( noCase ){
  93770. cx = sqlite3Toupper(c);
  93771. c = sqlite3Tolower(c);
  93772. }else{
  93773. cx = c;
  93774. }
  93775. while( (c2 = *(zString++))!=0 ){
  93776. if( c2!=c && c2!=cx ) continue;
  93777. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  93778. }
  93779. }else{
  93780. while( (c2 = Utf8Read(zString))!=0 ){
  93781. if( c2!=c ) continue;
  93782. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  93783. }
  93784. }
  93785. return 0;
  93786. }
  93787. if( c==matchOther ){
  93788. if( esc ){
  93789. c = sqlite3Utf8Read(&zPattern);
  93790. if( c==0 ) return 0;
  93791. zEscaped = zPattern;
  93792. }else{
  93793. u32 prior_c = 0;
  93794. int seen = 0;
  93795. int invert = 0;
  93796. c = sqlite3Utf8Read(&zString);
  93797. if( c==0 ) return 0;
  93798. c2 = sqlite3Utf8Read(&zPattern);
  93799. if( c2=='^' ){
  93800. invert = 1;
  93801. c2 = sqlite3Utf8Read(&zPattern);
  93802. }
  93803. if( c2==']' ){
  93804. if( c==']' ) seen = 1;
  93805. c2 = sqlite3Utf8Read(&zPattern);
  93806. }
  93807. while( c2 && c2!=']' ){
  93808. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  93809. c2 = sqlite3Utf8Read(&zPattern);
  93810. if( c>=prior_c && c<=c2 ) seen = 1;
  93811. prior_c = 0;
  93812. }else{
  93813. if( c==c2 ){
  93814. seen = 1;
  93815. }
  93816. prior_c = c2;
  93817. }
  93818. c2 = sqlite3Utf8Read(&zPattern);
  93819. }
  93820. if( c2==0 || (seen ^ invert)==0 ){
  93821. return 0;
  93822. }
  93823. continue;
  93824. }
  93825. }
  93826. c2 = Utf8Read(zString);
  93827. if( c==c2 ) continue;
  93828. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
  93829. continue;
  93830. }
  93831. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  93832. return 0;
  93833. }
  93834. return *zString==0;
  93835. }
  93836. /*
  93837. ** The sqlite3_strglob() interface.
  93838. */
  93839. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
  93840. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  93841. }
  93842. /*
  93843. ** The sqlite3_strlike() interface.
  93844. */
  93845. SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  93846. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0;
  93847. }
  93848. /*
  93849. ** Count the number of times that the LIKE operator (or GLOB which is
  93850. ** just a variation of LIKE) gets called. This is used for testing
  93851. ** only.
  93852. */
  93853. #ifdef SQLITE_TEST
  93854. SQLITE_API int sqlite3_like_count = 0;
  93855. #endif
  93856. /*
  93857. ** Implementation of the like() SQL function. This function implements
  93858. ** the build-in LIKE operator. The first argument to the function is the
  93859. ** pattern and the second argument is the string. So, the SQL statements:
  93860. **
  93861. ** A LIKE B
  93862. **
  93863. ** is implemented as like(B,A).
  93864. **
  93865. ** This same function (with a different compareInfo structure) computes
  93866. ** the GLOB operator.
  93867. */
  93868. static void likeFunc(
  93869. sqlite3_context *context,
  93870. int argc,
  93871. sqlite3_value **argv
  93872. ){
  93873. const unsigned char *zA, *zB;
  93874. u32 escape = 0;
  93875. int nPat;
  93876. sqlite3 *db = sqlite3_context_db_handle(context);
  93877. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  93878. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  93879. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  93880. ){
  93881. #ifdef SQLITE_TEST
  93882. sqlite3_like_count++;
  93883. #endif
  93884. sqlite3_result_int(context, 0);
  93885. return;
  93886. }
  93887. #endif
  93888. zB = sqlite3_value_text(argv[0]);
  93889. zA = sqlite3_value_text(argv[1]);
  93890. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  93891. ** of deep recursion and N*N behavior in patternCompare().
  93892. */
  93893. nPat = sqlite3_value_bytes(argv[0]);
  93894. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  93895. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  93896. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  93897. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  93898. return;
  93899. }
  93900. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  93901. if( argc==3 ){
  93902. /* The escape character string must consist of a single UTF-8 character.
  93903. ** Otherwise, return an error.
  93904. */
  93905. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  93906. if( zEsc==0 ) return;
  93907. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  93908. sqlite3_result_error(context,
  93909. "ESCAPE expression must be a single character", -1);
  93910. return;
  93911. }
  93912. escape = sqlite3Utf8Read(&zEsc);
  93913. }
  93914. if( zA && zB ){
  93915. struct compareInfo *pInfo = sqlite3_user_data(context);
  93916. #ifdef SQLITE_TEST
  93917. sqlite3_like_count++;
  93918. #endif
  93919. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  93920. }
  93921. }
  93922. /*
  93923. ** Implementation of the NULLIF(x,y) function. The result is the first
  93924. ** argument if the arguments are different. The result is NULL if the
  93925. ** arguments are equal to each other.
  93926. */
  93927. static void nullifFunc(
  93928. sqlite3_context *context,
  93929. int NotUsed,
  93930. sqlite3_value **argv
  93931. ){
  93932. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  93933. UNUSED_PARAMETER(NotUsed);
  93934. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  93935. sqlite3_result_value(context, argv[0]);
  93936. }
  93937. }
  93938. /*
  93939. ** Implementation of the sqlite_version() function. The result is the version
  93940. ** of the SQLite library that is running.
  93941. */
  93942. static void versionFunc(
  93943. sqlite3_context *context,
  93944. int NotUsed,
  93945. sqlite3_value **NotUsed2
  93946. ){
  93947. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93948. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  93949. ** sqlite3_libversion() C-interface. */
  93950. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  93951. }
  93952. /*
  93953. ** Implementation of the sqlite_source_id() function. The result is a string
  93954. ** that identifies the particular version of the source code used to build
  93955. ** SQLite.
  93956. */
  93957. static void sourceidFunc(
  93958. sqlite3_context *context,
  93959. int NotUsed,
  93960. sqlite3_value **NotUsed2
  93961. ){
  93962. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  93963. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  93964. ** sqlite3_sourceid() C interface. */
  93965. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  93966. }
  93967. /*
  93968. ** Implementation of the sqlite_log() function. This is a wrapper around
  93969. ** sqlite3_log(). The return value is NULL. The function exists purely for
  93970. ** its side-effects.
  93971. */
  93972. static void errlogFunc(
  93973. sqlite3_context *context,
  93974. int argc,
  93975. sqlite3_value **argv
  93976. ){
  93977. UNUSED_PARAMETER(argc);
  93978. UNUSED_PARAMETER(context);
  93979. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  93980. }
  93981. /*
  93982. ** Implementation of the sqlite_compileoption_used() function.
  93983. ** The result is an integer that identifies if the compiler option
  93984. ** was used to build SQLite.
  93985. */
  93986. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  93987. static void compileoptionusedFunc(
  93988. sqlite3_context *context,
  93989. int argc,
  93990. sqlite3_value **argv
  93991. ){
  93992. const char *zOptName;
  93993. assert( argc==1 );
  93994. UNUSED_PARAMETER(argc);
  93995. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  93996. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  93997. ** function.
  93998. */
  93999. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  94000. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  94001. }
  94002. }
  94003. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  94004. /*
  94005. ** Implementation of the sqlite_compileoption_get() function.
  94006. ** The result is a string that identifies the compiler options
  94007. ** used to build SQLite.
  94008. */
  94009. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  94010. static void compileoptiongetFunc(
  94011. sqlite3_context *context,
  94012. int argc,
  94013. sqlite3_value **argv
  94014. ){
  94015. int n;
  94016. assert( argc==1 );
  94017. UNUSED_PARAMETER(argc);
  94018. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  94019. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  94020. */
  94021. n = sqlite3_value_int(argv[0]);
  94022. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  94023. }
  94024. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  94025. /* Array for converting from half-bytes (nybbles) into ASCII hex
  94026. ** digits. */
  94027. static const char hexdigits[] = {
  94028. '0', '1', '2', '3', '4', '5', '6', '7',
  94029. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  94030. };
  94031. /*
  94032. ** Implementation of the QUOTE() function. This function takes a single
  94033. ** argument. If the argument is numeric, the return value is the same as
  94034. ** the argument. If the argument is NULL, the return value is the string
  94035. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  94036. ** single-quote escapes.
  94037. */
  94038. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  94039. assert( argc==1 );
  94040. UNUSED_PARAMETER(argc);
  94041. switch( sqlite3_value_type(argv[0]) ){
  94042. case SQLITE_FLOAT: {
  94043. double r1, r2;
  94044. char zBuf[50];
  94045. r1 = sqlite3_value_double(argv[0]);
  94046. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  94047. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  94048. if( r1!=r2 ){
  94049. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  94050. }
  94051. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  94052. break;
  94053. }
  94054. case SQLITE_INTEGER: {
  94055. sqlite3_result_value(context, argv[0]);
  94056. break;
  94057. }
  94058. case SQLITE_BLOB: {
  94059. char *zText = 0;
  94060. char const *zBlob = sqlite3_value_blob(argv[0]);
  94061. int nBlob = sqlite3_value_bytes(argv[0]);
  94062. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  94063. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  94064. if( zText ){
  94065. int i;
  94066. for(i=0; i<nBlob; i++){
  94067. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  94068. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  94069. }
  94070. zText[(nBlob*2)+2] = '\'';
  94071. zText[(nBlob*2)+3] = '\0';
  94072. zText[0] = 'X';
  94073. zText[1] = '\'';
  94074. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  94075. sqlite3_free(zText);
  94076. }
  94077. break;
  94078. }
  94079. case SQLITE_TEXT: {
  94080. int i,j;
  94081. u64 n;
  94082. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  94083. char *z;
  94084. if( zArg==0 ) return;
  94085. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  94086. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  94087. if( z ){
  94088. z[0] = '\'';
  94089. for(i=0, j=1; zArg[i]; i++){
  94090. z[j++] = zArg[i];
  94091. if( zArg[i]=='\'' ){
  94092. z[j++] = '\'';
  94093. }
  94094. }
  94095. z[j++] = '\'';
  94096. z[j] = 0;
  94097. sqlite3_result_text(context, z, j, sqlite3_free);
  94098. }
  94099. break;
  94100. }
  94101. default: {
  94102. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  94103. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  94104. break;
  94105. }
  94106. }
  94107. }
  94108. /*
  94109. ** The unicode() function. Return the integer unicode code-point value
  94110. ** for the first character of the input string.
  94111. */
  94112. static void unicodeFunc(
  94113. sqlite3_context *context,
  94114. int argc,
  94115. sqlite3_value **argv
  94116. ){
  94117. const unsigned char *z = sqlite3_value_text(argv[0]);
  94118. (void)argc;
  94119. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  94120. }
  94121. /*
  94122. ** The char() function takes zero or more arguments, each of which is
  94123. ** an integer. It constructs a string where each character of the string
  94124. ** is the unicode character for the corresponding integer argument.
  94125. */
  94126. static void charFunc(
  94127. sqlite3_context *context,
  94128. int argc,
  94129. sqlite3_value **argv
  94130. ){
  94131. unsigned char *z, *zOut;
  94132. int i;
  94133. zOut = z = sqlite3_malloc64( argc*4+1 );
  94134. if( z==0 ){
  94135. sqlite3_result_error_nomem(context);
  94136. return;
  94137. }
  94138. for(i=0; i<argc; i++){
  94139. sqlite3_int64 x;
  94140. unsigned c;
  94141. x = sqlite3_value_int64(argv[i]);
  94142. if( x<0 || x>0x10ffff ) x = 0xfffd;
  94143. c = (unsigned)(x & 0x1fffff);
  94144. if( c<0x00080 ){
  94145. *zOut++ = (u8)(c&0xFF);
  94146. }else if( c<0x00800 ){
  94147. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  94148. *zOut++ = 0x80 + (u8)(c & 0x3F);
  94149. }else if( c<0x10000 ){
  94150. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  94151. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  94152. *zOut++ = 0x80 + (u8)(c & 0x3F);
  94153. }else{
  94154. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  94155. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  94156. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  94157. *zOut++ = 0x80 + (u8)(c & 0x3F);
  94158. } \
  94159. }
  94160. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  94161. }
  94162. /*
  94163. ** The hex() function. Interpret the argument as a blob. Return
  94164. ** a hexadecimal rendering as text.
  94165. */
  94166. static void hexFunc(
  94167. sqlite3_context *context,
  94168. int argc,
  94169. sqlite3_value **argv
  94170. ){
  94171. int i, n;
  94172. const unsigned char *pBlob;
  94173. char *zHex, *z;
  94174. assert( argc==1 );
  94175. UNUSED_PARAMETER(argc);
  94176. pBlob = sqlite3_value_blob(argv[0]);
  94177. n = sqlite3_value_bytes(argv[0]);
  94178. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  94179. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  94180. if( zHex ){
  94181. for(i=0; i<n; i++, pBlob++){
  94182. unsigned char c = *pBlob;
  94183. *(z++) = hexdigits[(c>>4)&0xf];
  94184. *(z++) = hexdigits[c&0xf];
  94185. }
  94186. *z = 0;
  94187. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  94188. }
  94189. }
  94190. /*
  94191. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  94192. */
  94193. static void zeroblobFunc(
  94194. sqlite3_context *context,
  94195. int argc,
  94196. sqlite3_value **argv
  94197. ){
  94198. i64 n;
  94199. int rc;
  94200. assert( argc==1 );
  94201. UNUSED_PARAMETER(argc);
  94202. n = sqlite3_value_int64(argv[0]);
  94203. if( n<0 ) n = 0;
  94204. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  94205. if( rc ){
  94206. sqlite3_result_error_code(context, rc);
  94207. }
  94208. }
  94209. /*
  94210. ** The replace() function. Three arguments are all strings: call
  94211. ** them A, B, and C. The result is also a string which is derived
  94212. ** from A by replacing every occurrence of B with C. The match
  94213. ** must be exact. Collating sequences are not used.
  94214. */
  94215. static void replaceFunc(
  94216. sqlite3_context *context,
  94217. int argc,
  94218. sqlite3_value **argv
  94219. ){
  94220. const unsigned char *zStr; /* The input string A */
  94221. const unsigned char *zPattern; /* The pattern string B */
  94222. const unsigned char *zRep; /* The replacement string C */
  94223. unsigned char *zOut; /* The output */
  94224. int nStr; /* Size of zStr */
  94225. int nPattern; /* Size of zPattern */
  94226. int nRep; /* Size of zRep */
  94227. i64 nOut; /* Maximum size of zOut */
  94228. int loopLimit; /* Last zStr[] that might match zPattern[] */
  94229. int i, j; /* Loop counters */
  94230. assert( argc==3 );
  94231. UNUSED_PARAMETER(argc);
  94232. zStr = sqlite3_value_text(argv[0]);
  94233. if( zStr==0 ) return;
  94234. nStr = sqlite3_value_bytes(argv[0]);
  94235. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  94236. zPattern = sqlite3_value_text(argv[1]);
  94237. if( zPattern==0 ){
  94238. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  94239. || sqlite3_context_db_handle(context)->mallocFailed );
  94240. return;
  94241. }
  94242. if( zPattern[0]==0 ){
  94243. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  94244. sqlite3_result_value(context, argv[0]);
  94245. return;
  94246. }
  94247. nPattern = sqlite3_value_bytes(argv[1]);
  94248. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  94249. zRep = sqlite3_value_text(argv[2]);
  94250. if( zRep==0 ) return;
  94251. nRep = sqlite3_value_bytes(argv[2]);
  94252. assert( zRep==sqlite3_value_text(argv[2]) );
  94253. nOut = nStr + 1;
  94254. assert( nOut<SQLITE_MAX_LENGTH );
  94255. zOut = contextMalloc(context, (i64)nOut);
  94256. if( zOut==0 ){
  94257. return;
  94258. }
  94259. loopLimit = nStr - nPattern;
  94260. for(i=j=0; i<=loopLimit; i++){
  94261. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  94262. zOut[j++] = zStr[i];
  94263. }else{
  94264. u8 *zOld;
  94265. sqlite3 *db = sqlite3_context_db_handle(context);
  94266. nOut += nRep - nPattern;
  94267. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  94268. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  94269. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  94270. sqlite3_result_error_toobig(context);
  94271. sqlite3_free(zOut);
  94272. return;
  94273. }
  94274. zOld = zOut;
  94275. zOut = sqlite3_realloc64(zOut, (int)nOut);
  94276. if( zOut==0 ){
  94277. sqlite3_result_error_nomem(context);
  94278. sqlite3_free(zOld);
  94279. return;
  94280. }
  94281. memcpy(&zOut[j], zRep, nRep);
  94282. j += nRep;
  94283. i += nPattern-1;
  94284. }
  94285. }
  94286. assert( j+nStr-i+1==nOut );
  94287. memcpy(&zOut[j], &zStr[i], nStr-i);
  94288. j += nStr - i;
  94289. assert( j<=nOut );
  94290. zOut[j] = 0;
  94291. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  94292. }
  94293. /*
  94294. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  94295. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  94296. */
  94297. static void trimFunc(
  94298. sqlite3_context *context,
  94299. int argc,
  94300. sqlite3_value **argv
  94301. ){
  94302. const unsigned char *zIn; /* Input string */
  94303. const unsigned char *zCharSet; /* Set of characters to trim */
  94304. int nIn; /* Number of bytes in input */
  94305. int flags; /* 1: trimleft 2: trimright 3: trim */
  94306. int i; /* Loop counter */
  94307. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  94308. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  94309. int nChar; /* Number of characters in zCharSet */
  94310. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  94311. return;
  94312. }
  94313. zIn = sqlite3_value_text(argv[0]);
  94314. if( zIn==0 ) return;
  94315. nIn = sqlite3_value_bytes(argv[0]);
  94316. assert( zIn==sqlite3_value_text(argv[0]) );
  94317. if( argc==1 ){
  94318. static const unsigned char lenOne[] = { 1 };
  94319. static unsigned char * const azOne[] = { (u8*)" " };
  94320. nChar = 1;
  94321. aLen = (u8*)lenOne;
  94322. azChar = (unsigned char **)azOne;
  94323. zCharSet = 0;
  94324. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  94325. return;
  94326. }else{
  94327. const unsigned char *z;
  94328. for(z=zCharSet, nChar=0; *z; nChar++){
  94329. SQLITE_SKIP_UTF8(z);
  94330. }
  94331. if( nChar>0 ){
  94332. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  94333. if( azChar==0 ){
  94334. return;
  94335. }
  94336. aLen = (unsigned char*)&azChar[nChar];
  94337. for(z=zCharSet, nChar=0; *z; nChar++){
  94338. azChar[nChar] = (unsigned char *)z;
  94339. SQLITE_SKIP_UTF8(z);
  94340. aLen[nChar] = (u8)(z - azChar[nChar]);
  94341. }
  94342. }
  94343. }
  94344. if( nChar>0 ){
  94345. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  94346. if( flags & 1 ){
  94347. while( nIn>0 ){
  94348. int len = 0;
  94349. for(i=0; i<nChar; i++){
  94350. len = aLen[i];
  94351. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  94352. }
  94353. if( i>=nChar ) break;
  94354. zIn += len;
  94355. nIn -= len;
  94356. }
  94357. }
  94358. if( flags & 2 ){
  94359. while( nIn>0 ){
  94360. int len = 0;
  94361. for(i=0; i<nChar; i++){
  94362. len = aLen[i];
  94363. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  94364. }
  94365. if( i>=nChar ) break;
  94366. nIn -= len;
  94367. }
  94368. }
  94369. if( zCharSet ){
  94370. sqlite3_free(azChar);
  94371. }
  94372. }
  94373. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  94374. }
  94375. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  94376. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  94377. ** when SQLite is built.
  94378. */
  94379. #ifdef SQLITE_SOUNDEX
  94380. /*
  94381. ** Compute the soundex encoding of a word.
  94382. **
  94383. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  94384. ** soundex encoding of the string X.
  94385. */
  94386. static void soundexFunc(
  94387. sqlite3_context *context,
  94388. int argc,
  94389. sqlite3_value **argv
  94390. ){
  94391. char zResult[8];
  94392. const u8 *zIn;
  94393. int i, j;
  94394. static const unsigned char iCode[] = {
  94395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  94396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  94397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  94398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  94399. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  94400. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  94401. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  94402. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  94403. };
  94404. assert( argc==1 );
  94405. zIn = (u8*)sqlite3_value_text(argv[0]);
  94406. if( zIn==0 ) zIn = (u8*)"";
  94407. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  94408. if( zIn[i] ){
  94409. u8 prevcode = iCode[zIn[i]&0x7f];
  94410. zResult[0] = sqlite3Toupper(zIn[i]);
  94411. for(j=1; j<4 && zIn[i]; i++){
  94412. int code = iCode[zIn[i]&0x7f];
  94413. if( code>0 ){
  94414. if( code!=prevcode ){
  94415. prevcode = code;
  94416. zResult[j++] = code + '0';
  94417. }
  94418. }else{
  94419. prevcode = 0;
  94420. }
  94421. }
  94422. while( j<4 ){
  94423. zResult[j++] = '0';
  94424. }
  94425. zResult[j] = 0;
  94426. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  94427. }else{
  94428. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  94429. ** is NULL or contains no ASCII alphabetic characters. */
  94430. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  94431. }
  94432. }
  94433. #endif /* SQLITE_SOUNDEX */
  94434. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  94435. /*
  94436. ** A function that loads a shared-library extension then returns NULL.
  94437. */
  94438. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  94439. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  94440. const char *zProc;
  94441. sqlite3 *db = sqlite3_context_db_handle(context);
  94442. char *zErrMsg = 0;
  94443. if( argc==2 ){
  94444. zProc = (const char *)sqlite3_value_text(argv[1]);
  94445. }else{
  94446. zProc = 0;
  94447. }
  94448. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  94449. sqlite3_result_error(context, zErrMsg, -1);
  94450. sqlite3_free(zErrMsg);
  94451. }
  94452. }
  94453. #endif
  94454. /*
  94455. ** An instance of the following structure holds the context of a
  94456. ** sum() or avg() aggregate computation.
  94457. */
  94458. typedef struct SumCtx SumCtx;
  94459. struct SumCtx {
  94460. double rSum; /* Floating point sum */
  94461. i64 iSum; /* Integer sum */
  94462. i64 cnt; /* Number of elements summed */
  94463. u8 overflow; /* True if integer overflow seen */
  94464. u8 approx; /* True if non-integer value was input to the sum */
  94465. };
  94466. /*
  94467. ** Routines used to compute the sum, average, and total.
  94468. **
  94469. ** The SUM() function follows the (broken) SQL standard which means
  94470. ** that it returns NULL if it sums over no inputs. TOTAL returns
  94471. ** 0.0 in that case. In addition, TOTAL always returns a float where
  94472. ** SUM might return an integer if it never encounters a floating point
  94473. ** value. TOTAL never fails, but SUM might through an exception if
  94474. ** it overflows an integer.
  94475. */
  94476. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  94477. SumCtx *p;
  94478. int type;
  94479. assert( argc==1 );
  94480. UNUSED_PARAMETER(argc);
  94481. p = sqlite3_aggregate_context(context, sizeof(*p));
  94482. type = sqlite3_value_numeric_type(argv[0]);
  94483. if( p && type!=SQLITE_NULL ){
  94484. p->cnt++;
  94485. if( type==SQLITE_INTEGER ){
  94486. i64 v = sqlite3_value_int64(argv[0]);
  94487. p->rSum += v;
  94488. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  94489. p->overflow = 1;
  94490. }
  94491. }else{
  94492. p->rSum += sqlite3_value_double(argv[0]);
  94493. p->approx = 1;
  94494. }
  94495. }
  94496. }
  94497. static void sumFinalize(sqlite3_context *context){
  94498. SumCtx *p;
  94499. p = sqlite3_aggregate_context(context, 0);
  94500. if( p && p->cnt>0 ){
  94501. if( p->overflow ){
  94502. sqlite3_result_error(context,"integer overflow",-1);
  94503. }else if( p->approx ){
  94504. sqlite3_result_double(context, p->rSum);
  94505. }else{
  94506. sqlite3_result_int64(context, p->iSum);
  94507. }
  94508. }
  94509. }
  94510. static void avgFinalize(sqlite3_context *context){
  94511. SumCtx *p;
  94512. p = sqlite3_aggregate_context(context, 0);
  94513. if( p && p->cnt>0 ){
  94514. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  94515. }
  94516. }
  94517. static void totalFinalize(sqlite3_context *context){
  94518. SumCtx *p;
  94519. p = sqlite3_aggregate_context(context, 0);
  94520. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  94521. sqlite3_result_double(context, p ? p->rSum : (double)0);
  94522. }
  94523. /*
  94524. ** The following structure keeps track of state information for the
  94525. ** count() aggregate function.
  94526. */
  94527. typedef struct CountCtx CountCtx;
  94528. struct CountCtx {
  94529. i64 n;
  94530. };
  94531. /*
  94532. ** Routines to implement the count() aggregate function.
  94533. */
  94534. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  94535. CountCtx *p;
  94536. p = sqlite3_aggregate_context(context, sizeof(*p));
  94537. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  94538. p->n++;
  94539. }
  94540. #ifndef SQLITE_OMIT_DEPRECATED
  94541. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  94542. ** sure it still operates correctly, verify that its count agrees with our
  94543. ** internal count when using count(*) and when the total count can be
  94544. ** expressed as a 32-bit integer. */
  94545. assert( argc==1 || p==0 || p->n>0x7fffffff
  94546. || p->n==sqlite3_aggregate_count(context) );
  94547. #endif
  94548. }
  94549. static void countFinalize(sqlite3_context *context){
  94550. CountCtx *p;
  94551. p = sqlite3_aggregate_context(context, 0);
  94552. sqlite3_result_int64(context, p ? p->n : 0);
  94553. }
  94554. /*
  94555. ** Routines to implement min() and max() aggregate functions.
  94556. */
  94557. static void minmaxStep(
  94558. sqlite3_context *context,
  94559. int NotUsed,
  94560. sqlite3_value **argv
  94561. ){
  94562. Mem *pArg = (Mem *)argv[0];
  94563. Mem *pBest;
  94564. UNUSED_PARAMETER(NotUsed);
  94565. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  94566. if( !pBest ) return;
  94567. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  94568. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  94569. }else if( pBest->flags ){
  94570. int max;
  94571. int cmp;
  94572. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  94573. /* This step function is used for both the min() and max() aggregates,
  94574. ** the only difference between the two being that the sense of the
  94575. ** comparison is inverted. For the max() aggregate, the
  94576. ** sqlite3_user_data() function returns (void *)-1. For min() it
  94577. ** returns (void *)db, where db is the sqlite3* database pointer.
  94578. ** Therefore the next statement sets variable 'max' to 1 for the max()
  94579. ** aggregate, or 0 for min().
  94580. */
  94581. max = sqlite3_user_data(context)!=0;
  94582. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  94583. if( (max && cmp<0) || (!max && cmp>0) ){
  94584. sqlite3VdbeMemCopy(pBest, pArg);
  94585. }else{
  94586. sqlite3SkipAccumulatorLoad(context);
  94587. }
  94588. }else{
  94589. pBest->db = sqlite3_context_db_handle(context);
  94590. sqlite3VdbeMemCopy(pBest, pArg);
  94591. }
  94592. }
  94593. static void minMaxFinalize(sqlite3_context *context){
  94594. sqlite3_value *pRes;
  94595. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  94596. if( pRes ){
  94597. if( pRes->flags ){
  94598. sqlite3_result_value(context, pRes);
  94599. }
  94600. sqlite3VdbeMemRelease(pRes);
  94601. }
  94602. }
  94603. /*
  94604. ** group_concat(EXPR, ?SEPARATOR?)
  94605. */
  94606. static void groupConcatStep(
  94607. sqlite3_context *context,
  94608. int argc,
  94609. sqlite3_value **argv
  94610. ){
  94611. const char *zVal;
  94612. StrAccum *pAccum;
  94613. const char *zSep;
  94614. int nVal, nSep;
  94615. assert( argc==1 || argc==2 );
  94616. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  94617. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  94618. if( pAccum ){
  94619. sqlite3 *db = sqlite3_context_db_handle(context);
  94620. int firstTerm = pAccum->mxAlloc==0;
  94621. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  94622. if( !firstTerm ){
  94623. if( argc==2 ){
  94624. zSep = (char*)sqlite3_value_text(argv[1]);
  94625. nSep = sqlite3_value_bytes(argv[1]);
  94626. }else{
  94627. zSep = ",";
  94628. nSep = 1;
  94629. }
  94630. if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  94631. }
  94632. zVal = (char*)sqlite3_value_text(argv[0]);
  94633. nVal = sqlite3_value_bytes(argv[0]);
  94634. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  94635. }
  94636. }
  94637. static void groupConcatFinalize(sqlite3_context *context){
  94638. StrAccum *pAccum;
  94639. pAccum = sqlite3_aggregate_context(context, 0);
  94640. if( pAccum ){
  94641. if( pAccum->accError==STRACCUM_TOOBIG ){
  94642. sqlite3_result_error_toobig(context);
  94643. }else if( pAccum->accError==STRACCUM_NOMEM ){
  94644. sqlite3_result_error_nomem(context);
  94645. }else{
  94646. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  94647. sqlite3_free);
  94648. }
  94649. }
  94650. }
  94651. /*
  94652. ** This routine does per-connection function registration. Most
  94653. ** of the built-in functions above are part of the global function set.
  94654. ** This routine only deals with those that are not global.
  94655. */
  94656. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  94657. int rc = sqlite3_overload_function(db, "MATCH", 2);
  94658. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  94659. if( rc==SQLITE_NOMEM ){
  94660. db->mallocFailed = 1;
  94661. }
  94662. }
  94663. /*
  94664. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  94665. */
  94666. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  94667. FuncDef *pDef;
  94668. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  94669. 2, SQLITE_UTF8, 0);
  94670. if( ALWAYS(pDef) ){
  94671. pDef->funcFlags |= flagVal;
  94672. }
  94673. }
  94674. /*
  94675. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  94676. ** parameter determines whether or not the LIKE operator is case
  94677. ** sensitive. GLOB is always case sensitive.
  94678. */
  94679. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  94680. struct compareInfo *pInfo;
  94681. if( caseSensitive ){
  94682. pInfo = (struct compareInfo*)&likeInfoAlt;
  94683. }else{
  94684. pInfo = (struct compareInfo*)&likeInfoNorm;
  94685. }
  94686. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  94687. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  94688. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  94689. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  94690. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  94691. setLikeOptFlag(db, "like",
  94692. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  94693. }
  94694. /*
  94695. ** pExpr points to an expression which implements a function. If
  94696. ** it is appropriate to apply the LIKE optimization to that function
  94697. ** then set aWc[0] through aWc[2] to the wildcard characters and
  94698. ** return TRUE. If the function is not a LIKE-style function then
  94699. ** return FALSE.
  94700. **
  94701. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  94702. ** the function (default for LIKE). If the function makes the distinction
  94703. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  94704. ** false.
  94705. */
  94706. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  94707. FuncDef *pDef;
  94708. if( pExpr->op!=TK_FUNCTION
  94709. || !pExpr->x.pList
  94710. || pExpr->x.pList->nExpr!=2
  94711. ){
  94712. return 0;
  94713. }
  94714. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  94715. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  94716. sqlite3Strlen30(pExpr->u.zToken),
  94717. 2, SQLITE_UTF8, 0);
  94718. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  94719. return 0;
  94720. }
  94721. /* The memcpy() statement assumes that the wildcard characters are
  94722. ** the first three statements in the compareInfo structure. The
  94723. ** asserts() that follow verify that assumption
  94724. */
  94725. memcpy(aWc, pDef->pUserData, 3);
  94726. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  94727. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  94728. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  94729. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  94730. return 1;
  94731. }
  94732. /*
  94733. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  94734. ** to the global function hash table. This occurs at start-time (as
  94735. ** a consequence of calling sqlite3_initialize()).
  94736. **
  94737. ** After this routine runs
  94738. */
  94739. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  94740. /*
  94741. ** The following array holds FuncDef structures for all of the functions
  94742. ** defined in this file.
  94743. **
  94744. ** The array cannot be constant since changes are made to the
  94745. ** FuncDef.pHash elements at start-time. The elements of this array
  94746. ** are read-only after initialization is complete.
  94747. */
  94748. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  94749. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  94750. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  94751. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  94752. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  94753. FUNCTION(trim, 1, 3, 0, trimFunc ),
  94754. FUNCTION(trim, 2, 3, 0, trimFunc ),
  94755. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  94756. FUNCTION(min, 0, 0, 1, 0 ),
  94757. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  94758. SQLITE_FUNC_MINMAX ),
  94759. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  94760. FUNCTION(max, 0, 1, 1, 0 ),
  94761. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  94762. SQLITE_FUNC_MINMAX ),
  94763. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  94764. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  94765. FUNCTION(instr, 2, 0, 0, instrFunc ),
  94766. FUNCTION(substr, 2, 0, 0, substrFunc ),
  94767. FUNCTION(substr, 3, 0, 0, substrFunc ),
  94768. FUNCTION(printf, -1, 0, 0, printfFunc ),
  94769. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  94770. FUNCTION(char, -1, 0, 0, charFunc ),
  94771. FUNCTION(abs, 1, 0, 0, absFunc ),
  94772. #ifndef SQLITE_OMIT_FLOATING_POINT
  94773. FUNCTION(round, 1, 0, 0, roundFunc ),
  94774. FUNCTION(round, 2, 0, 0, roundFunc ),
  94775. #endif
  94776. FUNCTION(upper, 1, 0, 0, upperFunc ),
  94777. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  94778. FUNCTION(coalesce, 1, 0, 0, 0 ),
  94779. FUNCTION(coalesce, 0, 0, 0, 0 ),
  94780. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  94781. FUNCTION(hex, 1, 0, 0, hexFunc ),
  94782. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  94783. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  94784. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  94785. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  94786. VFUNCTION(random, 0, 0, 0, randomFunc ),
  94787. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  94788. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  94789. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  94790. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  94791. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  94792. #if SQLITE_USER_AUTHENTICATION
  94793. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  94794. #endif
  94795. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  94796. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  94797. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  94798. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  94799. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  94800. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  94801. VFUNCTION(changes, 0, 0, 0, changes ),
  94802. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  94803. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  94804. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  94805. #ifdef SQLITE_SOUNDEX
  94806. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  94807. #endif
  94808. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  94809. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  94810. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  94811. #endif
  94812. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  94813. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  94814. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  94815. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  94816. SQLITE_FUNC_COUNT ),
  94817. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  94818. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  94819. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  94820. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  94821. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  94822. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  94823. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  94824. #else
  94825. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  94826. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  94827. #endif
  94828. };
  94829. int i;
  94830. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  94831. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  94832. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  94833. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  94834. }
  94835. sqlite3RegisterDateTimeFunctions();
  94836. #ifndef SQLITE_OMIT_ALTERTABLE
  94837. sqlite3AlterFunctions();
  94838. #endif
  94839. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  94840. sqlite3AnalyzeFunctions();
  94841. #endif
  94842. }
  94843. /************** End of func.c ************************************************/
  94844. /************** Begin file fkey.c ********************************************/
  94845. /*
  94846. **
  94847. ** The author disclaims copyright to this source code. In place of
  94848. ** a legal notice, here is a blessing:
  94849. **
  94850. ** May you do good and not evil.
  94851. ** May you find forgiveness for yourself and forgive others.
  94852. ** May you share freely, never taking more than you give.
  94853. **
  94854. *************************************************************************
  94855. ** This file contains code used by the compiler to add foreign key
  94856. ** support to compiled SQL statements.
  94857. */
  94858. /* #include "sqliteInt.h" */
  94859. #ifndef SQLITE_OMIT_FOREIGN_KEY
  94860. #ifndef SQLITE_OMIT_TRIGGER
  94861. /*
  94862. ** Deferred and Immediate FKs
  94863. ** --------------------------
  94864. **
  94865. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  94866. ** If an immediate foreign key constraint is violated,
  94867. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  94868. ** statement transaction rolled back. If a
  94869. ** deferred foreign key constraint is violated, no action is taken
  94870. ** immediately. However if the application attempts to commit the
  94871. ** transaction before fixing the constraint violation, the attempt fails.
  94872. **
  94873. ** Deferred constraints are implemented using a simple counter associated
  94874. ** with the database handle. The counter is set to zero each time a
  94875. ** database transaction is opened. Each time a statement is executed
  94876. ** that causes a foreign key violation, the counter is incremented. Each
  94877. ** time a statement is executed that removes an existing violation from
  94878. ** the database, the counter is decremented. When the transaction is
  94879. ** committed, the commit fails if the current value of the counter is
  94880. ** greater than zero. This scheme has two big drawbacks:
  94881. **
  94882. ** * When a commit fails due to a deferred foreign key constraint,
  94883. ** there is no way to tell which foreign constraint is not satisfied,
  94884. ** or which row it is not satisfied for.
  94885. **
  94886. ** * If the database contains foreign key violations when the
  94887. ** transaction is opened, this may cause the mechanism to malfunction.
  94888. **
  94889. ** Despite these problems, this approach is adopted as it seems simpler
  94890. ** than the alternatives.
  94891. **
  94892. ** INSERT operations:
  94893. **
  94894. ** I.1) For each FK for which the table is the child table, search
  94895. ** the parent table for a match. If none is found increment the
  94896. ** constraint counter.
  94897. **
  94898. ** I.2) For each FK for which the table is the parent table,
  94899. ** search the child table for rows that correspond to the new
  94900. ** row in the parent table. Decrement the counter for each row
  94901. ** found (as the constraint is now satisfied).
  94902. **
  94903. ** DELETE operations:
  94904. **
  94905. ** D.1) For each FK for which the table is the child table,
  94906. ** search the parent table for a row that corresponds to the
  94907. ** deleted row in the child table. If such a row is not found,
  94908. ** decrement the counter.
  94909. **
  94910. ** D.2) For each FK for which the table is the parent table, search
  94911. ** the child table for rows that correspond to the deleted row
  94912. ** in the parent table. For each found increment the counter.
  94913. **
  94914. ** UPDATE operations:
  94915. **
  94916. ** An UPDATE command requires that all 4 steps above are taken, but only
  94917. ** for FK constraints for which the affected columns are actually
  94918. ** modified (values must be compared at runtime).
  94919. **
  94920. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  94921. ** This simplifies the implementation a bit.
  94922. **
  94923. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  94924. ** resolution is considered to delete rows before the new row is inserted.
  94925. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  94926. ** is thrown, even if the FK constraint would be satisfied after the new
  94927. ** row is inserted.
  94928. **
  94929. ** Immediate constraints are usually handled similarly. The only difference
  94930. ** is that the counter used is stored as part of each individual statement
  94931. ** object (struct Vdbe). If, after the statement has run, its immediate
  94932. ** constraint counter is greater than zero,
  94933. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  94934. ** and the statement transaction is rolled back. An exception is an INSERT
  94935. ** statement that inserts a single row only (no triggers). In this case,
  94936. ** instead of using a counter, an exception is thrown immediately if the
  94937. ** INSERT violates a foreign key constraint. This is necessary as such
  94938. ** an INSERT does not open a statement transaction.
  94939. **
  94940. ** TODO: How should dropping a table be handled? How should renaming a
  94941. ** table be handled?
  94942. **
  94943. **
  94944. ** Query API Notes
  94945. ** ---------------
  94946. **
  94947. ** Before coding an UPDATE or DELETE row operation, the code-generator
  94948. ** for those two operations needs to know whether or not the operation
  94949. ** requires any FK processing and, if so, which columns of the original
  94950. ** row are required by the FK processing VDBE code (i.e. if FKs were
  94951. ** implemented using triggers, which of the old.* columns would be
  94952. ** accessed). No information is required by the code-generator before
  94953. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  94954. ** generation code to query for this information are:
  94955. **
  94956. ** sqlite3FkRequired() - Test to see if FK processing is required.
  94957. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  94958. **
  94959. **
  94960. ** Externally accessible module functions
  94961. ** --------------------------------------
  94962. **
  94963. ** sqlite3FkCheck() - Check for foreign key violations.
  94964. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  94965. ** sqlite3FkDelete() - Delete an FKey structure.
  94966. */
  94967. /*
  94968. ** VDBE Calling Convention
  94969. ** -----------------------
  94970. **
  94971. ** Example:
  94972. **
  94973. ** For the following INSERT statement:
  94974. **
  94975. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  94976. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  94977. **
  94978. ** Register (x): 2 (type integer)
  94979. ** Register (x+1): 1 (type integer)
  94980. ** Register (x+2): NULL (type NULL)
  94981. ** Register (x+3): 3.1 (type real)
  94982. */
  94983. /*
  94984. ** A foreign key constraint requires that the key columns in the parent
  94985. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  94986. ** Given that pParent is the parent table for foreign key constraint pFKey,
  94987. ** search the schema for a unique index on the parent key columns.
  94988. **
  94989. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  94990. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  94991. ** is set to point to the unique index.
  94992. **
  94993. ** If the parent key consists of a single column (the foreign key constraint
  94994. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  94995. ** Otherwise, it is set to point to an allocated array of size N, where
  94996. ** N is the number of columns in the parent key. The first element of the
  94997. ** array is the index of the child table column that is mapped by the FK
  94998. ** constraint to the parent table column stored in the left-most column
  94999. ** of index *ppIdx. The second element of the array is the index of the
  95000. ** child table column that corresponds to the second left-most column of
  95001. ** *ppIdx, and so on.
  95002. **
  95003. ** If the required index cannot be found, either because:
  95004. **
  95005. ** 1) The named parent key columns do not exist, or
  95006. **
  95007. ** 2) The named parent key columns do exist, but are not subject to a
  95008. ** UNIQUE or PRIMARY KEY constraint, or
  95009. **
  95010. ** 3) No parent key columns were provided explicitly as part of the
  95011. ** foreign key definition, and the parent table does not have a
  95012. ** PRIMARY KEY, or
  95013. **
  95014. ** 4) No parent key columns were provided explicitly as part of the
  95015. ** foreign key definition, and the PRIMARY KEY of the parent table
  95016. ** consists of a different number of columns to the child key in
  95017. ** the child table.
  95018. **
  95019. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  95020. ** into pParse. If an OOM error occurs, non-zero is returned and the
  95021. ** pParse->db->mallocFailed flag is set.
  95022. */
  95023. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  95024. Parse *pParse, /* Parse context to store any error in */
  95025. Table *pParent, /* Parent table of FK constraint pFKey */
  95026. FKey *pFKey, /* Foreign key to find index for */
  95027. Index **ppIdx, /* OUT: Unique index on parent table */
  95028. int **paiCol /* OUT: Map of index columns in pFKey */
  95029. ){
  95030. Index *pIdx = 0; /* Value to return via *ppIdx */
  95031. int *aiCol = 0; /* Value to return via *paiCol */
  95032. int nCol = pFKey->nCol; /* Number of columns in parent key */
  95033. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  95034. /* The caller is responsible for zeroing output parameters. */
  95035. assert( ppIdx && *ppIdx==0 );
  95036. assert( !paiCol || *paiCol==0 );
  95037. assert( pParse );
  95038. /* If this is a non-composite (single column) foreign key, check if it
  95039. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  95040. ** and *paiCol set to zero and return early.
  95041. **
  95042. ** Otherwise, for a composite foreign key (more than one column), allocate
  95043. ** space for the aiCol array (returned via output parameter *paiCol).
  95044. ** Non-composite foreign keys do not require the aiCol array.
  95045. */
  95046. if( nCol==1 ){
  95047. /* The FK maps to the IPK if any of the following are true:
  95048. **
  95049. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  95050. ** mapped to the primary key of table pParent, or
  95051. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  95052. ** PRIMARY KEY.
  95053. */
  95054. if( pParent->iPKey>=0 ){
  95055. if( !zKey ) return 0;
  95056. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  95057. }
  95058. }else if( paiCol ){
  95059. assert( nCol>1 );
  95060. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  95061. if( !aiCol ) return 1;
  95062. *paiCol = aiCol;
  95063. }
  95064. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  95065. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
  95066. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  95067. ** of columns. If each indexed column corresponds to a foreign key
  95068. ** column of pFKey, then this index is a winner. */
  95069. if( zKey==0 ){
  95070. /* If zKey is NULL, then this foreign key is implicitly mapped to
  95071. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  95072. ** identified by the test. */
  95073. if( IsPrimaryKeyIndex(pIdx) ){
  95074. if( aiCol ){
  95075. int i;
  95076. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  95077. }
  95078. break;
  95079. }
  95080. }else{
  95081. /* If zKey is non-NULL, then this foreign key was declared to
  95082. ** map to an explicit list of columns in table pParent. Check if this
  95083. ** index matches those columns. Also, check that the index uses
  95084. ** the default collation sequences for each column. */
  95085. int i, j;
  95086. for(i=0; i<nCol; i++){
  95087. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  95088. const char *zDfltColl; /* Def. collation for column */
  95089. char *zIdxCol; /* Name of indexed column */
  95090. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  95091. /* If the index uses a collation sequence that is different from
  95092. ** the default collation sequence for the column, this index is
  95093. ** unusable. Bail out early in this case. */
  95094. zDfltColl = pParent->aCol[iCol].zColl;
  95095. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  95096. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  95097. zIdxCol = pParent->aCol[iCol].zName;
  95098. for(j=0; j<nCol; j++){
  95099. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  95100. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  95101. break;
  95102. }
  95103. }
  95104. if( j==nCol ) break;
  95105. }
  95106. if( i==nCol ) break; /* pIdx is usable */
  95107. }
  95108. }
  95109. }
  95110. if( !pIdx ){
  95111. if( !pParse->disableTriggers ){
  95112. sqlite3ErrorMsg(pParse,
  95113. "foreign key mismatch - \"%w\" referencing \"%w\"",
  95114. pFKey->pFrom->zName, pFKey->zTo);
  95115. }
  95116. sqlite3DbFree(pParse->db, aiCol);
  95117. return 1;
  95118. }
  95119. *ppIdx = pIdx;
  95120. return 0;
  95121. }
  95122. /*
  95123. ** This function is called when a row is inserted into or deleted from the
  95124. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  95125. ** on the child table of pFKey, this function is invoked twice for each row
  95126. ** affected - once to "delete" the old row, and then again to "insert" the
  95127. ** new row.
  95128. **
  95129. ** Each time it is called, this function generates VDBE code to locate the
  95130. ** row in the parent table that corresponds to the row being inserted into
  95131. ** or deleted from the child table. If the parent row can be found, no
  95132. ** special action is taken. Otherwise, if the parent row can *not* be
  95133. ** found in the parent table:
  95134. **
  95135. ** Operation | FK type | Action taken
  95136. ** --------------------------------------------------------------------------
  95137. ** INSERT immediate Increment the "immediate constraint counter".
  95138. **
  95139. ** DELETE immediate Decrement the "immediate constraint counter".
  95140. **
  95141. ** INSERT deferred Increment the "deferred constraint counter".
  95142. **
  95143. ** DELETE deferred Decrement the "deferred constraint counter".
  95144. **
  95145. ** These operations are identified in the comment at the top of this file
  95146. ** (fkey.c) as "I.1" and "D.1".
  95147. */
  95148. static void fkLookupParent(
  95149. Parse *pParse, /* Parse context */
  95150. int iDb, /* Index of database housing pTab */
  95151. Table *pTab, /* Parent table of FK pFKey */
  95152. Index *pIdx, /* Unique index on parent key columns in pTab */
  95153. FKey *pFKey, /* Foreign key constraint */
  95154. int *aiCol, /* Map from parent key columns to child table columns */
  95155. int regData, /* Address of array containing child table row */
  95156. int nIncr, /* Increment constraint counter by this */
  95157. int isIgnore /* If true, pretend pTab contains all NULL values */
  95158. ){
  95159. int i; /* Iterator variable */
  95160. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  95161. int iCur = pParse->nTab - 1; /* Cursor number to use */
  95162. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  95163. /* If nIncr is less than zero, then check at runtime if there are any
  95164. ** outstanding constraints to resolve. If there are not, there is no need
  95165. ** to check if deleting this row resolves any outstanding violations.
  95166. **
  95167. ** Check if any of the key columns in the child table row are NULL. If
  95168. ** any are, then the constraint is considered satisfied. No need to
  95169. ** search for a matching row in the parent table. */
  95170. if( nIncr<0 ){
  95171. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  95172. VdbeCoverage(v);
  95173. }
  95174. for(i=0; i<pFKey->nCol; i++){
  95175. int iReg = aiCol[i] + regData + 1;
  95176. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  95177. }
  95178. if( isIgnore==0 ){
  95179. if( pIdx==0 ){
  95180. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  95181. ** column of the parent table (table pTab). */
  95182. int iMustBeInt; /* Address of MustBeInt instruction */
  95183. int regTemp = sqlite3GetTempReg(pParse);
  95184. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  95185. ** apply the affinity of the parent key). If this fails, then there
  95186. ** is no matching parent key. Before using MustBeInt, make a copy of
  95187. ** the value. Otherwise, the value inserted into the child key column
  95188. ** will have INTEGER affinity applied to it, which may not be correct. */
  95189. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  95190. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  95191. VdbeCoverage(v);
  95192. /* If the parent table is the same as the child table, and we are about
  95193. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  95194. ** then check if the row being inserted matches itself. If so, do not
  95195. ** increment the constraint-counter. */
  95196. if( pTab==pFKey->pFrom && nIncr==1 ){
  95197. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  95198. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  95199. }
  95200. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  95201. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  95202. sqlite3VdbeGoto(v, iOk);
  95203. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  95204. sqlite3VdbeJumpHere(v, iMustBeInt);
  95205. sqlite3ReleaseTempReg(pParse, regTemp);
  95206. }else{
  95207. int nCol = pFKey->nCol;
  95208. int regTemp = sqlite3GetTempRange(pParse, nCol);
  95209. int regRec = sqlite3GetTempReg(pParse);
  95210. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  95211. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  95212. for(i=0; i<nCol; i++){
  95213. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  95214. }
  95215. /* If the parent table is the same as the child table, and we are about
  95216. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  95217. ** then check if the row being inserted matches itself. If so, do not
  95218. ** increment the constraint-counter.
  95219. **
  95220. ** If any of the parent-key values are NULL, then the row cannot match
  95221. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  95222. ** of the parent-key values are NULL (at this point it is known that
  95223. ** none of the child key values are).
  95224. */
  95225. if( pTab==pFKey->pFrom && nIncr==1 ){
  95226. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  95227. for(i=0; i<nCol; i++){
  95228. int iChild = aiCol[i]+1+regData;
  95229. int iParent = pIdx->aiColumn[i]+1+regData;
  95230. assert( pIdx->aiColumn[i]>=0 );
  95231. assert( aiCol[i]!=pTab->iPKey );
  95232. if( pIdx->aiColumn[i]==pTab->iPKey ){
  95233. /* The parent key is a composite key that includes the IPK column */
  95234. iParent = regData;
  95235. }
  95236. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  95237. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  95238. }
  95239. sqlite3VdbeGoto(v, iOk);
  95240. }
  95241. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  95242. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  95243. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  95244. sqlite3ReleaseTempReg(pParse, regRec);
  95245. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  95246. }
  95247. }
  95248. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  95249. && !pParse->pToplevel
  95250. && !pParse->isMultiWrite
  95251. ){
  95252. /* Special case: If this is an INSERT statement that will insert exactly
  95253. ** one row into the table, raise a constraint immediately instead of
  95254. ** incrementing a counter. This is necessary as the VM code is being
  95255. ** generated for will not open a statement transaction. */
  95256. assert( nIncr==1 );
  95257. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  95258. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  95259. }else{
  95260. if( nIncr>0 && pFKey->isDeferred==0 ){
  95261. sqlite3MayAbort(pParse);
  95262. }
  95263. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  95264. }
  95265. sqlite3VdbeResolveLabel(v, iOk);
  95266. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  95267. }
  95268. /*
  95269. ** Return an Expr object that refers to a memory register corresponding
  95270. ** to column iCol of table pTab.
  95271. **
  95272. ** regBase is the first of an array of register that contains the data
  95273. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  95274. ** column. regBase+2 holds the second column, and so forth.
  95275. */
  95276. static Expr *exprTableRegister(
  95277. Parse *pParse, /* Parsing and code generating context */
  95278. Table *pTab, /* The table whose content is at r[regBase]... */
  95279. int regBase, /* Contents of table pTab */
  95280. i16 iCol /* Which column of pTab is desired */
  95281. ){
  95282. Expr *pExpr;
  95283. Column *pCol;
  95284. const char *zColl;
  95285. sqlite3 *db = pParse->db;
  95286. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  95287. if( pExpr ){
  95288. if( iCol>=0 && iCol!=pTab->iPKey ){
  95289. pCol = &pTab->aCol[iCol];
  95290. pExpr->iTable = regBase + iCol + 1;
  95291. pExpr->affinity = pCol->affinity;
  95292. zColl = pCol->zColl;
  95293. if( zColl==0 ) zColl = db->pDfltColl->zName;
  95294. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  95295. }else{
  95296. pExpr->iTable = regBase;
  95297. pExpr->affinity = SQLITE_AFF_INTEGER;
  95298. }
  95299. }
  95300. return pExpr;
  95301. }
  95302. /*
  95303. ** Return an Expr object that refers to column iCol of table pTab which
  95304. ** has cursor iCur.
  95305. */
  95306. static Expr *exprTableColumn(
  95307. sqlite3 *db, /* The database connection */
  95308. Table *pTab, /* The table whose column is desired */
  95309. int iCursor, /* The open cursor on the table */
  95310. i16 iCol /* The column that is wanted */
  95311. ){
  95312. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  95313. if( pExpr ){
  95314. pExpr->pTab = pTab;
  95315. pExpr->iTable = iCursor;
  95316. pExpr->iColumn = iCol;
  95317. }
  95318. return pExpr;
  95319. }
  95320. /*
  95321. ** This function is called to generate code executed when a row is deleted
  95322. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  95323. ** deferred, when a row is inserted into the same table. When generating
  95324. ** code for an SQL UPDATE operation, this function may be called twice -
  95325. ** once to "delete" the old row and once to "insert" the new row.
  95326. **
  95327. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  95328. ** the number of FK violations in the db) or +1 when deleting one (as this
  95329. ** may increase the number of FK constraint problems).
  95330. **
  95331. ** The code generated by this function scans through the rows in the child
  95332. ** table that correspond to the parent table row being deleted or inserted.
  95333. ** For each child row found, one of the following actions is taken:
  95334. **
  95335. ** Operation | FK type | Action taken
  95336. ** --------------------------------------------------------------------------
  95337. ** DELETE immediate Increment the "immediate constraint counter".
  95338. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  95339. ** throw a "FOREIGN KEY constraint failed" exception.
  95340. **
  95341. ** INSERT immediate Decrement the "immediate constraint counter".
  95342. **
  95343. ** DELETE deferred Increment the "deferred constraint counter".
  95344. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  95345. ** throw a "FOREIGN KEY constraint failed" exception.
  95346. **
  95347. ** INSERT deferred Decrement the "deferred constraint counter".
  95348. **
  95349. ** These operations are identified in the comment at the top of this file
  95350. ** (fkey.c) as "I.2" and "D.2".
  95351. */
  95352. static void fkScanChildren(
  95353. Parse *pParse, /* Parse context */
  95354. SrcList *pSrc, /* The child table to be scanned */
  95355. Table *pTab, /* The parent table */
  95356. Index *pIdx, /* Index on parent covering the foreign key */
  95357. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  95358. int *aiCol, /* Map from pIdx cols to child table cols */
  95359. int regData, /* Parent row data starts here */
  95360. int nIncr /* Amount to increment deferred counter by */
  95361. ){
  95362. sqlite3 *db = pParse->db; /* Database handle */
  95363. int i; /* Iterator variable */
  95364. Expr *pWhere = 0; /* WHERE clause to scan with */
  95365. NameContext sNameContext; /* Context used to resolve WHERE clause */
  95366. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  95367. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  95368. Vdbe *v = sqlite3GetVdbe(pParse);
  95369. assert( pIdx==0 || pIdx->pTable==pTab );
  95370. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  95371. assert( pIdx!=0 || pFKey->nCol==1 );
  95372. assert( pIdx!=0 || HasRowid(pTab) );
  95373. if( nIncr<0 ){
  95374. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  95375. VdbeCoverage(v);
  95376. }
  95377. /* Create an Expr object representing an SQL expression like:
  95378. **
  95379. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  95380. **
  95381. ** The collation sequence used for the comparison should be that of
  95382. ** the parent key columns. The affinity of the parent key column should
  95383. ** be applied to each child key value before the comparison takes place.
  95384. */
  95385. for(i=0; i<pFKey->nCol; i++){
  95386. Expr *pLeft; /* Value from parent table row */
  95387. Expr *pRight; /* Column ref to child table */
  95388. Expr *pEq; /* Expression (pLeft = pRight) */
  95389. i16 iCol; /* Index of column in child table */
  95390. const char *zCol; /* Name of column in child table */
  95391. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  95392. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  95393. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  95394. assert( iCol>=0 );
  95395. zCol = pFKey->pFrom->aCol[iCol].zName;
  95396. pRight = sqlite3Expr(db, TK_ID, zCol);
  95397. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  95398. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  95399. }
  95400. /* If the child table is the same as the parent table, then add terms
  95401. ** to the WHERE clause that prevent this entry from being scanned.
  95402. ** The added WHERE clause terms are like this:
  95403. **
  95404. ** $current_rowid!=rowid
  95405. ** NOT( $current_a==a AND $current_b==b AND ... )
  95406. **
  95407. ** The first form is used for rowid tables. The second form is used
  95408. ** for WITHOUT ROWID tables. In the second form, the primary key is
  95409. ** (a,b,...)
  95410. */
  95411. if( pTab==pFKey->pFrom && nIncr>0 ){
  95412. Expr *pNe; /* Expression (pLeft != pRight) */
  95413. Expr *pLeft; /* Value from parent table row */
  95414. Expr *pRight; /* Column ref to child table */
  95415. if( HasRowid(pTab) ){
  95416. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  95417. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  95418. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  95419. }else{
  95420. Expr *pEq, *pAll = 0;
  95421. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  95422. assert( pIdx!=0 );
  95423. for(i=0; i<pPk->nKeyCol; i++){
  95424. i16 iCol = pIdx->aiColumn[i];
  95425. assert( iCol>=0 );
  95426. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  95427. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  95428. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  95429. pAll = sqlite3ExprAnd(db, pAll, pEq);
  95430. }
  95431. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
  95432. }
  95433. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  95434. }
  95435. /* Resolve the references in the WHERE clause. */
  95436. memset(&sNameContext, 0, sizeof(NameContext));
  95437. sNameContext.pSrcList = pSrc;
  95438. sNameContext.pParse = pParse;
  95439. sqlite3ResolveExprNames(&sNameContext, pWhere);
  95440. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  95441. ** clause. For each row found, increment either the deferred or immediate
  95442. ** foreign key constraint counter. */
  95443. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  95444. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  95445. if( pWInfo ){
  95446. sqlite3WhereEnd(pWInfo);
  95447. }
  95448. /* Clean up the WHERE clause constructed above. */
  95449. sqlite3ExprDelete(db, pWhere);
  95450. if( iFkIfZero ){
  95451. sqlite3VdbeJumpHere(v, iFkIfZero);
  95452. }
  95453. }
  95454. /*
  95455. ** This function returns a linked list of FKey objects (connected by
  95456. ** FKey.pNextTo) holding all children of table pTab. For example,
  95457. ** given the following schema:
  95458. **
  95459. ** CREATE TABLE t1(a PRIMARY KEY);
  95460. ** CREATE TABLE t2(b REFERENCES t1(a);
  95461. **
  95462. ** Calling this function with table "t1" as an argument returns a pointer
  95463. ** to the FKey structure representing the foreign key constraint on table
  95464. ** "t2". Calling this function with "t2" as the argument would return a
  95465. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  95466. ** table).
  95467. */
  95468. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  95469. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  95470. }
  95471. /*
  95472. ** The second argument is a Trigger structure allocated by the
  95473. ** fkActionTrigger() routine. This function deletes the Trigger structure
  95474. ** and all of its sub-components.
  95475. **
  95476. ** The Trigger structure or any of its sub-components may be allocated from
  95477. ** the lookaside buffer belonging to database handle dbMem.
  95478. */
  95479. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  95480. if( p ){
  95481. TriggerStep *pStep = p->step_list;
  95482. sqlite3ExprDelete(dbMem, pStep->pWhere);
  95483. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  95484. sqlite3SelectDelete(dbMem, pStep->pSelect);
  95485. sqlite3ExprDelete(dbMem, p->pWhen);
  95486. sqlite3DbFree(dbMem, p);
  95487. }
  95488. }
  95489. /*
  95490. ** This function is called to generate code that runs when table pTab is
  95491. ** being dropped from the database. The SrcList passed as the second argument
  95492. ** to this function contains a single entry guaranteed to resolve to
  95493. ** table pTab.
  95494. **
  95495. ** Normally, no code is required. However, if either
  95496. **
  95497. ** (a) The table is the parent table of a FK constraint, or
  95498. ** (b) The table is the child table of a deferred FK constraint and it is
  95499. ** determined at runtime that there are outstanding deferred FK
  95500. ** constraint violations in the database,
  95501. **
  95502. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  95503. ** the table from the database. Triggers are disabled while running this
  95504. ** DELETE, but foreign key actions are not.
  95505. */
  95506. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  95507. sqlite3 *db = pParse->db;
  95508. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  95509. int iSkip = 0;
  95510. Vdbe *v = sqlite3GetVdbe(pParse);
  95511. assert( v ); /* VDBE has already been allocated */
  95512. if( sqlite3FkReferences(pTab)==0 ){
  95513. /* Search for a deferred foreign key constraint for which this table
  95514. ** is the child table. If one cannot be found, return without
  95515. ** generating any VDBE code. If one can be found, then jump over
  95516. ** the entire DELETE if there are no outstanding deferred constraints
  95517. ** when this statement is run. */
  95518. FKey *p;
  95519. for(p=pTab->pFKey; p; p=p->pNextFrom){
  95520. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  95521. }
  95522. if( !p ) return;
  95523. iSkip = sqlite3VdbeMakeLabel(v);
  95524. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  95525. }
  95526. pParse->disableTriggers = 1;
  95527. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  95528. pParse->disableTriggers = 0;
  95529. /* If the DELETE has generated immediate foreign key constraint
  95530. ** violations, halt the VDBE and return an error at this point, before
  95531. ** any modifications to the schema are made. This is because statement
  95532. ** transactions are not able to rollback schema changes.
  95533. **
  95534. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  95535. ** the statement transaction will not be rolled back even if FK
  95536. ** constraints are violated.
  95537. */
  95538. if( (db->flags & SQLITE_DeferFKs)==0 ){
  95539. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  95540. VdbeCoverage(v);
  95541. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  95542. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  95543. }
  95544. if( iSkip ){
  95545. sqlite3VdbeResolveLabel(v, iSkip);
  95546. }
  95547. }
  95548. }
  95549. /*
  95550. ** The second argument points to an FKey object representing a foreign key
  95551. ** for which pTab is the child table. An UPDATE statement against pTab
  95552. ** is currently being processed. For each column of the table that is
  95553. ** actually updated, the corresponding element in the aChange[] array
  95554. ** is zero or greater (if a column is unmodified the corresponding element
  95555. ** is set to -1). If the rowid column is modified by the UPDATE statement
  95556. ** the bChngRowid argument is non-zero.
  95557. **
  95558. ** This function returns true if any of the columns that are part of the
  95559. ** child key for FK constraint *p are modified.
  95560. */
  95561. static int fkChildIsModified(
  95562. Table *pTab, /* Table being updated */
  95563. FKey *p, /* Foreign key for which pTab is the child */
  95564. int *aChange, /* Array indicating modified columns */
  95565. int bChngRowid /* True if rowid is modified by this update */
  95566. ){
  95567. int i;
  95568. for(i=0; i<p->nCol; i++){
  95569. int iChildKey = p->aCol[i].iFrom;
  95570. if( aChange[iChildKey]>=0 ) return 1;
  95571. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  95572. }
  95573. return 0;
  95574. }
  95575. /*
  95576. ** The second argument points to an FKey object representing a foreign key
  95577. ** for which pTab is the parent table. An UPDATE statement against pTab
  95578. ** is currently being processed. For each column of the table that is
  95579. ** actually updated, the corresponding element in the aChange[] array
  95580. ** is zero or greater (if a column is unmodified the corresponding element
  95581. ** is set to -1). If the rowid column is modified by the UPDATE statement
  95582. ** the bChngRowid argument is non-zero.
  95583. **
  95584. ** This function returns true if any of the columns that are part of the
  95585. ** parent key for FK constraint *p are modified.
  95586. */
  95587. static int fkParentIsModified(
  95588. Table *pTab,
  95589. FKey *p,
  95590. int *aChange,
  95591. int bChngRowid
  95592. ){
  95593. int i;
  95594. for(i=0; i<p->nCol; i++){
  95595. char *zKey = p->aCol[i].zCol;
  95596. int iKey;
  95597. for(iKey=0; iKey<pTab->nCol; iKey++){
  95598. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  95599. Column *pCol = &pTab->aCol[iKey];
  95600. if( zKey ){
  95601. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  95602. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  95603. return 1;
  95604. }
  95605. }
  95606. }
  95607. }
  95608. return 0;
  95609. }
  95610. /*
  95611. ** Return true if the parser passed as the first argument is being
  95612. ** used to code a trigger that is really a "SET NULL" action belonging
  95613. ** to trigger pFKey.
  95614. */
  95615. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  95616. Parse *pTop = sqlite3ParseToplevel(pParse);
  95617. if( pTop->pTriggerPrg ){
  95618. Trigger *p = pTop->pTriggerPrg->pTrigger;
  95619. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  95620. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  95621. ){
  95622. return 1;
  95623. }
  95624. }
  95625. return 0;
  95626. }
  95627. /*
  95628. ** This function is called when inserting, deleting or updating a row of
  95629. ** table pTab to generate VDBE code to perform foreign key constraint
  95630. ** processing for the operation.
  95631. **
  95632. ** For a DELETE operation, parameter regOld is passed the index of the
  95633. ** first register in an array of (pTab->nCol+1) registers containing the
  95634. ** rowid of the row being deleted, followed by each of the column values
  95635. ** of the row being deleted, from left to right. Parameter regNew is passed
  95636. ** zero in this case.
  95637. **
  95638. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  95639. ** first register of an array of (pTab->nCol+1) registers containing the new
  95640. ** row data.
  95641. **
  95642. ** For an UPDATE operation, this function is called twice. Once before
  95643. ** the original record is deleted from the table using the calling convention
  95644. ** described for DELETE. Then again after the original record is deleted
  95645. ** but before the new record is inserted using the INSERT convention.
  95646. */
  95647. SQLITE_PRIVATE void sqlite3FkCheck(
  95648. Parse *pParse, /* Parse context */
  95649. Table *pTab, /* Row is being deleted from this table */
  95650. int regOld, /* Previous row data is stored here */
  95651. int regNew, /* New row data is stored here */
  95652. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  95653. int bChngRowid /* True if rowid is UPDATEd */
  95654. ){
  95655. sqlite3 *db = pParse->db; /* Database handle */
  95656. FKey *pFKey; /* Used to iterate through FKs */
  95657. int iDb; /* Index of database containing pTab */
  95658. const char *zDb; /* Name of database containing pTab */
  95659. int isIgnoreErrors = pParse->disableTriggers;
  95660. /* Exactly one of regOld and regNew should be non-zero. */
  95661. assert( (regOld==0)!=(regNew==0) );
  95662. /* If foreign-keys are disabled, this function is a no-op. */
  95663. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  95664. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95665. zDb = db->aDb[iDb].zName;
  95666. /* Loop through all the foreign key constraints for which pTab is the
  95667. ** child table (the table that the foreign key definition is part of). */
  95668. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  95669. Table *pTo; /* Parent table of foreign key pFKey */
  95670. Index *pIdx = 0; /* Index on key columns in pTo */
  95671. int *aiFree = 0;
  95672. int *aiCol;
  95673. int iCol;
  95674. int i;
  95675. int bIgnore = 0;
  95676. if( aChange
  95677. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  95678. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  95679. ){
  95680. continue;
  95681. }
  95682. /* Find the parent table of this foreign key. Also find a unique index
  95683. ** on the parent key columns in the parent table. If either of these
  95684. ** schema items cannot be located, set an error in pParse and return
  95685. ** early. */
  95686. if( pParse->disableTriggers ){
  95687. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  95688. }else{
  95689. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  95690. }
  95691. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  95692. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  95693. if( !isIgnoreErrors || db->mallocFailed ) return;
  95694. if( pTo==0 ){
  95695. /* If isIgnoreErrors is true, then a table is being dropped. In this
  95696. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  95697. ** before actually dropping it in order to check FK constraints.
  95698. ** If the parent table of an FK constraint on the current table is
  95699. ** missing, behave as if it is empty. i.e. decrement the relevant
  95700. ** FK counter for each row of the current table with non-NULL keys.
  95701. */
  95702. Vdbe *v = sqlite3GetVdbe(pParse);
  95703. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  95704. for(i=0; i<pFKey->nCol; i++){
  95705. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  95706. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  95707. }
  95708. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  95709. }
  95710. continue;
  95711. }
  95712. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  95713. if( aiFree ){
  95714. aiCol = aiFree;
  95715. }else{
  95716. iCol = pFKey->aCol[0].iFrom;
  95717. aiCol = &iCol;
  95718. }
  95719. for(i=0; i<pFKey->nCol; i++){
  95720. if( aiCol[i]==pTab->iPKey ){
  95721. aiCol[i] = -1;
  95722. }
  95723. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  95724. #ifndef SQLITE_OMIT_AUTHORIZATION
  95725. /* Request permission to read the parent key columns. If the
  95726. ** authorization callback returns SQLITE_IGNORE, behave as if any
  95727. ** values read from the parent table are NULL. */
  95728. if( db->xAuth ){
  95729. int rcauth;
  95730. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  95731. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  95732. bIgnore = (rcauth==SQLITE_IGNORE);
  95733. }
  95734. #endif
  95735. }
  95736. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  95737. ** a cursor to use to search the unique index on the parent key columns
  95738. ** in the parent table. */
  95739. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  95740. pParse->nTab++;
  95741. if( regOld!=0 ){
  95742. /* A row is being removed from the child table. Search for the parent.
  95743. ** If the parent does not exist, removing the child row resolves an
  95744. ** outstanding foreign key constraint violation. */
  95745. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  95746. }
  95747. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  95748. /* A row is being added to the child table. If a parent row cannot
  95749. ** be found, adding the child row has violated the FK constraint.
  95750. **
  95751. ** If this operation is being performed as part of a trigger program
  95752. ** that is actually a "SET NULL" action belonging to this very
  95753. ** foreign key, then omit this scan altogether. As all child key
  95754. ** values are guaranteed to be NULL, it is not possible for adding
  95755. ** this row to cause an FK violation. */
  95756. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  95757. }
  95758. sqlite3DbFree(db, aiFree);
  95759. }
  95760. /* Loop through all the foreign key constraints that refer to this table.
  95761. ** (the "child" constraints) */
  95762. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  95763. Index *pIdx = 0; /* Foreign key index for pFKey */
  95764. SrcList *pSrc;
  95765. int *aiCol = 0;
  95766. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  95767. continue;
  95768. }
  95769. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  95770. && !pParse->pToplevel && !pParse->isMultiWrite
  95771. ){
  95772. assert( regOld==0 && regNew!=0 );
  95773. /* Inserting a single row into a parent table cannot cause (or fix)
  95774. ** an immediate foreign key violation. So do nothing in this case. */
  95775. continue;
  95776. }
  95777. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  95778. if( !isIgnoreErrors || db->mallocFailed ) return;
  95779. continue;
  95780. }
  95781. assert( aiCol || pFKey->nCol==1 );
  95782. /* Create a SrcList structure containing the child table. We need the
  95783. ** child table as a SrcList for sqlite3WhereBegin() */
  95784. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  95785. if( pSrc ){
  95786. struct SrcList_item *pItem = pSrc->a;
  95787. pItem->pTab = pFKey->pFrom;
  95788. pItem->zName = pFKey->pFrom->zName;
  95789. pItem->pTab->nRef++;
  95790. pItem->iCursor = pParse->nTab++;
  95791. if( regNew!=0 ){
  95792. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  95793. }
  95794. if( regOld!=0 ){
  95795. int eAction = pFKey->aAction[aChange!=0];
  95796. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  95797. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  95798. ** action applies, then any foreign key violations caused by
  95799. ** removing the parent key will be rectified by the action trigger.
  95800. ** So do not set the "may-abort" flag in this case.
  95801. **
  95802. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  95803. ** may-abort flag will eventually be set on this statement anyway
  95804. ** (when this function is called as part of processing the UPDATE
  95805. ** within the action trigger).
  95806. **
  95807. ** Note 2: At first glance it may seem like SQLite could simply omit
  95808. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  95809. ** applies. The trouble starts if the CASCADE or SET NULL action
  95810. ** trigger causes other triggers or action rules attached to the
  95811. ** child table to fire. In these cases the fk constraint counters
  95812. ** might be set incorrectly if any OP_FkCounter related scans are
  95813. ** omitted. */
  95814. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  95815. sqlite3MayAbort(pParse);
  95816. }
  95817. }
  95818. pItem->zName = 0;
  95819. sqlite3SrcListDelete(db, pSrc);
  95820. }
  95821. sqlite3DbFree(db, aiCol);
  95822. }
  95823. }
  95824. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  95825. /*
  95826. ** This function is called before generating code to update or delete a
  95827. ** row contained in table pTab.
  95828. */
  95829. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  95830. Parse *pParse, /* Parse context */
  95831. Table *pTab /* Table being modified */
  95832. ){
  95833. u32 mask = 0;
  95834. if( pParse->db->flags&SQLITE_ForeignKeys ){
  95835. FKey *p;
  95836. int i;
  95837. for(p=pTab->pFKey; p; p=p->pNextFrom){
  95838. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  95839. }
  95840. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  95841. Index *pIdx = 0;
  95842. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  95843. if( pIdx ){
  95844. for(i=0; i<pIdx->nKeyCol; i++){
  95845. assert( pIdx->aiColumn[i]>=0 );
  95846. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  95847. }
  95848. }
  95849. }
  95850. }
  95851. return mask;
  95852. }
  95853. /*
  95854. ** This function is called before generating code to update or delete a
  95855. ** row contained in table pTab. If the operation is a DELETE, then
  95856. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  95857. ** to an array of size N, where N is the number of columns in table pTab.
  95858. ** If the i'th column is not modified by the UPDATE, then the corresponding
  95859. ** entry in the aChange[] array is set to -1. If the column is modified,
  95860. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  95861. ** UPDATE statement modifies the rowid fields of the table.
  95862. **
  95863. ** If any foreign key processing will be required, this function returns
  95864. ** true. If there is no foreign key related processing, this function
  95865. ** returns false.
  95866. */
  95867. SQLITE_PRIVATE int sqlite3FkRequired(
  95868. Parse *pParse, /* Parse context */
  95869. Table *pTab, /* Table being modified */
  95870. int *aChange, /* Non-NULL for UPDATE operations */
  95871. int chngRowid /* True for UPDATE that affects rowid */
  95872. ){
  95873. if( pParse->db->flags&SQLITE_ForeignKeys ){
  95874. if( !aChange ){
  95875. /* A DELETE operation. Foreign key processing is required if the
  95876. ** table in question is either the child or parent table for any
  95877. ** foreign key constraint. */
  95878. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  95879. }else{
  95880. /* This is an UPDATE. Foreign key processing is only required if the
  95881. ** operation modifies one or more child or parent key columns. */
  95882. FKey *p;
  95883. /* Check if any child key columns are being modified. */
  95884. for(p=pTab->pFKey; p; p=p->pNextFrom){
  95885. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  95886. }
  95887. /* Check if any parent key columns are being modified. */
  95888. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  95889. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  95890. }
  95891. }
  95892. }
  95893. return 0;
  95894. }
  95895. /*
  95896. ** This function is called when an UPDATE or DELETE operation is being
  95897. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  95898. ** If the current operation is an UPDATE, then the pChanges parameter is
  95899. ** passed a pointer to the list of columns being modified. If it is a
  95900. ** DELETE, pChanges is passed a NULL pointer.
  95901. **
  95902. ** It returns a pointer to a Trigger structure containing a trigger
  95903. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  95904. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  95905. ** returned (these actions require no special handling by the triggers
  95906. ** sub-system, code for them is created by fkScanChildren()).
  95907. **
  95908. ** For example, if pFKey is the foreign key and pTab is table "p" in
  95909. ** the following schema:
  95910. **
  95911. ** CREATE TABLE p(pk PRIMARY KEY);
  95912. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  95913. **
  95914. ** then the returned trigger structure is equivalent to:
  95915. **
  95916. ** CREATE TRIGGER ... DELETE ON p BEGIN
  95917. ** DELETE FROM c WHERE ck = old.pk;
  95918. ** END;
  95919. **
  95920. ** The returned pointer is cached as part of the foreign key object. It
  95921. ** is eventually freed along with the rest of the foreign key object by
  95922. ** sqlite3FkDelete().
  95923. */
  95924. static Trigger *fkActionTrigger(
  95925. Parse *pParse, /* Parse context */
  95926. Table *pTab, /* Table being updated or deleted from */
  95927. FKey *pFKey, /* Foreign key to get action for */
  95928. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  95929. ){
  95930. sqlite3 *db = pParse->db; /* Database handle */
  95931. int action; /* One of OE_None, OE_Cascade etc. */
  95932. Trigger *pTrigger; /* Trigger definition to return */
  95933. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  95934. action = pFKey->aAction[iAction];
  95935. pTrigger = pFKey->apTrigger[iAction];
  95936. if( action!=OE_None && !pTrigger ){
  95937. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  95938. char const *zFrom; /* Name of child table */
  95939. int nFrom; /* Length in bytes of zFrom */
  95940. Index *pIdx = 0; /* Parent key index for this FK */
  95941. int *aiCol = 0; /* child table cols -> parent key cols */
  95942. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  95943. Expr *pWhere = 0; /* WHERE clause of trigger step */
  95944. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  95945. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  95946. int i; /* Iterator variable */
  95947. Expr *pWhen = 0; /* WHEN clause for the trigger */
  95948. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  95949. assert( aiCol || pFKey->nCol==1 );
  95950. for(i=0; i<pFKey->nCol; i++){
  95951. Token tOld = { "old", 3 }; /* Literal "old" token */
  95952. Token tNew = { "new", 3 }; /* Literal "new" token */
  95953. Token tFromCol; /* Name of column in child table */
  95954. Token tToCol; /* Name of column in parent table */
  95955. int iFromCol; /* Idx of column in child table */
  95956. Expr *pEq; /* tFromCol = OLD.tToCol */
  95957. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  95958. assert( iFromCol>=0 );
  95959. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  95960. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  95961. tToCol.z = pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName;
  95962. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  95963. tToCol.n = sqlite3Strlen30(tToCol.z);
  95964. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  95965. /* Create the expression "OLD.zToCol = zFromCol". It is important
  95966. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  95967. ** that the affinity and collation sequence associated with the
  95968. ** parent table are used for the comparison. */
  95969. pEq = sqlite3PExpr(pParse, TK_EQ,
  95970. sqlite3PExpr(pParse, TK_DOT,
  95971. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  95972. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  95973. , 0),
  95974. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  95975. , 0);
  95976. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  95977. /* For ON UPDATE, construct the next term of the WHEN clause.
  95978. ** The final WHEN clause will be like this:
  95979. **
  95980. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  95981. */
  95982. if( pChanges ){
  95983. pEq = sqlite3PExpr(pParse, TK_IS,
  95984. sqlite3PExpr(pParse, TK_DOT,
  95985. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  95986. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  95987. 0),
  95988. sqlite3PExpr(pParse, TK_DOT,
  95989. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  95990. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  95991. 0),
  95992. 0);
  95993. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  95994. }
  95995. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  95996. Expr *pNew;
  95997. if( action==OE_Cascade ){
  95998. pNew = sqlite3PExpr(pParse, TK_DOT,
  95999. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  96000. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  96001. , 0);
  96002. }else if( action==OE_SetDflt ){
  96003. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  96004. if( pDflt ){
  96005. pNew = sqlite3ExprDup(db, pDflt, 0);
  96006. }else{
  96007. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  96008. }
  96009. }else{
  96010. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  96011. }
  96012. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  96013. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  96014. }
  96015. }
  96016. sqlite3DbFree(db, aiCol);
  96017. zFrom = pFKey->pFrom->zName;
  96018. nFrom = sqlite3Strlen30(zFrom);
  96019. if( action==OE_Restrict ){
  96020. Token tFrom;
  96021. Expr *pRaise;
  96022. tFrom.z = zFrom;
  96023. tFrom.n = nFrom;
  96024. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  96025. if( pRaise ){
  96026. pRaise->affinity = OE_Abort;
  96027. }
  96028. pSelect = sqlite3SelectNew(pParse,
  96029. sqlite3ExprListAppend(pParse, 0, pRaise),
  96030. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  96031. pWhere,
  96032. 0, 0, 0, 0, 0, 0
  96033. );
  96034. pWhere = 0;
  96035. }
  96036. /* Disable lookaside memory allocation */
  96037. enableLookaside = db->lookaside.bEnabled;
  96038. db->lookaside.bEnabled = 0;
  96039. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  96040. sizeof(Trigger) + /* struct Trigger */
  96041. sizeof(TriggerStep) + /* Single step in trigger program */
  96042. nFrom + 1 /* Space for pStep->zTarget */
  96043. );
  96044. if( pTrigger ){
  96045. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  96046. pStep->zTarget = (char *)&pStep[1];
  96047. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  96048. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  96049. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  96050. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  96051. if( pWhen ){
  96052. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  96053. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  96054. }
  96055. }
  96056. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  96057. db->lookaside.bEnabled = enableLookaside;
  96058. sqlite3ExprDelete(db, pWhere);
  96059. sqlite3ExprDelete(db, pWhen);
  96060. sqlite3ExprListDelete(db, pList);
  96061. sqlite3SelectDelete(db, pSelect);
  96062. if( db->mallocFailed==1 ){
  96063. fkTriggerDelete(db, pTrigger);
  96064. return 0;
  96065. }
  96066. assert( pStep!=0 );
  96067. switch( action ){
  96068. case OE_Restrict:
  96069. pStep->op = TK_SELECT;
  96070. break;
  96071. case OE_Cascade:
  96072. if( !pChanges ){
  96073. pStep->op = TK_DELETE;
  96074. break;
  96075. }
  96076. default:
  96077. pStep->op = TK_UPDATE;
  96078. }
  96079. pStep->pTrig = pTrigger;
  96080. pTrigger->pSchema = pTab->pSchema;
  96081. pTrigger->pTabSchema = pTab->pSchema;
  96082. pFKey->apTrigger[iAction] = pTrigger;
  96083. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  96084. }
  96085. return pTrigger;
  96086. }
  96087. /*
  96088. ** This function is called when deleting or updating a row to implement
  96089. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  96090. */
  96091. SQLITE_PRIVATE void sqlite3FkActions(
  96092. Parse *pParse, /* Parse context */
  96093. Table *pTab, /* Table being updated or deleted from */
  96094. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  96095. int regOld, /* Address of array containing old row */
  96096. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  96097. int bChngRowid /* True if rowid is UPDATEd */
  96098. ){
  96099. /* If foreign-key support is enabled, iterate through all FKs that
  96100. ** refer to table pTab. If there is an action associated with the FK
  96101. ** for this operation (either update or delete), invoke the associated
  96102. ** trigger sub-program. */
  96103. if( pParse->db->flags&SQLITE_ForeignKeys ){
  96104. FKey *pFKey; /* Iterator variable */
  96105. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  96106. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  96107. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  96108. if( pAct ){
  96109. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  96110. }
  96111. }
  96112. }
  96113. }
  96114. }
  96115. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  96116. /*
  96117. ** Free all memory associated with foreign key definitions attached to
  96118. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  96119. ** hash table.
  96120. */
  96121. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  96122. FKey *pFKey; /* Iterator variable */
  96123. FKey *pNext; /* Copy of pFKey->pNextFrom */
  96124. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  96125. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  96126. /* Remove the FK from the fkeyHash hash table. */
  96127. if( !db || db->pnBytesFreed==0 ){
  96128. if( pFKey->pPrevTo ){
  96129. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  96130. }else{
  96131. void *p = (void *)pFKey->pNextTo;
  96132. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  96133. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  96134. }
  96135. if( pFKey->pNextTo ){
  96136. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  96137. }
  96138. }
  96139. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  96140. ** classified as either immediate or deferred.
  96141. */
  96142. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  96143. /* Delete any triggers created to implement actions for this FK. */
  96144. #ifndef SQLITE_OMIT_TRIGGER
  96145. fkTriggerDelete(db, pFKey->apTrigger[0]);
  96146. fkTriggerDelete(db, pFKey->apTrigger[1]);
  96147. #endif
  96148. pNext = pFKey->pNextFrom;
  96149. sqlite3DbFree(db, pFKey);
  96150. }
  96151. }
  96152. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  96153. /************** End of fkey.c ************************************************/
  96154. /************** Begin file insert.c ******************************************/
  96155. /*
  96156. ** 2001 September 15
  96157. **
  96158. ** The author disclaims copyright to this source code. In place of
  96159. ** a legal notice, here is a blessing:
  96160. **
  96161. ** May you do good and not evil.
  96162. ** May you find forgiveness for yourself and forgive others.
  96163. ** May you share freely, never taking more than you give.
  96164. **
  96165. *************************************************************************
  96166. ** This file contains C code routines that are called by the parser
  96167. ** to handle INSERT statements in SQLite.
  96168. */
  96169. /* #include "sqliteInt.h" */
  96170. /*
  96171. ** Generate code that will
  96172. **
  96173. ** (1) acquire a lock for table pTab then
  96174. ** (2) open pTab as cursor iCur.
  96175. **
  96176. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  96177. ** for that table that is actually opened.
  96178. */
  96179. SQLITE_PRIVATE void sqlite3OpenTable(
  96180. Parse *pParse, /* Generate code into this VDBE */
  96181. int iCur, /* The cursor number of the table */
  96182. int iDb, /* The database index in sqlite3.aDb[] */
  96183. Table *pTab, /* The table to be opened */
  96184. int opcode /* OP_OpenRead or OP_OpenWrite */
  96185. ){
  96186. Vdbe *v;
  96187. assert( !IsVirtual(pTab) );
  96188. v = sqlite3GetVdbe(pParse);
  96189. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  96190. sqlite3TableLock(pParse, iDb, pTab->tnum,
  96191. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  96192. if( HasRowid(pTab) ){
  96193. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  96194. VdbeComment((v, "%s", pTab->zName));
  96195. }else{
  96196. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  96197. assert( pPk!=0 );
  96198. assert( pPk->tnum==pTab->tnum );
  96199. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  96200. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  96201. VdbeComment((v, "%s", pTab->zName));
  96202. }
  96203. }
  96204. /*
  96205. ** Return a pointer to the column affinity string associated with index
  96206. ** pIdx. A column affinity string has one character for each column in
  96207. ** the table, according to the affinity of the column:
  96208. **
  96209. ** Character Column affinity
  96210. ** ------------------------------
  96211. ** 'A' BLOB
  96212. ** 'B' TEXT
  96213. ** 'C' NUMERIC
  96214. ** 'D' INTEGER
  96215. ** 'F' REAL
  96216. **
  96217. ** An extra 'D' is appended to the end of the string to cover the
  96218. ** rowid that appears as the last column in every index.
  96219. **
  96220. ** Memory for the buffer containing the column index affinity string
  96221. ** is managed along with the rest of the Index structure. It will be
  96222. ** released when sqlite3DeleteIndex() is called.
  96223. */
  96224. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  96225. if( !pIdx->zColAff ){
  96226. /* The first time a column affinity string for a particular index is
  96227. ** required, it is allocated and populated here. It is then stored as
  96228. ** a member of the Index structure for subsequent use.
  96229. **
  96230. ** The column affinity string will eventually be deleted by
  96231. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  96232. ** up.
  96233. */
  96234. int n;
  96235. Table *pTab = pIdx->pTable;
  96236. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  96237. if( !pIdx->zColAff ){
  96238. db->mallocFailed = 1;
  96239. return 0;
  96240. }
  96241. for(n=0; n<pIdx->nColumn; n++){
  96242. i16 x = pIdx->aiColumn[n];
  96243. if( x>=0 ){
  96244. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  96245. }else if( x==XN_ROWID ){
  96246. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  96247. }else{
  96248. char aff;
  96249. assert( x==XN_EXPR );
  96250. assert( pIdx->aColExpr!=0 );
  96251. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  96252. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  96253. pIdx->zColAff[n] = aff;
  96254. }
  96255. }
  96256. pIdx->zColAff[n] = 0;
  96257. }
  96258. return pIdx->zColAff;
  96259. }
  96260. /*
  96261. ** Compute the affinity string for table pTab, if it has not already been
  96262. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  96263. **
  96264. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  96265. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  96266. ** for register iReg and following. Or if affinities exists and iReg==0,
  96267. ** then just set the P4 operand of the previous opcode (which should be
  96268. ** an OP_MakeRecord) to the affinity string.
  96269. **
  96270. ** A column affinity string has one character per column:
  96271. **
  96272. ** Character Column affinity
  96273. ** ------------------------------
  96274. ** 'A' BLOB
  96275. ** 'B' TEXT
  96276. ** 'C' NUMERIC
  96277. ** 'D' INTEGER
  96278. ** 'E' REAL
  96279. */
  96280. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  96281. int i;
  96282. char *zColAff = pTab->zColAff;
  96283. if( zColAff==0 ){
  96284. sqlite3 *db = sqlite3VdbeDb(v);
  96285. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  96286. if( !zColAff ){
  96287. db->mallocFailed = 1;
  96288. return;
  96289. }
  96290. for(i=0; i<pTab->nCol; i++){
  96291. zColAff[i] = pTab->aCol[i].affinity;
  96292. }
  96293. do{
  96294. zColAff[i--] = 0;
  96295. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  96296. pTab->zColAff = zColAff;
  96297. }
  96298. i = sqlite3Strlen30(zColAff);
  96299. if( i ){
  96300. if( iReg ){
  96301. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  96302. }else{
  96303. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  96304. }
  96305. }
  96306. }
  96307. /*
  96308. ** Return non-zero if the table pTab in database iDb or any of its indices
  96309. ** have been opened at any point in the VDBE program. This is used to see if
  96310. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  96311. ** run without using a temporary table for the results of the SELECT.
  96312. */
  96313. static int readsTable(Parse *p, int iDb, Table *pTab){
  96314. Vdbe *v = sqlite3GetVdbe(p);
  96315. int i;
  96316. int iEnd = sqlite3VdbeCurrentAddr(v);
  96317. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96318. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  96319. #endif
  96320. for(i=1; i<iEnd; i++){
  96321. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  96322. assert( pOp!=0 );
  96323. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  96324. Index *pIndex;
  96325. int tnum = pOp->p2;
  96326. if( tnum==pTab->tnum ){
  96327. return 1;
  96328. }
  96329. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  96330. if( tnum==pIndex->tnum ){
  96331. return 1;
  96332. }
  96333. }
  96334. }
  96335. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96336. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  96337. assert( pOp->p4.pVtab!=0 );
  96338. assert( pOp->p4type==P4_VTAB );
  96339. return 1;
  96340. }
  96341. #endif
  96342. }
  96343. return 0;
  96344. }
  96345. #ifndef SQLITE_OMIT_AUTOINCREMENT
  96346. /*
  96347. ** Locate or create an AutoincInfo structure associated with table pTab
  96348. ** which is in database iDb. Return the register number for the register
  96349. ** that holds the maximum rowid.
  96350. **
  96351. ** There is at most one AutoincInfo structure per table even if the
  96352. ** same table is autoincremented multiple times due to inserts within
  96353. ** triggers. A new AutoincInfo structure is created if this is the
  96354. ** first use of table pTab. On 2nd and subsequent uses, the original
  96355. ** AutoincInfo structure is used.
  96356. **
  96357. ** Three memory locations are allocated:
  96358. **
  96359. ** (1) Register to hold the name of the pTab table.
  96360. ** (2) Register to hold the maximum ROWID of pTab.
  96361. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  96362. **
  96363. ** The 2nd register is the one that is returned. That is all the
  96364. ** insert routine needs to know about.
  96365. */
  96366. static int autoIncBegin(
  96367. Parse *pParse, /* Parsing context */
  96368. int iDb, /* Index of the database holding pTab */
  96369. Table *pTab /* The table we are writing to */
  96370. ){
  96371. int memId = 0; /* Register holding maximum rowid */
  96372. if( pTab->tabFlags & TF_Autoincrement ){
  96373. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  96374. AutoincInfo *pInfo;
  96375. pInfo = pToplevel->pAinc;
  96376. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  96377. if( pInfo==0 ){
  96378. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  96379. if( pInfo==0 ) return 0;
  96380. pInfo->pNext = pToplevel->pAinc;
  96381. pToplevel->pAinc = pInfo;
  96382. pInfo->pTab = pTab;
  96383. pInfo->iDb = iDb;
  96384. pToplevel->nMem++; /* Register to hold name of table */
  96385. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  96386. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  96387. }
  96388. memId = pInfo->regCtr;
  96389. }
  96390. return memId;
  96391. }
  96392. /*
  96393. ** This routine generates code that will initialize all of the
  96394. ** register used by the autoincrement tracker.
  96395. */
  96396. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  96397. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  96398. sqlite3 *db = pParse->db; /* The database connection */
  96399. Db *pDb; /* Database only autoinc table */
  96400. int memId; /* Register holding max rowid */
  96401. int addr; /* A VDBE address */
  96402. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  96403. /* This routine is never called during trigger-generation. It is
  96404. ** only called from the top-level */
  96405. assert( pParse->pTriggerTab==0 );
  96406. assert( sqlite3IsToplevel(pParse) );
  96407. assert( v ); /* We failed long ago if this is not so */
  96408. for(p = pParse->pAinc; p; p = p->pNext){
  96409. pDb = &db->aDb[p->iDb];
  96410. memId = p->regCtr;
  96411. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  96412. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  96413. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  96414. addr = sqlite3VdbeCurrentAddr(v);
  96415. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  96416. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
  96417. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  96418. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
  96419. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  96420. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  96421. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  96422. sqlite3VdbeGoto(v, addr+9);
  96423. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
  96424. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  96425. sqlite3VdbeAddOp0(v, OP_Close);
  96426. }
  96427. }
  96428. /*
  96429. ** Update the maximum rowid for an autoincrement calculation.
  96430. **
  96431. ** This routine should be called when the top of the stack holds a
  96432. ** new rowid that is about to be inserted. If that new rowid is
  96433. ** larger than the maximum rowid in the memId memory cell, then the
  96434. ** memory cell is updated. The stack is unchanged.
  96435. */
  96436. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  96437. if( memId>0 ){
  96438. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  96439. }
  96440. }
  96441. /*
  96442. ** This routine generates the code needed to write autoincrement
  96443. ** maximum rowid values back into the sqlite_sequence register.
  96444. ** Every statement that might do an INSERT into an autoincrement
  96445. ** table (either directly or through triggers) needs to call this
  96446. ** routine just before the "exit" code.
  96447. */
  96448. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  96449. AutoincInfo *p;
  96450. Vdbe *v = pParse->pVdbe;
  96451. sqlite3 *db = pParse->db;
  96452. assert( v );
  96453. for(p = pParse->pAinc; p; p = p->pNext){
  96454. Db *pDb = &db->aDb[p->iDb];
  96455. int addr1;
  96456. int iRec;
  96457. int memId = p->regCtr;
  96458. iRec = sqlite3GetTempReg(pParse);
  96459. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  96460. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  96461. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
  96462. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  96463. sqlite3VdbeJumpHere(v, addr1);
  96464. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  96465. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  96466. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  96467. sqlite3VdbeAddOp0(v, OP_Close);
  96468. sqlite3ReleaseTempReg(pParse, iRec);
  96469. }
  96470. }
  96471. #else
  96472. /*
  96473. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  96474. ** above are all no-ops
  96475. */
  96476. # define autoIncBegin(A,B,C) (0)
  96477. # define autoIncStep(A,B,C)
  96478. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  96479. /* Forward declaration */
  96480. static int xferOptimization(
  96481. Parse *pParse, /* Parser context */
  96482. Table *pDest, /* The table we are inserting into */
  96483. Select *pSelect, /* A SELECT statement to use as the data source */
  96484. int onError, /* How to handle constraint errors */
  96485. int iDbDest /* The database of pDest */
  96486. );
  96487. /*
  96488. ** This routine is called to handle SQL of the following forms:
  96489. **
  96490. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  96491. ** insert into TABLE (IDLIST) select
  96492. ** insert into TABLE (IDLIST) default values
  96493. **
  96494. ** The IDLIST following the table name is always optional. If omitted,
  96495. ** then a list of all (non-hidden) columns for the table is substituted.
  96496. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  96497. ** is omitted.
  96498. **
  96499. ** For the pSelect parameter holds the values to be inserted for the
  96500. ** first two forms shown above. A VALUES clause is really just short-hand
  96501. ** for a SELECT statement that omits the FROM clause and everything else
  96502. ** that follows. If the pSelect parameter is NULL, that means that the
  96503. ** DEFAULT VALUES form of the INSERT statement is intended.
  96504. **
  96505. ** The code generated follows one of four templates. For a simple
  96506. ** insert with data coming from a single-row VALUES clause, the code executes
  96507. ** once straight down through. Pseudo-code follows (we call this
  96508. ** the "1st template"):
  96509. **
  96510. ** open write cursor to <table> and its indices
  96511. ** put VALUES clause expressions into registers
  96512. ** write the resulting record into <table>
  96513. ** cleanup
  96514. **
  96515. ** The three remaining templates assume the statement is of the form
  96516. **
  96517. ** INSERT INTO <table> SELECT ...
  96518. **
  96519. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  96520. ** in other words if the SELECT pulls all columns from a single table
  96521. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  96522. ** if <table2> and <table1> are distinct tables but have identical
  96523. ** schemas, including all the same indices, then a special optimization
  96524. ** is invoked that copies raw records from <table2> over to <table1>.
  96525. ** See the xferOptimization() function for the implementation of this
  96526. ** template. This is the 2nd template.
  96527. **
  96528. ** open a write cursor to <table>
  96529. ** open read cursor on <table2>
  96530. ** transfer all records in <table2> over to <table>
  96531. ** close cursors
  96532. ** foreach index on <table>
  96533. ** open a write cursor on the <table> index
  96534. ** open a read cursor on the corresponding <table2> index
  96535. ** transfer all records from the read to the write cursors
  96536. ** close cursors
  96537. ** end foreach
  96538. **
  96539. ** The 3rd template is for when the second template does not apply
  96540. ** and the SELECT clause does not read from <table> at any time.
  96541. ** The generated code follows this template:
  96542. **
  96543. ** X <- A
  96544. ** goto B
  96545. ** A: setup for the SELECT
  96546. ** loop over the rows in the SELECT
  96547. ** load values into registers R..R+n
  96548. ** yield X
  96549. ** end loop
  96550. ** cleanup after the SELECT
  96551. ** end-coroutine X
  96552. ** B: open write cursor to <table> and its indices
  96553. ** C: yield X, at EOF goto D
  96554. ** insert the select result into <table> from R..R+n
  96555. ** goto C
  96556. ** D: cleanup
  96557. **
  96558. ** The 4th template is used if the insert statement takes its
  96559. ** values from a SELECT but the data is being inserted into a table
  96560. ** that is also read as part of the SELECT. In the third form,
  96561. ** we have to use an intermediate table to store the results of
  96562. ** the select. The template is like this:
  96563. **
  96564. ** X <- A
  96565. ** goto B
  96566. ** A: setup for the SELECT
  96567. ** loop over the tables in the SELECT
  96568. ** load value into register R..R+n
  96569. ** yield X
  96570. ** end loop
  96571. ** cleanup after the SELECT
  96572. ** end co-routine R
  96573. ** B: open temp table
  96574. ** L: yield X, at EOF goto M
  96575. ** insert row from R..R+n into temp table
  96576. ** goto L
  96577. ** M: open write cursor to <table> and its indices
  96578. ** rewind temp table
  96579. ** C: loop over rows of intermediate table
  96580. ** transfer values form intermediate table into <table>
  96581. ** end loop
  96582. ** D: cleanup
  96583. */
  96584. SQLITE_PRIVATE void sqlite3Insert(
  96585. Parse *pParse, /* Parser context */
  96586. SrcList *pTabList, /* Name of table into which we are inserting */
  96587. Select *pSelect, /* A SELECT statement to use as the data source */
  96588. IdList *pColumn, /* Column names corresponding to IDLIST. */
  96589. int onError /* How to handle constraint errors */
  96590. ){
  96591. sqlite3 *db; /* The main database structure */
  96592. Table *pTab; /* The table to insert into. aka TABLE */
  96593. char *zTab; /* Name of the table into which we are inserting */
  96594. const char *zDb; /* Name of the database holding this table */
  96595. int i, j, idx; /* Loop counters */
  96596. Vdbe *v; /* Generate code into this virtual machine */
  96597. Index *pIdx; /* For looping over indices of the table */
  96598. int nColumn; /* Number of columns in the data */
  96599. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  96600. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  96601. int iIdxCur = 0; /* First index cursor */
  96602. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  96603. int endOfLoop; /* Label for the end of the insertion loop */
  96604. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  96605. int addrInsTop = 0; /* Jump to label "D" */
  96606. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  96607. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  96608. int iDb; /* Index of database holding TABLE */
  96609. Db *pDb; /* The database containing table being inserted into */
  96610. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  96611. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  96612. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  96613. u8 bIdListInOrder; /* True if IDLIST is in table order */
  96614. ExprList *pList = 0; /* List of VALUES() to be inserted */
  96615. /* Register allocations */
  96616. int regFromSelect = 0;/* Base register for data coming from SELECT */
  96617. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  96618. int regRowCount = 0; /* Memory cell used for the row counter */
  96619. int regIns; /* Block of regs holding rowid+data being inserted */
  96620. int regRowid; /* registers holding insert rowid */
  96621. int regData; /* register holding first column to insert */
  96622. int *aRegIdx = 0; /* One register allocated to each index */
  96623. #ifndef SQLITE_OMIT_TRIGGER
  96624. int isView; /* True if attempting to insert into a view */
  96625. Trigger *pTrigger; /* List of triggers on pTab, if required */
  96626. int tmask; /* Mask of trigger times */
  96627. #endif
  96628. db = pParse->db;
  96629. memset(&dest, 0, sizeof(dest));
  96630. if( pParse->nErr || db->mallocFailed ){
  96631. goto insert_cleanup;
  96632. }
  96633. /* If the Select object is really just a simple VALUES() list with a
  96634. ** single row (the common case) then keep that one row of values
  96635. ** and discard the other (unused) parts of the pSelect object
  96636. */
  96637. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  96638. pList = pSelect->pEList;
  96639. pSelect->pEList = 0;
  96640. sqlite3SelectDelete(db, pSelect);
  96641. pSelect = 0;
  96642. }
  96643. /* Locate the table into which we will be inserting new information.
  96644. */
  96645. assert( pTabList->nSrc==1 );
  96646. zTab = pTabList->a[0].zName;
  96647. if( NEVER(zTab==0) ) goto insert_cleanup;
  96648. pTab = sqlite3SrcListLookup(pParse, pTabList);
  96649. if( pTab==0 ){
  96650. goto insert_cleanup;
  96651. }
  96652. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96653. assert( iDb<db->nDb );
  96654. pDb = &db->aDb[iDb];
  96655. zDb = pDb->zName;
  96656. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  96657. goto insert_cleanup;
  96658. }
  96659. withoutRowid = !HasRowid(pTab);
  96660. /* Figure out if we have any triggers and if the table being
  96661. ** inserted into is a view
  96662. */
  96663. #ifndef SQLITE_OMIT_TRIGGER
  96664. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  96665. isView = pTab->pSelect!=0;
  96666. #else
  96667. # define pTrigger 0
  96668. # define tmask 0
  96669. # define isView 0
  96670. #endif
  96671. #ifdef SQLITE_OMIT_VIEW
  96672. # undef isView
  96673. # define isView 0
  96674. #endif
  96675. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  96676. /* If pTab is really a view, make sure it has been initialized.
  96677. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  96678. */
  96679. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  96680. goto insert_cleanup;
  96681. }
  96682. /* Cannot insert into a read-only table.
  96683. */
  96684. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  96685. goto insert_cleanup;
  96686. }
  96687. /* Allocate a VDBE
  96688. */
  96689. v = sqlite3GetVdbe(pParse);
  96690. if( v==0 ) goto insert_cleanup;
  96691. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  96692. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  96693. #ifndef SQLITE_OMIT_XFER_OPT
  96694. /* If the statement is of the form
  96695. **
  96696. ** INSERT INTO <table1> SELECT * FROM <table2>;
  96697. **
  96698. ** Then special optimizations can be applied that make the transfer
  96699. ** very fast and which reduce fragmentation of indices.
  96700. **
  96701. ** This is the 2nd template.
  96702. */
  96703. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  96704. assert( !pTrigger );
  96705. assert( pList==0 );
  96706. goto insert_end;
  96707. }
  96708. #endif /* SQLITE_OMIT_XFER_OPT */
  96709. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  96710. ** sqlite_sequence table and store it in memory cell regAutoinc.
  96711. */
  96712. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  96713. /* Allocate registers for holding the rowid of the new row,
  96714. ** the content of the new row, and the assembled row record.
  96715. */
  96716. regRowid = regIns = pParse->nMem+1;
  96717. pParse->nMem += pTab->nCol + 1;
  96718. if( IsVirtual(pTab) ){
  96719. regRowid++;
  96720. pParse->nMem++;
  96721. }
  96722. regData = regRowid+1;
  96723. /* If the INSERT statement included an IDLIST term, then make sure
  96724. ** all elements of the IDLIST really are columns of the table and
  96725. ** remember the column indices.
  96726. **
  96727. ** If the table has an INTEGER PRIMARY KEY column and that column
  96728. ** is named in the IDLIST, then record in the ipkColumn variable
  96729. ** the index into IDLIST of the primary key column. ipkColumn is
  96730. ** the index of the primary key as it appears in IDLIST, not as
  96731. ** is appears in the original table. (The index of the INTEGER
  96732. ** PRIMARY KEY in the original table is pTab->iPKey.)
  96733. */
  96734. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  96735. if( pColumn ){
  96736. for(i=0; i<pColumn->nId; i++){
  96737. pColumn->a[i].idx = -1;
  96738. }
  96739. for(i=0; i<pColumn->nId; i++){
  96740. for(j=0; j<pTab->nCol; j++){
  96741. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  96742. pColumn->a[i].idx = j;
  96743. if( i!=j ) bIdListInOrder = 0;
  96744. if( j==pTab->iPKey ){
  96745. ipkColumn = i; assert( !withoutRowid );
  96746. }
  96747. break;
  96748. }
  96749. }
  96750. if( j>=pTab->nCol ){
  96751. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  96752. ipkColumn = i;
  96753. bIdListInOrder = 0;
  96754. }else{
  96755. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  96756. pTabList, 0, pColumn->a[i].zName);
  96757. pParse->checkSchema = 1;
  96758. goto insert_cleanup;
  96759. }
  96760. }
  96761. }
  96762. }
  96763. /* Figure out how many columns of data are supplied. If the data
  96764. ** is coming from a SELECT statement, then generate a co-routine that
  96765. ** produces a single row of the SELECT on each invocation. The
  96766. ** co-routine is the common header to the 3rd and 4th templates.
  96767. */
  96768. if( pSelect ){
  96769. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  96770. ** Generate a co-routine to run the SELECT. */
  96771. int regYield; /* Register holding co-routine entry-point */
  96772. int addrTop; /* Top of the co-routine */
  96773. int rc; /* Result code */
  96774. regYield = ++pParse->nMem;
  96775. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  96776. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  96777. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  96778. dest.iSdst = bIdListInOrder ? regData : 0;
  96779. dest.nSdst = pTab->nCol;
  96780. rc = sqlite3Select(pParse, pSelect, &dest);
  96781. regFromSelect = dest.iSdst;
  96782. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  96783. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  96784. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  96785. assert( pSelect->pEList );
  96786. nColumn = pSelect->pEList->nExpr;
  96787. /* Set useTempTable to TRUE if the result of the SELECT statement
  96788. ** should be written into a temporary table (template 4). Set to
  96789. ** FALSE if each output row of the SELECT can be written directly into
  96790. ** the destination table (template 3).
  96791. **
  96792. ** A temp table must be used if the table being updated is also one
  96793. ** of the tables being read by the SELECT statement. Also use a
  96794. ** temp table in the case of row triggers.
  96795. */
  96796. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  96797. useTempTable = 1;
  96798. }
  96799. if( useTempTable ){
  96800. /* Invoke the coroutine to extract information from the SELECT
  96801. ** and add it to a transient table srcTab. The code generated
  96802. ** here is from the 4th template:
  96803. **
  96804. ** B: open temp table
  96805. ** L: yield X, goto M at EOF
  96806. ** insert row from R..R+n into temp table
  96807. ** goto L
  96808. ** M: ...
  96809. */
  96810. int regRec; /* Register to hold packed record */
  96811. int regTempRowid; /* Register to hold temp table ROWID */
  96812. int addrL; /* Label "L" */
  96813. srcTab = pParse->nTab++;
  96814. regRec = sqlite3GetTempReg(pParse);
  96815. regTempRowid = sqlite3GetTempReg(pParse);
  96816. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  96817. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  96818. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  96819. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  96820. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  96821. sqlite3VdbeGoto(v, addrL);
  96822. sqlite3VdbeJumpHere(v, addrL);
  96823. sqlite3ReleaseTempReg(pParse, regRec);
  96824. sqlite3ReleaseTempReg(pParse, regTempRowid);
  96825. }
  96826. }else{
  96827. /* This is the case if the data for the INSERT is coming from a
  96828. ** single-row VALUES clause
  96829. */
  96830. NameContext sNC;
  96831. memset(&sNC, 0, sizeof(sNC));
  96832. sNC.pParse = pParse;
  96833. srcTab = -1;
  96834. assert( useTempTable==0 );
  96835. if( pList ){
  96836. nColumn = pList->nExpr;
  96837. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  96838. goto insert_cleanup;
  96839. }
  96840. }else{
  96841. nColumn = 0;
  96842. }
  96843. }
  96844. /* If there is no IDLIST term but the table has an integer primary
  96845. ** key, the set the ipkColumn variable to the integer primary key
  96846. ** column index in the original table definition.
  96847. */
  96848. if( pColumn==0 && nColumn>0 ){
  96849. ipkColumn = pTab->iPKey;
  96850. }
  96851. /* Make sure the number of columns in the source data matches the number
  96852. ** of columns to be inserted into the table.
  96853. */
  96854. for(i=0; i<pTab->nCol; i++){
  96855. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  96856. }
  96857. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  96858. sqlite3ErrorMsg(pParse,
  96859. "table %S has %d columns but %d values were supplied",
  96860. pTabList, 0, pTab->nCol-nHidden, nColumn);
  96861. goto insert_cleanup;
  96862. }
  96863. if( pColumn!=0 && nColumn!=pColumn->nId ){
  96864. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  96865. goto insert_cleanup;
  96866. }
  96867. /* Initialize the count of rows to be inserted
  96868. */
  96869. if( db->flags & SQLITE_CountRows ){
  96870. regRowCount = ++pParse->nMem;
  96871. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  96872. }
  96873. /* If this is not a view, open the table and and all indices */
  96874. if( !isView ){
  96875. int nIdx;
  96876. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  96877. &iDataCur, &iIdxCur);
  96878. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  96879. if( aRegIdx==0 ){
  96880. goto insert_cleanup;
  96881. }
  96882. for(i=0; i<nIdx; i++){
  96883. aRegIdx[i] = ++pParse->nMem;
  96884. }
  96885. }
  96886. /* This is the top of the main insertion loop */
  96887. if( useTempTable ){
  96888. /* This block codes the top of loop only. The complete loop is the
  96889. ** following pseudocode (template 4):
  96890. **
  96891. ** rewind temp table, if empty goto D
  96892. ** C: loop over rows of intermediate table
  96893. ** transfer values form intermediate table into <table>
  96894. ** end loop
  96895. ** D: ...
  96896. */
  96897. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  96898. addrCont = sqlite3VdbeCurrentAddr(v);
  96899. }else if( pSelect ){
  96900. /* This block codes the top of loop only. The complete loop is the
  96901. ** following pseudocode (template 3):
  96902. **
  96903. ** C: yield X, at EOF goto D
  96904. ** insert the select result into <table> from R..R+n
  96905. ** goto C
  96906. ** D: ...
  96907. */
  96908. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  96909. VdbeCoverage(v);
  96910. }
  96911. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  96912. */
  96913. endOfLoop = sqlite3VdbeMakeLabel(v);
  96914. if( tmask & TRIGGER_BEFORE ){
  96915. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  96916. /* build the NEW.* reference row. Note that if there is an INTEGER
  96917. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  96918. ** translated into a unique ID for the row. But on a BEFORE trigger,
  96919. ** we do not know what the unique ID will be (because the insert has
  96920. ** not happened yet) so we substitute a rowid of -1
  96921. */
  96922. if( ipkColumn<0 ){
  96923. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  96924. }else{
  96925. int addr1;
  96926. assert( !withoutRowid );
  96927. if( useTempTable ){
  96928. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  96929. }else{
  96930. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  96931. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  96932. }
  96933. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  96934. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  96935. sqlite3VdbeJumpHere(v, addr1);
  96936. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  96937. }
  96938. /* Cannot have triggers on a virtual table. If it were possible,
  96939. ** this block would have to account for hidden column.
  96940. */
  96941. assert( !IsVirtual(pTab) );
  96942. /* Create the new column data
  96943. */
  96944. for(i=j=0; i<pTab->nCol; i++){
  96945. if( pColumn ){
  96946. for(j=0; j<pColumn->nId; j++){
  96947. if( pColumn->a[j].idx==i ) break;
  96948. }
  96949. }
  96950. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  96951. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  96952. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  96953. }else if( useTempTable ){
  96954. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  96955. }else{
  96956. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  96957. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  96958. }
  96959. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  96960. }
  96961. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  96962. ** do not attempt any conversions before assembling the record.
  96963. ** If this is a real table, attempt conversions as required by the
  96964. ** table column affinities.
  96965. */
  96966. if( !isView ){
  96967. sqlite3TableAffinity(v, pTab, regCols+1);
  96968. }
  96969. /* Fire BEFORE or INSTEAD OF triggers */
  96970. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  96971. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  96972. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  96973. }
  96974. /* Compute the content of the next row to insert into a range of
  96975. ** registers beginning at regIns.
  96976. */
  96977. if( !isView ){
  96978. if( IsVirtual(pTab) ){
  96979. /* The row that the VUpdate opcode will delete: none */
  96980. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  96981. }
  96982. if( ipkColumn>=0 ){
  96983. if( useTempTable ){
  96984. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  96985. }else if( pSelect ){
  96986. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  96987. }else{
  96988. VdbeOp *pOp;
  96989. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  96990. pOp = sqlite3VdbeGetOp(v, -1);
  96991. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  96992. appendFlag = 1;
  96993. pOp->opcode = OP_NewRowid;
  96994. pOp->p1 = iDataCur;
  96995. pOp->p2 = regRowid;
  96996. pOp->p3 = regAutoinc;
  96997. }
  96998. }
  96999. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  97000. ** to generate a unique primary key value.
  97001. */
  97002. if( !appendFlag ){
  97003. int addr1;
  97004. if( !IsVirtual(pTab) ){
  97005. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  97006. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  97007. sqlite3VdbeJumpHere(v, addr1);
  97008. }else{
  97009. addr1 = sqlite3VdbeCurrentAddr(v);
  97010. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  97011. }
  97012. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  97013. }
  97014. }else if( IsVirtual(pTab) || withoutRowid ){
  97015. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  97016. }else{
  97017. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  97018. appendFlag = 1;
  97019. }
  97020. autoIncStep(pParse, regAutoinc, regRowid);
  97021. /* Compute data for all columns of the new entry, beginning
  97022. ** with the first column.
  97023. */
  97024. nHidden = 0;
  97025. for(i=0; i<pTab->nCol; i++){
  97026. int iRegStore = regRowid+1+i;
  97027. if( i==pTab->iPKey ){
  97028. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  97029. ** Whenever this column is read, the rowid will be substituted
  97030. ** in its place. Hence, fill this column with a NULL to avoid
  97031. ** taking up data space with information that will never be used.
  97032. ** As there may be shallow copies of this value, make it a soft-NULL */
  97033. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  97034. continue;
  97035. }
  97036. if( pColumn==0 ){
  97037. if( IsHiddenColumn(&pTab->aCol[i]) ){
  97038. j = -1;
  97039. nHidden++;
  97040. }else{
  97041. j = i - nHidden;
  97042. }
  97043. }else{
  97044. for(j=0; j<pColumn->nId; j++){
  97045. if( pColumn->a[j].idx==i ) break;
  97046. }
  97047. }
  97048. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  97049. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  97050. }else if( useTempTable ){
  97051. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  97052. }else if( pSelect ){
  97053. if( regFromSelect!=regData ){
  97054. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  97055. }
  97056. }else{
  97057. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  97058. }
  97059. }
  97060. /* Generate code to check constraints and generate index keys and
  97061. ** do the insertion.
  97062. */
  97063. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97064. if( IsVirtual(pTab) ){
  97065. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  97066. sqlite3VtabMakeWritable(pParse, pTab);
  97067. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  97068. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  97069. sqlite3MayAbort(pParse);
  97070. }else
  97071. #endif
  97072. {
  97073. int isReplace; /* Set to true if constraints may cause a replace */
  97074. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  97075. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
  97076. );
  97077. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  97078. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  97079. regIns, aRegIdx, 0, appendFlag, isReplace==0);
  97080. }
  97081. }
  97082. /* Update the count of rows that are inserted
  97083. */
  97084. if( (db->flags & SQLITE_CountRows)!=0 ){
  97085. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  97086. }
  97087. if( pTrigger ){
  97088. /* Code AFTER triggers */
  97089. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  97090. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  97091. }
  97092. /* The bottom of the main insertion loop, if the data source
  97093. ** is a SELECT statement.
  97094. */
  97095. sqlite3VdbeResolveLabel(v, endOfLoop);
  97096. if( useTempTable ){
  97097. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  97098. sqlite3VdbeJumpHere(v, addrInsTop);
  97099. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  97100. }else if( pSelect ){
  97101. sqlite3VdbeGoto(v, addrCont);
  97102. sqlite3VdbeJumpHere(v, addrInsTop);
  97103. }
  97104. if( !IsVirtual(pTab) && !isView ){
  97105. /* Close all tables opened */
  97106. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  97107. for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  97108. sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
  97109. }
  97110. }
  97111. insert_end:
  97112. /* Update the sqlite_sequence table by storing the content of the
  97113. ** maximum rowid counter values recorded while inserting into
  97114. ** autoincrement tables.
  97115. */
  97116. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  97117. sqlite3AutoincrementEnd(pParse);
  97118. }
  97119. /*
  97120. ** Return the number of rows inserted. If this routine is
  97121. ** generating code because of a call to sqlite3NestedParse(), do not
  97122. ** invoke the callback function.
  97123. */
  97124. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  97125. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  97126. sqlite3VdbeSetNumCols(v, 1);
  97127. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  97128. }
  97129. insert_cleanup:
  97130. sqlite3SrcListDelete(db, pTabList);
  97131. sqlite3ExprListDelete(db, pList);
  97132. sqlite3SelectDelete(db, pSelect);
  97133. sqlite3IdListDelete(db, pColumn);
  97134. sqlite3DbFree(db, aRegIdx);
  97135. }
  97136. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  97137. ** they may interfere with compilation of other functions in this file
  97138. ** (or in another file, if this file becomes part of the amalgamation). */
  97139. #ifdef isView
  97140. #undef isView
  97141. #endif
  97142. #ifdef pTrigger
  97143. #undef pTrigger
  97144. #endif
  97145. #ifdef tmask
  97146. #undef tmask
  97147. #endif
  97148. /*
  97149. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  97150. ** on table pTab.
  97151. **
  97152. ** The regNewData parameter is the first register in a range that contains
  97153. ** the data to be inserted or the data after the update. There will be
  97154. ** pTab->nCol+1 registers in this range. The first register (the one
  97155. ** that regNewData points to) will contain the new rowid, or NULL in the
  97156. ** case of a WITHOUT ROWID table. The second register in the range will
  97157. ** contain the content of the first table column. The third register will
  97158. ** contain the content of the second table column. And so forth.
  97159. **
  97160. ** The regOldData parameter is similar to regNewData except that it contains
  97161. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  97162. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  97163. ** checking regOldData for zero.
  97164. **
  97165. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  97166. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  97167. ** might be modified by the UPDATE. If pkChng is false, then the key of
  97168. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  97169. **
  97170. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  97171. ** was explicitly specified as part of the INSERT statement. If pkChng
  97172. ** is zero, it means that the either rowid is computed automatically or
  97173. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  97174. ** pkChng will only be true if the INSERT statement provides an integer
  97175. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  97176. **
  97177. ** The code generated by this routine will store new index entries into
  97178. ** registers identified by aRegIdx[]. No index entry is created for
  97179. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  97180. ** the same as the order of indices on the linked list of indices
  97181. ** at pTab->pIndex.
  97182. **
  97183. ** The caller must have already opened writeable cursors on the main
  97184. ** table and all applicable indices (that is to say, all indices for which
  97185. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  97186. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  97187. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  97188. ** for the first index in the pTab->pIndex list. Cursors for other indices
  97189. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  97190. **
  97191. ** This routine also generates code to check constraints. NOT NULL,
  97192. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  97193. ** then the appropriate action is performed. There are five possible
  97194. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  97195. **
  97196. ** Constraint type Action What Happens
  97197. ** --------------- ---------- ----------------------------------------
  97198. ** any ROLLBACK The current transaction is rolled back and
  97199. ** sqlite3_step() returns immediately with a
  97200. ** return code of SQLITE_CONSTRAINT.
  97201. **
  97202. ** any ABORT Back out changes from the current command
  97203. ** only (do not do a complete rollback) then
  97204. ** cause sqlite3_step() to return immediately
  97205. ** with SQLITE_CONSTRAINT.
  97206. **
  97207. ** any FAIL Sqlite3_step() returns immediately with a
  97208. ** return code of SQLITE_CONSTRAINT. The
  97209. ** transaction is not rolled back and any
  97210. ** changes to prior rows are retained.
  97211. **
  97212. ** any IGNORE The attempt in insert or update the current
  97213. ** row is skipped, without throwing an error.
  97214. ** Processing continues with the next row.
  97215. ** (There is an immediate jump to ignoreDest.)
  97216. **
  97217. ** NOT NULL REPLACE The NULL value is replace by the default
  97218. ** value for that column. If the default value
  97219. ** is NULL, the action is the same as ABORT.
  97220. **
  97221. ** UNIQUE REPLACE The other row that conflicts with the row
  97222. ** being inserted is removed.
  97223. **
  97224. ** CHECK REPLACE Illegal. The results in an exception.
  97225. **
  97226. ** Which action to take is determined by the overrideError parameter.
  97227. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  97228. ** is used. Or if pParse->onError==OE_Default then the onError value
  97229. ** for the constraint is used.
  97230. */
  97231. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  97232. Parse *pParse, /* The parser context */
  97233. Table *pTab, /* The table being inserted or updated */
  97234. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  97235. int iDataCur, /* Canonical data cursor (main table or PK index) */
  97236. int iIdxCur, /* First index cursor */
  97237. int regNewData, /* First register in a range holding values to insert */
  97238. int regOldData, /* Previous content. 0 for INSERTs */
  97239. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  97240. u8 overrideError, /* Override onError to this if not OE_Default */
  97241. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  97242. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  97243. ){
  97244. Vdbe *v; /* VDBE under constrution */
  97245. Index *pIdx; /* Pointer to one of the indices */
  97246. Index *pPk = 0; /* The PRIMARY KEY index */
  97247. sqlite3 *db; /* Database connection */
  97248. int i; /* loop counter */
  97249. int ix; /* Index loop counter */
  97250. int nCol; /* Number of columns */
  97251. int onError; /* Conflict resolution strategy */
  97252. int addr1; /* Address of jump instruction */
  97253. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  97254. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  97255. int ipkTop = 0; /* Top of the rowid change constraint check */
  97256. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  97257. u8 isUpdate; /* True if this is an UPDATE operation */
  97258. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  97259. int regRowid = -1; /* Register holding ROWID value */
  97260. isUpdate = regOldData!=0;
  97261. db = pParse->db;
  97262. v = sqlite3GetVdbe(pParse);
  97263. assert( v!=0 );
  97264. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  97265. nCol = pTab->nCol;
  97266. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  97267. ** normal rowid tables. nPkField is the number of key fields in the
  97268. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  97269. ** number of fields in the true primary key of the table. */
  97270. if( HasRowid(pTab) ){
  97271. pPk = 0;
  97272. nPkField = 1;
  97273. }else{
  97274. pPk = sqlite3PrimaryKeyIndex(pTab);
  97275. nPkField = pPk->nKeyCol;
  97276. }
  97277. /* Record that this module has started */
  97278. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  97279. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  97280. /* Test all NOT NULL constraints.
  97281. */
  97282. for(i=0; i<nCol; i++){
  97283. if( i==pTab->iPKey ){
  97284. continue;
  97285. }
  97286. onError = pTab->aCol[i].notNull;
  97287. if( onError==OE_None ) continue;
  97288. if( overrideError!=OE_Default ){
  97289. onError = overrideError;
  97290. }else if( onError==OE_Default ){
  97291. onError = OE_Abort;
  97292. }
  97293. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  97294. onError = OE_Abort;
  97295. }
  97296. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  97297. || onError==OE_Ignore || onError==OE_Replace );
  97298. switch( onError ){
  97299. case OE_Abort:
  97300. sqlite3MayAbort(pParse);
  97301. /* Fall through */
  97302. case OE_Rollback:
  97303. case OE_Fail: {
  97304. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  97305. pTab->aCol[i].zName);
  97306. sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  97307. regNewData+1+i, zMsg, P4_DYNAMIC);
  97308. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  97309. VdbeCoverage(v);
  97310. break;
  97311. }
  97312. case OE_Ignore: {
  97313. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  97314. VdbeCoverage(v);
  97315. break;
  97316. }
  97317. default: {
  97318. assert( onError==OE_Replace );
  97319. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  97320. VdbeCoverage(v);
  97321. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  97322. sqlite3VdbeJumpHere(v, addr1);
  97323. break;
  97324. }
  97325. }
  97326. }
  97327. /* Test all CHECK constraints
  97328. */
  97329. #ifndef SQLITE_OMIT_CHECK
  97330. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  97331. ExprList *pCheck = pTab->pCheck;
  97332. pParse->ckBase = regNewData+1;
  97333. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  97334. for(i=0; i<pCheck->nExpr; i++){
  97335. int allOk = sqlite3VdbeMakeLabel(v);
  97336. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  97337. if( onError==OE_Ignore ){
  97338. sqlite3VdbeGoto(v, ignoreDest);
  97339. }else{
  97340. char *zName = pCheck->a[i].zName;
  97341. if( zName==0 ) zName = pTab->zName;
  97342. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  97343. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  97344. onError, zName, P4_TRANSIENT,
  97345. P5_ConstraintCheck);
  97346. }
  97347. sqlite3VdbeResolveLabel(v, allOk);
  97348. }
  97349. }
  97350. #endif /* !defined(SQLITE_OMIT_CHECK) */
  97351. /* If rowid is changing, make sure the new rowid does not previously
  97352. ** exist in the table.
  97353. */
  97354. if( pkChng && pPk==0 ){
  97355. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  97356. /* Figure out what action to take in case of a rowid collision */
  97357. onError = pTab->keyConf;
  97358. if( overrideError!=OE_Default ){
  97359. onError = overrideError;
  97360. }else if( onError==OE_Default ){
  97361. onError = OE_Abort;
  97362. }
  97363. if( isUpdate ){
  97364. /* pkChng!=0 does not mean that the rowid has change, only that
  97365. ** it might have changed. Skip the conflict logic below if the rowid
  97366. ** is unchanged. */
  97367. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  97368. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  97369. VdbeCoverage(v);
  97370. }
  97371. /* If the response to a rowid conflict is REPLACE but the response
  97372. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  97373. ** to defer the running of the rowid conflict checking until after
  97374. ** the UNIQUE constraints have run.
  97375. */
  97376. if( onError==OE_Replace && overrideError!=OE_Replace ){
  97377. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  97378. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  97379. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  97380. break;
  97381. }
  97382. }
  97383. }
  97384. /* Check to see if the new rowid already exists in the table. Skip
  97385. ** the following conflict logic if it does not. */
  97386. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  97387. VdbeCoverage(v);
  97388. /* Generate code that deals with a rowid collision */
  97389. switch( onError ){
  97390. default: {
  97391. onError = OE_Abort;
  97392. /* Fall thru into the next case */
  97393. }
  97394. case OE_Rollback:
  97395. case OE_Abort:
  97396. case OE_Fail: {
  97397. sqlite3RowidConstraint(pParse, onError, pTab);
  97398. break;
  97399. }
  97400. case OE_Replace: {
  97401. /* If there are DELETE triggers on this table and the
  97402. ** recursive-triggers flag is set, call GenerateRowDelete() to
  97403. ** remove the conflicting row from the table. This will fire
  97404. ** the triggers and remove both the table and index b-tree entries.
  97405. **
  97406. ** Otherwise, if there are no triggers or the recursive-triggers
  97407. ** flag is not set, but the table has one or more indexes, call
  97408. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  97409. ** only. The table b-tree entry will be replaced by the new entry
  97410. ** when it is inserted.
  97411. **
  97412. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  97413. ** also invoke MultiWrite() to indicate that this VDBE may require
  97414. ** statement rollback (if the statement is aborted after the delete
  97415. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  97416. ** but being more selective here allows statements like:
  97417. **
  97418. ** REPLACE INTO t(rowid) VALUES($newrowid)
  97419. **
  97420. ** to run without a statement journal if there are no indexes on the
  97421. ** table.
  97422. */
  97423. Trigger *pTrigger = 0;
  97424. if( db->flags&SQLITE_RecTriggers ){
  97425. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  97426. }
  97427. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  97428. sqlite3MultiWrite(pParse);
  97429. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  97430. regNewData, 1, 0, OE_Replace,
  97431. ONEPASS_SINGLE, -1);
  97432. }else{
  97433. if( pTab->pIndex ){
  97434. sqlite3MultiWrite(pParse);
  97435. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  97436. }
  97437. }
  97438. seenReplace = 1;
  97439. break;
  97440. }
  97441. case OE_Ignore: {
  97442. /*assert( seenReplace==0 );*/
  97443. sqlite3VdbeGoto(v, ignoreDest);
  97444. break;
  97445. }
  97446. }
  97447. sqlite3VdbeResolveLabel(v, addrRowidOk);
  97448. if( ipkTop ){
  97449. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  97450. sqlite3VdbeJumpHere(v, ipkTop);
  97451. }
  97452. }
  97453. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  97454. ** index and making sure that duplicate entries do not already exist.
  97455. ** Compute the revised record entries for indices as we go.
  97456. **
  97457. ** This loop also handles the case of the PRIMARY KEY index for a
  97458. ** WITHOUT ROWID table.
  97459. */
  97460. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  97461. int regIdx; /* Range of registers hold conent for pIdx */
  97462. int regR; /* Range of registers holding conflicting PK */
  97463. int iThisCur; /* Cursor for this UNIQUE index */
  97464. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  97465. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  97466. if( bAffinityDone==0 ){
  97467. sqlite3TableAffinity(v, pTab, regNewData+1);
  97468. bAffinityDone = 1;
  97469. }
  97470. iThisCur = iIdxCur+ix;
  97471. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  97472. /* Skip partial indices for which the WHERE clause is not true */
  97473. if( pIdx->pPartIdxWhere ){
  97474. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  97475. pParse->ckBase = regNewData+1;
  97476. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  97477. SQLITE_JUMPIFNULL);
  97478. pParse->ckBase = 0;
  97479. }
  97480. /* Create a record for this index entry as it should appear after
  97481. ** the insert or update. Store that record in the aRegIdx[ix] register
  97482. */
  97483. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
  97484. for(i=0; i<pIdx->nColumn; i++){
  97485. int iField = pIdx->aiColumn[i];
  97486. int x;
  97487. if( iField==XN_EXPR ){
  97488. pParse->ckBase = regNewData+1;
  97489. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  97490. pParse->ckBase = 0;
  97491. VdbeComment((v, "%s column %d", pIdx->zName, i));
  97492. }else{
  97493. if( iField==XN_ROWID || iField==pTab->iPKey ){
  97494. if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
  97495. x = regNewData;
  97496. regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
  97497. }else{
  97498. x = iField + regNewData + 1;
  97499. }
  97500. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  97501. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  97502. }
  97503. }
  97504. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  97505. VdbeComment((v, "for %s", pIdx->zName));
  97506. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
  97507. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  97508. ** of a WITHOUT ROWID table and there has been no change the
  97509. ** primary key, then no collision is possible. The collision detection
  97510. ** logic below can all be skipped. */
  97511. if( isUpdate && pPk==pIdx && pkChng==0 ){
  97512. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  97513. continue;
  97514. }
  97515. /* Find out what action to take in case there is a uniqueness conflict */
  97516. onError = pIdx->onError;
  97517. if( onError==OE_None ){
  97518. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  97519. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  97520. continue; /* pIdx is not a UNIQUE index */
  97521. }
  97522. if( overrideError!=OE_Default ){
  97523. onError = overrideError;
  97524. }else if( onError==OE_Default ){
  97525. onError = OE_Abort;
  97526. }
  97527. /* Check to see if the new index entry will be unique */
  97528. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  97529. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  97530. /* Generate code to handle collisions */
  97531. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  97532. if( isUpdate || onError==OE_Replace ){
  97533. if( HasRowid(pTab) ){
  97534. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  97535. /* Conflict only if the rowid of the existing index entry
  97536. ** is different from old-rowid */
  97537. if( isUpdate ){
  97538. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  97539. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  97540. VdbeCoverage(v);
  97541. }
  97542. }else{
  97543. int x;
  97544. /* Extract the PRIMARY KEY from the end of the index entry and
  97545. ** store it in registers regR..regR+nPk-1 */
  97546. if( pIdx!=pPk ){
  97547. for(i=0; i<pPk->nKeyCol; i++){
  97548. assert( pPk->aiColumn[i]>=0 );
  97549. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  97550. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  97551. VdbeComment((v, "%s.%s", pTab->zName,
  97552. pTab->aCol[pPk->aiColumn[i]].zName));
  97553. }
  97554. }
  97555. if( isUpdate ){
  97556. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  97557. ** table, only conflict if the new PRIMARY KEY values are actually
  97558. ** different from the old.
  97559. **
  97560. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  97561. ** of the matched index row are different from the original PRIMARY
  97562. ** KEY values of this row before the update. */
  97563. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  97564. int op = OP_Ne;
  97565. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  97566. for(i=0; i<pPk->nKeyCol; i++){
  97567. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  97568. x = pPk->aiColumn[i];
  97569. assert( x>=0 );
  97570. if( i==(pPk->nKeyCol-1) ){
  97571. addrJump = addrUniqueOk;
  97572. op = OP_Eq;
  97573. }
  97574. sqlite3VdbeAddOp4(v, op,
  97575. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  97576. );
  97577. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  97578. VdbeCoverageIf(v, op==OP_Eq);
  97579. VdbeCoverageIf(v, op==OP_Ne);
  97580. }
  97581. }
  97582. }
  97583. }
  97584. /* Generate code that executes if the new index entry is not unique */
  97585. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  97586. || onError==OE_Ignore || onError==OE_Replace );
  97587. switch( onError ){
  97588. case OE_Rollback:
  97589. case OE_Abort:
  97590. case OE_Fail: {
  97591. sqlite3UniqueConstraint(pParse, onError, pIdx);
  97592. break;
  97593. }
  97594. case OE_Ignore: {
  97595. sqlite3VdbeGoto(v, ignoreDest);
  97596. break;
  97597. }
  97598. default: {
  97599. Trigger *pTrigger = 0;
  97600. assert( onError==OE_Replace );
  97601. sqlite3MultiWrite(pParse);
  97602. if( db->flags&SQLITE_RecTriggers ){
  97603. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  97604. }
  97605. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  97606. regR, nPkField, 0, OE_Replace,
  97607. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
  97608. seenReplace = 1;
  97609. break;
  97610. }
  97611. }
  97612. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  97613. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  97614. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  97615. }
  97616. if( ipkTop ){
  97617. sqlite3VdbeGoto(v, ipkTop+1);
  97618. sqlite3VdbeJumpHere(v, ipkBottom);
  97619. }
  97620. *pbMayReplace = seenReplace;
  97621. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  97622. }
  97623. /*
  97624. ** This routine generates code to finish the INSERT or UPDATE operation
  97625. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  97626. ** A consecutive range of registers starting at regNewData contains the
  97627. ** rowid and the content to be inserted.
  97628. **
  97629. ** The arguments to this routine should be the same as the first six
  97630. ** arguments to sqlite3GenerateConstraintChecks.
  97631. */
  97632. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  97633. Parse *pParse, /* The parser context */
  97634. Table *pTab, /* the table into which we are inserting */
  97635. int iDataCur, /* Cursor of the canonical data source */
  97636. int iIdxCur, /* First index cursor */
  97637. int regNewData, /* Range of content */
  97638. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  97639. int isUpdate, /* True for UPDATE, False for INSERT */
  97640. int appendBias, /* True if this is likely to be an append */
  97641. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  97642. ){
  97643. Vdbe *v; /* Prepared statements under construction */
  97644. Index *pIdx; /* An index being inserted or updated */
  97645. u8 pik_flags; /* flag values passed to the btree insert */
  97646. int regData; /* Content registers (after the rowid) */
  97647. int regRec; /* Register holding assembled record for the table */
  97648. int i; /* Loop counter */
  97649. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  97650. v = sqlite3GetVdbe(pParse);
  97651. assert( v!=0 );
  97652. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  97653. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  97654. if( aRegIdx[i]==0 ) continue;
  97655. bAffinityDone = 1;
  97656. if( pIdx->pPartIdxWhere ){
  97657. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  97658. VdbeCoverage(v);
  97659. }
  97660. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
  97661. pik_flags = 0;
  97662. if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
  97663. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  97664. assert( pParse->nested==0 );
  97665. pik_flags |= OPFLAG_NCHANGE;
  97666. }
  97667. if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
  97668. }
  97669. if( !HasRowid(pTab) ) return;
  97670. regData = regNewData + 1;
  97671. regRec = sqlite3GetTempReg(pParse);
  97672. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  97673. if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
  97674. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  97675. if( pParse->nested ){
  97676. pik_flags = 0;
  97677. }else{
  97678. pik_flags = OPFLAG_NCHANGE;
  97679. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  97680. }
  97681. if( appendBias ){
  97682. pik_flags |= OPFLAG_APPEND;
  97683. }
  97684. if( useSeekResult ){
  97685. pik_flags |= OPFLAG_USESEEKRESULT;
  97686. }
  97687. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  97688. if( !pParse->nested ){
  97689. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  97690. }
  97691. sqlite3VdbeChangeP5(v, pik_flags);
  97692. }
  97693. /*
  97694. ** Allocate cursors for the pTab table and all its indices and generate
  97695. ** code to open and initialized those cursors.
  97696. **
  97697. ** The cursor for the object that contains the complete data (normally
  97698. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  97699. ** ROWID table) is returned in *piDataCur. The first index cursor is
  97700. ** returned in *piIdxCur. The number of indices is returned.
  97701. **
  97702. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  97703. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  97704. ** If iBase is negative, then allocate the next available cursor.
  97705. **
  97706. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  97707. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  97708. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  97709. ** pTab->pIndex list.
  97710. **
  97711. ** If pTab is a virtual table, then this routine is a no-op and the
  97712. ** *piDataCur and *piIdxCur values are left uninitialized.
  97713. */
  97714. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  97715. Parse *pParse, /* Parsing context */
  97716. Table *pTab, /* Table to be opened */
  97717. int op, /* OP_OpenRead or OP_OpenWrite */
  97718. u8 p5, /* P5 value for OP_Open* instructions */
  97719. int iBase, /* Use this for the table cursor, if there is one */
  97720. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  97721. int *piDataCur, /* Write the database source cursor number here */
  97722. int *piIdxCur /* Write the first index cursor number here */
  97723. ){
  97724. int i;
  97725. int iDb;
  97726. int iDataCur;
  97727. Index *pIdx;
  97728. Vdbe *v;
  97729. assert( op==OP_OpenRead || op==OP_OpenWrite );
  97730. assert( op==OP_OpenWrite || p5==0 );
  97731. if( IsVirtual(pTab) ){
  97732. /* This routine is a no-op for virtual tables. Leave the output
  97733. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  97734. ** can detect if they are used by mistake in the caller. */
  97735. return 0;
  97736. }
  97737. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  97738. v = sqlite3GetVdbe(pParse);
  97739. assert( v!=0 );
  97740. if( iBase<0 ) iBase = pParse->nTab;
  97741. iDataCur = iBase++;
  97742. if( piDataCur ) *piDataCur = iDataCur;
  97743. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  97744. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  97745. }else{
  97746. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  97747. }
  97748. if( piIdxCur ) *piIdxCur = iBase;
  97749. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  97750. int iIdxCur = iBase++;
  97751. assert( pIdx->pSchema==pTab->pSchema );
  97752. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
  97753. *piDataCur = iIdxCur;
  97754. }
  97755. if( aToOpen==0 || aToOpen[i+1] ){
  97756. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  97757. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  97758. sqlite3VdbeChangeP5(v, p5);
  97759. VdbeComment((v, "%s", pIdx->zName));
  97760. }
  97761. }
  97762. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  97763. return i;
  97764. }
  97765. #ifdef SQLITE_TEST
  97766. /*
  97767. ** The following global variable is incremented whenever the
  97768. ** transfer optimization is used. This is used for testing
  97769. ** purposes only - to make sure the transfer optimization really
  97770. ** is happening when it is supposed to.
  97771. */
  97772. SQLITE_API int sqlite3_xferopt_count;
  97773. #endif /* SQLITE_TEST */
  97774. #ifndef SQLITE_OMIT_XFER_OPT
  97775. /*
  97776. ** Check to see if index pSrc is compatible as a source of data
  97777. ** for index pDest in an insert transfer optimization. The rules
  97778. ** for a compatible index:
  97779. **
  97780. ** * The index is over the same set of columns
  97781. ** * The same DESC and ASC markings occurs on all columns
  97782. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  97783. ** * The same collating sequence on each column
  97784. ** * The index has the exact same WHERE clause
  97785. */
  97786. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  97787. int i;
  97788. assert( pDest && pSrc );
  97789. assert( pDest->pTable!=pSrc->pTable );
  97790. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  97791. return 0; /* Different number of columns */
  97792. }
  97793. if( pDest->onError!=pSrc->onError ){
  97794. return 0; /* Different conflict resolution strategies */
  97795. }
  97796. for(i=0; i<pSrc->nKeyCol; i++){
  97797. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  97798. return 0; /* Different columns indexed */
  97799. }
  97800. if( pSrc->aiColumn[i]==XN_EXPR ){
  97801. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  97802. if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
  97803. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  97804. return 0; /* Different expressions in the index */
  97805. }
  97806. }
  97807. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  97808. return 0; /* Different sort orders */
  97809. }
  97810. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  97811. return 0; /* Different collating sequences */
  97812. }
  97813. }
  97814. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  97815. return 0; /* Different WHERE clauses */
  97816. }
  97817. /* If no test above fails then the indices must be compatible */
  97818. return 1;
  97819. }
  97820. /*
  97821. ** Attempt the transfer optimization on INSERTs of the form
  97822. **
  97823. ** INSERT INTO tab1 SELECT * FROM tab2;
  97824. **
  97825. ** The xfer optimization transfers raw records from tab2 over to tab1.
  97826. ** Columns are not decoded and reassembled, which greatly improves
  97827. ** performance. Raw index records are transferred in the same way.
  97828. **
  97829. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  97830. ** There are lots of rules for determining compatibility - see comments
  97831. ** embedded in the code for details.
  97832. **
  97833. ** This routine returns TRUE if the optimization is guaranteed to be used.
  97834. ** Sometimes the xfer optimization will only work if the destination table
  97835. ** is empty - a factor that can only be determined at run-time. In that
  97836. ** case, this routine generates code for the xfer optimization but also
  97837. ** does a test to see if the destination table is empty and jumps over the
  97838. ** xfer optimization code if the test fails. In that case, this routine
  97839. ** returns FALSE so that the caller will know to go ahead and generate
  97840. ** an unoptimized transfer. This routine also returns FALSE if there
  97841. ** is no chance that the xfer optimization can be applied.
  97842. **
  97843. ** This optimization is particularly useful at making VACUUM run faster.
  97844. */
  97845. static int xferOptimization(
  97846. Parse *pParse, /* Parser context */
  97847. Table *pDest, /* The table we are inserting into */
  97848. Select *pSelect, /* A SELECT statement to use as the data source */
  97849. int onError, /* How to handle constraint errors */
  97850. int iDbDest /* The database of pDest */
  97851. ){
  97852. sqlite3 *db = pParse->db;
  97853. ExprList *pEList; /* The result set of the SELECT */
  97854. Table *pSrc; /* The table in the FROM clause of SELECT */
  97855. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  97856. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  97857. int i; /* Loop counter */
  97858. int iDbSrc; /* The database of pSrc */
  97859. int iSrc, iDest; /* Cursors from source and destination */
  97860. int addr1, addr2; /* Loop addresses */
  97861. int emptyDestTest = 0; /* Address of test for empty pDest */
  97862. int emptySrcTest = 0; /* Address of test for empty pSrc */
  97863. Vdbe *v; /* The VDBE we are building */
  97864. int regAutoinc; /* Memory register used by AUTOINC */
  97865. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  97866. int regData, regRowid; /* Registers holding data and rowid */
  97867. if( pSelect==0 ){
  97868. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  97869. }
  97870. if( pParse->pWith || pSelect->pWith ){
  97871. /* Do not attempt to process this query if there are an WITH clauses
  97872. ** attached to it. Proceeding may generate a false "no such table: xxx"
  97873. ** error if pSelect reads from a CTE named "xxx". */
  97874. return 0;
  97875. }
  97876. if( sqlite3TriggerList(pParse, pDest) ){
  97877. return 0; /* tab1 must not have triggers */
  97878. }
  97879. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97880. if( pDest->tabFlags & TF_Virtual ){
  97881. return 0; /* tab1 must not be a virtual table */
  97882. }
  97883. #endif
  97884. if( onError==OE_Default ){
  97885. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  97886. if( onError==OE_Default ) onError = OE_Abort;
  97887. }
  97888. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  97889. if( pSelect->pSrc->nSrc!=1 ){
  97890. return 0; /* FROM clause must have exactly one term */
  97891. }
  97892. if( pSelect->pSrc->a[0].pSelect ){
  97893. return 0; /* FROM clause cannot contain a subquery */
  97894. }
  97895. if( pSelect->pWhere ){
  97896. return 0; /* SELECT may not have a WHERE clause */
  97897. }
  97898. if( pSelect->pOrderBy ){
  97899. return 0; /* SELECT may not have an ORDER BY clause */
  97900. }
  97901. /* Do not need to test for a HAVING clause. If HAVING is present but
  97902. ** there is no ORDER BY, we will get an error. */
  97903. if( pSelect->pGroupBy ){
  97904. return 0; /* SELECT may not have a GROUP BY clause */
  97905. }
  97906. if( pSelect->pLimit ){
  97907. return 0; /* SELECT may not have a LIMIT clause */
  97908. }
  97909. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  97910. if( pSelect->pPrior ){
  97911. return 0; /* SELECT may not be a compound query */
  97912. }
  97913. if( pSelect->selFlags & SF_Distinct ){
  97914. return 0; /* SELECT may not be DISTINCT */
  97915. }
  97916. pEList = pSelect->pEList;
  97917. assert( pEList!=0 );
  97918. if( pEList->nExpr!=1 ){
  97919. return 0; /* The result set must have exactly one column */
  97920. }
  97921. assert( pEList->a[0].pExpr );
  97922. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  97923. return 0; /* The result set must be the special operator "*" */
  97924. }
  97925. /* At this point we have established that the statement is of the
  97926. ** correct syntactic form to participate in this optimization. Now
  97927. ** we have to check the semantics.
  97928. */
  97929. pItem = pSelect->pSrc->a;
  97930. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  97931. if( pSrc==0 ){
  97932. return 0; /* FROM clause does not contain a real table */
  97933. }
  97934. if( pSrc==pDest ){
  97935. return 0; /* tab1 and tab2 may not be the same table */
  97936. }
  97937. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  97938. return 0; /* source and destination must both be WITHOUT ROWID or not */
  97939. }
  97940. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97941. if( pSrc->tabFlags & TF_Virtual ){
  97942. return 0; /* tab2 must not be a virtual table */
  97943. }
  97944. #endif
  97945. if( pSrc->pSelect ){
  97946. return 0; /* tab2 may not be a view */
  97947. }
  97948. if( pDest->nCol!=pSrc->nCol ){
  97949. return 0; /* Number of columns must be the same in tab1 and tab2 */
  97950. }
  97951. if( pDest->iPKey!=pSrc->iPKey ){
  97952. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  97953. }
  97954. for(i=0; i<pDest->nCol; i++){
  97955. Column *pDestCol = &pDest->aCol[i];
  97956. Column *pSrcCol = &pSrc->aCol[i];
  97957. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  97958. if( (db->flags & SQLITE_Vacuum)==0
  97959. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  97960. ){
  97961. return 0; /* Neither table may have __hidden__ columns */
  97962. }
  97963. #endif
  97964. if( pDestCol->affinity!=pSrcCol->affinity ){
  97965. return 0; /* Affinity must be the same on all columns */
  97966. }
  97967. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  97968. return 0; /* Collating sequence must be the same on all columns */
  97969. }
  97970. if( pDestCol->notNull && !pSrcCol->notNull ){
  97971. return 0; /* tab2 must be NOT NULL if tab1 is */
  97972. }
  97973. /* Default values for second and subsequent columns need to match. */
  97974. if( i>0
  97975. && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
  97976. || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
  97977. ){
  97978. return 0; /* Default values must be the same for all columns */
  97979. }
  97980. }
  97981. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  97982. if( IsUniqueIndex(pDestIdx) ){
  97983. destHasUniqueIdx = 1;
  97984. }
  97985. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  97986. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  97987. }
  97988. if( pSrcIdx==0 ){
  97989. return 0; /* pDestIdx has no corresponding index in pSrc */
  97990. }
  97991. }
  97992. #ifndef SQLITE_OMIT_CHECK
  97993. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  97994. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  97995. }
  97996. #endif
  97997. #ifndef SQLITE_OMIT_FOREIGN_KEY
  97998. /* Disallow the transfer optimization if the destination table constains
  97999. ** any foreign key constraints. This is more restrictive than necessary.
  98000. ** But the main beneficiary of the transfer optimization is the VACUUM
  98001. ** command, and the VACUUM command disables foreign key constraints. So
  98002. ** the extra complication to make this rule less restrictive is probably
  98003. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  98004. */
  98005. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  98006. return 0;
  98007. }
  98008. #endif
  98009. if( (db->flags & SQLITE_CountRows)!=0 ){
  98010. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  98011. }
  98012. /* If we get this far, it means that the xfer optimization is at
  98013. ** least a possibility, though it might only work if the destination
  98014. ** table (tab1) is initially empty.
  98015. */
  98016. #ifdef SQLITE_TEST
  98017. sqlite3_xferopt_count++;
  98018. #endif
  98019. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  98020. v = sqlite3GetVdbe(pParse);
  98021. sqlite3CodeVerifySchema(pParse, iDbSrc);
  98022. iSrc = pParse->nTab++;
  98023. iDest = pParse->nTab++;
  98024. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  98025. regData = sqlite3GetTempReg(pParse);
  98026. regRowid = sqlite3GetTempReg(pParse);
  98027. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  98028. assert( HasRowid(pDest) || destHasUniqueIdx );
  98029. if( (db->flags & SQLITE_Vacuum)==0 && (
  98030. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  98031. || destHasUniqueIdx /* (2) */
  98032. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  98033. )){
  98034. /* In some circumstances, we are able to run the xfer optimization
  98035. ** only if the destination table is initially empty. Unless the
  98036. ** SQLITE_Vacuum flag is set, this block generates code to make
  98037. ** that determination. If SQLITE_Vacuum is set, then the destination
  98038. ** table is always empty.
  98039. **
  98040. ** Conditions under which the destination must be empty:
  98041. **
  98042. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  98043. ** (If the destination is not initially empty, the rowid fields
  98044. ** of index entries might need to change.)
  98045. **
  98046. ** (2) The destination has a unique index. (The xfer optimization
  98047. ** is unable to test uniqueness.)
  98048. **
  98049. ** (3) onError is something other than OE_Abort and OE_Rollback.
  98050. */
  98051. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  98052. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  98053. sqlite3VdbeJumpHere(v, addr1);
  98054. }
  98055. if( HasRowid(pSrc) ){
  98056. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  98057. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  98058. if( pDest->iPKey>=0 ){
  98059. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  98060. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  98061. VdbeCoverage(v);
  98062. sqlite3RowidConstraint(pParse, onError, pDest);
  98063. sqlite3VdbeJumpHere(v, addr2);
  98064. autoIncStep(pParse, regAutoinc, regRowid);
  98065. }else if( pDest->pIndex==0 ){
  98066. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  98067. }else{
  98068. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  98069. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  98070. }
  98071. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  98072. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  98073. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  98074. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  98075. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  98076. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  98077. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  98078. }else{
  98079. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  98080. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  98081. }
  98082. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  98083. u8 idxInsFlags = 0;
  98084. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  98085. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  98086. }
  98087. assert( pSrcIdx );
  98088. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  98089. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  98090. VdbeComment((v, "%s", pSrcIdx->zName));
  98091. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  98092. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  98093. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  98094. VdbeComment((v, "%s", pDestIdx->zName));
  98095. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  98096. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  98097. if( db->flags & SQLITE_Vacuum ){
  98098. /* This INSERT command is part of a VACUUM operation, which guarantees
  98099. ** that the destination table is empty. If all indexed columns use
  98100. ** collation sequence BINARY, then it can also be assumed that the
  98101. ** index will be populated by inserting keys in strictly sorted
  98102. ** order. In this case, instead of seeking within the b-tree as part
  98103. ** of every OP_IdxInsert opcode, an OP_Last is added before the
  98104. ** OP_IdxInsert to seek to the point within the b-tree where each key
  98105. ** should be inserted. This is faster.
  98106. **
  98107. ** If any of the indexed columns use a collation sequence other than
  98108. ** BINARY, this optimization is disabled. This is because the user
  98109. ** might change the definition of a collation sequence and then run
  98110. ** a VACUUM command. In that case keys may not be written in strictly
  98111. ** sorted order. */
  98112. for(i=0; i<pSrcIdx->nColumn; i++){
  98113. const char *zColl = pSrcIdx->azColl[i];
  98114. assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
  98115. || sqlite3StrBINARY==zColl );
  98116. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  98117. }
  98118. if( i==pSrcIdx->nColumn ){
  98119. idxInsFlags = OPFLAG_USESEEKRESULT;
  98120. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  98121. }
  98122. }
  98123. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  98124. idxInsFlags |= OPFLAG_NCHANGE;
  98125. }
  98126. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  98127. sqlite3VdbeChangeP5(v, idxInsFlags);
  98128. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  98129. sqlite3VdbeJumpHere(v, addr1);
  98130. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  98131. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  98132. }
  98133. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  98134. sqlite3ReleaseTempReg(pParse, regRowid);
  98135. sqlite3ReleaseTempReg(pParse, regData);
  98136. if( emptyDestTest ){
  98137. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  98138. sqlite3VdbeJumpHere(v, emptyDestTest);
  98139. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  98140. return 0;
  98141. }else{
  98142. return 1;
  98143. }
  98144. }
  98145. #endif /* SQLITE_OMIT_XFER_OPT */
  98146. /************** End of insert.c **********************************************/
  98147. /************** Begin file legacy.c ******************************************/
  98148. /*
  98149. ** 2001 September 15
  98150. **
  98151. ** The author disclaims copyright to this source code. In place of
  98152. ** a legal notice, here is a blessing:
  98153. **
  98154. ** May you do good and not evil.
  98155. ** May you find forgiveness for yourself and forgive others.
  98156. ** May you share freely, never taking more than you give.
  98157. **
  98158. *************************************************************************
  98159. ** Main file for the SQLite library. The routines in this file
  98160. ** implement the programmer interface to the library. Routines in
  98161. ** other files are for internal use by SQLite and should not be
  98162. ** accessed by users of the library.
  98163. */
  98164. /* #include "sqliteInt.h" */
  98165. /*
  98166. ** Execute SQL code. Return one of the SQLITE_ success/failure
  98167. ** codes. Also write an error message into memory obtained from
  98168. ** malloc() and make *pzErrMsg point to that message.
  98169. **
  98170. ** If the SQL is a query, then for each row in the query result
  98171. ** the xCallback() function is called. pArg becomes the first
  98172. ** argument to xCallback(). If xCallback=NULL then no callback
  98173. ** is invoked, even for queries.
  98174. */
  98175. SQLITE_API int SQLITE_STDCALL sqlite3_exec(
  98176. sqlite3 *db, /* The database on which the SQL executes */
  98177. const char *zSql, /* The SQL to be executed */
  98178. sqlite3_callback xCallback, /* Invoke this callback routine */
  98179. void *pArg, /* First argument to xCallback() */
  98180. char **pzErrMsg /* Write error messages here */
  98181. ){
  98182. int rc = SQLITE_OK; /* Return code */
  98183. const char *zLeftover; /* Tail of unprocessed SQL */
  98184. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  98185. char **azCols = 0; /* Names of result columns */
  98186. int callbackIsInit; /* True if callback data is initialized */
  98187. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  98188. if( zSql==0 ) zSql = "";
  98189. sqlite3_mutex_enter(db->mutex);
  98190. sqlite3Error(db, SQLITE_OK);
  98191. while( rc==SQLITE_OK && zSql[0] ){
  98192. int nCol;
  98193. char **azVals = 0;
  98194. pStmt = 0;
  98195. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  98196. assert( rc==SQLITE_OK || pStmt==0 );
  98197. if( rc!=SQLITE_OK ){
  98198. continue;
  98199. }
  98200. if( !pStmt ){
  98201. /* this happens for a comment or white-space */
  98202. zSql = zLeftover;
  98203. continue;
  98204. }
  98205. callbackIsInit = 0;
  98206. nCol = sqlite3_column_count(pStmt);
  98207. while( 1 ){
  98208. int i;
  98209. rc = sqlite3_step(pStmt);
  98210. /* Invoke the callback function if required */
  98211. if( xCallback && (SQLITE_ROW==rc ||
  98212. (SQLITE_DONE==rc && !callbackIsInit
  98213. && db->flags&SQLITE_NullCallback)) ){
  98214. if( !callbackIsInit ){
  98215. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  98216. if( azCols==0 ){
  98217. goto exec_out;
  98218. }
  98219. for(i=0; i<nCol; i++){
  98220. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  98221. /* sqlite3VdbeSetColName() installs column names as UTF8
  98222. ** strings so there is no way for sqlite3_column_name() to fail. */
  98223. assert( azCols[i]!=0 );
  98224. }
  98225. callbackIsInit = 1;
  98226. }
  98227. if( rc==SQLITE_ROW ){
  98228. azVals = &azCols[nCol];
  98229. for(i=0; i<nCol; i++){
  98230. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  98231. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  98232. db->mallocFailed = 1;
  98233. goto exec_out;
  98234. }
  98235. }
  98236. }
  98237. if( xCallback(pArg, nCol, azVals, azCols) ){
  98238. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  98239. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  98240. ** return SQLITE_ABORT. */
  98241. rc = SQLITE_ABORT;
  98242. sqlite3VdbeFinalize((Vdbe *)pStmt);
  98243. pStmt = 0;
  98244. sqlite3Error(db, SQLITE_ABORT);
  98245. goto exec_out;
  98246. }
  98247. }
  98248. if( rc!=SQLITE_ROW ){
  98249. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  98250. pStmt = 0;
  98251. zSql = zLeftover;
  98252. while( sqlite3Isspace(zSql[0]) ) zSql++;
  98253. break;
  98254. }
  98255. }
  98256. sqlite3DbFree(db, azCols);
  98257. azCols = 0;
  98258. }
  98259. exec_out:
  98260. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  98261. sqlite3DbFree(db, azCols);
  98262. rc = sqlite3ApiExit(db, rc);
  98263. if( rc!=SQLITE_OK && pzErrMsg ){
  98264. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  98265. *pzErrMsg = sqlite3Malloc(nErrMsg);
  98266. if( *pzErrMsg ){
  98267. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  98268. }else{
  98269. rc = SQLITE_NOMEM;
  98270. sqlite3Error(db, SQLITE_NOMEM);
  98271. }
  98272. }else if( pzErrMsg ){
  98273. *pzErrMsg = 0;
  98274. }
  98275. assert( (rc&db->errMask)==rc );
  98276. sqlite3_mutex_leave(db->mutex);
  98277. return rc;
  98278. }
  98279. /************** End of legacy.c **********************************************/
  98280. /************** Begin file loadext.c *****************************************/
  98281. /*
  98282. ** 2006 June 7
  98283. **
  98284. ** The author disclaims copyright to this source code. In place of
  98285. ** a legal notice, here is a blessing:
  98286. **
  98287. ** May you do good and not evil.
  98288. ** May you find forgiveness for yourself and forgive others.
  98289. ** May you share freely, never taking more than you give.
  98290. **
  98291. *************************************************************************
  98292. ** This file contains code used to dynamically load extensions into
  98293. ** the SQLite library.
  98294. */
  98295. #ifndef SQLITE_CORE
  98296. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  98297. #endif
  98298. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  98299. /************** Begin file sqlite3ext.h **************************************/
  98300. /*
  98301. ** 2006 June 7
  98302. **
  98303. ** The author disclaims copyright to this source code. In place of
  98304. ** a legal notice, here is a blessing:
  98305. **
  98306. ** May you do good and not evil.
  98307. ** May you find forgiveness for yourself and forgive others.
  98308. ** May you share freely, never taking more than you give.
  98309. **
  98310. *************************************************************************
  98311. ** This header file defines the SQLite interface for use by
  98312. ** shared libraries that want to be imported as extensions into
  98313. ** an SQLite instance. Shared libraries that intend to be loaded
  98314. ** as extensions by SQLite should #include this file instead of
  98315. ** sqlite3.h.
  98316. */
  98317. #ifndef _SQLITE3EXT_H_
  98318. #define _SQLITE3EXT_H_
  98319. /* #include "sqlite3.h" */
  98320. typedef struct sqlite3_api_routines sqlite3_api_routines;
  98321. /*
  98322. ** The following structure holds pointers to all of the SQLite API
  98323. ** routines.
  98324. **
  98325. ** WARNING: In order to maintain backwards compatibility, add new
  98326. ** interfaces to the end of this structure only. If you insert new
  98327. ** interfaces in the middle of this structure, then older different
  98328. ** versions of SQLite will not be able to load each other's shared
  98329. ** libraries!
  98330. */
  98331. struct sqlite3_api_routines {
  98332. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  98333. int (*aggregate_count)(sqlite3_context*);
  98334. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  98335. int (*bind_double)(sqlite3_stmt*,int,double);
  98336. int (*bind_int)(sqlite3_stmt*,int,int);
  98337. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  98338. int (*bind_null)(sqlite3_stmt*,int);
  98339. int (*bind_parameter_count)(sqlite3_stmt*);
  98340. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  98341. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  98342. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  98343. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  98344. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  98345. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  98346. int (*busy_timeout)(sqlite3*,int ms);
  98347. int (*changes)(sqlite3*);
  98348. int (*close)(sqlite3*);
  98349. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  98350. int eTextRep,const char*));
  98351. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  98352. int eTextRep,const void*));
  98353. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  98354. int (*column_bytes)(sqlite3_stmt*,int iCol);
  98355. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  98356. int (*column_count)(sqlite3_stmt*pStmt);
  98357. const char * (*column_database_name)(sqlite3_stmt*,int);
  98358. const void * (*column_database_name16)(sqlite3_stmt*,int);
  98359. const char * (*column_decltype)(sqlite3_stmt*,int i);
  98360. const void * (*column_decltype16)(sqlite3_stmt*,int);
  98361. double (*column_double)(sqlite3_stmt*,int iCol);
  98362. int (*column_int)(sqlite3_stmt*,int iCol);
  98363. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  98364. const char * (*column_name)(sqlite3_stmt*,int);
  98365. const void * (*column_name16)(sqlite3_stmt*,int);
  98366. const char * (*column_origin_name)(sqlite3_stmt*,int);
  98367. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  98368. const char * (*column_table_name)(sqlite3_stmt*,int);
  98369. const void * (*column_table_name16)(sqlite3_stmt*,int);
  98370. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  98371. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  98372. int (*column_type)(sqlite3_stmt*,int iCol);
  98373. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  98374. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  98375. int (*complete)(const char*sql);
  98376. int (*complete16)(const void*sql);
  98377. int (*create_collation)(sqlite3*,const char*,int,void*,
  98378. int(*)(void*,int,const void*,int,const void*));
  98379. int (*create_collation16)(sqlite3*,const void*,int,void*,
  98380. int(*)(void*,int,const void*,int,const void*));
  98381. int (*create_function)(sqlite3*,const char*,int,int,void*,
  98382. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  98383. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  98384. void (*xFinal)(sqlite3_context*));
  98385. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  98386. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  98387. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  98388. void (*xFinal)(sqlite3_context*));
  98389. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  98390. int (*data_count)(sqlite3_stmt*pStmt);
  98391. sqlite3 * (*db_handle)(sqlite3_stmt*);
  98392. int (*declare_vtab)(sqlite3*,const char*);
  98393. int (*enable_shared_cache)(int);
  98394. int (*errcode)(sqlite3*db);
  98395. const char * (*errmsg)(sqlite3*);
  98396. const void * (*errmsg16)(sqlite3*);
  98397. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  98398. int (*expired)(sqlite3_stmt*);
  98399. int (*finalize)(sqlite3_stmt*pStmt);
  98400. void (*free)(void*);
  98401. void (*free_table)(char**result);
  98402. int (*get_autocommit)(sqlite3*);
  98403. void * (*get_auxdata)(sqlite3_context*,int);
  98404. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  98405. int (*global_recover)(void);
  98406. void (*interruptx)(sqlite3*);
  98407. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  98408. const char * (*libversion)(void);
  98409. int (*libversion_number)(void);
  98410. void *(*malloc)(int);
  98411. char * (*mprintf)(const char*,...);
  98412. int (*open)(const char*,sqlite3**);
  98413. int (*open16)(const void*,sqlite3**);
  98414. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  98415. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  98416. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  98417. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  98418. void *(*realloc)(void*,int);
  98419. int (*reset)(sqlite3_stmt*pStmt);
  98420. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  98421. void (*result_double)(sqlite3_context*,double);
  98422. void (*result_error)(sqlite3_context*,const char*,int);
  98423. void (*result_error16)(sqlite3_context*,const void*,int);
  98424. void (*result_int)(sqlite3_context*,int);
  98425. void (*result_int64)(sqlite3_context*,sqlite_int64);
  98426. void (*result_null)(sqlite3_context*);
  98427. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  98428. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  98429. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  98430. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  98431. void (*result_value)(sqlite3_context*,sqlite3_value*);
  98432. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  98433. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  98434. const char*,const char*),void*);
  98435. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  98436. char * (*snprintf)(int,char*,const char*,...);
  98437. int (*step)(sqlite3_stmt*);
  98438. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  98439. char const**,char const**,int*,int*,int*);
  98440. void (*thread_cleanup)(void);
  98441. int (*total_changes)(sqlite3*);
  98442. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  98443. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  98444. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  98445. sqlite_int64),void*);
  98446. void * (*user_data)(sqlite3_context*);
  98447. const void * (*value_blob)(sqlite3_value*);
  98448. int (*value_bytes)(sqlite3_value*);
  98449. int (*value_bytes16)(sqlite3_value*);
  98450. double (*value_double)(sqlite3_value*);
  98451. int (*value_int)(sqlite3_value*);
  98452. sqlite_int64 (*value_int64)(sqlite3_value*);
  98453. int (*value_numeric_type)(sqlite3_value*);
  98454. const unsigned char * (*value_text)(sqlite3_value*);
  98455. const void * (*value_text16)(sqlite3_value*);
  98456. const void * (*value_text16be)(sqlite3_value*);
  98457. const void * (*value_text16le)(sqlite3_value*);
  98458. int (*value_type)(sqlite3_value*);
  98459. char *(*vmprintf)(const char*,va_list);
  98460. /* Added ??? */
  98461. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  98462. /* Added by 3.3.13 */
  98463. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  98464. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  98465. int (*clear_bindings)(sqlite3_stmt*);
  98466. /* Added by 3.4.1 */
  98467. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  98468. void (*xDestroy)(void *));
  98469. /* Added by 3.5.0 */
  98470. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  98471. int (*blob_bytes)(sqlite3_blob*);
  98472. int (*blob_close)(sqlite3_blob*);
  98473. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  98474. int,sqlite3_blob**);
  98475. int (*blob_read)(sqlite3_blob*,void*,int,int);
  98476. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  98477. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  98478. int(*)(void*,int,const void*,int,const void*),
  98479. void(*)(void*));
  98480. int (*file_control)(sqlite3*,const char*,int,void*);
  98481. sqlite3_int64 (*memory_highwater)(int);
  98482. sqlite3_int64 (*memory_used)(void);
  98483. sqlite3_mutex *(*mutex_alloc)(int);
  98484. void (*mutex_enter)(sqlite3_mutex*);
  98485. void (*mutex_free)(sqlite3_mutex*);
  98486. void (*mutex_leave)(sqlite3_mutex*);
  98487. int (*mutex_try)(sqlite3_mutex*);
  98488. int (*open_v2)(const char*,sqlite3**,int,const char*);
  98489. int (*release_memory)(int);
  98490. void (*result_error_nomem)(sqlite3_context*);
  98491. void (*result_error_toobig)(sqlite3_context*);
  98492. int (*sleep)(int);
  98493. void (*soft_heap_limit)(int);
  98494. sqlite3_vfs *(*vfs_find)(const char*);
  98495. int (*vfs_register)(sqlite3_vfs*,int);
  98496. int (*vfs_unregister)(sqlite3_vfs*);
  98497. int (*xthreadsafe)(void);
  98498. void (*result_zeroblob)(sqlite3_context*,int);
  98499. void (*result_error_code)(sqlite3_context*,int);
  98500. int (*test_control)(int, ...);
  98501. void (*randomness)(int,void*);
  98502. sqlite3 *(*context_db_handle)(sqlite3_context*);
  98503. int (*extended_result_codes)(sqlite3*,int);
  98504. int (*limit)(sqlite3*,int,int);
  98505. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  98506. const char *(*sql)(sqlite3_stmt*);
  98507. int (*status)(int,int*,int*,int);
  98508. int (*backup_finish)(sqlite3_backup*);
  98509. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  98510. int (*backup_pagecount)(sqlite3_backup*);
  98511. int (*backup_remaining)(sqlite3_backup*);
  98512. int (*backup_step)(sqlite3_backup*,int);
  98513. const char *(*compileoption_get)(int);
  98514. int (*compileoption_used)(const char*);
  98515. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  98516. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  98517. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  98518. void (*xFinal)(sqlite3_context*),
  98519. void(*xDestroy)(void*));
  98520. int (*db_config)(sqlite3*,int,...);
  98521. sqlite3_mutex *(*db_mutex)(sqlite3*);
  98522. int (*db_status)(sqlite3*,int,int*,int*,int);
  98523. int (*extended_errcode)(sqlite3*);
  98524. void (*log)(int,const char*,...);
  98525. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  98526. const char *(*sourceid)(void);
  98527. int (*stmt_status)(sqlite3_stmt*,int,int);
  98528. int (*strnicmp)(const char*,const char*,int);
  98529. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  98530. int (*wal_autocheckpoint)(sqlite3*,int);
  98531. int (*wal_checkpoint)(sqlite3*,const char*);
  98532. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  98533. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  98534. int (*vtab_config)(sqlite3*,int op,...);
  98535. int (*vtab_on_conflict)(sqlite3*);
  98536. /* Version 3.7.16 and later */
  98537. int (*close_v2)(sqlite3*);
  98538. const char *(*db_filename)(sqlite3*,const char*);
  98539. int (*db_readonly)(sqlite3*,const char*);
  98540. int (*db_release_memory)(sqlite3*);
  98541. const char *(*errstr)(int);
  98542. int (*stmt_busy)(sqlite3_stmt*);
  98543. int (*stmt_readonly)(sqlite3_stmt*);
  98544. int (*stricmp)(const char*,const char*);
  98545. int (*uri_boolean)(const char*,const char*,int);
  98546. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  98547. const char *(*uri_parameter)(const char*,const char*);
  98548. char *(*vsnprintf)(int,char*,const char*,va_list);
  98549. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  98550. /* Version 3.8.7 and later */
  98551. int (*auto_extension)(void(*)(void));
  98552. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  98553. void(*)(void*));
  98554. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  98555. void(*)(void*),unsigned char);
  98556. int (*cancel_auto_extension)(void(*)(void));
  98557. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  98558. void *(*malloc64)(sqlite3_uint64);
  98559. sqlite3_uint64 (*msize)(void*);
  98560. void *(*realloc64)(void*,sqlite3_uint64);
  98561. void (*reset_auto_extension)(void);
  98562. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  98563. void(*)(void*));
  98564. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  98565. void(*)(void*), unsigned char);
  98566. int (*strglob)(const char*,const char*);
  98567. /* Version 3.8.11 and later */
  98568. sqlite3_value *(*value_dup)(const sqlite3_value*);
  98569. void (*value_free)(sqlite3_value*);
  98570. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  98571. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  98572. /* Version 3.9.0 and later */
  98573. unsigned int (*value_subtype)(sqlite3_value*);
  98574. void (*result_subtype)(sqlite3_context*,unsigned int);
  98575. /* Version 3.10.0 and later */
  98576. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  98577. int (*strlike)(const char*,const char*,unsigned int);
  98578. int (*db_cacheflush)(sqlite3*);
  98579. };
  98580. /*
  98581. ** The following macros redefine the API routines so that they are
  98582. ** redirected through the global sqlite3_api structure.
  98583. **
  98584. ** This header file is also used by the loadext.c source file
  98585. ** (part of the main SQLite library - not an extension) so that
  98586. ** it can get access to the sqlite3_api_routines structure
  98587. ** definition. But the main library does not want to redefine
  98588. ** the API. So the redefinition macros are only valid if the
  98589. ** SQLITE_CORE macros is undefined.
  98590. */
  98591. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  98592. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  98593. #ifndef SQLITE_OMIT_DEPRECATED
  98594. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  98595. #endif
  98596. #define sqlite3_bind_blob sqlite3_api->bind_blob
  98597. #define sqlite3_bind_double sqlite3_api->bind_double
  98598. #define sqlite3_bind_int sqlite3_api->bind_int
  98599. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  98600. #define sqlite3_bind_null sqlite3_api->bind_null
  98601. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  98602. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  98603. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  98604. #define sqlite3_bind_text sqlite3_api->bind_text
  98605. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  98606. #define sqlite3_bind_value sqlite3_api->bind_value
  98607. #define sqlite3_busy_handler sqlite3_api->busy_handler
  98608. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  98609. #define sqlite3_changes sqlite3_api->changes
  98610. #define sqlite3_close sqlite3_api->close
  98611. #define sqlite3_collation_needed sqlite3_api->collation_needed
  98612. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  98613. #define sqlite3_column_blob sqlite3_api->column_blob
  98614. #define sqlite3_column_bytes sqlite3_api->column_bytes
  98615. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  98616. #define sqlite3_column_count sqlite3_api->column_count
  98617. #define sqlite3_column_database_name sqlite3_api->column_database_name
  98618. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  98619. #define sqlite3_column_decltype sqlite3_api->column_decltype
  98620. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  98621. #define sqlite3_column_double sqlite3_api->column_double
  98622. #define sqlite3_column_int sqlite3_api->column_int
  98623. #define sqlite3_column_int64 sqlite3_api->column_int64
  98624. #define sqlite3_column_name sqlite3_api->column_name
  98625. #define sqlite3_column_name16 sqlite3_api->column_name16
  98626. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  98627. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  98628. #define sqlite3_column_table_name sqlite3_api->column_table_name
  98629. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  98630. #define sqlite3_column_text sqlite3_api->column_text
  98631. #define sqlite3_column_text16 sqlite3_api->column_text16
  98632. #define sqlite3_column_type sqlite3_api->column_type
  98633. #define sqlite3_column_value sqlite3_api->column_value
  98634. #define sqlite3_commit_hook sqlite3_api->commit_hook
  98635. #define sqlite3_complete sqlite3_api->complete
  98636. #define sqlite3_complete16 sqlite3_api->complete16
  98637. #define sqlite3_create_collation sqlite3_api->create_collation
  98638. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  98639. #define sqlite3_create_function sqlite3_api->create_function
  98640. #define sqlite3_create_function16 sqlite3_api->create_function16
  98641. #define sqlite3_create_module sqlite3_api->create_module
  98642. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  98643. #define sqlite3_data_count sqlite3_api->data_count
  98644. #define sqlite3_db_handle sqlite3_api->db_handle
  98645. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  98646. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  98647. #define sqlite3_errcode sqlite3_api->errcode
  98648. #define sqlite3_errmsg sqlite3_api->errmsg
  98649. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  98650. #define sqlite3_exec sqlite3_api->exec
  98651. #ifndef SQLITE_OMIT_DEPRECATED
  98652. #define sqlite3_expired sqlite3_api->expired
  98653. #endif
  98654. #define sqlite3_finalize sqlite3_api->finalize
  98655. #define sqlite3_free sqlite3_api->free
  98656. #define sqlite3_free_table sqlite3_api->free_table
  98657. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  98658. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  98659. #define sqlite3_get_table sqlite3_api->get_table
  98660. #ifndef SQLITE_OMIT_DEPRECATED
  98661. #define sqlite3_global_recover sqlite3_api->global_recover
  98662. #endif
  98663. #define sqlite3_interrupt sqlite3_api->interruptx
  98664. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  98665. #define sqlite3_libversion sqlite3_api->libversion
  98666. #define sqlite3_libversion_number sqlite3_api->libversion_number
  98667. #define sqlite3_malloc sqlite3_api->malloc
  98668. #define sqlite3_mprintf sqlite3_api->mprintf
  98669. #define sqlite3_open sqlite3_api->open
  98670. #define sqlite3_open16 sqlite3_api->open16
  98671. #define sqlite3_prepare sqlite3_api->prepare
  98672. #define sqlite3_prepare16 sqlite3_api->prepare16
  98673. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  98674. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  98675. #define sqlite3_profile sqlite3_api->profile
  98676. #define sqlite3_progress_handler sqlite3_api->progress_handler
  98677. #define sqlite3_realloc sqlite3_api->realloc
  98678. #define sqlite3_reset sqlite3_api->reset
  98679. #define sqlite3_result_blob sqlite3_api->result_blob
  98680. #define sqlite3_result_double sqlite3_api->result_double
  98681. #define sqlite3_result_error sqlite3_api->result_error
  98682. #define sqlite3_result_error16 sqlite3_api->result_error16
  98683. #define sqlite3_result_int sqlite3_api->result_int
  98684. #define sqlite3_result_int64 sqlite3_api->result_int64
  98685. #define sqlite3_result_null sqlite3_api->result_null
  98686. #define sqlite3_result_text sqlite3_api->result_text
  98687. #define sqlite3_result_text16 sqlite3_api->result_text16
  98688. #define sqlite3_result_text16be sqlite3_api->result_text16be
  98689. #define sqlite3_result_text16le sqlite3_api->result_text16le
  98690. #define sqlite3_result_value sqlite3_api->result_value
  98691. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  98692. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  98693. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  98694. #define sqlite3_snprintf sqlite3_api->snprintf
  98695. #define sqlite3_step sqlite3_api->step
  98696. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  98697. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  98698. #define sqlite3_total_changes sqlite3_api->total_changes
  98699. #define sqlite3_trace sqlite3_api->trace
  98700. #ifndef SQLITE_OMIT_DEPRECATED
  98701. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  98702. #endif
  98703. #define sqlite3_update_hook sqlite3_api->update_hook
  98704. #define sqlite3_user_data sqlite3_api->user_data
  98705. #define sqlite3_value_blob sqlite3_api->value_blob
  98706. #define sqlite3_value_bytes sqlite3_api->value_bytes
  98707. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  98708. #define sqlite3_value_double sqlite3_api->value_double
  98709. #define sqlite3_value_int sqlite3_api->value_int
  98710. #define sqlite3_value_int64 sqlite3_api->value_int64
  98711. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  98712. #define sqlite3_value_text sqlite3_api->value_text
  98713. #define sqlite3_value_text16 sqlite3_api->value_text16
  98714. #define sqlite3_value_text16be sqlite3_api->value_text16be
  98715. #define sqlite3_value_text16le sqlite3_api->value_text16le
  98716. #define sqlite3_value_type sqlite3_api->value_type
  98717. #define sqlite3_vmprintf sqlite3_api->vmprintf
  98718. #define sqlite3_vsnprintf sqlite3_api->vsnprintf
  98719. #define sqlite3_overload_function sqlite3_api->overload_function
  98720. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  98721. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  98722. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  98723. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  98724. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  98725. #define sqlite3_blob_close sqlite3_api->blob_close
  98726. #define sqlite3_blob_open sqlite3_api->blob_open
  98727. #define sqlite3_blob_read sqlite3_api->blob_read
  98728. #define sqlite3_blob_write sqlite3_api->blob_write
  98729. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  98730. #define sqlite3_file_control sqlite3_api->file_control
  98731. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  98732. #define sqlite3_memory_used sqlite3_api->memory_used
  98733. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  98734. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  98735. #define sqlite3_mutex_free sqlite3_api->mutex_free
  98736. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  98737. #define sqlite3_mutex_try sqlite3_api->mutex_try
  98738. #define sqlite3_open_v2 sqlite3_api->open_v2
  98739. #define sqlite3_release_memory sqlite3_api->release_memory
  98740. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  98741. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  98742. #define sqlite3_sleep sqlite3_api->sleep
  98743. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  98744. #define sqlite3_vfs_find sqlite3_api->vfs_find
  98745. #define sqlite3_vfs_register sqlite3_api->vfs_register
  98746. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  98747. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  98748. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  98749. #define sqlite3_result_error_code sqlite3_api->result_error_code
  98750. #define sqlite3_test_control sqlite3_api->test_control
  98751. #define sqlite3_randomness sqlite3_api->randomness
  98752. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  98753. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  98754. #define sqlite3_limit sqlite3_api->limit
  98755. #define sqlite3_next_stmt sqlite3_api->next_stmt
  98756. #define sqlite3_sql sqlite3_api->sql
  98757. #define sqlite3_status sqlite3_api->status
  98758. #define sqlite3_backup_finish sqlite3_api->backup_finish
  98759. #define sqlite3_backup_init sqlite3_api->backup_init
  98760. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  98761. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  98762. #define sqlite3_backup_step sqlite3_api->backup_step
  98763. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  98764. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  98765. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  98766. #define sqlite3_db_config sqlite3_api->db_config
  98767. #define sqlite3_db_mutex sqlite3_api->db_mutex
  98768. #define sqlite3_db_status sqlite3_api->db_status
  98769. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  98770. #define sqlite3_log sqlite3_api->log
  98771. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  98772. #define sqlite3_sourceid sqlite3_api->sourceid
  98773. #define sqlite3_stmt_status sqlite3_api->stmt_status
  98774. #define sqlite3_strnicmp sqlite3_api->strnicmp
  98775. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  98776. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  98777. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  98778. #define sqlite3_wal_hook sqlite3_api->wal_hook
  98779. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  98780. #define sqlite3_vtab_config sqlite3_api->vtab_config
  98781. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  98782. /* Version 3.7.16 and later */
  98783. #define sqlite3_close_v2 sqlite3_api->close_v2
  98784. #define sqlite3_db_filename sqlite3_api->db_filename
  98785. #define sqlite3_db_readonly sqlite3_api->db_readonly
  98786. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  98787. #define sqlite3_errstr sqlite3_api->errstr
  98788. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  98789. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  98790. #define sqlite3_stricmp sqlite3_api->stricmp
  98791. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  98792. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  98793. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  98794. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  98795. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  98796. /* Version 3.8.7 and later */
  98797. #define sqlite3_auto_extension sqlite3_api->auto_extension
  98798. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  98799. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  98800. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  98801. #define sqlite3_load_extension sqlite3_api->load_extension
  98802. #define sqlite3_malloc64 sqlite3_api->malloc64
  98803. #define sqlite3_msize sqlite3_api->msize
  98804. #define sqlite3_realloc64 sqlite3_api->realloc64
  98805. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  98806. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  98807. #define sqlite3_result_text64 sqlite3_api->result_text64
  98808. #define sqlite3_strglob sqlite3_api->strglob
  98809. /* Version 3.8.11 and later */
  98810. #define sqlite3_value_dup sqlite3_api->value_dup
  98811. #define sqlite3_value_free sqlite3_api->value_free
  98812. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  98813. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  98814. /* Version 3.9.0 and later */
  98815. #define sqlite3_value_subtype sqlite3_api->value_subtype
  98816. #define sqlite3_result_subtype sqlite3_api->result_subtype
  98817. /* Version 3.10.0 and later */
  98818. #define sqlite3_status64 sqlite3_api->status64
  98819. #define sqlite3_strlike sqlite3_api->strlike
  98820. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  98821. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  98822. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  98823. /* This case when the file really is being compiled as a loadable
  98824. ** extension */
  98825. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  98826. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  98827. # define SQLITE_EXTENSION_INIT3 \
  98828. extern const sqlite3_api_routines *sqlite3_api;
  98829. #else
  98830. /* This case when the file is being statically linked into the
  98831. ** application */
  98832. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  98833. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  98834. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  98835. #endif
  98836. #endif /* _SQLITE3EXT_H_ */
  98837. /************** End of sqlite3ext.h ******************************************/
  98838. /************** Continuing where we left off in loadext.c ********************/
  98839. /* #include "sqliteInt.h" */
  98840. /* #include <string.h> */
  98841. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  98842. /*
  98843. ** Some API routines are omitted when various features are
  98844. ** excluded from a build of SQLite. Substitute a NULL pointer
  98845. ** for any missing APIs.
  98846. */
  98847. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  98848. # define sqlite3_column_database_name 0
  98849. # define sqlite3_column_database_name16 0
  98850. # define sqlite3_column_table_name 0
  98851. # define sqlite3_column_table_name16 0
  98852. # define sqlite3_column_origin_name 0
  98853. # define sqlite3_column_origin_name16 0
  98854. #endif
  98855. #ifdef SQLITE_OMIT_AUTHORIZATION
  98856. # define sqlite3_set_authorizer 0
  98857. #endif
  98858. #ifdef SQLITE_OMIT_UTF16
  98859. # define sqlite3_bind_text16 0
  98860. # define sqlite3_collation_needed16 0
  98861. # define sqlite3_column_decltype16 0
  98862. # define sqlite3_column_name16 0
  98863. # define sqlite3_column_text16 0
  98864. # define sqlite3_complete16 0
  98865. # define sqlite3_create_collation16 0
  98866. # define sqlite3_create_function16 0
  98867. # define sqlite3_errmsg16 0
  98868. # define sqlite3_open16 0
  98869. # define sqlite3_prepare16 0
  98870. # define sqlite3_prepare16_v2 0
  98871. # define sqlite3_result_error16 0
  98872. # define sqlite3_result_text16 0
  98873. # define sqlite3_result_text16be 0
  98874. # define sqlite3_result_text16le 0
  98875. # define sqlite3_value_text16 0
  98876. # define sqlite3_value_text16be 0
  98877. # define sqlite3_value_text16le 0
  98878. # define sqlite3_column_database_name16 0
  98879. # define sqlite3_column_table_name16 0
  98880. # define sqlite3_column_origin_name16 0
  98881. #endif
  98882. #ifdef SQLITE_OMIT_COMPLETE
  98883. # define sqlite3_complete 0
  98884. # define sqlite3_complete16 0
  98885. #endif
  98886. #ifdef SQLITE_OMIT_DECLTYPE
  98887. # define sqlite3_column_decltype16 0
  98888. # define sqlite3_column_decltype 0
  98889. #endif
  98890. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  98891. # define sqlite3_progress_handler 0
  98892. #endif
  98893. #ifdef SQLITE_OMIT_VIRTUALTABLE
  98894. # define sqlite3_create_module 0
  98895. # define sqlite3_create_module_v2 0
  98896. # define sqlite3_declare_vtab 0
  98897. # define sqlite3_vtab_config 0
  98898. # define sqlite3_vtab_on_conflict 0
  98899. #endif
  98900. #ifdef SQLITE_OMIT_SHARED_CACHE
  98901. # define sqlite3_enable_shared_cache 0
  98902. #endif
  98903. #ifdef SQLITE_OMIT_TRACE
  98904. # define sqlite3_profile 0
  98905. # define sqlite3_trace 0
  98906. #endif
  98907. #ifdef SQLITE_OMIT_GET_TABLE
  98908. # define sqlite3_free_table 0
  98909. # define sqlite3_get_table 0
  98910. #endif
  98911. #ifdef SQLITE_OMIT_INCRBLOB
  98912. #define sqlite3_bind_zeroblob 0
  98913. #define sqlite3_blob_bytes 0
  98914. #define sqlite3_blob_close 0
  98915. #define sqlite3_blob_open 0
  98916. #define sqlite3_blob_read 0
  98917. #define sqlite3_blob_write 0
  98918. #define sqlite3_blob_reopen 0
  98919. #endif
  98920. /*
  98921. ** The following structure contains pointers to all SQLite API routines.
  98922. ** A pointer to this structure is passed into extensions when they are
  98923. ** loaded so that the extension can make calls back into the SQLite
  98924. ** library.
  98925. **
  98926. ** When adding new APIs, add them to the bottom of this structure
  98927. ** in order to preserve backwards compatibility.
  98928. **
  98929. ** Extensions that use newer APIs should first call the
  98930. ** sqlite3_libversion_number() to make sure that the API they
  98931. ** intend to use is supported by the library. Extensions should
  98932. ** also check to make sure that the pointer to the function is
  98933. ** not NULL before calling it.
  98934. */
  98935. static const sqlite3_api_routines sqlite3Apis = {
  98936. sqlite3_aggregate_context,
  98937. #ifndef SQLITE_OMIT_DEPRECATED
  98938. sqlite3_aggregate_count,
  98939. #else
  98940. 0,
  98941. #endif
  98942. sqlite3_bind_blob,
  98943. sqlite3_bind_double,
  98944. sqlite3_bind_int,
  98945. sqlite3_bind_int64,
  98946. sqlite3_bind_null,
  98947. sqlite3_bind_parameter_count,
  98948. sqlite3_bind_parameter_index,
  98949. sqlite3_bind_parameter_name,
  98950. sqlite3_bind_text,
  98951. sqlite3_bind_text16,
  98952. sqlite3_bind_value,
  98953. sqlite3_busy_handler,
  98954. sqlite3_busy_timeout,
  98955. sqlite3_changes,
  98956. sqlite3_close,
  98957. sqlite3_collation_needed,
  98958. sqlite3_collation_needed16,
  98959. sqlite3_column_blob,
  98960. sqlite3_column_bytes,
  98961. sqlite3_column_bytes16,
  98962. sqlite3_column_count,
  98963. sqlite3_column_database_name,
  98964. sqlite3_column_database_name16,
  98965. sqlite3_column_decltype,
  98966. sqlite3_column_decltype16,
  98967. sqlite3_column_double,
  98968. sqlite3_column_int,
  98969. sqlite3_column_int64,
  98970. sqlite3_column_name,
  98971. sqlite3_column_name16,
  98972. sqlite3_column_origin_name,
  98973. sqlite3_column_origin_name16,
  98974. sqlite3_column_table_name,
  98975. sqlite3_column_table_name16,
  98976. sqlite3_column_text,
  98977. sqlite3_column_text16,
  98978. sqlite3_column_type,
  98979. sqlite3_column_value,
  98980. sqlite3_commit_hook,
  98981. sqlite3_complete,
  98982. sqlite3_complete16,
  98983. sqlite3_create_collation,
  98984. sqlite3_create_collation16,
  98985. sqlite3_create_function,
  98986. sqlite3_create_function16,
  98987. sqlite3_create_module,
  98988. sqlite3_data_count,
  98989. sqlite3_db_handle,
  98990. sqlite3_declare_vtab,
  98991. sqlite3_enable_shared_cache,
  98992. sqlite3_errcode,
  98993. sqlite3_errmsg,
  98994. sqlite3_errmsg16,
  98995. sqlite3_exec,
  98996. #ifndef SQLITE_OMIT_DEPRECATED
  98997. sqlite3_expired,
  98998. #else
  98999. 0,
  99000. #endif
  99001. sqlite3_finalize,
  99002. sqlite3_free,
  99003. sqlite3_free_table,
  99004. sqlite3_get_autocommit,
  99005. sqlite3_get_auxdata,
  99006. sqlite3_get_table,
  99007. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  99008. sqlite3_interrupt,
  99009. sqlite3_last_insert_rowid,
  99010. sqlite3_libversion,
  99011. sqlite3_libversion_number,
  99012. sqlite3_malloc,
  99013. sqlite3_mprintf,
  99014. sqlite3_open,
  99015. sqlite3_open16,
  99016. sqlite3_prepare,
  99017. sqlite3_prepare16,
  99018. sqlite3_profile,
  99019. sqlite3_progress_handler,
  99020. sqlite3_realloc,
  99021. sqlite3_reset,
  99022. sqlite3_result_blob,
  99023. sqlite3_result_double,
  99024. sqlite3_result_error,
  99025. sqlite3_result_error16,
  99026. sqlite3_result_int,
  99027. sqlite3_result_int64,
  99028. sqlite3_result_null,
  99029. sqlite3_result_text,
  99030. sqlite3_result_text16,
  99031. sqlite3_result_text16be,
  99032. sqlite3_result_text16le,
  99033. sqlite3_result_value,
  99034. sqlite3_rollback_hook,
  99035. sqlite3_set_authorizer,
  99036. sqlite3_set_auxdata,
  99037. sqlite3_snprintf,
  99038. sqlite3_step,
  99039. sqlite3_table_column_metadata,
  99040. #ifndef SQLITE_OMIT_DEPRECATED
  99041. sqlite3_thread_cleanup,
  99042. #else
  99043. 0,
  99044. #endif
  99045. sqlite3_total_changes,
  99046. sqlite3_trace,
  99047. #ifndef SQLITE_OMIT_DEPRECATED
  99048. sqlite3_transfer_bindings,
  99049. #else
  99050. 0,
  99051. #endif
  99052. sqlite3_update_hook,
  99053. sqlite3_user_data,
  99054. sqlite3_value_blob,
  99055. sqlite3_value_bytes,
  99056. sqlite3_value_bytes16,
  99057. sqlite3_value_double,
  99058. sqlite3_value_int,
  99059. sqlite3_value_int64,
  99060. sqlite3_value_numeric_type,
  99061. sqlite3_value_text,
  99062. sqlite3_value_text16,
  99063. sqlite3_value_text16be,
  99064. sqlite3_value_text16le,
  99065. sqlite3_value_type,
  99066. sqlite3_vmprintf,
  99067. /*
  99068. ** The original API set ends here. All extensions can call any
  99069. ** of the APIs above provided that the pointer is not NULL. But
  99070. ** before calling APIs that follow, extension should check the
  99071. ** sqlite3_libversion_number() to make sure they are dealing with
  99072. ** a library that is new enough to support that API.
  99073. *************************************************************************
  99074. */
  99075. sqlite3_overload_function,
  99076. /*
  99077. ** Added after 3.3.13
  99078. */
  99079. sqlite3_prepare_v2,
  99080. sqlite3_prepare16_v2,
  99081. sqlite3_clear_bindings,
  99082. /*
  99083. ** Added for 3.4.1
  99084. */
  99085. sqlite3_create_module_v2,
  99086. /*
  99087. ** Added for 3.5.0
  99088. */
  99089. sqlite3_bind_zeroblob,
  99090. sqlite3_blob_bytes,
  99091. sqlite3_blob_close,
  99092. sqlite3_blob_open,
  99093. sqlite3_blob_read,
  99094. sqlite3_blob_write,
  99095. sqlite3_create_collation_v2,
  99096. sqlite3_file_control,
  99097. sqlite3_memory_highwater,
  99098. sqlite3_memory_used,
  99099. #ifdef SQLITE_MUTEX_OMIT
  99100. 0,
  99101. 0,
  99102. 0,
  99103. 0,
  99104. 0,
  99105. #else
  99106. sqlite3_mutex_alloc,
  99107. sqlite3_mutex_enter,
  99108. sqlite3_mutex_free,
  99109. sqlite3_mutex_leave,
  99110. sqlite3_mutex_try,
  99111. #endif
  99112. sqlite3_open_v2,
  99113. sqlite3_release_memory,
  99114. sqlite3_result_error_nomem,
  99115. sqlite3_result_error_toobig,
  99116. sqlite3_sleep,
  99117. sqlite3_soft_heap_limit,
  99118. sqlite3_vfs_find,
  99119. sqlite3_vfs_register,
  99120. sqlite3_vfs_unregister,
  99121. /*
  99122. ** Added for 3.5.8
  99123. */
  99124. sqlite3_threadsafe,
  99125. sqlite3_result_zeroblob,
  99126. sqlite3_result_error_code,
  99127. sqlite3_test_control,
  99128. sqlite3_randomness,
  99129. sqlite3_context_db_handle,
  99130. /*
  99131. ** Added for 3.6.0
  99132. */
  99133. sqlite3_extended_result_codes,
  99134. sqlite3_limit,
  99135. sqlite3_next_stmt,
  99136. sqlite3_sql,
  99137. sqlite3_status,
  99138. /*
  99139. ** Added for 3.7.4
  99140. */
  99141. sqlite3_backup_finish,
  99142. sqlite3_backup_init,
  99143. sqlite3_backup_pagecount,
  99144. sqlite3_backup_remaining,
  99145. sqlite3_backup_step,
  99146. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  99147. sqlite3_compileoption_get,
  99148. sqlite3_compileoption_used,
  99149. #else
  99150. 0,
  99151. 0,
  99152. #endif
  99153. sqlite3_create_function_v2,
  99154. sqlite3_db_config,
  99155. sqlite3_db_mutex,
  99156. sqlite3_db_status,
  99157. sqlite3_extended_errcode,
  99158. sqlite3_log,
  99159. sqlite3_soft_heap_limit64,
  99160. sqlite3_sourceid,
  99161. sqlite3_stmt_status,
  99162. sqlite3_strnicmp,
  99163. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  99164. sqlite3_unlock_notify,
  99165. #else
  99166. 0,
  99167. #endif
  99168. #ifndef SQLITE_OMIT_WAL
  99169. sqlite3_wal_autocheckpoint,
  99170. sqlite3_wal_checkpoint,
  99171. sqlite3_wal_hook,
  99172. #else
  99173. 0,
  99174. 0,
  99175. 0,
  99176. #endif
  99177. sqlite3_blob_reopen,
  99178. sqlite3_vtab_config,
  99179. sqlite3_vtab_on_conflict,
  99180. sqlite3_close_v2,
  99181. sqlite3_db_filename,
  99182. sqlite3_db_readonly,
  99183. sqlite3_db_release_memory,
  99184. sqlite3_errstr,
  99185. sqlite3_stmt_busy,
  99186. sqlite3_stmt_readonly,
  99187. sqlite3_stricmp,
  99188. sqlite3_uri_boolean,
  99189. sqlite3_uri_int64,
  99190. sqlite3_uri_parameter,
  99191. sqlite3_vsnprintf,
  99192. sqlite3_wal_checkpoint_v2,
  99193. /* Version 3.8.7 and later */
  99194. sqlite3_auto_extension,
  99195. sqlite3_bind_blob64,
  99196. sqlite3_bind_text64,
  99197. sqlite3_cancel_auto_extension,
  99198. sqlite3_load_extension,
  99199. sqlite3_malloc64,
  99200. sqlite3_msize,
  99201. sqlite3_realloc64,
  99202. sqlite3_reset_auto_extension,
  99203. sqlite3_result_blob64,
  99204. sqlite3_result_text64,
  99205. sqlite3_strglob,
  99206. /* Version 3.8.11 and later */
  99207. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  99208. sqlite3_value_free,
  99209. sqlite3_result_zeroblob64,
  99210. sqlite3_bind_zeroblob64,
  99211. /* Version 3.9.0 and later */
  99212. sqlite3_value_subtype,
  99213. sqlite3_result_subtype,
  99214. /* Version 3.10.0 and later */
  99215. sqlite3_status64,
  99216. sqlite3_strlike,
  99217. sqlite3_db_cacheflush
  99218. };
  99219. /*
  99220. ** Attempt to load an SQLite extension library contained in the file
  99221. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  99222. ** default entry point name (sqlite3_extension_init) is used. Use
  99223. ** of the default name is recommended.
  99224. **
  99225. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  99226. **
  99227. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  99228. ** error message text. The calling function should free this memory
  99229. ** by calling sqlite3DbFree(db, ).
  99230. */
  99231. static int sqlite3LoadExtension(
  99232. sqlite3 *db, /* Load the extension into this database connection */
  99233. const char *zFile, /* Name of the shared library containing extension */
  99234. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  99235. char **pzErrMsg /* Put error message here if not 0 */
  99236. ){
  99237. sqlite3_vfs *pVfs = db->pVfs;
  99238. void *handle;
  99239. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  99240. char *zErrmsg = 0;
  99241. const char *zEntry;
  99242. char *zAltEntry = 0;
  99243. void **aHandle;
  99244. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  99245. int ii;
  99246. /* Shared library endings to try if zFile cannot be loaded as written */
  99247. static const char *azEndings[] = {
  99248. #if SQLITE_OS_WIN
  99249. "dll"
  99250. #elif defined(__APPLE__)
  99251. "dylib"
  99252. #else
  99253. "so"
  99254. #endif
  99255. };
  99256. if( pzErrMsg ) *pzErrMsg = 0;
  99257. /* Ticket #1863. To avoid a creating security problems for older
  99258. ** applications that relink against newer versions of SQLite, the
  99259. ** ability to run load_extension is turned off by default. One
  99260. ** must call sqlite3_enable_load_extension() to turn on extension
  99261. ** loading. Otherwise you get the following error.
  99262. */
  99263. if( (db->flags & SQLITE_LoadExtension)==0 ){
  99264. if( pzErrMsg ){
  99265. *pzErrMsg = sqlite3_mprintf("not authorized");
  99266. }
  99267. return SQLITE_ERROR;
  99268. }
  99269. zEntry = zProc ? zProc : "sqlite3_extension_init";
  99270. handle = sqlite3OsDlOpen(pVfs, zFile);
  99271. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  99272. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  99273. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  99274. if( zAltFile==0 ) return SQLITE_NOMEM;
  99275. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  99276. sqlite3_free(zAltFile);
  99277. }
  99278. #endif
  99279. if( handle==0 ){
  99280. if( pzErrMsg ){
  99281. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  99282. if( zErrmsg ){
  99283. sqlite3_snprintf(nMsg, zErrmsg,
  99284. "unable to open shared library [%s]", zFile);
  99285. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  99286. }
  99287. }
  99288. return SQLITE_ERROR;
  99289. }
  99290. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  99291. sqlite3OsDlSym(pVfs, handle, zEntry);
  99292. /* If no entry point was specified and the default legacy
  99293. ** entry point name "sqlite3_extension_init" was not found, then
  99294. ** construct an entry point name "sqlite3_X_init" where the X is
  99295. ** replaced by the lowercase value of every ASCII alphabetic
  99296. ** character in the filename after the last "/" upto the first ".",
  99297. ** and eliding the first three characters if they are "lib".
  99298. ** Examples:
  99299. **
  99300. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  99301. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  99302. */
  99303. if( xInit==0 && zProc==0 ){
  99304. int iFile, iEntry, c;
  99305. int ncFile = sqlite3Strlen30(zFile);
  99306. zAltEntry = sqlite3_malloc64(ncFile+30);
  99307. if( zAltEntry==0 ){
  99308. sqlite3OsDlClose(pVfs, handle);
  99309. return SQLITE_NOMEM;
  99310. }
  99311. memcpy(zAltEntry, "sqlite3_", 8);
  99312. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  99313. iFile++;
  99314. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  99315. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  99316. if( sqlite3Isalpha(c) ){
  99317. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  99318. }
  99319. }
  99320. memcpy(zAltEntry+iEntry, "_init", 6);
  99321. zEntry = zAltEntry;
  99322. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  99323. sqlite3OsDlSym(pVfs, handle, zEntry);
  99324. }
  99325. if( xInit==0 ){
  99326. if( pzErrMsg ){
  99327. nMsg += sqlite3Strlen30(zEntry);
  99328. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  99329. if( zErrmsg ){
  99330. sqlite3_snprintf(nMsg, zErrmsg,
  99331. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  99332. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  99333. }
  99334. }
  99335. sqlite3OsDlClose(pVfs, handle);
  99336. sqlite3_free(zAltEntry);
  99337. return SQLITE_ERROR;
  99338. }
  99339. sqlite3_free(zAltEntry);
  99340. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  99341. if( pzErrMsg ){
  99342. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  99343. }
  99344. sqlite3_free(zErrmsg);
  99345. sqlite3OsDlClose(pVfs, handle);
  99346. return SQLITE_ERROR;
  99347. }
  99348. /* Append the new shared library handle to the db->aExtension array. */
  99349. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  99350. if( aHandle==0 ){
  99351. return SQLITE_NOMEM;
  99352. }
  99353. if( db->nExtension>0 ){
  99354. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  99355. }
  99356. sqlite3DbFree(db, db->aExtension);
  99357. db->aExtension = aHandle;
  99358. db->aExtension[db->nExtension++] = handle;
  99359. return SQLITE_OK;
  99360. }
  99361. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  99362. sqlite3 *db, /* Load the extension into this database connection */
  99363. const char *zFile, /* Name of the shared library containing extension */
  99364. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  99365. char **pzErrMsg /* Put error message here if not 0 */
  99366. ){
  99367. int rc;
  99368. sqlite3_mutex_enter(db->mutex);
  99369. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  99370. rc = sqlite3ApiExit(db, rc);
  99371. sqlite3_mutex_leave(db->mutex);
  99372. return rc;
  99373. }
  99374. /*
  99375. ** Call this routine when the database connection is closing in order
  99376. ** to clean up loaded extensions
  99377. */
  99378. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  99379. int i;
  99380. assert( sqlite3_mutex_held(db->mutex) );
  99381. for(i=0; i<db->nExtension; i++){
  99382. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  99383. }
  99384. sqlite3DbFree(db, db->aExtension);
  99385. }
  99386. /*
  99387. ** Enable or disable extension loading. Extension loading is disabled by
  99388. ** default so as not to open security holes in older applications.
  99389. */
  99390. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  99391. sqlite3_mutex_enter(db->mutex);
  99392. if( onoff ){
  99393. db->flags |= SQLITE_LoadExtension;
  99394. }else{
  99395. db->flags &= ~SQLITE_LoadExtension;
  99396. }
  99397. sqlite3_mutex_leave(db->mutex);
  99398. return SQLITE_OK;
  99399. }
  99400. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  99401. /*
  99402. ** The auto-extension code added regardless of whether or not extension
  99403. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  99404. ** code if regular extension loading is not available. This is that
  99405. ** dummy pointer.
  99406. */
  99407. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  99408. static const sqlite3_api_routines sqlite3Apis = { 0 };
  99409. #endif
  99410. /*
  99411. ** The following object holds the list of automatically loaded
  99412. ** extensions.
  99413. **
  99414. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  99415. ** mutex must be held while accessing this list.
  99416. */
  99417. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  99418. static SQLITE_WSD struct sqlite3AutoExtList {
  99419. u32 nExt; /* Number of entries in aExt[] */
  99420. void (**aExt)(void); /* Pointers to the extension init functions */
  99421. } sqlite3Autoext = { 0, 0 };
  99422. /* The "wsdAutoext" macro will resolve to the autoextension
  99423. ** state vector. If writable static data is unsupported on the target,
  99424. ** we have to locate the state vector at run-time. In the more common
  99425. ** case where writable static data is supported, wsdStat can refer directly
  99426. ** to the "sqlite3Autoext" state vector declared above.
  99427. */
  99428. #ifdef SQLITE_OMIT_WSD
  99429. # define wsdAutoextInit \
  99430. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  99431. # define wsdAutoext x[0]
  99432. #else
  99433. # define wsdAutoextInit
  99434. # define wsdAutoext sqlite3Autoext
  99435. #endif
  99436. /*
  99437. ** Register a statically linked extension that is automatically
  99438. ** loaded by every new database connection.
  99439. */
  99440. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
  99441. int rc = SQLITE_OK;
  99442. #ifndef SQLITE_OMIT_AUTOINIT
  99443. rc = sqlite3_initialize();
  99444. if( rc ){
  99445. return rc;
  99446. }else
  99447. #endif
  99448. {
  99449. u32 i;
  99450. #if SQLITE_THREADSAFE
  99451. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  99452. #endif
  99453. wsdAutoextInit;
  99454. sqlite3_mutex_enter(mutex);
  99455. for(i=0; i<wsdAutoext.nExt; i++){
  99456. if( wsdAutoext.aExt[i]==xInit ) break;
  99457. }
  99458. if( i==wsdAutoext.nExt ){
  99459. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  99460. void (**aNew)(void);
  99461. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  99462. if( aNew==0 ){
  99463. rc = SQLITE_NOMEM;
  99464. }else{
  99465. wsdAutoext.aExt = aNew;
  99466. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  99467. wsdAutoext.nExt++;
  99468. }
  99469. }
  99470. sqlite3_mutex_leave(mutex);
  99471. assert( (rc&0xff)==rc );
  99472. return rc;
  99473. }
  99474. }
  99475. /*
  99476. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  99477. ** set of routines that is invoked for each new database connection, if it
  99478. ** is currently on the list. If xInit is not on the list, then this
  99479. ** routine is a no-op.
  99480. **
  99481. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  99482. ** was not on the list.
  99483. */
  99484. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
  99485. #if SQLITE_THREADSAFE
  99486. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  99487. #endif
  99488. int i;
  99489. int n = 0;
  99490. wsdAutoextInit;
  99491. sqlite3_mutex_enter(mutex);
  99492. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  99493. if( wsdAutoext.aExt[i]==xInit ){
  99494. wsdAutoext.nExt--;
  99495. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  99496. n++;
  99497. break;
  99498. }
  99499. }
  99500. sqlite3_mutex_leave(mutex);
  99501. return n;
  99502. }
  99503. /*
  99504. ** Reset the automatic extension loading mechanism.
  99505. */
  99506. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
  99507. #ifndef SQLITE_OMIT_AUTOINIT
  99508. if( sqlite3_initialize()==SQLITE_OK )
  99509. #endif
  99510. {
  99511. #if SQLITE_THREADSAFE
  99512. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  99513. #endif
  99514. wsdAutoextInit;
  99515. sqlite3_mutex_enter(mutex);
  99516. sqlite3_free(wsdAutoext.aExt);
  99517. wsdAutoext.aExt = 0;
  99518. wsdAutoext.nExt = 0;
  99519. sqlite3_mutex_leave(mutex);
  99520. }
  99521. }
  99522. /*
  99523. ** Load all automatic extensions.
  99524. **
  99525. ** If anything goes wrong, set an error in the database connection.
  99526. */
  99527. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  99528. u32 i;
  99529. int go = 1;
  99530. int rc;
  99531. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  99532. wsdAutoextInit;
  99533. if( wsdAutoext.nExt==0 ){
  99534. /* Common case: early out without every having to acquire a mutex */
  99535. return;
  99536. }
  99537. for(i=0; go; i++){
  99538. char *zErrmsg;
  99539. #if SQLITE_THREADSAFE
  99540. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  99541. #endif
  99542. sqlite3_mutex_enter(mutex);
  99543. if( i>=wsdAutoext.nExt ){
  99544. xInit = 0;
  99545. go = 0;
  99546. }else{
  99547. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  99548. wsdAutoext.aExt[i];
  99549. }
  99550. sqlite3_mutex_leave(mutex);
  99551. zErrmsg = 0;
  99552. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  99553. sqlite3ErrorWithMsg(db, rc,
  99554. "automatic extension loading failed: %s", zErrmsg);
  99555. go = 0;
  99556. }
  99557. sqlite3_free(zErrmsg);
  99558. }
  99559. }
  99560. /************** End of loadext.c *********************************************/
  99561. /************** Begin file pragma.c ******************************************/
  99562. /*
  99563. ** 2003 April 6
  99564. **
  99565. ** The author disclaims copyright to this source code. In place of
  99566. ** a legal notice, here is a blessing:
  99567. **
  99568. ** May you do good and not evil.
  99569. ** May you find forgiveness for yourself and forgive others.
  99570. ** May you share freely, never taking more than you give.
  99571. **
  99572. *************************************************************************
  99573. ** This file contains code used to implement the PRAGMA command.
  99574. */
  99575. /* #include "sqliteInt.h" */
  99576. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  99577. # if defined(__APPLE__)
  99578. # define SQLITE_ENABLE_LOCKING_STYLE 1
  99579. # else
  99580. # define SQLITE_ENABLE_LOCKING_STYLE 0
  99581. # endif
  99582. #endif
  99583. /***************************************************************************
  99584. ** The "pragma.h" include file is an automatically generated file that
  99585. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  99586. ** object. This ensures that the aPragmaName[] table is arranged in
  99587. ** lexicographical order to facility a binary search of the pragma name.
  99588. ** Do not edit pragma.h directly. Edit and rerun the script in at
  99589. ** ../tool/mkpragmatab.tcl. */
  99590. /************** Include pragma.h in the middle of pragma.c *******************/
  99591. /************** Begin file pragma.h ******************************************/
  99592. /* DO NOT EDIT!
  99593. ** This file is automatically generated by the script at
  99594. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  99595. ** that script and rerun it.
  99596. */
  99597. #define PragTyp_HEADER_VALUE 0
  99598. #define PragTyp_AUTO_VACUUM 1
  99599. #define PragTyp_FLAG 2
  99600. #define PragTyp_BUSY_TIMEOUT 3
  99601. #define PragTyp_CACHE_SIZE 4
  99602. #define PragTyp_CACHE_SPILL 5
  99603. #define PragTyp_CASE_SENSITIVE_LIKE 6
  99604. #define PragTyp_COLLATION_LIST 7
  99605. #define PragTyp_COMPILE_OPTIONS 8
  99606. #define PragTyp_DATA_STORE_DIRECTORY 9
  99607. #define PragTyp_DATABASE_LIST 10
  99608. #define PragTyp_DEFAULT_CACHE_SIZE 11
  99609. #define PragTyp_ENCODING 12
  99610. #define PragTyp_FOREIGN_KEY_CHECK 13
  99611. #define PragTyp_FOREIGN_KEY_LIST 14
  99612. #define PragTyp_INCREMENTAL_VACUUM 15
  99613. #define PragTyp_INDEX_INFO 16
  99614. #define PragTyp_INDEX_LIST 17
  99615. #define PragTyp_INTEGRITY_CHECK 18
  99616. #define PragTyp_JOURNAL_MODE 19
  99617. #define PragTyp_JOURNAL_SIZE_LIMIT 20
  99618. #define PragTyp_LOCK_PROXY_FILE 21
  99619. #define PragTyp_LOCKING_MODE 22
  99620. #define PragTyp_PAGE_COUNT 23
  99621. #define PragTyp_MMAP_SIZE 24
  99622. #define PragTyp_PAGE_SIZE 25
  99623. #define PragTyp_SECURE_DELETE 26
  99624. #define PragTyp_SHRINK_MEMORY 27
  99625. #define PragTyp_SOFT_HEAP_LIMIT 28
  99626. #define PragTyp_STATS 29
  99627. #define PragTyp_SYNCHRONOUS 30
  99628. #define PragTyp_TABLE_INFO 31
  99629. #define PragTyp_TEMP_STORE 32
  99630. #define PragTyp_TEMP_STORE_DIRECTORY 33
  99631. #define PragTyp_THREADS 34
  99632. #define PragTyp_WAL_AUTOCHECKPOINT 35
  99633. #define PragTyp_WAL_CHECKPOINT 36
  99634. #define PragTyp_ACTIVATE_EXTENSIONS 37
  99635. #define PragTyp_HEXKEY 38
  99636. #define PragTyp_KEY 39
  99637. #define PragTyp_REKEY 40
  99638. #define PragTyp_LOCK_STATUS 41
  99639. #define PragTyp_PARSER_TRACE 42
  99640. #define PragFlag_NeedSchema 0x01
  99641. #define PragFlag_ReadOnly 0x02
  99642. static const struct sPragmaNames {
  99643. const char *const zName; /* Name of pragma */
  99644. u8 ePragTyp; /* PragTyp_XXX value */
  99645. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  99646. u32 iArg; /* Extra argument */
  99647. } aPragmaNames[] = {
  99648. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  99649. { /* zName: */ "activate_extensions",
  99650. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  99651. /* ePragFlag: */ 0,
  99652. /* iArg: */ 0 },
  99653. #endif
  99654. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  99655. { /* zName: */ "application_id",
  99656. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  99657. /* ePragFlag: */ 0,
  99658. /* iArg: */ BTREE_APPLICATION_ID },
  99659. #endif
  99660. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  99661. { /* zName: */ "auto_vacuum",
  99662. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  99663. /* ePragFlag: */ PragFlag_NeedSchema,
  99664. /* iArg: */ 0 },
  99665. #endif
  99666. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99667. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  99668. { /* zName: */ "automatic_index",
  99669. /* ePragTyp: */ PragTyp_FLAG,
  99670. /* ePragFlag: */ 0,
  99671. /* iArg: */ SQLITE_AutoIndex },
  99672. #endif
  99673. #endif
  99674. { /* zName: */ "busy_timeout",
  99675. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  99676. /* ePragFlag: */ 0,
  99677. /* iArg: */ 0 },
  99678. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99679. { /* zName: */ "cache_size",
  99680. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  99681. /* ePragFlag: */ PragFlag_NeedSchema,
  99682. /* iArg: */ 0 },
  99683. #endif
  99684. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99685. { /* zName: */ "cache_spill",
  99686. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  99687. /* ePragFlag: */ 0,
  99688. /* iArg: */ 0 },
  99689. #endif
  99690. { /* zName: */ "case_sensitive_like",
  99691. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  99692. /* ePragFlag: */ 0,
  99693. /* iArg: */ 0 },
  99694. { /* zName: */ "cell_size_check",
  99695. /* ePragTyp: */ PragTyp_FLAG,
  99696. /* ePragFlag: */ 0,
  99697. /* iArg: */ SQLITE_CellSizeCk },
  99698. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99699. { /* zName: */ "checkpoint_fullfsync",
  99700. /* ePragTyp: */ PragTyp_FLAG,
  99701. /* ePragFlag: */ 0,
  99702. /* iArg: */ SQLITE_CkptFullFSync },
  99703. #endif
  99704. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  99705. { /* zName: */ "collation_list",
  99706. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  99707. /* ePragFlag: */ 0,
  99708. /* iArg: */ 0 },
  99709. #endif
  99710. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  99711. { /* zName: */ "compile_options",
  99712. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  99713. /* ePragFlag: */ 0,
  99714. /* iArg: */ 0 },
  99715. #endif
  99716. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99717. { /* zName: */ "count_changes",
  99718. /* ePragTyp: */ PragTyp_FLAG,
  99719. /* ePragFlag: */ 0,
  99720. /* iArg: */ SQLITE_CountRows },
  99721. #endif
  99722. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  99723. { /* zName: */ "data_store_directory",
  99724. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  99725. /* ePragFlag: */ 0,
  99726. /* iArg: */ 0 },
  99727. #endif
  99728. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  99729. { /* zName: */ "data_version",
  99730. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  99731. /* ePragFlag: */ PragFlag_ReadOnly,
  99732. /* iArg: */ BTREE_DATA_VERSION },
  99733. #endif
  99734. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  99735. { /* zName: */ "database_list",
  99736. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  99737. /* ePragFlag: */ PragFlag_NeedSchema,
  99738. /* iArg: */ 0 },
  99739. #endif
  99740. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  99741. { /* zName: */ "default_cache_size",
  99742. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  99743. /* ePragFlag: */ PragFlag_NeedSchema,
  99744. /* iArg: */ 0 },
  99745. #endif
  99746. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99747. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  99748. { /* zName: */ "defer_foreign_keys",
  99749. /* ePragTyp: */ PragTyp_FLAG,
  99750. /* ePragFlag: */ 0,
  99751. /* iArg: */ SQLITE_DeferFKs },
  99752. #endif
  99753. #endif
  99754. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99755. { /* zName: */ "empty_result_callbacks",
  99756. /* ePragTyp: */ PragTyp_FLAG,
  99757. /* ePragFlag: */ 0,
  99758. /* iArg: */ SQLITE_NullCallback },
  99759. #endif
  99760. #if !defined(SQLITE_OMIT_UTF16)
  99761. { /* zName: */ "encoding",
  99762. /* ePragTyp: */ PragTyp_ENCODING,
  99763. /* ePragFlag: */ 0,
  99764. /* iArg: */ 0 },
  99765. #endif
  99766. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  99767. { /* zName: */ "foreign_key_check",
  99768. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  99769. /* ePragFlag: */ PragFlag_NeedSchema,
  99770. /* iArg: */ 0 },
  99771. #endif
  99772. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  99773. { /* zName: */ "foreign_key_list",
  99774. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  99775. /* ePragFlag: */ PragFlag_NeedSchema,
  99776. /* iArg: */ 0 },
  99777. #endif
  99778. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99779. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  99780. { /* zName: */ "foreign_keys",
  99781. /* ePragTyp: */ PragTyp_FLAG,
  99782. /* ePragFlag: */ 0,
  99783. /* iArg: */ SQLITE_ForeignKeys },
  99784. #endif
  99785. #endif
  99786. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  99787. { /* zName: */ "freelist_count",
  99788. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  99789. /* ePragFlag: */ PragFlag_ReadOnly,
  99790. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  99791. #endif
  99792. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99793. { /* zName: */ "full_column_names",
  99794. /* ePragTyp: */ PragTyp_FLAG,
  99795. /* ePragFlag: */ 0,
  99796. /* iArg: */ SQLITE_FullColNames },
  99797. { /* zName: */ "fullfsync",
  99798. /* ePragTyp: */ PragTyp_FLAG,
  99799. /* ePragFlag: */ 0,
  99800. /* iArg: */ SQLITE_FullFSync },
  99801. #endif
  99802. #if defined(SQLITE_HAS_CODEC)
  99803. { /* zName: */ "hexkey",
  99804. /* ePragTyp: */ PragTyp_HEXKEY,
  99805. /* ePragFlag: */ 0,
  99806. /* iArg: */ 0 },
  99807. { /* zName: */ "hexrekey",
  99808. /* ePragTyp: */ PragTyp_HEXKEY,
  99809. /* ePragFlag: */ 0,
  99810. /* iArg: */ 0 },
  99811. #endif
  99812. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99813. #if !defined(SQLITE_OMIT_CHECK)
  99814. { /* zName: */ "ignore_check_constraints",
  99815. /* ePragTyp: */ PragTyp_FLAG,
  99816. /* ePragFlag: */ 0,
  99817. /* iArg: */ SQLITE_IgnoreChecks },
  99818. #endif
  99819. #endif
  99820. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  99821. { /* zName: */ "incremental_vacuum",
  99822. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  99823. /* ePragFlag: */ PragFlag_NeedSchema,
  99824. /* iArg: */ 0 },
  99825. #endif
  99826. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  99827. { /* zName: */ "index_info",
  99828. /* ePragTyp: */ PragTyp_INDEX_INFO,
  99829. /* ePragFlag: */ PragFlag_NeedSchema,
  99830. /* iArg: */ 0 },
  99831. { /* zName: */ "index_list",
  99832. /* ePragTyp: */ PragTyp_INDEX_LIST,
  99833. /* ePragFlag: */ PragFlag_NeedSchema,
  99834. /* iArg: */ 0 },
  99835. { /* zName: */ "index_xinfo",
  99836. /* ePragTyp: */ PragTyp_INDEX_INFO,
  99837. /* ePragFlag: */ PragFlag_NeedSchema,
  99838. /* iArg: */ 1 },
  99839. #endif
  99840. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  99841. { /* zName: */ "integrity_check",
  99842. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  99843. /* ePragFlag: */ PragFlag_NeedSchema,
  99844. /* iArg: */ 0 },
  99845. #endif
  99846. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99847. { /* zName: */ "journal_mode",
  99848. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  99849. /* ePragFlag: */ PragFlag_NeedSchema,
  99850. /* iArg: */ 0 },
  99851. { /* zName: */ "journal_size_limit",
  99852. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  99853. /* ePragFlag: */ 0,
  99854. /* iArg: */ 0 },
  99855. #endif
  99856. #if defined(SQLITE_HAS_CODEC)
  99857. { /* zName: */ "key",
  99858. /* ePragTyp: */ PragTyp_KEY,
  99859. /* ePragFlag: */ 0,
  99860. /* iArg: */ 0 },
  99861. #endif
  99862. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99863. { /* zName: */ "legacy_file_format",
  99864. /* ePragTyp: */ PragTyp_FLAG,
  99865. /* ePragFlag: */ 0,
  99866. /* iArg: */ SQLITE_LegacyFileFmt },
  99867. #endif
  99868. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  99869. { /* zName: */ "lock_proxy_file",
  99870. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  99871. /* ePragFlag: */ 0,
  99872. /* iArg: */ 0 },
  99873. #endif
  99874. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  99875. { /* zName: */ "lock_status",
  99876. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  99877. /* ePragFlag: */ 0,
  99878. /* iArg: */ 0 },
  99879. #endif
  99880. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99881. { /* zName: */ "locking_mode",
  99882. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  99883. /* ePragFlag: */ 0,
  99884. /* iArg: */ 0 },
  99885. { /* zName: */ "max_page_count",
  99886. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  99887. /* ePragFlag: */ PragFlag_NeedSchema,
  99888. /* iArg: */ 0 },
  99889. { /* zName: */ "mmap_size",
  99890. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  99891. /* ePragFlag: */ 0,
  99892. /* iArg: */ 0 },
  99893. { /* zName: */ "page_count",
  99894. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  99895. /* ePragFlag: */ PragFlag_NeedSchema,
  99896. /* iArg: */ 0 },
  99897. { /* zName: */ "page_size",
  99898. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  99899. /* ePragFlag: */ 0,
  99900. /* iArg: */ 0 },
  99901. #endif
  99902. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
  99903. { /* zName: */ "parser_trace",
  99904. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  99905. /* ePragFlag: */ 0,
  99906. /* iArg: */ 0 },
  99907. #endif
  99908. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99909. { /* zName: */ "query_only",
  99910. /* ePragTyp: */ PragTyp_FLAG,
  99911. /* ePragFlag: */ 0,
  99912. /* iArg: */ SQLITE_QueryOnly },
  99913. #endif
  99914. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  99915. { /* zName: */ "quick_check",
  99916. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  99917. /* ePragFlag: */ PragFlag_NeedSchema,
  99918. /* iArg: */ 0 },
  99919. #endif
  99920. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99921. { /* zName: */ "read_uncommitted",
  99922. /* ePragTyp: */ PragTyp_FLAG,
  99923. /* ePragFlag: */ 0,
  99924. /* iArg: */ SQLITE_ReadUncommitted },
  99925. { /* zName: */ "recursive_triggers",
  99926. /* ePragTyp: */ PragTyp_FLAG,
  99927. /* ePragFlag: */ 0,
  99928. /* iArg: */ SQLITE_RecTriggers },
  99929. #endif
  99930. #if defined(SQLITE_HAS_CODEC)
  99931. { /* zName: */ "rekey",
  99932. /* ePragTyp: */ PragTyp_REKEY,
  99933. /* ePragFlag: */ 0,
  99934. /* iArg: */ 0 },
  99935. #endif
  99936. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99937. { /* zName: */ "reverse_unordered_selects",
  99938. /* ePragTyp: */ PragTyp_FLAG,
  99939. /* ePragFlag: */ 0,
  99940. /* iArg: */ SQLITE_ReverseOrder },
  99941. #endif
  99942. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  99943. { /* zName: */ "schema_version",
  99944. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  99945. /* ePragFlag: */ 0,
  99946. /* iArg: */ BTREE_SCHEMA_VERSION },
  99947. #endif
  99948. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99949. { /* zName: */ "secure_delete",
  99950. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  99951. /* ePragFlag: */ 0,
  99952. /* iArg: */ 0 },
  99953. #endif
  99954. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99955. { /* zName: */ "short_column_names",
  99956. /* ePragTyp: */ PragTyp_FLAG,
  99957. /* ePragFlag: */ 0,
  99958. /* iArg: */ SQLITE_ShortColNames },
  99959. #endif
  99960. { /* zName: */ "shrink_memory",
  99961. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  99962. /* ePragFlag: */ 0,
  99963. /* iArg: */ 0 },
  99964. { /* zName: */ "soft_heap_limit",
  99965. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  99966. /* ePragFlag: */ 0,
  99967. /* iArg: */ 0 },
  99968. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  99969. #if defined(SQLITE_DEBUG)
  99970. { /* zName: */ "sql_trace",
  99971. /* ePragTyp: */ PragTyp_FLAG,
  99972. /* ePragFlag: */ 0,
  99973. /* iArg: */ SQLITE_SqlTrace },
  99974. #endif
  99975. #endif
  99976. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  99977. { /* zName: */ "stats",
  99978. /* ePragTyp: */ PragTyp_STATS,
  99979. /* ePragFlag: */ PragFlag_NeedSchema,
  99980. /* iArg: */ 0 },
  99981. #endif
  99982. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99983. { /* zName: */ "synchronous",
  99984. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  99985. /* ePragFlag: */ PragFlag_NeedSchema,
  99986. /* iArg: */ 0 },
  99987. #endif
  99988. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  99989. { /* zName: */ "table_info",
  99990. /* ePragTyp: */ PragTyp_TABLE_INFO,
  99991. /* ePragFlag: */ PragFlag_NeedSchema,
  99992. /* iArg: */ 0 },
  99993. #endif
  99994. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  99995. { /* zName: */ "temp_store",
  99996. /* ePragTyp: */ PragTyp_TEMP_STORE,
  99997. /* ePragFlag: */ 0,
  99998. /* iArg: */ 0 },
  99999. { /* zName: */ "temp_store_directory",
  100000. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  100001. /* ePragFlag: */ 0,
  100002. /* iArg: */ 0 },
  100003. #endif
  100004. { /* zName: */ "threads",
  100005. /* ePragTyp: */ PragTyp_THREADS,
  100006. /* ePragFlag: */ 0,
  100007. /* iArg: */ 0 },
  100008. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  100009. { /* zName: */ "user_version",
  100010. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  100011. /* ePragFlag: */ 0,
  100012. /* iArg: */ BTREE_USER_VERSION },
  100013. #endif
  100014. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100015. #if defined(SQLITE_DEBUG)
  100016. { /* zName: */ "vdbe_addoptrace",
  100017. /* ePragTyp: */ PragTyp_FLAG,
  100018. /* ePragFlag: */ 0,
  100019. /* iArg: */ SQLITE_VdbeAddopTrace },
  100020. { /* zName: */ "vdbe_debug",
  100021. /* ePragTyp: */ PragTyp_FLAG,
  100022. /* ePragFlag: */ 0,
  100023. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  100024. { /* zName: */ "vdbe_eqp",
  100025. /* ePragTyp: */ PragTyp_FLAG,
  100026. /* ePragFlag: */ 0,
  100027. /* iArg: */ SQLITE_VdbeEQP },
  100028. { /* zName: */ "vdbe_listing",
  100029. /* ePragTyp: */ PragTyp_FLAG,
  100030. /* ePragFlag: */ 0,
  100031. /* iArg: */ SQLITE_VdbeListing },
  100032. { /* zName: */ "vdbe_trace",
  100033. /* ePragTyp: */ PragTyp_FLAG,
  100034. /* ePragFlag: */ 0,
  100035. /* iArg: */ SQLITE_VdbeTrace },
  100036. #endif
  100037. #endif
  100038. #if !defined(SQLITE_OMIT_WAL)
  100039. { /* zName: */ "wal_autocheckpoint",
  100040. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  100041. /* ePragFlag: */ 0,
  100042. /* iArg: */ 0 },
  100043. { /* zName: */ "wal_checkpoint",
  100044. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  100045. /* ePragFlag: */ PragFlag_NeedSchema,
  100046. /* iArg: */ 0 },
  100047. #endif
  100048. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  100049. { /* zName: */ "writable_schema",
  100050. /* ePragTyp: */ PragTyp_FLAG,
  100051. /* ePragFlag: */ 0,
  100052. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  100053. #endif
  100054. };
  100055. /* Number of pragmas: 60 on by default, 73 total. */
  100056. /************** End of pragma.h **********************************************/
  100057. /************** Continuing where we left off in pragma.c *********************/
  100058. /*
  100059. ** Interpret the given string as a safety level. Return 0 for OFF,
  100060. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  100061. ** unrecognized string argument. The FULL option is disallowed
  100062. ** if the omitFull parameter it 1.
  100063. **
  100064. ** Note that the values returned are one less that the values that
  100065. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  100066. ** to support legacy SQL code. The safety level used to be boolean
  100067. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  100068. */
  100069. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  100070. /* 123456789 123456789 */
  100071. static const char zText[] = "onoffalseyestruefull";
  100072. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  100073. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  100074. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  100075. int i, n;
  100076. if( sqlite3Isdigit(*z) ){
  100077. return (u8)sqlite3Atoi(z);
  100078. }
  100079. n = sqlite3Strlen30(z);
  100080. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  100081. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  100082. return iValue[i];
  100083. }
  100084. }
  100085. return dflt;
  100086. }
  100087. /*
  100088. ** Interpret the given string as a boolean value.
  100089. */
  100090. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  100091. return getSafetyLevel(z,1,dflt)!=0;
  100092. }
  100093. /* The sqlite3GetBoolean() function is used by other modules but the
  100094. ** remainder of this file is specific to PRAGMA processing. So omit
  100095. ** the rest of the file if PRAGMAs are omitted from the build.
  100096. */
  100097. #if !defined(SQLITE_OMIT_PRAGMA)
  100098. /*
  100099. ** Interpret the given string as a locking mode value.
  100100. */
  100101. static int getLockingMode(const char *z){
  100102. if( z ){
  100103. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  100104. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  100105. }
  100106. return PAGER_LOCKINGMODE_QUERY;
  100107. }
  100108. #ifndef SQLITE_OMIT_AUTOVACUUM
  100109. /*
  100110. ** Interpret the given string as an auto-vacuum mode value.
  100111. **
  100112. ** The following strings, "none", "full" and "incremental" are
  100113. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  100114. */
  100115. static int getAutoVacuum(const char *z){
  100116. int i;
  100117. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  100118. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  100119. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  100120. i = sqlite3Atoi(z);
  100121. return (u8)((i>=0&&i<=2)?i:0);
  100122. }
  100123. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  100124. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  100125. /*
  100126. ** Interpret the given string as a temp db location. Return 1 for file
  100127. ** backed temporary databases, 2 for the Red-Black tree in memory database
  100128. ** and 0 to use the compile-time default.
  100129. */
  100130. static int getTempStore(const char *z){
  100131. if( z[0]>='0' && z[0]<='2' ){
  100132. return z[0] - '0';
  100133. }else if( sqlite3StrICmp(z, "file")==0 ){
  100134. return 1;
  100135. }else if( sqlite3StrICmp(z, "memory")==0 ){
  100136. return 2;
  100137. }else{
  100138. return 0;
  100139. }
  100140. }
  100141. #endif /* SQLITE_PAGER_PRAGMAS */
  100142. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  100143. /*
  100144. ** Invalidate temp storage, either when the temp storage is changed
  100145. ** from default, or when 'file' and the temp_store_directory has changed
  100146. */
  100147. static int invalidateTempStorage(Parse *pParse){
  100148. sqlite3 *db = pParse->db;
  100149. if( db->aDb[1].pBt!=0 ){
  100150. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  100151. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  100152. "from within a transaction");
  100153. return SQLITE_ERROR;
  100154. }
  100155. sqlite3BtreeClose(db->aDb[1].pBt);
  100156. db->aDb[1].pBt = 0;
  100157. sqlite3ResetAllSchemasOfConnection(db);
  100158. }
  100159. return SQLITE_OK;
  100160. }
  100161. #endif /* SQLITE_PAGER_PRAGMAS */
  100162. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  100163. /*
  100164. ** If the TEMP database is open, close it and mark the database schema
  100165. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  100166. ** or DEFAULT_TEMP_STORE pragmas.
  100167. */
  100168. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  100169. int ts = getTempStore(zStorageType);
  100170. sqlite3 *db = pParse->db;
  100171. if( db->temp_store==ts ) return SQLITE_OK;
  100172. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  100173. return SQLITE_ERROR;
  100174. }
  100175. db->temp_store = (u8)ts;
  100176. return SQLITE_OK;
  100177. }
  100178. #endif /* SQLITE_PAGER_PRAGMAS */
  100179. /*
  100180. ** Set the names of the first N columns to the values in azCol[]
  100181. */
  100182. static void setAllColumnNames(
  100183. Vdbe *v, /* The query under construction */
  100184. int N, /* Number of columns */
  100185. const char **azCol /* Names of columns */
  100186. ){
  100187. int i;
  100188. sqlite3VdbeSetNumCols(v, N);
  100189. for(i=0; i<N; i++){
  100190. sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
  100191. }
  100192. }
  100193. static void setOneColumnName(Vdbe *v, const char *z){
  100194. setAllColumnNames(v, 1, &z);
  100195. }
  100196. /*
  100197. ** Generate code to return a single integer value.
  100198. */
  100199. static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
  100200. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  100201. setOneColumnName(v, zLabel);
  100202. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  100203. }
  100204. /*
  100205. ** Generate code to return a single text value.
  100206. */
  100207. static void returnSingleText(
  100208. Vdbe *v, /* Prepared statement under construction */
  100209. const char *zLabel, /* Name of the result column */
  100210. const char *zValue /* Value to be returned */
  100211. ){
  100212. if( zValue ){
  100213. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  100214. setOneColumnName(v, zLabel);
  100215. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  100216. }
  100217. }
  100218. /*
  100219. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  100220. ** set these values for all pagers.
  100221. */
  100222. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  100223. static void setAllPagerFlags(sqlite3 *db){
  100224. if( db->autoCommit ){
  100225. Db *pDb = db->aDb;
  100226. int n = db->nDb;
  100227. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  100228. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  100229. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  100230. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  100231. == PAGER_FLAGS_MASK );
  100232. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  100233. while( (n--) > 0 ){
  100234. if( pDb->pBt ){
  100235. sqlite3BtreeSetPagerFlags(pDb->pBt,
  100236. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  100237. }
  100238. pDb++;
  100239. }
  100240. }
  100241. }
  100242. #else
  100243. # define setAllPagerFlags(X) /* no-op */
  100244. #endif
  100245. /*
  100246. ** Return a human-readable name for a constraint resolution action.
  100247. */
  100248. #ifndef SQLITE_OMIT_FOREIGN_KEY
  100249. static const char *actionName(u8 action){
  100250. const char *zName;
  100251. switch( action ){
  100252. case OE_SetNull: zName = "SET NULL"; break;
  100253. case OE_SetDflt: zName = "SET DEFAULT"; break;
  100254. case OE_Cascade: zName = "CASCADE"; break;
  100255. case OE_Restrict: zName = "RESTRICT"; break;
  100256. default: zName = "NO ACTION";
  100257. assert( action==OE_None ); break;
  100258. }
  100259. return zName;
  100260. }
  100261. #endif
  100262. /*
  100263. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  100264. ** defined in pager.h. This function returns the associated lowercase
  100265. ** journal-mode name.
  100266. */
  100267. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  100268. static char * const azModeName[] = {
  100269. "delete", "persist", "off", "truncate", "memory"
  100270. #ifndef SQLITE_OMIT_WAL
  100271. , "wal"
  100272. #endif
  100273. };
  100274. assert( PAGER_JOURNALMODE_DELETE==0 );
  100275. assert( PAGER_JOURNALMODE_PERSIST==1 );
  100276. assert( PAGER_JOURNALMODE_OFF==2 );
  100277. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  100278. assert( PAGER_JOURNALMODE_MEMORY==4 );
  100279. assert( PAGER_JOURNALMODE_WAL==5 );
  100280. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  100281. if( eMode==ArraySize(azModeName) ) return 0;
  100282. return azModeName[eMode];
  100283. }
  100284. /*
  100285. ** Process a pragma statement.
  100286. **
  100287. ** Pragmas are of this form:
  100288. **
  100289. ** PRAGMA [schema.]id [= value]
  100290. **
  100291. ** The identifier might also be a string. The value is a string, and
  100292. ** identifier, or a number. If minusFlag is true, then the value is
  100293. ** a number that was preceded by a minus sign.
  100294. **
  100295. ** If the left side is "database.id" then pId1 is the database name
  100296. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  100297. ** id and pId2 is any empty string.
  100298. */
  100299. SQLITE_PRIVATE void sqlite3Pragma(
  100300. Parse *pParse,
  100301. Token *pId1, /* First part of [schema.]id field */
  100302. Token *pId2, /* Second part of [schema.]id field, or NULL */
  100303. Token *pValue, /* Token for <value>, or NULL */
  100304. int minusFlag /* True if a '-' sign preceded <value> */
  100305. ){
  100306. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  100307. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  100308. const char *zDb = 0; /* The database name */
  100309. Token *pId; /* Pointer to <id> token */
  100310. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  100311. int iDb; /* Database index for <database> */
  100312. int lwr, upr, mid = 0; /* Binary search bounds */
  100313. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  100314. sqlite3 *db = pParse->db; /* The database connection */
  100315. Db *pDb; /* The specific database being pragmaed */
  100316. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  100317. const struct sPragmaNames *pPragma;
  100318. if( v==0 ) return;
  100319. sqlite3VdbeRunOnlyOnce(v);
  100320. pParse->nMem = 2;
  100321. /* Interpret the [schema.] part of the pragma statement. iDb is the
  100322. ** index of the database this pragma is being applied to in db.aDb[]. */
  100323. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  100324. if( iDb<0 ) return;
  100325. pDb = &db->aDb[iDb];
  100326. /* If the temp database has been explicitly named as part of the
  100327. ** pragma, make sure it is open.
  100328. */
  100329. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  100330. return;
  100331. }
  100332. zLeft = sqlite3NameFromToken(db, pId);
  100333. if( !zLeft ) return;
  100334. if( minusFlag ){
  100335. zRight = sqlite3MPrintf(db, "-%T", pValue);
  100336. }else{
  100337. zRight = sqlite3NameFromToken(db, pValue);
  100338. }
  100339. assert( pId2 );
  100340. zDb = pId2->n>0 ? pDb->zName : 0;
  100341. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  100342. goto pragma_out;
  100343. }
  100344. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  100345. ** connection. If it returns SQLITE_OK, then assume that the VFS
  100346. ** handled the pragma and generate a no-op prepared statement.
  100347. **
  100348. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  100349. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  100350. ** object corresponding to the database file to which the pragma
  100351. ** statement refers.
  100352. **
  100353. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  100354. ** file control is an array of pointers to strings (char**) in which the
  100355. ** second element of the array is the name of the pragma and the third
  100356. ** element is the argument to the pragma or NULL if the pragma has no
  100357. ** argument.
  100358. */
  100359. aFcntl[0] = 0;
  100360. aFcntl[1] = zLeft;
  100361. aFcntl[2] = zRight;
  100362. aFcntl[3] = 0;
  100363. db->busyHandler.nBusy = 0;
  100364. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  100365. if( rc==SQLITE_OK ){
  100366. returnSingleText(v, "result", aFcntl[0]);
  100367. sqlite3_free(aFcntl[0]);
  100368. goto pragma_out;
  100369. }
  100370. if( rc!=SQLITE_NOTFOUND ){
  100371. if( aFcntl[0] ){
  100372. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  100373. sqlite3_free(aFcntl[0]);
  100374. }
  100375. pParse->nErr++;
  100376. pParse->rc = rc;
  100377. goto pragma_out;
  100378. }
  100379. /* Locate the pragma in the lookup table */
  100380. lwr = 0;
  100381. upr = ArraySize(aPragmaNames)-1;
  100382. while( lwr<=upr ){
  100383. mid = (lwr+upr)/2;
  100384. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  100385. if( rc==0 ) break;
  100386. if( rc<0 ){
  100387. upr = mid - 1;
  100388. }else{
  100389. lwr = mid + 1;
  100390. }
  100391. }
  100392. if( lwr>upr ) goto pragma_out;
  100393. pPragma = &aPragmaNames[mid];
  100394. /* Make sure the database schema is loaded if the pragma requires that */
  100395. if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
  100396. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  100397. }
  100398. /* Jump to the appropriate pragma handler */
  100399. switch( pPragma->ePragTyp ){
  100400. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  100401. /*
  100402. ** PRAGMA [schema.]default_cache_size
  100403. ** PRAGMA [schema.]default_cache_size=N
  100404. **
  100405. ** The first form reports the current persistent setting for the
  100406. ** page cache size. The value returned is the maximum number of
  100407. ** pages in the page cache. The second form sets both the current
  100408. ** page cache size value and the persistent page cache size value
  100409. ** stored in the database file.
  100410. **
  100411. ** Older versions of SQLite would set the default cache size to a
  100412. ** negative number to indicate synchronous=OFF. These days, synchronous
  100413. ** is always on by default regardless of the sign of the default cache
  100414. ** size. But continue to take the absolute value of the default cache
  100415. ** size of historical compatibility.
  100416. */
  100417. case PragTyp_DEFAULT_CACHE_SIZE: {
  100418. static const int iLn = VDBE_OFFSET_LINENO(2);
  100419. static const VdbeOpList getCacheSize[] = {
  100420. { OP_Transaction, 0, 0, 0}, /* 0 */
  100421. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  100422. { OP_IfPos, 1, 8, 0},
  100423. { OP_Integer, 0, 2, 0},
  100424. { OP_Subtract, 1, 2, 1},
  100425. { OP_IfPos, 1, 8, 0},
  100426. { OP_Integer, 0, 1, 0}, /* 6 */
  100427. { OP_Noop, 0, 0, 0},
  100428. { OP_ResultRow, 1, 1, 0},
  100429. };
  100430. int addr;
  100431. sqlite3VdbeUsesBtree(v, iDb);
  100432. if( !zRight ){
  100433. setOneColumnName(v, "cache_size");
  100434. pParse->nMem += 2;
  100435. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
  100436. sqlite3VdbeChangeP1(v, addr, iDb);
  100437. sqlite3VdbeChangeP1(v, addr+1, iDb);
  100438. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  100439. }else{
  100440. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  100441. sqlite3BeginWriteOperation(pParse, 0, iDb);
  100442. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  100443. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  100444. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100445. pDb->pSchema->cache_size = size;
  100446. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  100447. }
  100448. break;
  100449. }
  100450. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  100451. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  100452. /*
  100453. ** PRAGMA [schema.]page_size
  100454. ** PRAGMA [schema.]page_size=N
  100455. **
  100456. ** The first form reports the current setting for the
  100457. ** database page size in bytes. The second form sets the
  100458. ** database page size value. The value can only be set if
  100459. ** the database has not yet been created.
  100460. */
  100461. case PragTyp_PAGE_SIZE: {
  100462. Btree *pBt = pDb->pBt;
  100463. assert( pBt!=0 );
  100464. if( !zRight ){
  100465. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  100466. returnSingleInt(v, "page_size", size);
  100467. }else{
  100468. /* Malloc may fail when setting the page-size, as there is an internal
  100469. ** buffer that the pager module resizes using sqlite3_realloc().
  100470. */
  100471. db->nextPagesize = sqlite3Atoi(zRight);
  100472. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  100473. db->mallocFailed = 1;
  100474. }
  100475. }
  100476. break;
  100477. }
  100478. /*
  100479. ** PRAGMA [schema.]secure_delete
  100480. ** PRAGMA [schema.]secure_delete=ON/OFF
  100481. **
  100482. ** The first form reports the current setting for the
  100483. ** secure_delete flag. The second form changes the secure_delete
  100484. ** flag setting and reports thenew value.
  100485. */
  100486. case PragTyp_SECURE_DELETE: {
  100487. Btree *pBt = pDb->pBt;
  100488. int b = -1;
  100489. assert( pBt!=0 );
  100490. if( zRight ){
  100491. b = sqlite3GetBoolean(zRight, 0);
  100492. }
  100493. if( pId2->n==0 && b>=0 ){
  100494. int ii;
  100495. for(ii=0; ii<db->nDb; ii++){
  100496. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  100497. }
  100498. }
  100499. b = sqlite3BtreeSecureDelete(pBt, b);
  100500. returnSingleInt(v, "secure_delete", b);
  100501. break;
  100502. }
  100503. /*
  100504. ** PRAGMA [schema.]max_page_count
  100505. ** PRAGMA [schema.]max_page_count=N
  100506. **
  100507. ** The first form reports the current setting for the
  100508. ** maximum number of pages in the database file. The
  100509. ** second form attempts to change this setting. Both
  100510. ** forms return the current setting.
  100511. **
  100512. ** The absolute value of N is used. This is undocumented and might
  100513. ** change. The only purpose is to provide an easy way to test
  100514. ** the sqlite3AbsInt32() function.
  100515. **
  100516. ** PRAGMA [schema.]page_count
  100517. **
  100518. ** Return the number of pages in the specified database.
  100519. */
  100520. case PragTyp_PAGE_COUNT: {
  100521. int iReg;
  100522. sqlite3CodeVerifySchema(pParse, iDb);
  100523. iReg = ++pParse->nMem;
  100524. if( sqlite3Tolower(zLeft[0])=='p' ){
  100525. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  100526. }else{
  100527. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  100528. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  100529. }
  100530. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  100531. sqlite3VdbeSetNumCols(v, 1);
  100532. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  100533. break;
  100534. }
  100535. /*
  100536. ** PRAGMA [schema.]locking_mode
  100537. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  100538. */
  100539. case PragTyp_LOCKING_MODE: {
  100540. const char *zRet = "normal";
  100541. int eMode = getLockingMode(zRight);
  100542. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  100543. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  100544. ** the current default locking mode (which may be different to
  100545. ** the locking-mode of the main database).
  100546. */
  100547. eMode = db->dfltLockMode;
  100548. }else{
  100549. Pager *pPager;
  100550. if( pId2->n==0 ){
  100551. /* This indicates that no database name was specified as part
  100552. ** of the PRAGMA command. In this case the locking-mode must be
  100553. ** set on all attached databases, as well as the main db file.
  100554. **
  100555. ** Also, the sqlite3.dfltLockMode variable is set so that
  100556. ** any subsequently attached databases also use the specified
  100557. ** locking mode.
  100558. */
  100559. int ii;
  100560. assert(pDb==&db->aDb[0]);
  100561. for(ii=2; ii<db->nDb; ii++){
  100562. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  100563. sqlite3PagerLockingMode(pPager, eMode);
  100564. }
  100565. db->dfltLockMode = (u8)eMode;
  100566. }
  100567. pPager = sqlite3BtreePager(pDb->pBt);
  100568. eMode = sqlite3PagerLockingMode(pPager, eMode);
  100569. }
  100570. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  100571. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  100572. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  100573. zRet = "exclusive";
  100574. }
  100575. returnSingleText(v, "locking_mode", zRet);
  100576. break;
  100577. }
  100578. /*
  100579. ** PRAGMA [schema.]journal_mode
  100580. ** PRAGMA [schema.]journal_mode =
  100581. ** (delete|persist|off|truncate|memory|wal|off)
  100582. */
  100583. case PragTyp_JOURNAL_MODE: {
  100584. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  100585. int ii; /* Loop counter */
  100586. setOneColumnName(v, "journal_mode");
  100587. if( zRight==0 ){
  100588. /* If there is no "=MODE" part of the pragma, do a query for the
  100589. ** current mode */
  100590. eMode = PAGER_JOURNALMODE_QUERY;
  100591. }else{
  100592. const char *zMode;
  100593. int n = sqlite3Strlen30(zRight);
  100594. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  100595. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  100596. }
  100597. if( !zMode ){
  100598. /* If the "=MODE" part does not match any known journal mode,
  100599. ** then do a query */
  100600. eMode = PAGER_JOURNALMODE_QUERY;
  100601. }
  100602. }
  100603. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  100604. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  100605. iDb = 0;
  100606. pId2->n = 1;
  100607. }
  100608. for(ii=db->nDb-1; ii>=0; ii--){
  100609. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  100610. sqlite3VdbeUsesBtree(v, ii);
  100611. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  100612. }
  100613. }
  100614. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  100615. break;
  100616. }
  100617. /*
  100618. ** PRAGMA [schema.]journal_size_limit
  100619. ** PRAGMA [schema.]journal_size_limit=N
  100620. **
  100621. ** Get or set the size limit on rollback journal files.
  100622. */
  100623. case PragTyp_JOURNAL_SIZE_LIMIT: {
  100624. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  100625. i64 iLimit = -2;
  100626. if( zRight ){
  100627. sqlite3DecOrHexToI64(zRight, &iLimit);
  100628. if( iLimit<-1 ) iLimit = -1;
  100629. }
  100630. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  100631. returnSingleInt(v, "journal_size_limit", iLimit);
  100632. break;
  100633. }
  100634. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  100635. /*
  100636. ** PRAGMA [schema.]auto_vacuum
  100637. ** PRAGMA [schema.]auto_vacuum=N
  100638. **
  100639. ** Get or set the value of the database 'auto-vacuum' parameter.
  100640. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  100641. */
  100642. #ifndef SQLITE_OMIT_AUTOVACUUM
  100643. case PragTyp_AUTO_VACUUM: {
  100644. Btree *pBt = pDb->pBt;
  100645. assert( pBt!=0 );
  100646. if( !zRight ){
  100647. returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  100648. }else{
  100649. int eAuto = getAutoVacuum(zRight);
  100650. assert( eAuto>=0 && eAuto<=2 );
  100651. db->nextAutovac = (u8)eAuto;
  100652. /* Call SetAutoVacuum() to set initialize the internal auto and
  100653. ** incr-vacuum flags. This is required in case this connection
  100654. ** creates the database file. It is important that it is created
  100655. ** as an auto-vacuum capable db.
  100656. */
  100657. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  100658. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  100659. /* When setting the auto_vacuum mode to either "full" or
  100660. ** "incremental", write the value of meta[6] in the database
  100661. ** file. Before writing to meta[6], check that meta[3] indicates
  100662. ** that this really is an auto-vacuum capable database.
  100663. */
  100664. static const int iLn = VDBE_OFFSET_LINENO(2);
  100665. static const VdbeOpList setMeta6[] = {
  100666. { OP_Transaction, 0, 1, 0}, /* 0 */
  100667. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  100668. { OP_If, 1, 0, 0}, /* 2 */
  100669. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  100670. { OP_Integer, 0, 1, 0}, /* 4 */
  100671. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  100672. };
  100673. int iAddr;
  100674. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  100675. sqlite3VdbeChangeP1(v, iAddr, iDb);
  100676. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  100677. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  100678. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  100679. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  100680. sqlite3VdbeUsesBtree(v, iDb);
  100681. }
  100682. }
  100683. break;
  100684. }
  100685. #endif
  100686. /*
  100687. ** PRAGMA [schema.]incremental_vacuum(N)
  100688. **
  100689. ** Do N steps of incremental vacuuming on a database.
  100690. */
  100691. #ifndef SQLITE_OMIT_AUTOVACUUM
  100692. case PragTyp_INCREMENTAL_VACUUM: {
  100693. int iLimit, addr;
  100694. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  100695. iLimit = 0x7fffffff;
  100696. }
  100697. sqlite3BeginWriteOperation(pParse, 0, iDb);
  100698. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  100699. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  100700. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  100701. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  100702. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  100703. sqlite3VdbeJumpHere(v, addr);
  100704. break;
  100705. }
  100706. #endif
  100707. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  100708. /*
  100709. ** PRAGMA [schema.]cache_size
  100710. ** PRAGMA [schema.]cache_size=N
  100711. **
  100712. ** The first form reports the current local setting for the
  100713. ** page cache size. The second form sets the local
  100714. ** page cache size value. If N is positive then that is the
  100715. ** number of pages in the cache. If N is negative, then the
  100716. ** number of pages is adjusted so that the cache uses -N kibibytes
  100717. ** of memory.
  100718. */
  100719. case PragTyp_CACHE_SIZE: {
  100720. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100721. if( !zRight ){
  100722. returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
  100723. }else{
  100724. int size = sqlite3Atoi(zRight);
  100725. pDb->pSchema->cache_size = size;
  100726. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  100727. }
  100728. break;
  100729. }
  100730. /*
  100731. ** PRAGMA [schema.]cache_spill
  100732. ** PRAGMA cache_spill=BOOLEAN
  100733. ** PRAGMA [schema.]cache_spill=N
  100734. **
  100735. ** The first form reports the current local setting for the
  100736. ** page cache spill size. The second form turns cache spill on
  100737. ** or off. When turnning cache spill on, the size is set to the
  100738. ** current cache_size. The third form sets a spill size that
  100739. ** may be different form the cache size.
  100740. ** If N is positive then that is the
  100741. ** number of pages in the cache. If N is negative, then the
  100742. ** number of pages is adjusted so that the cache uses -N kibibytes
  100743. ** of memory.
  100744. **
  100745. ** If the number of cache_spill pages is less then the number of
  100746. ** cache_size pages, no spilling occurs until the page count exceeds
  100747. ** the number of cache_size pages.
  100748. **
  100749. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  100750. ** not just the schema specified.
  100751. */
  100752. case PragTyp_CACHE_SPILL: {
  100753. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100754. if( !zRight ){
  100755. returnSingleInt(v, "cache_spill",
  100756. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  100757. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  100758. }else{
  100759. int size = 1;
  100760. if( sqlite3GetInt32(zRight, &size) ){
  100761. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  100762. }
  100763. if( sqlite3GetBoolean(zRight, size!=0) ){
  100764. db->flags |= SQLITE_CacheSpill;
  100765. }else{
  100766. db->flags &= ~SQLITE_CacheSpill;
  100767. }
  100768. setAllPagerFlags(db);
  100769. }
  100770. break;
  100771. }
  100772. /*
  100773. ** PRAGMA [schema.]mmap_size(N)
  100774. **
  100775. ** Used to set mapping size limit. The mapping size limit is
  100776. ** used to limit the aggregate size of all memory mapped regions of the
  100777. ** database file. If this parameter is set to zero, then memory mapping
  100778. ** is not used at all. If N is negative, then the default memory map
  100779. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  100780. ** The parameter N is measured in bytes.
  100781. **
  100782. ** This value is advisory. The underlying VFS is free to memory map
  100783. ** as little or as much as it wants. Except, if N is set to 0 then the
  100784. ** upper layers will never invoke the xFetch interfaces to the VFS.
  100785. */
  100786. case PragTyp_MMAP_SIZE: {
  100787. sqlite3_int64 sz;
  100788. #if SQLITE_MAX_MMAP_SIZE>0
  100789. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100790. if( zRight ){
  100791. int ii;
  100792. sqlite3DecOrHexToI64(zRight, &sz);
  100793. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  100794. if( pId2->n==0 ) db->szMmap = sz;
  100795. for(ii=db->nDb-1; ii>=0; ii--){
  100796. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  100797. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  100798. }
  100799. }
  100800. }
  100801. sz = -1;
  100802. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  100803. #else
  100804. sz = 0;
  100805. rc = SQLITE_OK;
  100806. #endif
  100807. if( rc==SQLITE_OK ){
  100808. returnSingleInt(v, "mmap_size", sz);
  100809. }else if( rc!=SQLITE_NOTFOUND ){
  100810. pParse->nErr++;
  100811. pParse->rc = rc;
  100812. }
  100813. break;
  100814. }
  100815. /*
  100816. ** PRAGMA temp_store
  100817. ** PRAGMA temp_store = "default"|"memory"|"file"
  100818. **
  100819. ** Return or set the local value of the temp_store flag. Changing
  100820. ** the local value does not make changes to the disk file and the default
  100821. ** value will be restored the next time the database is opened.
  100822. **
  100823. ** Note that it is possible for the library compile-time options to
  100824. ** override this setting
  100825. */
  100826. case PragTyp_TEMP_STORE: {
  100827. if( !zRight ){
  100828. returnSingleInt(v, "temp_store", db->temp_store);
  100829. }else{
  100830. changeTempStorage(pParse, zRight);
  100831. }
  100832. break;
  100833. }
  100834. /*
  100835. ** PRAGMA temp_store_directory
  100836. ** PRAGMA temp_store_directory = ""|"directory_name"
  100837. **
  100838. ** Return or set the local value of the temp_store_directory flag. Changing
  100839. ** the value sets a specific directory to be used for temporary files.
  100840. ** Setting to a null string reverts to the default temporary directory search.
  100841. ** If temporary directory is changed, then invalidateTempStorage.
  100842. **
  100843. */
  100844. case PragTyp_TEMP_STORE_DIRECTORY: {
  100845. if( !zRight ){
  100846. returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
  100847. }else{
  100848. #ifndef SQLITE_OMIT_WSD
  100849. if( zRight[0] ){
  100850. int res;
  100851. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  100852. if( rc!=SQLITE_OK || res==0 ){
  100853. sqlite3ErrorMsg(pParse, "not a writable directory");
  100854. goto pragma_out;
  100855. }
  100856. }
  100857. if( SQLITE_TEMP_STORE==0
  100858. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  100859. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  100860. ){
  100861. invalidateTempStorage(pParse);
  100862. }
  100863. sqlite3_free(sqlite3_temp_directory);
  100864. if( zRight[0] ){
  100865. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  100866. }else{
  100867. sqlite3_temp_directory = 0;
  100868. }
  100869. #endif /* SQLITE_OMIT_WSD */
  100870. }
  100871. break;
  100872. }
  100873. #if SQLITE_OS_WIN
  100874. /*
  100875. ** PRAGMA data_store_directory
  100876. ** PRAGMA data_store_directory = ""|"directory_name"
  100877. **
  100878. ** Return or set the local value of the data_store_directory flag. Changing
  100879. ** the value sets a specific directory to be used for database files that
  100880. ** were specified with a relative pathname. Setting to a null string reverts
  100881. ** to the default database directory, which for database files specified with
  100882. ** a relative path will probably be based on the current directory for the
  100883. ** process. Database file specified with an absolute path are not impacted
  100884. ** by this setting, regardless of its value.
  100885. **
  100886. */
  100887. case PragTyp_DATA_STORE_DIRECTORY: {
  100888. if( !zRight ){
  100889. returnSingleText(v, "data_store_directory", sqlite3_data_directory);
  100890. }else{
  100891. #ifndef SQLITE_OMIT_WSD
  100892. if( zRight[0] ){
  100893. int res;
  100894. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  100895. if( rc!=SQLITE_OK || res==0 ){
  100896. sqlite3ErrorMsg(pParse, "not a writable directory");
  100897. goto pragma_out;
  100898. }
  100899. }
  100900. sqlite3_free(sqlite3_data_directory);
  100901. if( zRight[0] ){
  100902. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  100903. }else{
  100904. sqlite3_data_directory = 0;
  100905. }
  100906. #endif /* SQLITE_OMIT_WSD */
  100907. }
  100908. break;
  100909. }
  100910. #endif
  100911. #if SQLITE_ENABLE_LOCKING_STYLE
  100912. /*
  100913. ** PRAGMA [schema.]lock_proxy_file
  100914. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  100915. **
  100916. ** Return or set the value of the lock_proxy_file flag. Changing
  100917. ** the value sets a specific file to be used for database access locks.
  100918. **
  100919. */
  100920. case PragTyp_LOCK_PROXY_FILE: {
  100921. if( !zRight ){
  100922. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  100923. char *proxy_file_path = NULL;
  100924. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  100925. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  100926. &proxy_file_path);
  100927. returnSingleText(v, "lock_proxy_file", proxy_file_path);
  100928. }else{
  100929. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  100930. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  100931. int res;
  100932. if( zRight[0] ){
  100933. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  100934. zRight);
  100935. } else {
  100936. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  100937. NULL);
  100938. }
  100939. if( res!=SQLITE_OK ){
  100940. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  100941. goto pragma_out;
  100942. }
  100943. }
  100944. break;
  100945. }
  100946. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  100947. /*
  100948. ** PRAGMA [schema.]synchronous
  100949. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL
  100950. **
  100951. ** Return or set the local value of the synchronous flag. Changing
  100952. ** the local value does not make changes to the disk file and the
  100953. ** default value will be restored the next time the database is
  100954. ** opened.
  100955. */
  100956. case PragTyp_SYNCHRONOUS: {
  100957. if( !zRight ){
  100958. returnSingleInt(v, "synchronous", pDb->safety_level-1);
  100959. }else{
  100960. if( !db->autoCommit ){
  100961. sqlite3ErrorMsg(pParse,
  100962. "Safety level may not be changed inside a transaction");
  100963. }else{
  100964. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  100965. if( iLevel==0 ) iLevel = 1;
  100966. pDb->safety_level = iLevel;
  100967. setAllPagerFlags(db);
  100968. }
  100969. }
  100970. break;
  100971. }
  100972. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  100973. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  100974. case PragTyp_FLAG: {
  100975. if( zRight==0 ){
  100976. returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
  100977. }else{
  100978. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  100979. if( db->autoCommit==0 ){
  100980. /* Foreign key support may not be enabled or disabled while not
  100981. ** in auto-commit mode. */
  100982. mask &= ~(SQLITE_ForeignKeys);
  100983. }
  100984. #if SQLITE_USER_AUTHENTICATION
  100985. if( db->auth.authLevel==UAUTH_User ){
  100986. /* Do not allow non-admin users to modify the schema arbitrarily */
  100987. mask &= ~(SQLITE_WriteSchema);
  100988. }
  100989. #endif
  100990. if( sqlite3GetBoolean(zRight, 0) ){
  100991. db->flags |= mask;
  100992. }else{
  100993. db->flags &= ~mask;
  100994. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  100995. }
  100996. /* Many of the flag-pragmas modify the code generated by the SQL
  100997. ** compiler (eg. count_changes). So add an opcode to expire all
  100998. ** compiled SQL statements after modifying a pragma value.
  100999. */
  101000. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  101001. setAllPagerFlags(db);
  101002. }
  101003. break;
  101004. }
  101005. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  101006. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  101007. /*
  101008. ** PRAGMA table_info(<table>)
  101009. **
  101010. ** Return a single row for each column of the named table. The columns of
  101011. ** the returned data set are:
  101012. **
  101013. ** cid: Column id (numbered from left to right, starting at 0)
  101014. ** name: Column name
  101015. ** type: Column declaration type.
  101016. ** notnull: True if 'NOT NULL' is part of column declaration
  101017. ** dflt_value: The default value for the column, if any.
  101018. */
  101019. case PragTyp_TABLE_INFO: if( zRight ){
  101020. Table *pTab;
  101021. pTab = sqlite3FindTable(db, zRight, zDb);
  101022. if( pTab ){
  101023. static const char *azCol[] = {
  101024. "cid", "name", "type", "notnull", "dflt_value", "pk"
  101025. };
  101026. int i, k;
  101027. int nHidden = 0;
  101028. Column *pCol;
  101029. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  101030. pParse->nMem = 6;
  101031. sqlite3CodeVerifySchema(pParse, iDb);
  101032. setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
  101033. sqlite3ViewGetColumnNames(pParse, pTab);
  101034. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  101035. if( IsHiddenColumn(pCol) ){
  101036. nHidden++;
  101037. continue;
  101038. }
  101039. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  101040. k = 0;
  101041. }else if( pPk==0 ){
  101042. k = 1;
  101043. }else{
  101044. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  101045. }
  101046. sqlite3VdbeMultiLoad(v, 1, "issisi",
  101047. i-nHidden,
  101048. pCol->zName,
  101049. pCol->zType ? pCol->zType : "",
  101050. pCol->notNull ? 1 : 0,
  101051. pCol->zDflt,
  101052. k);
  101053. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  101054. }
  101055. }
  101056. }
  101057. break;
  101058. case PragTyp_STATS: {
  101059. static const char *azCol[] = { "table", "index", "width", "height" };
  101060. Index *pIdx;
  101061. HashElem *i;
  101062. v = sqlite3GetVdbe(pParse);
  101063. pParse->nMem = 4;
  101064. sqlite3CodeVerifySchema(pParse, iDb);
  101065. setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
  101066. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  101067. Table *pTab = sqliteHashData(i);
  101068. sqlite3VdbeMultiLoad(v, 1, "ssii",
  101069. pTab->zName,
  101070. 0,
  101071. (int)sqlite3LogEstToInt(pTab->szTabRow),
  101072. (int)sqlite3LogEstToInt(pTab->nRowLogEst));
  101073. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  101074. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101075. sqlite3VdbeMultiLoad(v, 2, "sii",
  101076. pIdx->zName,
  101077. (int)sqlite3LogEstToInt(pIdx->szIdxRow),
  101078. (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]));
  101079. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  101080. }
  101081. }
  101082. }
  101083. break;
  101084. case PragTyp_INDEX_INFO: if( zRight ){
  101085. Index *pIdx;
  101086. Table *pTab;
  101087. pIdx = sqlite3FindIndex(db, zRight, zDb);
  101088. if( pIdx ){
  101089. static const char *azCol[] = {
  101090. "seqno", "cid", "name", "desc", "coll", "key"
  101091. };
  101092. int i;
  101093. int mx;
  101094. if( pPragma->iArg ){
  101095. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  101096. mx = pIdx->nColumn;
  101097. pParse->nMem = 6;
  101098. }else{
  101099. /* PRAGMA index_info (legacy version) */
  101100. mx = pIdx->nKeyCol;
  101101. pParse->nMem = 3;
  101102. }
  101103. pTab = pIdx->pTable;
  101104. sqlite3CodeVerifySchema(pParse, iDb);
  101105. assert( pParse->nMem<=ArraySize(azCol) );
  101106. setAllColumnNames(v, pParse->nMem, azCol);
  101107. for(i=0; i<mx; i++){
  101108. i16 cnum = pIdx->aiColumn[i];
  101109. sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
  101110. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  101111. if( pPragma->iArg ){
  101112. sqlite3VdbeMultiLoad(v, 4, "isi",
  101113. pIdx->aSortOrder[i],
  101114. pIdx->azColl[i],
  101115. i<pIdx->nKeyCol);
  101116. }
  101117. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  101118. }
  101119. }
  101120. }
  101121. break;
  101122. case PragTyp_INDEX_LIST: if( zRight ){
  101123. Index *pIdx;
  101124. Table *pTab;
  101125. int i;
  101126. pTab = sqlite3FindTable(db, zRight, zDb);
  101127. if( pTab ){
  101128. static const char *azCol[] = {
  101129. "seq", "name", "unique", "origin", "partial"
  101130. };
  101131. v = sqlite3GetVdbe(pParse);
  101132. pParse->nMem = 5;
  101133. sqlite3CodeVerifySchema(pParse, iDb);
  101134. setAllColumnNames(v, 5, azCol); assert( 5==ArraySize(azCol) );
  101135. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  101136. const char *azOrigin[] = { "c", "u", "pk" };
  101137. sqlite3VdbeMultiLoad(v, 1, "isisi",
  101138. i,
  101139. pIdx->zName,
  101140. IsUniqueIndex(pIdx),
  101141. azOrigin[pIdx->idxType],
  101142. pIdx->pPartIdxWhere!=0);
  101143. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  101144. }
  101145. }
  101146. }
  101147. break;
  101148. case PragTyp_DATABASE_LIST: {
  101149. static const char *azCol[] = { "seq", "name", "file" };
  101150. int i;
  101151. pParse->nMem = 3;
  101152. setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
  101153. for(i=0; i<db->nDb; i++){
  101154. if( db->aDb[i].pBt==0 ) continue;
  101155. assert( db->aDb[i].zName!=0 );
  101156. sqlite3VdbeMultiLoad(v, 1, "iss",
  101157. i,
  101158. db->aDb[i].zName,
  101159. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  101160. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  101161. }
  101162. }
  101163. break;
  101164. case PragTyp_COLLATION_LIST: {
  101165. static const char *azCol[] = { "seq", "name" };
  101166. int i = 0;
  101167. HashElem *p;
  101168. pParse->nMem = 2;
  101169. setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
  101170. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  101171. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  101172. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  101173. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  101174. }
  101175. }
  101176. break;
  101177. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  101178. #ifndef SQLITE_OMIT_FOREIGN_KEY
  101179. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  101180. FKey *pFK;
  101181. Table *pTab;
  101182. pTab = sqlite3FindTable(db, zRight, zDb);
  101183. if( pTab ){
  101184. v = sqlite3GetVdbe(pParse);
  101185. pFK = pTab->pFKey;
  101186. if( pFK ){
  101187. static const char *azCol[] = {
  101188. "id", "seq", "table", "from", "to", "on_update", "on_delete",
  101189. "match"
  101190. };
  101191. int i = 0;
  101192. pParse->nMem = 8;
  101193. sqlite3CodeVerifySchema(pParse, iDb);
  101194. setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
  101195. while(pFK){
  101196. int j;
  101197. for(j=0; j<pFK->nCol; j++){
  101198. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  101199. i,
  101200. j,
  101201. pFK->zTo,
  101202. pTab->aCol[pFK->aCol[j].iFrom].zName,
  101203. pFK->aCol[j].zCol,
  101204. actionName(pFK->aAction[1]), /* ON UPDATE */
  101205. actionName(pFK->aAction[0]), /* ON DELETE */
  101206. "NONE");
  101207. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  101208. }
  101209. ++i;
  101210. pFK = pFK->pNextFrom;
  101211. }
  101212. }
  101213. }
  101214. }
  101215. break;
  101216. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  101217. #ifndef SQLITE_OMIT_FOREIGN_KEY
  101218. #ifndef SQLITE_OMIT_TRIGGER
  101219. case PragTyp_FOREIGN_KEY_CHECK: {
  101220. FKey *pFK; /* A foreign key constraint */
  101221. Table *pTab; /* Child table contain "REFERENCES" keyword */
  101222. Table *pParent; /* Parent table that child points to */
  101223. Index *pIdx; /* Index in the parent table */
  101224. int i; /* Loop counter: Foreign key number for pTab */
  101225. int j; /* Loop counter: Field of the foreign key */
  101226. HashElem *k; /* Loop counter: Next table in schema */
  101227. int x; /* result variable */
  101228. int regResult; /* 3 registers to hold a result row */
  101229. int regKey; /* Register to hold key for checking the FK */
  101230. int regRow; /* Registers to hold a row from pTab */
  101231. int addrTop; /* Top of a loop checking foreign keys */
  101232. int addrOk; /* Jump here if the key is OK */
  101233. int *aiCols; /* child to parent column mapping */
  101234. static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
  101235. regResult = pParse->nMem+1;
  101236. pParse->nMem += 4;
  101237. regKey = ++pParse->nMem;
  101238. regRow = ++pParse->nMem;
  101239. v = sqlite3GetVdbe(pParse);
  101240. setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
  101241. sqlite3CodeVerifySchema(pParse, iDb);
  101242. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  101243. while( k ){
  101244. if( zRight ){
  101245. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  101246. k = 0;
  101247. }else{
  101248. pTab = (Table*)sqliteHashData(k);
  101249. k = sqliteHashNext(k);
  101250. }
  101251. if( pTab==0 || pTab->pFKey==0 ) continue;
  101252. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  101253. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  101254. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  101255. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  101256. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  101257. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  101258. if( pParent==0 ) continue;
  101259. pIdx = 0;
  101260. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  101261. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  101262. if( x==0 ){
  101263. if( pIdx==0 ){
  101264. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  101265. }else{
  101266. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  101267. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  101268. }
  101269. }else{
  101270. k = 0;
  101271. break;
  101272. }
  101273. }
  101274. assert( pParse->nErr>0 || pFK==0 );
  101275. if( pFK ) break;
  101276. if( pParse->nTab<i ) pParse->nTab = i;
  101277. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  101278. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  101279. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  101280. pIdx = 0;
  101281. aiCols = 0;
  101282. if( pParent ){
  101283. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  101284. assert( x==0 );
  101285. }
  101286. addrOk = sqlite3VdbeMakeLabel(v);
  101287. if( pParent && pIdx==0 ){
  101288. int iKey = pFK->aCol[0].iFrom;
  101289. assert( iKey>=0 && iKey<pTab->nCol );
  101290. if( iKey!=pTab->iPKey ){
  101291. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  101292. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  101293. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
  101294. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  101295. sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
  101296. }else{
  101297. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  101298. }
  101299. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
  101300. sqlite3VdbeGoto(v, addrOk);
  101301. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  101302. }else{
  101303. for(j=0; j<pFK->nCol; j++){
  101304. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  101305. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  101306. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  101307. }
  101308. if( pParent ){
  101309. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  101310. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  101311. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  101312. VdbeCoverage(v);
  101313. }
  101314. }
  101315. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  101316. sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
  101317. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  101318. sqlite3VdbeResolveLabel(v, addrOk);
  101319. sqlite3DbFree(db, aiCols);
  101320. }
  101321. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  101322. sqlite3VdbeJumpHere(v, addrTop);
  101323. }
  101324. }
  101325. break;
  101326. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  101327. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  101328. #ifndef NDEBUG
  101329. case PragTyp_PARSER_TRACE: {
  101330. if( zRight ){
  101331. if( sqlite3GetBoolean(zRight, 0) ){
  101332. sqlite3ParserTrace(stdout, "parser: ");
  101333. }else{
  101334. sqlite3ParserTrace(0, 0);
  101335. }
  101336. }
  101337. }
  101338. break;
  101339. #endif
  101340. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  101341. ** used will be case sensitive or not depending on the RHS.
  101342. */
  101343. case PragTyp_CASE_SENSITIVE_LIKE: {
  101344. if( zRight ){
  101345. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  101346. }
  101347. }
  101348. break;
  101349. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  101350. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  101351. #endif
  101352. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  101353. /* Pragma "quick_check" is reduced version of
  101354. ** integrity_check designed to detect most database corruption
  101355. ** without most of the overhead of a full integrity-check.
  101356. */
  101357. case PragTyp_INTEGRITY_CHECK: {
  101358. int i, j, addr, mxErr;
  101359. /* Code that appears at the end of the integrity check. If no error
  101360. ** messages have been generated, output OK. Otherwise output the
  101361. ** error message
  101362. */
  101363. static const int iLn = VDBE_OFFSET_LINENO(2);
  101364. static const VdbeOpList endCode[] = {
  101365. { OP_AddImm, 1, 0, 0}, /* 0 */
  101366. { OP_If, 1, 0, 0}, /* 1 */
  101367. { OP_String8, 0, 3, 0}, /* 2 */
  101368. { OP_ResultRow, 3, 1, 0},
  101369. };
  101370. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  101371. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  101372. ** then iDb is set to the index of the database identified by <db>.
  101373. ** In this case, the integrity of database iDb only is verified by
  101374. ** the VDBE created below.
  101375. **
  101376. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  101377. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  101378. ** to -1 here, to indicate that the VDBE should verify the integrity
  101379. ** of all attached databases. */
  101380. assert( iDb>=0 );
  101381. assert( iDb==0 || pId2->z );
  101382. if( pId2->z==0 ) iDb = -1;
  101383. /* Initialize the VDBE program */
  101384. pParse->nMem = 6;
  101385. setOneColumnName(v, "integrity_check");
  101386. /* Set the maximum error count */
  101387. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  101388. if( zRight ){
  101389. sqlite3GetInt32(zRight, &mxErr);
  101390. if( mxErr<=0 ){
  101391. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  101392. }
  101393. }
  101394. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  101395. /* Do an integrity check on each database file */
  101396. for(i=0; i<db->nDb; i++){
  101397. HashElem *x;
  101398. Hash *pTbls;
  101399. int cnt = 0;
  101400. if( OMIT_TEMPDB && i==1 ) continue;
  101401. if( iDb>=0 && i!=iDb ) continue;
  101402. sqlite3CodeVerifySchema(pParse, i);
  101403. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  101404. VdbeCoverage(v);
  101405. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  101406. sqlite3VdbeJumpHere(v, addr);
  101407. /* Do an integrity check of the B-Tree
  101408. **
  101409. ** Begin by filling registers 2, 3, ... with the root pages numbers
  101410. ** for all tables and indices in the database.
  101411. */
  101412. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  101413. pTbls = &db->aDb[i].pSchema->tblHash;
  101414. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  101415. Table *pTab = sqliteHashData(x);
  101416. Index *pIdx;
  101417. if( HasRowid(pTab) ){
  101418. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  101419. VdbeComment((v, "%s", pTab->zName));
  101420. cnt++;
  101421. }
  101422. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101423. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  101424. VdbeComment((v, "%s", pIdx->zName));
  101425. cnt++;
  101426. }
  101427. }
  101428. /* Make sure sufficient number of registers have been allocated */
  101429. pParse->nMem = MAX( pParse->nMem, cnt+8 );
  101430. /* Do the b-tree integrity checks */
  101431. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  101432. sqlite3VdbeChangeP5(v, (u8)i);
  101433. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  101434. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  101435. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  101436. P4_DYNAMIC);
  101437. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  101438. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  101439. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  101440. sqlite3VdbeJumpHere(v, addr);
  101441. /* Make sure all the indices are constructed correctly.
  101442. */
  101443. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  101444. Table *pTab = sqliteHashData(x);
  101445. Index *pIdx, *pPk;
  101446. Index *pPrior = 0;
  101447. int loopTop;
  101448. int iDataCur, iIdxCur;
  101449. int r1 = -1;
  101450. if( pTab->pIndex==0 ) continue;
  101451. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  101452. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  101453. VdbeCoverage(v);
  101454. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  101455. sqlite3VdbeJumpHere(v, addr);
  101456. sqlite3ExprCacheClear(pParse);
  101457. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  101458. 1, 0, &iDataCur, &iIdxCur);
  101459. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  101460. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  101461. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  101462. }
  101463. pParse->nMem = MAX(pParse->nMem, 8+j);
  101464. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  101465. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  101466. /* Verify that all NOT NULL columns really are NOT NULL */
  101467. for(j=0; j<pTab->nCol; j++){
  101468. char *zErr;
  101469. int jmp2, jmp3;
  101470. if( j==pTab->iPKey ) continue;
  101471. if( pTab->aCol[j].notNull==0 ) continue;
  101472. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  101473. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  101474. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  101475. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  101476. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  101477. pTab->aCol[j].zName);
  101478. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  101479. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  101480. jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  101481. sqlite3VdbeAddOp0(v, OP_Halt);
  101482. sqlite3VdbeJumpHere(v, jmp2);
  101483. sqlite3VdbeJumpHere(v, jmp3);
  101484. }
  101485. /* Validate index entries for the current row */
  101486. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  101487. int jmp2, jmp3, jmp4, jmp5;
  101488. int ckUniq = sqlite3VdbeMakeLabel(v);
  101489. if( pPk==pIdx ) continue;
  101490. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  101491. pPrior, r1);
  101492. pPrior = pIdx;
  101493. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  101494. /* Verify that an index entry exists for the current table row */
  101495. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  101496. pIdx->nColumn); VdbeCoverage(v);
  101497. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  101498. sqlite3VdbeLoadString(v, 3, "row ");
  101499. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  101500. sqlite3VdbeLoadString(v, 4, " missing from index ");
  101501. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  101502. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  101503. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  101504. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  101505. jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  101506. sqlite3VdbeAddOp0(v, OP_Halt);
  101507. sqlite3VdbeJumpHere(v, jmp2);
  101508. /* For UNIQUE indexes, verify that only one entry exists with the
  101509. ** current key. The entry is unique if (1) any column is NULL
  101510. ** or (2) the next entry has a different key */
  101511. if( IsUniqueIndex(pIdx) ){
  101512. int uniqOk = sqlite3VdbeMakeLabel(v);
  101513. int jmp6;
  101514. int kk;
  101515. for(kk=0; kk<pIdx->nKeyCol; kk++){
  101516. int iCol = pIdx->aiColumn[kk];
  101517. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  101518. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  101519. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  101520. VdbeCoverage(v);
  101521. }
  101522. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  101523. sqlite3VdbeGoto(v, uniqOk);
  101524. sqlite3VdbeJumpHere(v, jmp6);
  101525. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  101526. pIdx->nKeyCol); VdbeCoverage(v);
  101527. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  101528. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  101529. sqlite3VdbeGoto(v, jmp5);
  101530. sqlite3VdbeResolveLabel(v, uniqOk);
  101531. }
  101532. sqlite3VdbeJumpHere(v, jmp4);
  101533. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  101534. }
  101535. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  101536. sqlite3VdbeJumpHere(v, loopTop-1);
  101537. #ifndef SQLITE_OMIT_BTREECOUNT
  101538. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  101539. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  101540. if( pPk==pIdx ) continue;
  101541. addr = sqlite3VdbeCurrentAddr(v);
  101542. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
  101543. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  101544. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  101545. sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
  101546. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  101547. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  101548. sqlite3VdbeLoadString(v, 3, pIdx->zName);
  101549. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  101550. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  101551. }
  101552. #endif /* SQLITE_OMIT_BTREECOUNT */
  101553. }
  101554. }
  101555. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  101556. sqlite3VdbeChangeP2(v, addr, -mxErr);
  101557. sqlite3VdbeJumpHere(v, addr+1);
  101558. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  101559. }
  101560. break;
  101561. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  101562. #ifndef SQLITE_OMIT_UTF16
  101563. /*
  101564. ** PRAGMA encoding
  101565. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  101566. **
  101567. ** In its first form, this pragma returns the encoding of the main
  101568. ** database. If the database is not initialized, it is initialized now.
  101569. **
  101570. ** The second form of this pragma is a no-op if the main database file
  101571. ** has not already been initialized. In this case it sets the default
  101572. ** encoding that will be used for the main database file if a new file
  101573. ** is created. If an existing main database file is opened, then the
  101574. ** default text encoding for the existing database is used.
  101575. **
  101576. ** In all cases new databases created using the ATTACH command are
  101577. ** created to use the same default text encoding as the main database. If
  101578. ** the main database has not been initialized and/or created when ATTACH
  101579. ** is executed, this is done before the ATTACH operation.
  101580. **
  101581. ** In the second form this pragma sets the text encoding to be used in
  101582. ** new database files created using this database handle. It is only
  101583. ** useful if invoked immediately after the main database i
  101584. */
  101585. case PragTyp_ENCODING: {
  101586. static const struct EncName {
  101587. char *zName;
  101588. u8 enc;
  101589. } encnames[] = {
  101590. { "UTF8", SQLITE_UTF8 },
  101591. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  101592. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  101593. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  101594. { "UTF16le", SQLITE_UTF16LE },
  101595. { "UTF16be", SQLITE_UTF16BE },
  101596. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  101597. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  101598. { 0, 0 }
  101599. };
  101600. const struct EncName *pEnc;
  101601. if( !zRight ){ /* "PRAGMA encoding" */
  101602. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  101603. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  101604. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  101605. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  101606. returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
  101607. }else{ /* "PRAGMA encoding = XXX" */
  101608. /* Only change the value of sqlite.enc if the database handle is not
  101609. ** initialized. If the main database exists, the new sqlite.enc value
  101610. ** will be overwritten when the schema is next loaded. If it does not
  101611. ** already exists, it will be created to use the new encoding value.
  101612. */
  101613. if(
  101614. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  101615. DbHasProperty(db, 0, DB_Empty)
  101616. ){
  101617. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  101618. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  101619. SCHEMA_ENC(db) = ENC(db) =
  101620. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  101621. break;
  101622. }
  101623. }
  101624. if( !pEnc->zName ){
  101625. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  101626. }
  101627. }
  101628. }
  101629. }
  101630. break;
  101631. #endif /* SQLITE_OMIT_UTF16 */
  101632. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  101633. /*
  101634. ** PRAGMA [schema.]schema_version
  101635. ** PRAGMA [schema.]schema_version = <integer>
  101636. **
  101637. ** PRAGMA [schema.]user_version
  101638. ** PRAGMA [schema.]user_version = <integer>
  101639. **
  101640. ** PRAGMA [schema.]freelist_count = <integer>
  101641. **
  101642. ** PRAGMA [schema.]application_id
  101643. ** PRAGMA [schema.]application_id = <integer>
  101644. **
  101645. ** The pragma's schema_version and user_version are used to set or get
  101646. ** the value of the schema-version and user-version, respectively. Both
  101647. ** the schema-version and the user-version are 32-bit signed integers
  101648. ** stored in the database header.
  101649. **
  101650. ** The schema-cookie is usually only manipulated internally by SQLite. It
  101651. ** is incremented by SQLite whenever the database schema is modified (by
  101652. ** creating or dropping a table or index). The schema version is used by
  101653. ** SQLite each time a query is executed to ensure that the internal cache
  101654. ** of the schema used when compiling the SQL query matches the schema of
  101655. ** the database against which the compiled query is actually executed.
  101656. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  101657. ** the schema-version is potentially dangerous and may lead to program
  101658. ** crashes or database corruption. Use with caution!
  101659. **
  101660. ** The user-version is not used internally by SQLite. It may be used by
  101661. ** applications for any purpose.
  101662. */
  101663. case PragTyp_HEADER_VALUE: {
  101664. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  101665. sqlite3VdbeUsesBtree(v, iDb);
  101666. if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
  101667. /* Write the specified cookie value */
  101668. static const VdbeOpList setCookie[] = {
  101669. { OP_Transaction, 0, 1, 0}, /* 0 */
  101670. { OP_Integer, 0, 1, 0}, /* 1 */
  101671. { OP_SetCookie, 0, 0, 1}, /* 2 */
  101672. };
  101673. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  101674. sqlite3VdbeChangeP1(v, addr, iDb);
  101675. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  101676. sqlite3VdbeChangeP1(v, addr+2, iDb);
  101677. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  101678. }else{
  101679. /* Read the specified cookie value */
  101680. static const VdbeOpList readCookie[] = {
  101681. { OP_Transaction, 0, 0, 0}, /* 0 */
  101682. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  101683. { OP_ResultRow, 1, 1, 0}
  101684. };
  101685. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
  101686. sqlite3VdbeChangeP1(v, addr, iDb);
  101687. sqlite3VdbeChangeP1(v, addr+1, iDb);
  101688. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  101689. sqlite3VdbeSetNumCols(v, 1);
  101690. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  101691. }
  101692. }
  101693. break;
  101694. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  101695. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  101696. /*
  101697. ** PRAGMA compile_options
  101698. **
  101699. ** Return the names of all compile-time options used in this build,
  101700. ** one option per row.
  101701. */
  101702. case PragTyp_COMPILE_OPTIONS: {
  101703. int i = 0;
  101704. const char *zOpt;
  101705. pParse->nMem = 1;
  101706. setOneColumnName(v, "compile_option");
  101707. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  101708. sqlite3VdbeLoadString(v, 1, zOpt);
  101709. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  101710. }
  101711. }
  101712. break;
  101713. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  101714. #ifndef SQLITE_OMIT_WAL
  101715. /*
  101716. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  101717. **
  101718. ** Checkpoint the database.
  101719. */
  101720. case PragTyp_WAL_CHECKPOINT: {
  101721. static const char *azCol[] = { "busy", "log", "checkpointed" };
  101722. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  101723. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  101724. if( zRight ){
  101725. if( sqlite3StrICmp(zRight, "full")==0 ){
  101726. eMode = SQLITE_CHECKPOINT_FULL;
  101727. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  101728. eMode = SQLITE_CHECKPOINT_RESTART;
  101729. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  101730. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  101731. }
  101732. }
  101733. setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
  101734. pParse->nMem = 3;
  101735. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  101736. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  101737. }
  101738. break;
  101739. /*
  101740. ** PRAGMA wal_autocheckpoint
  101741. ** PRAGMA wal_autocheckpoint = N
  101742. **
  101743. ** Configure a database connection to automatically checkpoint a database
  101744. ** after accumulating N frames in the log. Or query for the current value
  101745. ** of N.
  101746. */
  101747. case PragTyp_WAL_AUTOCHECKPOINT: {
  101748. if( zRight ){
  101749. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  101750. }
  101751. returnSingleInt(v, "wal_autocheckpoint",
  101752. db->xWalCallback==sqlite3WalDefaultHook ?
  101753. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  101754. }
  101755. break;
  101756. #endif
  101757. /*
  101758. ** PRAGMA shrink_memory
  101759. **
  101760. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  101761. ** connection on which it is invoked to free up as much memory as it
  101762. ** can, by calling sqlite3_db_release_memory().
  101763. */
  101764. case PragTyp_SHRINK_MEMORY: {
  101765. sqlite3_db_release_memory(db);
  101766. break;
  101767. }
  101768. /*
  101769. ** PRAGMA busy_timeout
  101770. ** PRAGMA busy_timeout = N
  101771. **
  101772. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  101773. ** if one is set. If no busy handler or a different busy handler is set
  101774. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  101775. ** disables the timeout.
  101776. */
  101777. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  101778. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  101779. if( zRight ){
  101780. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  101781. }
  101782. returnSingleInt(v, "timeout", db->busyTimeout);
  101783. break;
  101784. }
  101785. /*
  101786. ** PRAGMA soft_heap_limit
  101787. ** PRAGMA soft_heap_limit = N
  101788. **
  101789. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  101790. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  101791. ** specified and is a non-negative integer.
  101792. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  101793. ** returns the same integer that would be returned by the
  101794. ** sqlite3_soft_heap_limit64(-1) C-language function.
  101795. */
  101796. case PragTyp_SOFT_HEAP_LIMIT: {
  101797. sqlite3_int64 N;
  101798. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  101799. sqlite3_soft_heap_limit64(N);
  101800. }
  101801. returnSingleInt(v, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  101802. break;
  101803. }
  101804. /*
  101805. ** PRAGMA threads
  101806. ** PRAGMA threads = N
  101807. **
  101808. ** Configure the maximum number of worker threads. Return the new
  101809. ** maximum, which might be less than requested.
  101810. */
  101811. case PragTyp_THREADS: {
  101812. sqlite3_int64 N;
  101813. if( zRight
  101814. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  101815. && N>=0
  101816. ){
  101817. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  101818. }
  101819. returnSingleInt(v, "threads",
  101820. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  101821. break;
  101822. }
  101823. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  101824. /*
  101825. ** Report the current state of file logs for all databases
  101826. */
  101827. case PragTyp_LOCK_STATUS: {
  101828. static const char *const azLockName[] = {
  101829. "unlocked", "shared", "reserved", "pending", "exclusive"
  101830. };
  101831. static const char *azCol[] = { "database", "status" };
  101832. int i;
  101833. setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
  101834. pParse->nMem = 2;
  101835. for(i=0; i<db->nDb; i++){
  101836. Btree *pBt;
  101837. const char *zState = "unknown";
  101838. int j;
  101839. if( db->aDb[i].zName==0 ) continue;
  101840. pBt = db->aDb[i].pBt;
  101841. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  101842. zState = "closed";
  101843. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  101844. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  101845. zState = azLockName[j];
  101846. }
  101847. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
  101848. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  101849. }
  101850. break;
  101851. }
  101852. #endif
  101853. #ifdef SQLITE_HAS_CODEC
  101854. case PragTyp_KEY: {
  101855. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  101856. break;
  101857. }
  101858. case PragTyp_REKEY: {
  101859. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  101860. break;
  101861. }
  101862. case PragTyp_HEXKEY: {
  101863. if( zRight ){
  101864. u8 iByte;
  101865. int i;
  101866. char zKey[40];
  101867. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  101868. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  101869. if( (i&1)!=0 ) zKey[i/2] = iByte;
  101870. }
  101871. if( (zLeft[3] & 0xf)==0xb ){
  101872. sqlite3_key_v2(db, zDb, zKey, i/2);
  101873. }else{
  101874. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  101875. }
  101876. }
  101877. break;
  101878. }
  101879. #endif
  101880. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  101881. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  101882. #ifdef SQLITE_HAS_CODEC
  101883. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  101884. sqlite3_activate_see(&zRight[4]);
  101885. }
  101886. #endif
  101887. #ifdef SQLITE_ENABLE_CEROD
  101888. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  101889. sqlite3_activate_cerod(&zRight[6]);
  101890. }
  101891. #endif
  101892. }
  101893. break;
  101894. #endif
  101895. } /* End of the PRAGMA switch */
  101896. pragma_out:
  101897. sqlite3DbFree(db, zLeft);
  101898. sqlite3DbFree(db, zRight);
  101899. }
  101900. #endif /* SQLITE_OMIT_PRAGMA */
  101901. /************** End of pragma.c **********************************************/
  101902. /************** Begin file prepare.c *****************************************/
  101903. /*
  101904. ** 2005 May 25
  101905. **
  101906. ** The author disclaims copyright to this source code. In place of
  101907. ** a legal notice, here is a blessing:
  101908. **
  101909. ** May you do good and not evil.
  101910. ** May you find forgiveness for yourself and forgive others.
  101911. ** May you share freely, never taking more than you give.
  101912. **
  101913. *************************************************************************
  101914. ** This file contains the implementation of the sqlite3_prepare()
  101915. ** interface, and routines that contribute to loading the database schema
  101916. ** from disk.
  101917. */
  101918. /* #include "sqliteInt.h" */
  101919. /*
  101920. ** Fill the InitData structure with an error message that indicates
  101921. ** that the database is corrupt.
  101922. */
  101923. static void corruptSchema(
  101924. InitData *pData, /* Initialization context */
  101925. const char *zObj, /* Object being parsed at the point of error */
  101926. const char *zExtra /* Error information */
  101927. ){
  101928. sqlite3 *db = pData->db;
  101929. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  101930. char *z;
  101931. if( zObj==0 ) zObj = "?";
  101932. z = sqlite3_mprintf("malformed database schema (%s)", zObj);
  101933. if( z && zExtra ) z = sqlite3_mprintf("%z - %s", z, zExtra);
  101934. sqlite3DbFree(db, *pData->pzErrMsg);
  101935. *pData->pzErrMsg = z;
  101936. if( z==0 ) db->mallocFailed = 1;
  101937. }
  101938. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  101939. }
  101940. /*
  101941. ** This is the callback routine for the code that initializes the
  101942. ** database. See sqlite3Init() below for additional information.
  101943. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  101944. **
  101945. ** Each callback contains the following information:
  101946. **
  101947. ** argv[0] = name of thing being created
  101948. ** argv[1] = root page number for table or index. 0 for trigger or view.
  101949. ** argv[2] = SQL text for the CREATE statement.
  101950. **
  101951. */
  101952. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  101953. InitData *pData = (InitData*)pInit;
  101954. sqlite3 *db = pData->db;
  101955. int iDb = pData->iDb;
  101956. assert( argc==3 );
  101957. UNUSED_PARAMETER2(NotUsed, argc);
  101958. assert( sqlite3_mutex_held(db->mutex) );
  101959. DbClearProperty(db, iDb, DB_Empty);
  101960. if( db->mallocFailed ){
  101961. corruptSchema(pData, argv[0], 0);
  101962. return 1;
  101963. }
  101964. assert( iDb>=0 && iDb<db->nDb );
  101965. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  101966. if( argv[1]==0 ){
  101967. corruptSchema(pData, argv[0], 0);
  101968. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  101969. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  101970. ** But because db->init.busy is set to 1, no VDBE code is generated
  101971. ** or executed. All the parser does is build the internal data
  101972. ** structures that describe the table, index, or view.
  101973. */
  101974. int rc;
  101975. sqlite3_stmt *pStmt;
  101976. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  101977. assert( db->init.busy );
  101978. db->init.iDb = iDb;
  101979. db->init.newTnum = sqlite3Atoi(argv[1]);
  101980. db->init.orphanTrigger = 0;
  101981. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  101982. rc = db->errCode;
  101983. assert( (rc&0xFF)==(rcp&0xFF) );
  101984. db->init.iDb = 0;
  101985. if( SQLITE_OK!=rc ){
  101986. if( db->init.orphanTrigger ){
  101987. assert( iDb==1 );
  101988. }else{
  101989. pData->rc = rc;
  101990. if( rc==SQLITE_NOMEM ){
  101991. db->mallocFailed = 1;
  101992. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  101993. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  101994. }
  101995. }
  101996. }
  101997. sqlite3_finalize(pStmt);
  101998. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  101999. corruptSchema(pData, argv[0], 0);
  102000. }else{
  102001. /* If the SQL column is blank it means this is an index that
  102002. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  102003. ** constraint for a CREATE TABLE. The index should have already
  102004. ** been created when we processed the CREATE TABLE. All we have
  102005. ** to do here is record the root page number for that index.
  102006. */
  102007. Index *pIndex;
  102008. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  102009. if( pIndex==0 ){
  102010. /* This can occur if there exists an index on a TEMP table which
  102011. ** has the same name as another index on a permanent index. Since
  102012. ** the permanent table is hidden by the TEMP table, we can also
  102013. ** safely ignore the index on the permanent table.
  102014. */
  102015. /* Do Nothing */;
  102016. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  102017. corruptSchema(pData, argv[0], "invalid rootpage");
  102018. }
  102019. }
  102020. return 0;
  102021. }
  102022. /*
  102023. ** Attempt to read the database schema and initialize internal
  102024. ** data structures for a single database file. The index of the
  102025. ** database file is given by iDb. iDb==0 is used for the main
  102026. ** database. iDb==1 should never be used. iDb>=2 is used for
  102027. ** auxiliary databases. Return one of the SQLITE_ error codes to
  102028. ** indicate success or failure.
  102029. */
  102030. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  102031. int rc;
  102032. int i;
  102033. #ifndef SQLITE_OMIT_DEPRECATED
  102034. int size;
  102035. #endif
  102036. Table *pTab;
  102037. Db *pDb;
  102038. char const *azArg[4];
  102039. int meta[5];
  102040. InitData initData;
  102041. char const *zMasterSchema;
  102042. char const *zMasterName;
  102043. int openedTransaction = 0;
  102044. /*
  102045. ** The master database table has a structure like this
  102046. */
  102047. static const char master_schema[] =
  102048. "CREATE TABLE sqlite_master(\n"
  102049. " type text,\n"
  102050. " name text,\n"
  102051. " tbl_name text,\n"
  102052. " rootpage integer,\n"
  102053. " sql text\n"
  102054. ")"
  102055. ;
  102056. #ifndef SQLITE_OMIT_TEMPDB
  102057. static const char temp_master_schema[] =
  102058. "CREATE TEMP TABLE sqlite_temp_master(\n"
  102059. " type text,\n"
  102060. " name text,\n"
  102061. " tbl_name text,\n"
  102062. " rootpage integer,\n"
  102063. " sql text\n"
  102064. ")"
  102065. ;
  102066. #else
  102067. #define temp_master_schema 0
  102068. #endif
  102069. assert( iDb>=0 && iDb<db->nDb );
  102070. assert( db->aDb[iDb].pSchema );
  102071. assert( sqlite3_mutex_held(db->mutex) );
  102072. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  102073. /* zMasterSchema and zInitScript are set to point at the master schema
  102074. ** and initialisation script appropriate for the database being
  102075. ** initialized. zMasterName is the name of the master table.
  102076. */
  102077. if( !OMIT_TEMPDB && iDb==1 ){
  102078. zMasterSchema = temp_master_schema;
  102079. }else{
  102080. zMasterSchema = master_schema;
  102081. }
  102082. zMasterName = SCHEMA_TABLE(iDb);
  102083. /* Construct the schema tables. */
  102084. azArg[0] = zMasterName;
  102085. azArg[1] = "1";
  102086. azArg[2] = zMasterSchema;
  102087. azArg[3] = 0;
  102088. initData.db = db;
  102089. initData.iDb = iDb;
  102090. initData.rc = SQLITE_OK;
  102091. initData.pzErrMsg = pzErrMsg;
  102092. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  102093. if( initData.rc ){
  102094. rc = initData.rc;
  102095. goto error_out;
  102096. }
  102097. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  102098. if( ALWAYS(pTab) ){
  102099. pTab->tabFlags |= TF_Readonly;
  102100. }
  102101. /* Create a cursor to hold the database open
  102102. */
  102103. pDb = &db->aDb[iDb];
  102104. if( pDb->pBt==0 ){
  102105. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  102106. DbSetProperty(db, 1, DB_SchemaLoaded);
  102107. }
  102108. return SQLITE_OK;
  102109. }
  102110. /* If there is not already a read-only (or read-write) transaction opened
  102111. ** on the b-tree database, open one now. If a transaction is opened, it
  102112. ** will be closed before this function returns. */
  102113. sqlite3BtreeEnter(pDb->pBt);
  102114. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  102115. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  102116. if( rc!=SQLITE_OK ){
  102117. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  102118. goto initone_error_out;
  102119. }
  102120. openedTransaction = 1;
  102121. }
  102122. /* Get the database meta information.
  102123. **
  102124. ** Meta values are as follows:
  102125. ** meta[0] Schema cookie. Changes with each schema change.
  102126. ** meta[1] File format of schema layer.
  102127. ** meta[2] Size of the page cache.
  102128. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  102129. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  102130. ** meta[5] User version
  102131. ** meta[6] Incremental vacuum mode
  102132. ** meta[7] unused
  102133. ** meta[8] unused
  102134. ** meta[9] unused
  102135. **
  102136. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  102137. ** the possible values of meta[4].
  102138. */
  102139. for(i=0; i<ArraySize(meta); i++){
  102140. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  102141. }
  102142. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  102143. /* If opening a non-empty database, check the text encoding. For the
  102144. ** main database, set sqlite3.enc to the encoding of the main database.
  102145. ** For an attached db, it is an error if the encoding is not the same
  102146. ** as sqlite3.enc.
  102147. */
  102148. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  102149. if( iDb==0 ){
  102150. #ifndef SQLITE_OMIT_UTF16
  102151. u8 encoding;
  102152. /* If opening the main database, set ENC(db). */
  102153. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  102154. if( encoding==0 ) encoding = SQLITE_UTF8;
  102155. ENC(db) = encoding;
  102156. #else
  102157. ENC(db) = SQLITE_UTF8;
  102158. #endif
  102159. }else{
  102160. /* If opening an attached database, the encoding much match ENC(db) */
  102161. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  102162. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  102163. " text encoding as main database");
  102164. rc = SQLITE_ERROR;
  102165. goto initone_error_out;
  102166. }
  102167. }
  102168. }else{
  102169. DbSetProperty(db, iDb, DB_Empty);
  102170. }
  102171. pDb->pSchema->enc = ENC(db);
  102172. if( pDb->pSchema->cache_size==0 ){
  102173. #ifndef SQLITE_OMIT_DEPRECATED
  102174. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  102175. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  102176. pDb->pSchema->cache_size = size;
  102177. #else
  102178. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  102179. #endif
  102180. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  102181. }
  102182. /*
  102183. ** file_format==1 Version 3.0.0.
  102184. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  102185. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  102186. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  102187. */
  102188. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  102189. if( pDb->pSchema->file_format==0 ){
  102190. pDb->pSchema->file_format = 1;
  102191. }
  102192. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  102193. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  102194. rc = SQLITE_ERROR;
  102195. goto initone_error_out;
  102196. }
  102197. /* Ticket #2804: When we open a database in the newer file format,
  102198. ** clear the legacy_file_format pragma flag so that a VACUUM will
  102199. ** not downgrade the database and thus invalidate any descending
  102200. ** indices that the user might have created.
  102201. */
  102202. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  102203. db->flags &= ~SQLITE_LegacyFileFmt;
  102204. }
  102205. /* Read the schema information out of the schema tables
  102206. */
  102207. assert( db->init.busy );
  102208. {
  102209. char *zSql;
  102210. zSql = sqlite3MPrintf(db,
  102211. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  102212. db->aDb[iDb].zName, zMasterName);
  102213. #ifndef SQLITE_OMIT_AUTHORIZATION
  102214. {
  102215. sqlite3_xauth xAuth;
  102216. xAuth = db->xAuth;
  102217. db->xAuth = 0;
  102218. #endif
  102219. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  102220. #ifndef SQLITE_OMIT_AUTHORIZATION
  102221. db->xAuth = xAuth;
  102222. }
  102223. #endif
  102224. if( rc==SQLITE_OK ) rc = initData.rc;
  102225. sqlite3DbFree(db, zSql);
  102226. #ifndef SQLITE_OMIT_ANALYZE
  102227. if( rc==SQLITE_OK ){
  102228. sqlite3AnalysisLoad(db, iDb);
  102229. }
  102230. #endif
  102231. }
  102232. if( db->mallocFailed ){
  102233. rc = SQLITE_NOMEM;
  102234. sqlite3ResetAllSchemasOfConnection(db);
  102235. }
  102236. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  102237. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  102238. ** the schema loaded, even if errors occurred. In this situation the
  102239. ** current sqlite3_prepare() operation will fail, but the following one
  102240. ** will attempt to compile the supplied statement against whatever subset
  102241. ** of the schema was loaded before the error occurred. The primary
  102242. ** purpose of this is to allow access to the sqlite_master table
  102243. ** even when its contents have been corrupted.
  102244. */
  102245. DbSetProperty(db, iDb, DB_SchemaLoaded);
  102246. rc = SQLITE_OK;
  102247. }
  102248. /* Jump here for an error that occurs after successfully allocating
  102249. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  102250. ** before that point, jump to error_out.
  102251. */
  102252. initone_error_out:
  102253. if( openedTransaction ){
  102254. sqlite3BtreeCommit(pDb->pBt);
  102255. }
  102256. sqlite3BtreeLeave(pDb->pBt);
  102257. error_out:
  102258. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  102259. db->mallocFailed = 1;
  102260. }
  102261. return rc;
  102262. }
  102263. /*
  102264. ** Initialize all database files - the main database file, the file
  102265. ** used to store temporary tables, and any additional database files
  102266. ** created using ATTACH statements. Return a success code. If an
  102267. ** error occurs, write an error message into *pzErrMsg.
  102268. **
  102269. ** After a database is initialized, the DB_SchemaLoaded bit is set
  102270. ** bit is set in the flags field of the Db structure. If the database
  102271. ** file was of zero-length, then the DB_Empty flag is also set.
  102272. */
  102273. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  102274. int i, rc;
  102275. int commit_internal = !(db->flags&SQLITE_InternChanges);
  102276. assert( sqlite3_mutex_held(db->mutex) );
  102277. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  102278. assert( db->init.busy==0 );
  102279. rc = SQLITE_OK;
  102280. db->init.busy = 1;
  102281. ENC(db) = SCHEMA_ENC(db);
  102282. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  102283. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  102284. rc = sqlite3InitOne(db, i, pzErrMsg);
  102285. if( rc ){
  102286. sqlite3ResetOneSchema(db, i);
  102287. }
  102288. }
  102289. /* Once all the other databases have been initialized, load the schema
  102290. ** for the TEMP database. This is loaded last, as the TEMP database
  102291. ** schema may contain references to objects in other databases.
  102292. */
  102293. #ifndef SQLITE_OMIT_TEMPDB
  102294. assert( db->nDb>1 );
  102295. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  102296. rc = sqlite3InitOne(db, 1, pzErrMsg);
  102297. if( rc ){
  102298. sqlite3ResetOneSchema(db, 1);
  102299. }
  102300. }
  102301. #endif
  102302. db->init.busy = 0;
  102303. if( rc==SQLITE_OK && commit_internal ){
  102304. sqlite3CommitInternalChanges(db);
  102305. }
  102306. return rc;
  102307. }
  102308. /*
  102309. ** This routine is a no-op if the database schema is already initialized.
  102310. ** Otherwise, the schema is loaded. An error code is returned.
  102311. */
  102312. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  102313. int rc = SQLITE_OK;
  102314. sqlite3 *db = pParse->db;
  102315. assert( sqlite3_mutex_held(db->mutex) );
  102316. if( !db->init.busy ){
  102317. rc = sqlite3Init(db, &pParse->zErrMsg);
  102318. }
  102319. if( rc!=SQLITE_OK ){
  102320. pParse->rc = rc;
  102321. pParse->nErr++;
  102322. }
  102323. return rc;
  102324. }
  102325. /*
  102326. ** Check schema cookies in all databases. If any cookie is out
  102327. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  102328. ** make no changes to pParse->rc.
  102329. */
  102330. static void schemaIsValid(Parse *pParse){
  102331. sqlite3 *db = pParse->db;
  102332. int iDb;
  102333. int rc;
  102334. int cookie;
  102335. assert( pParse->checkSchema );
  102336. assert( sqlite3_mutex_held(db->mutex) );
  102337. for(iDb=0; iDb<db->nDb; iDb++){
  102338. int openedTransaction = 0; /* True if a transaction is opened */
  102339. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  102340. if( pBt==0 ) continue;
  102341. /* If there is not already a read-only (or read-write) transaction opened
  102342. ** on the b-tree database, open one now. If a transaction is opened, it
  102343. ** will be closed immediately after reading the meta-value. */
  102344. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  102345. rc = sqlite3BtreeBeginTrans(pBt, 0);
  102346. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  102347. db->mallocFailed = 1;
  102348. }
  102349. if( rc!=SQLITE_OK ) return;
  102350. openedTransaction = 1;
  102351. }
  102352. /* Read the schema cookie from the database. If it does not match the
  102353. ** value stored as part of the in-memory schema representation,
  102354. ** set Parse.rc to SQLITE_SCHEMA. */
  102355. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  102356. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102357. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  102358. sqlite3ResetOneSchema(db, iDb);
  102359. pParse->rc = SQLITE_SCHEMA;
  102360. }
  102361. /* Close the transaction, if one was opened. */
  102362. if( openedTransaction ){
  102363. sqlite3BtreeCommit(pBt);
  102364. }
  102365. }
  102366. }
  102367. /*
  102368. ** Convert a schema pointer into the iDb index that indicates
  102369. ** which database file in db->aDb[] the schema refers to.
  102370. **
  102371. ** If the same database is attached more than once, the first
  102372. ** attached database is returned.
  102373. */
  102374. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  102375. int i = -1000000;
  102376. /* If pSchema is NULL, then return -1000000. This happens when code in
  102377. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  102378. ** created by a sub-select). In this case the return value of this
  102379. ** function should never be used.
  102380. **
  102381. ** We return -1000000 instead of the more usual -1 simply because using
  102382. ** -1000000 as the incorrect index into db->aDb[] is much
  102383. ** more likely to cause a segfault than -1 (of course there are assert()
  102384. ** statements too, but it never hurts to play the odds).
  102385. */
  102386. assert( sqlite3_mutex_held(db->mutex) );
  102387. if( pSchema ){
  102388. for(i=0; ALWAYS(i<db->nDb); i++){
  102389. if( db->aDb[i].pSchema==pSchema ){
  102390. break;
  102391. }
  102392. }
  102393. assert( i>=0 && i<db->nDb );
  102394. }
  102395. return i;
  102396. }
  102397. /*
  102398. ** Free all memory allocations in the pParse object
  102399. */
  102400. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  102401. if( pParse ){
  102402. sqlite3 *db = pParse->db;
  102403. sqlite3DbFree(db, pParse->aLabel);
  102404. sqlite3ExprListDelete(db, pParse->pConstExpr);
  102405. }
  102406. }
  102407. /*
  102408. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  102409. */
  102410. static int sqlite3Prepare(
  102411. sqlite3 *db, /* Database handle. */
  102412. const char *zSql, /* UTF-8 encoded SQL statement. */
  102413. int nBytes, /* Length of zSql in bytes. */
  102414. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  102415. Vdbe *pReprepare, /* VM being reprepared */
  102416. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  102417. const char **pzTail /* OUT: End of parsed string */
  102418. ){
  102419. Parse *pParse; /* Parsing context */
  102420. char *zErrMsg = 0; /* Error message */
  102421. int rc = SQLITE_OK; /* Result code */
  102422. int i; /* Loop counter */
  102423. /* Allocate the parsing context */
  102424. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  102425. if( pParse==0 ){
  102426. rc = SQLITE_NOMEM;
  102427. goto end_prepare;
  102428. }
  102429. pParse->pReprepare = pReprepare;
  102430. assert( ppStmt && *ppStmt==0 );
  102431. assert( !db->mallocFailed );
  102432. assert( sqlite3_mutex_held(db->mutex) );
  102433. /* Check to verify that it is possible to get a read lock on all
  102434. ** database schemas. The inability to get a read lock indicates that
  102435. ** some other database connection is holding a write-lock, which in
  102436. ** turn means that the other connection has made uncommitted changes
  102437. ** to the schema.
  102438. **
  102439. ** Were we to proceed and prepare the statement against the uncommitted
  102440. ** schema changes and if those schema changes are subsequently rolled
  102441. ** back and different changes are made in their place, then when this
  102442. ** prepared statement goes to run the schema cookie would fail to detect
  102443. ** the schema change. Disaster would follow.
  102444. **
  102445. ** This thread is currently holding mutexes on all Btrees (because
  102446. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  102447. ** is not possible for another thread to start a new schema change
  102448. ** while this routine is running. Hence, we do not need to hold
  102449. ** locks on the schema, we just need to make sure nobody else is
  102450. ** holding them.
  102451. **
  102452. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  102453. ** but it does *not* override schema lock detection, so this all still
  102454. ** works even if READ_UNCOMMITTED is set.
  102455. */
  102456. for(i=0; i<db->nDb; i++) {
  102457. Btree *pBt = db->aDb[i].pBt;
  102458. if( pBt ){
  102459. assert( sqlite3BtreeHoldsMutex(pBt) );
  102460. rc = sqlite3BtreeSchemaLocked(pBt);
  102461. if( rc ){
  102462. const char *zDb = db->aDb[i].zName;
  102463. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  102464. testcase( db->flags & SQLITE_ReadUncommitted );
  102465. goto end_prepare;
  102466. }
  102467. }
  102468. }
  102469. sqlite3VtabUnlockList(db);
  102470. pParse->db = db;
  102471. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  102472. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  102473. char *zSqlCopy;
  102474. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  102475. testcase( nBytes==mxLen );
  102476. testcase( nBytes==mxLen+1 );
  102477. if( nBytes>mxLen ){
  102478. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  102479. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  102480. goto end_prepare;
  102481. }
  102482. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  102483. if( zSqlCopy ){
  102484. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  102485. sqlite3DbFree(db, zSqlCopy);
  102486. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  102487. }else{
  102488. pParse->zTail = &zSql[nBytes];
  102489. }
  102490. }else{
  102491. sqlite3RunParser(pParse, zSql, &zErrMsg);
  102492. }
  102493. assert( 0==pParse->nQueryLoop );
  102494. if( db->mallocFailed ){
  102495. pParse->rc = SQLITE_NOMEM;
  102496. }
  102497. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  102498. if( pParse->checkSchema ){
  102499. schemaIsValid(pParse);
  102500. }
  102501. if( db->mallocFailed ){
  102502. pParse->rc = SQLITE_NOMEM;
  102503. }
  102504. if( pzTail ){
  102505. *pzTail = pParse->zTail;
  102506. }
  102507. rc = pParse->rc;
  102508. #ifndef SQLITE_OMIT_EXPLAIN
  102509. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  102510. static const char * const azColName[] = {
  102511. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  102512. "selectid", "order", "from", "detail"
  102513. };
  102514. int iFirst, mx;
  102515. if( pParse->explain==2 ){
  102516. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  102517. iFirst = 8;
  102518. mx = 12;
  102519. }else{
  102520. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  102521. iFirst = 0;
  102522. mx = 8;
  102523. }
  102524. for(i=iFirst; i<mx; i++){
  102525. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  102526. azColName[i], SQLITE_STATIC);
  102527. }
  102528. }
  102529. #endif
  102530. if( db->init.busy==0 ){
  102531. Vdbe *pVdbe = pParse->pVdbe;
  102532. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  102533. }
  102534. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  102535. sqlite3VdbeFinalize(pParse->pVdbe);
  102536. assert(!(*ppStmt));
  102537. }else{
  102538. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  102539. }
  102540. if( zErrMsg ){
  102541. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  102542. sqlite3DbFree(db, zErrMsg);
  102543. }else{
  102544. sqlite3Error(db, rc);
  102545. }
  102546. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  102547. while( pParse->pTriggerPrg ){
  102548. TriggerPrg *pT = pParse->pTriggerPrg;
  102549. pParse->pTriggerPrg = pT->pNext;
  102550. sqlite3DbFree(db, pT);
  102551. }
  102552. end_prepare:
  102553. sqlite3ParserReset(pParse);
  102554. sqlite3StackFree(db, pParse);
  102555. rc = sqlite3ApiExit(db, rc);
  102556. assert( (rc&db->errMask)==rc );
  102557. return rc;
  102558. }
  102559. static int sqlite3LockAndPrepare(
  102560. sqlite3 *db, /* Database handle. */
  102561. const char *zSql, /* UTF-8 encoded SQL statement. */
  102562. int nBytes, /* Length of zSql in bytes. */
  102563. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  102564. Vdbe *pOld, /* VM being reprepared */
  102565. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  102566. const char **pzTail /* OUT: End of parsed string */
  102567. ){
  102568. int rc;
  102569. #ifdef SQLITE_ENABLE_API_ARMOR
  102570. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  102571. #endif
  102572. *ppStmt = 0;
  102573. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  102574. return SQLITE_MISUSE_BKPT;
  102575. }
  102576. sqlite3_mutex_enter(db->mutex);
  102577. sqlite3BtreeEnterAll(db);
  102578. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  102579. if( rc==SQLITE_SCHEMA ){
  102580. sqlite3_finalize(*ppStmt);
  102581. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  102582. }
  102583. sqlite3BtreeLeaveAll(db);
  102584. sqlite3_mutex_leave(db->mutex);
  102585. assert( rc==SQLITE_OK || *ppStmt==0 );
  102586. return rc;
  102587. }
  102588. /*
  102589. ** Rerun the compilation of a statement after a schema change.
  102590. **
  102591. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  102592. ** if the statement cannot be recompiled because another connection has
  102593. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  102594. ** occurs, return SQLITE_SCHEMA.
  102595. */
  102596. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  102597. int rc;
  102598. sqlite3_stmt *pNew;
  102599. const char *zSql;
  102600. sqlite3 *db;
  102601. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  102602. zSql = sqlite3_sql((sqlite3_stmt *)p);
  102603. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  102604. db = sqlite3VdbeDb(p);
  102605. assert( sqlite3_mutex_held(db->mutex) );
  102606. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  102607. if( rc ){
  102608. if( rc==SQLITE_NOMEM ){
  102609. db->mallocFailed = 1;
  102610. }
  102611. assert( pNew==0 );
  102612. return rc;
  102613. }else{
  102614. assert( pNew!=0 );
  102615. }
  102616. sqlite3VdbeSwap((Vdbe*)pNew, p);
  102617. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  102618. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  102619. sqlite3VdbeFinalize((Vdbe*)pNew);
  102620. return SQLITE_OK;
  102621. }
  102622. /*
  102623. ** Two versions of the official API. Legacy and new use. In the legacy
  102624. ** version, the original SQL text is not saved in the prepared statement
  102625. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  102626. ** sqlite3_step(). In the new version, the original SQL text is retained
  102627. ** and the statement is automatically recompiled if an schema change
  102628. ** occurs.
  102629. */
  102630. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  102631. sqlite3 *db, /* Database handle. */
  102632. const char *zSql, /* UTF-8 encoded SQL statement. */
  102633. int nBytes, /* Length of zSql in bytes. */
  102634. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  102635. const char **pzTail /* OUT: End of parsed string */
  102636. ){
  102637. int rc;
  102638. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  102639. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  102640. return rc;
  102641. }
  102642. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  102643. sqlite3 *db, /* Database handle. */
  102644. const char *zSql, /* UTF-8 encoded SQL statement. */
  102645. int nBytes, /* Length of zSql in bytes. */
  102646. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  102647. const char **pzTail /* OUT: End of parsed string */
  102648. ){
  102649. int rc;
  102650. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  102651. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  102652. return rc;
  102653. }
  102654. #ifndef SQLITE_OMIT_UTF16
  102655. /*
  102656. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  102657. */
  102658. static int sqlite3Prepare16(
  102659. sqlite3 *db, /* Database handle. */
  102660. const void *zSql, /* UTF-16 encoded SQL statement. */
  102661. int nBytes, /* Length of zSql in bytes. */
  102662. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  102663. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  102664. const void **pzTail /* OUT: End of parsed string */
  102665. ){
  102666. /* This function currently works by first transforming the UTF-16
  102667. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  102668. ** tricky bit is figuring out the pointer to return in *pzTail.
  102669. */
  102670. char *zSql8;
  102671. const char *zTail8 = 0;
  102672. int rc = SQLITE_OK;
  102673. #ifdef SQLITE_ENABLE_API_ARMOR
  102674. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  102675. #endif
  102676. *ppStmt = 0;
  102677. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  102678. return SQLITE_MISUSE_BKPT;
  102679. }
  102680. if( nBytes>=0 ){
  102681. int sz;
  102682. const char *z = (const char*)zSql;
  102683. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  102684. nBytes = sz;
  102685. }
  102686. sqlite3_mutex_enter(db->mutex);
  102687. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  102688. if( zSql8 ){
  102689. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  102690. }
  102691. if( zTail8 && pzTail ){
  102692. /* If sqlite3_prepare returns a tail pointer, we calculate the
  102693. ** equivalent pointer into the UTF-16 string by counting the unicode
  102694. ** characters between zSql8 and zTail8, and then returning a pointer
  102695. ** the same number of characters into the UTF-16 string.
  102696. */
  102697. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  102698. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  102699. }
  102700. sqlite3DbFree(db, zSql8);
  102701. rc = sqlite3ApiExit(db, rc);
  102702. sqlite3_mutex_leave(db->mutex);
  102703. return rc;
  102704. }
  102705. /*
  102706. ** Two versions of the official API. Legacy and new use. In the legacy
  102707. ** version, the original SQL text is not saved in the prepared statement
  102708. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  102709. ** sqlite3_step(). In the new version, the original SQL text is retained
  102710. ** and the statement is automatically recompiled if an schema change
  102711. ** occurs.
  102712. */
  102713. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  102714. sqlite3 *db, /* Database handle. */
  102715. const void *zSql, /* UTF-16 encoded SQL statement. */
  102716. int nBytes, /* Length of zSql in bytes. */
  102717. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  102718. const void **pzTail /* OUT: End of parsed string */
  102719. ){
  102720. int rc;
  102721. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  102722. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  102723. return rc;
  102724. }
  102725. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  102726. sqlite3 *db, /* Database handle. */
  102727. const void *zSql, /* UTF-16 encoded SQL statement. */
  102728. int nBytes, /* Length of zSql in bytes. */
  102729. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  102730. const void **pzTail /* OUT: End of parsed string */
  102731. ){
  102732. int rc;
  102733. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  102734. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  102735. return rc;
  102736. }
  102737. #endif /* SQLITE_OMIT_UTF16 */
  102738. /************** End of prepare.c *********************************************/
  102739. /************** Begin file select.c ******************************************/
  102740. /*
  102741. ** 2001 September 15
  102742. **
  102743. ** The author disclaims copyright to this source code. In place of
  102744. ** a legal notice, here is a blessing:
  102745. **
  102746. ** May you do good and not evil.
  102747. ** May you find forgiveness for yourself and forgive others.
  102748. ** May you share freely, never taking more than you give.
  102749. **
  102750. *************************************************************************
  102751. ** This file contains C code routines that are called by the parser
  102752. ** to handle SELECT statements in SQLite.
  102753. */
  102754. /* #include "sqliteInt.h" */
  102755. /*
  102756. ** Trace output macros
  102757. */
  102758. #if SELECTTRACE_ENABLED
  102759. /***/ int sqlite3SelectTrace = 0;
  102760. # define SELECTTRACE(K,P,S,X) \
  102761. if(sqlite3SelectTrace&(K)) \
  102762. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
  102763. (S)->zSelName,(S)),\
  102764. sqlite3DebugPrintf X
  102765. #else
  102766. # define SELECTTRACE(K,P,S,X)
  102767. #endif
  102768. /*
  102769. ** An instance of the following object is used to record information about
  102770. ** how to process the DISTINCT keyword, to simplify passing that information
  102771. ** into the selectInnerLoop() routine.
  102772. */
  102773. typedef struct DistinctCtx DistinctCtx;
  102774. struct DistinctCtx {
  102775. u8 isTnct; /* True if the DISTINCT keyword is present */
  102776. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  102777. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  102778. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  102779. };
  102780. /*
  102781. ** An instance of the following object is used to record information about
  102782. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  102783. */
  102784. typedef struct SortCtx SortCtx;
  102785. struct SortCtx {
  102786. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  102787. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  102788. int iECursor; /* Cursor number for the sorter */
  102789. int regReturn; /* Register holding block-output return address */
  102790. int labelBkOut; /* Start label for the block-output subroutine */
  102791. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  102792. int labelDone; /* Jump here when done, ex: LIMIT reached */
  102793. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  102794. };
  102795. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  102796. /*
  102797. ** Delete all the content of a Select structure. Deallocate the structure
  102798. ** itself only if bFree is true.
  102799. */
  102800. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  102801. while( p ){
  102802. Select *pPrior = p->pPrior;
  102803. sqlite3ExprListDelete(db, p->pEList);
  102804. sqlite3SrcListDelete(db, p->pSrc);
  102805. sqlite3ExprDelete(db, p->pWhere);
  102806. sqlite3ExprListDelete(db, p->pGroupBy);
  102807. sqlite3ExprDelete(db, p->pHaving);
  102808. sqlite3ExprListDelete(db, p->pOrderBy);
  102809. sqlite3ExprDelete(db, p->pLimit);
  102810. sqlite3ExprDelete(db, p->pOffset);
  102811. sqlite3WithDelete(db, p->pWith);
  102812. if( bFree ) sqlite3DbFree(db, p);
  102813. p = pPrior;
  102814. bFree = 1;
  102815. }
  102816. }
  102817. /*
  102818. ** Initialize a SelectDest structure.
  102819. */
  102820. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  102821. pDest->eDest = (u8)eDest;
  102822. pDest->iSDParm = iParm;
  102823. pDest->affSdst = 0;
  102824. pDest->iSdst = 0;
  102825. pDest->nSdst = 0;
  102826. }
  102827. /*
  102828. ** Allocate a new Select structure and return a pointer to that
  102829. ** structure.
  102830. */
  102831. SQLITE_PRIVATE Select *sqlite3SelectNew(
  102832. Parse *pParse, /* Parsing context */
  102833. ExprList *pEList, /* which columns to include in the result */
  102834. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  102835. Expr *pWhere, /* the WHERE clause */
  102836. ExprList *pGroupBy, /* the GROUP BY clause */
  102837. Expr *pHaving, /* the HAVING clause */
  102838. ExprList *pOrderBy, /* the ORDER BY clause */
  102839. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  102840. Expr *pLimit, /* LIMIT value. NULL means not used */
  102841. Expr *pOffset /* OFFSET value. NULL means no offset */
  102842. ){
  102843. Select *pNew;
  102844. Select standin;
  102845. sqlite3 *db = pParse->db;
  102846. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  102847. if( pNew==0 ){
  102848. assert( db->mallocFailed );
  102849. pNew = &standin;
  102850. memset(pNew, 0, sizeof(*pNew));
  102851. }
  102852. if( pEList==0 ){
  102853. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
  102854. }
  102855. pNew->pEList = pEList;
  102856. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  102857. pNew->pSrc = pSrc;
  102858. pNew->pWhere = pWhere;
  102859. pNew->pGroupBy = pGroupBy;
  102860. pNew->pHaving = pHaving;
  102861. pNew->pOrderBy = pOrderBy;
  102862. pNew->selFlags = selFlags;
  102863. pNew->op = TK_SELECT;
  102864. pNew->pLimit = pLimit;
  102865. pNew->pOffset = pOffset;
  102866. assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
  102867. pNew->addrOpenEphm[0] = -1;
  102868. pNew->addrOpenEphm[1] = -1;
  102869. if( db->mallocFailed ) {
  102870. clearSelect(db, pNew, pNew!=&standin);
  102871. pNew = 0;
  102872. }else{
  102873. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  102874. }
  102875. assert( pNew!=&standin );
  102876. return pNew;
  102877. }
  102878. #if SELECTTRACE_ENABLED
  102879. /*
  102880. ** Set the name of a Select object
  102881. */
  102882. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  102883. if( p && zName ){
  102884. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  102885. }
  102886. }
  102887. #endif
  102888. /*
  102889. ** Delete the given Select structure and all of its substructures.
  102890. */
  102891. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  102892. clearSelect(db, p, 1);
  102893. }
  102894. /*
  102895. ** Return a pointer to the right-most SELECT statement in a compound.
  102896. */
  102897. static Select *findRightmost(Select *p){
  102898. while( p->pNext ) p = p->pNext;
  102899. return p;
  102900. }
  102901. /*
  102902. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  102903. ** type of join. Return an integer constant that expresses that type
  102904. ** in terms of the following bit values:
  102905. **
  102906. ** JT_INNER
  102907. ** JT_CROSS
  102908. ** JT_OUTER
  102909. ** JT_NATURAL
  102910. ** JT_LEFT
  102911. ** JT_RIGHT
  102912. **
  102913. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  102914. **
  102915. ** If an illegal or unsupported join type is seen, then still return
  102916. ** a join type, but put an error in the pParse structure.
  102917. */
  102918. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  102919. int jointype = 0;
  102920. Token *apAll[3];
  102921. Token *p;
  102922. /* 0123456789 123456789 123456789 123 */
  102923. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  102924. static const struct {
  102925. u8 i; /* Beginning of keyword text in zKeyText[] */
  102926. u8 nChar; /* Length of the keyword in characters */
  102927. u8 code; /* Join type mask */
  102928. } aKeyword[] = {
  102929. /* natural */ { 0, 7, JT_NATURAL },
  102930. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  102931. /* outer */ { 10, 5, JT_OUTER },
  102932. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  102933. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  102934. /* inner */ { 23, 5, JT_INNER },
  102935. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  102936. };
  102937. int i, j;
  102938. apAll[0] = pA;
  102939. apAll[1] = pB;
  102940. apAll[2] = pC;
  102941. for(i=0; i<3 && apAll[i]; i++){
  102942. p = apAll[i];
  102943. for(j=0; j<ArraySize(aKeyword); j++){
  102944. if( p->n==aKeyword[j].nChar
  102945. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  102946. jointype |= aKeyword[j].code;
  102947. break;
  102948. }
  102949. }
  102950. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  102951. if( j>=ArraySize(aKeyword) ){
  102952. jointype |= JT_ERROR;
  102953. break;
  102954. }
  102955. }
  102956. if(
  102957. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  102958. (jointype & JT_ERROR)!=0
  102959. ){
  102960. const char *zSp = " ";
  102961. assert( pB!=0 );
  102962. if( pC==0 ){ zSp++; }
  102963. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  102964. "%T %T%s%T", pA, pB, zSp, pC);
  102965. jointype = JT_INNER;
  102966. }else if( (jointype & JT_OUTER)!=0
  102967. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  102968. sqlite3ErrorMsg(pParse,
  102969. "RIGHT and FULL OUTER JOINs are not currently supported");
  102970. jointype = JT_INNER;
  102971. }
  102972. return jointype;
  102973. }
  102974. /*
  102975. ** Return the index of a column in a table. Return -1 if the column
  102976. ** is not contained in the table.
  102977. */
  102978. static int columnIndex(Table *pTab, const char *zCol){
  102979. int i;
  102980. for(i=0; i<pTab->nCol; i++){
  102981. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  102982. }
  102983. return -1;
  102984. }
  102985. /*
  102986. ** Search the first N tables in pSrc, from left to right, looking for a
  102987. ** table that has a column named zCol.
  102988. **
  102989. ** When found, set *piTab and *piCol to the table index and column index
  102990. ** of the matching column and return TRUE.
  102991. **
  102992. ** If not found, return FALSE.
  102993. */
  102994. static int tableAndColumnIndex(
  102995. SrcList *pSrc, /* Array of tables to search */
  102996. int N, /* Number of tables in pSrc->a[] to search */
  102997. const char *zCol, /* Name of the column we are looking for */
  102998. int *piTab, /* Write index of pSrc->a[] here */
  102999. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  103000. ){
  103001. int i; /* For looping over tables in pSrc */
  103002. int iCol; /* Index of column matching zCol */
  103003. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  103004. for(i=0; i<N; i++){
  103005. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  103006. if( iCol>=0 ){
  103007. if( piTab ){
  103008. *piTab = i;
  103009. *piCol = iCol;
  103010. }
  103011. return 1;
  103012. }
  103013. }
  103014. return 0;
  103015. }
  103016. /*
  103017. ** This function is used to add terms implied by JOIN syntax to the
  103018. ** WHERE clause expression of a SELECT statement. The new term, which
  103019. ** is ANDed with the existing WHERE clause, is of the form:
  103020. **
  103021. ** (tab1.col1 = tab2.col2)
  103022. **
  103023. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  103024. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  103025. ** column iColRight of tab2.
  103026. */
  103027. static void addWhereTerm(
  103028. Parse *pParse, /* Parsing context */
  103029. SrcList *pSrc, /* List of tables in FROM clause */
  103030. int iLeft, /* Index of first table to join in pSrc */
  103031. int iColLeft, /* Index of column in first table */
  103032. int iRight, /* Index of second table in pSrc */
  103033. int iColRight, /* Index of column in second table */
  103034. int isOuterJoin, /* True if this is an OUTER join */
  103035. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  103036. ){
  103037. sqlite3 *db = pParse->db;
  103038. Expr *pE1;
  103039. Expr *pE2;
  103040. Expr *pEq;
  103041. assert( iLeft<iRight );
  103042. assert( pSrc->nSrc>iRight );
  103043. assert( pSrc->a[iLeft].pTab );
  103044. assert( pSrc->a[iRight].pTab );
  103045. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  103046. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  103047. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  103048. if( pEq && isOuterJoin ){
  103049. ExprSetProperty(pEq, EP_FromJoin);
  103050. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  103051. ExprSetVVAProperty(pEq, EP_NoReduce);
  103052. pEq->iRightJoinTable = (i16)pE2->iTable;
  103053. }
  103054. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  103055. }
  103056. /*
  103057. ** Set the EP_FromJoin property on all terms of the given expression.
  103058. ** And set the Expr.iRightJoinTable to iTable for every term in the
  103059. ** expression.
  103060. **
  103061. ** The EP_FromJoin property is used on terms of an expression to tell
  103062. ** the LEFT OUTER JOIN processing logic that this term is part of the
  103063. ** join restriction specified in the ON or USING clause and not a part
  103064. ** of the more general WHERE clause. These terms are moved over to the
  103065. ** WHERE clause during join processing but we need to remember that they
  103066. ** originated in the ON or USING clause.
  103067. **
  103068. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  103069. ** expression depends on table iRightJoinTable even if that table is not
  103070. ** explicitly mentioned in the expression. That information is needed
  103071. ** for cases like this:
  103072. **
  103073. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  103074. **
  103075. ** The where clause needs to defer the handling of the t1.x=5
  103076. ** term until after the t2 loop of the join. In that way, a
  103077. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  103078. ** defer the handling of t1.x=5, it will be processed immediately
  103079. ** after the t1 loop and rows with t1.x!=5 will never appear in
  103080. ** the output, which is incorrect.
  103081. */
  103082. static void setJoinExpr(Expr *p, int iTable){
  103083. while( p ){
  103084. ExprSetProperty(p, EP_FromJoin);
  103085. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  103086. ExprSetVVAProperty(p, EP_NoReduce);
  103087. p->iRightJoinTable = (i16)iTable;
  103088. if( p->op==TK_FUNCTION && p->x.pList ){
  103089. int i;
  103090. for(i=0; i<p->x.pList->nExpr; i++){
  103091. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  103092. }
  103093. }
  103094. setJoinExpr(p->pLeft, iTable);
  103095. p = p->pRight;
  103096. }
  103097. }
  103098. /*
  103099. ** This routine processes the join information for a SELECT statement.
  103100. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  103101. ** NATURAL joins also create extra WHERE clause terms.
  103102. **
  103103. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  103104. ** The left most table is the first entry in Select.pSrc. The right-most
  103105. ** table is the last entry. The join operator is held in the entry to
  103106. ** the left. Thus entry 0 contains the join operator for the join between
  103107. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  103108. ** also attached to the left entry.
  103109. **
  103110. ** This routine returns the number of errors encountered.
  103111. */
  103112. static int sqliteProcessJoin(Parse *pParse, Select *p){
  103113. SrcList *pSrc; /* All tables in the FROM clause */
  103114. int i, j; /* Loop counters */
  103115. struct SrcList_item *pLeft; /* Left table being joined */
  103116. struct SrcList_item *pRight; /* Right table being joined */
  103117. pSrc = p->pSrc;
  103118. pLeft = &pSrc->a[0];
  103119. pRight = &pLeft[1];
  103120. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  103121. Table *pLeftTab = pLeft->pTab;
  103122. Table *pRightTab = pRight->pTab;
  103123. int isOuter;
  103124. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  103125. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  103126. /* When the NATURAL keyword is present, add WHERE clause terms for
  103127. ** every column that the two tables have in common.
  103128. */
  103129. if( pRight->fg.jointype & JT_NATURAL ){
  103130. if( pRight->pOn || pRight->pUsing ){
  103131. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  103132. "an ON or USING clause", 0);
  103133. return 1;
  103134. }
  103135. for(j=0; j<pRightTab->nCol; j++){
  103136. char *zName; /* Name of column in the right table */
  103137. int iLeft; /* Matching left table */
  103138. int iLeftCol; /* Matching column in the left table */
  103139. zName = pRightTab->aCol[j].zName;
  103140. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  103141. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  103142. isOuter, &p->pWhere);
  103143. }
  103144. }
  103145. }
  103146. /* Disallow both ON and USING clauses in the same join
  103147. */
  103148. if( pRight->pOn && pRight->pUsing ){
  103149. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  103150. "clauses in the same join");
  103151. return 1;
  103152. }
  103153. /* Add the ON clause to the end of the WHERE clause, connected by
  103154. ** an AND operator.
  103155. */
  103156. if( pRight->pOn ){
  103157. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  103158. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  103159. pRight->pOn = 0;
  103160. }
  103161. /* Create extra terms on the WHERE clause for each column named
  103162. ** in the USING clause. Example: If the two tables to be joined are
  103163. ** A and B and the USING clause names X, Y, and Z, then add this
  103164. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  103165. ** Report an error if any column mentioned in the USING clause is
  103166. ** not contained in both tables to be joined.
  103167. */
  103168. if( pRight->pUsing ){
  103169. IdList *pList = pRight->pUsing;
  103170. for(j=0; j<pList->nId; j++){
  103171. char *zName; /* Name of the term in the USING clause */
  103172. int iLeft; /* Table on the left with matching column name */
  103173. int iLeftCol; /* Column number of matching column on the left */
  103174. int iRightCol; /* Column number of matching column on the right */
  103175. zName = pList->a[j].zName;
  103176. iRightCol = columnIndex(pRightTab, zName);
  103177. if( iRightCol<0
  103178. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  103179. ){
  103180. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  103181. "not present in both tables", zName);
  103182. return 1;
  103183. }
  103184. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  103185. isOuter, &p->pWhere);
  103186. }
  103187. }
  103188. }
  103189. return 0;
  103190. }
  103191. /* Forward reference */
  103192. static KeyInfo *keyInfoFromExprList(
  103193. Parse *pParse, /* Parsing context */
  103194. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  103195. int iStart, /* Begin with this column of pList */
  103196. int nExtra /* Add this many extra columns to the end */
  103197. );
  103198. /*
  103199. ** Generate code that will push the record in registers regData
  103200. ** through regData+nData-1 onto the sorter.
  103201. */
  103202. static void pushOntoSorter(
  103203. Parse *pParse, /* Parser context */
  103204. SortCtx *pSort, /* Information about the ORDER BY clause */
  103205. Select *pSelect, /* The whole SELECT statement */
  103206. int regData, /* First register holding data to be sorted */
  103207. int regOrigData, /* First register holding data before packing */
  103208. int nData, /* Number of elements in the data array */
  103209. int nPrefixReg /* No. of reg prior to regData available for use */
  103210. ){
  103211. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  103212. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  103213. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  103214. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  103215. int regBase; /* Regs for sorter record */
  103216. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  103217. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  103218. int op; /* Opcode to add sorter record to sorter */
  103219. int iLimit; /* LIMIT counter */
  103220. assert( bSeq==0 || bSeq==1 );
  103221. assert( nData==1 || regData==regOrigData );
  103222. if( nPrefixReg ){
  103223. assert( nPrefixReg==nExpr+bSeq );
  103224. regBase = regData - nExpr - bSeq;
  103225. }else{
  103226. regBase = pParse->nMem + 1;
  103227. pParse->nMem += nBase;
  103228. }
  103229. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  103230. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  103231. pSort->labelDone = sqlite3VdbeMakeLabel(v);
  103232. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  103233. SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
  103234. if( bSeq ){
  103235. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  103236. }
  103237. if( nPrefixReg==0 ){
  103238. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  103239. }
  103240. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  103241. if( nOBSat>0 ){
  103242. int regPrevKey; /* The first nOBSat columns of the previous row */
  103243. int addrFirst; /* Address of the OP_IfNot opcode */
  103244. int addrJmp; /* Address of the OP_Jump opcode */
  103245. VdbeOp *pOp; /* Opcode that opens the sorter */
  103246. int nKey; /* Number of sorting key columns, including OP_Sequence */
  103247. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  103248. regPrevKey = pParse->nMem+1;
  103249. pParse->nMem += pSort->nOBSat;
  103250. nKey = nExpr - pSort->nOBSat + bSeq;
  103251. if( bSeq ){
  103252. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  103253. }else{
  103254. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  103255. }
  103256. VdbeCoverage(v);
  103257. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  103258. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  103259. if( pParse->db->mallocFailed ) return;
  103260. pOp->p2 = nKey + nData;
  103261. pKI = pOp->p4.pKeyInfo;
  103262. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  103263. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  103264. testcase( pKI->nXField>2 );
  103265. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  103266. pKI->nXField-1);
  103267. addrJmp = sqlite3VdbeCurrentAddr(v);
  103268. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  103269. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  103270. pSort->regReturn = ++pParse->nMem;
  103271. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  103272. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  103273. if( iLimit ){
  103274. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  103275. VdbeCoverage(v);
  103276. }
  103277. sqlite3VdbeJumpHere(v, addrFirst);
  103278. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  103279. sqlite3VdbeJumpHere(v, addrJmp);
  103280. }
  103281. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  103282. op = OP_SorterInsert;
  103283. }else{
  103284. op = OP_IdxInsert;
  103285. }
  103286. sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
  103287. if( iLimit ){
  103288. int addr;
  103289. addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
  103290. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  103291. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  103292. sqlite3VdbeJumpHere(v, addr);
  103293. }
  103294. }
  103295. /*
  103296. ** Add code to implement the OFFSET
  103297. */
  103298. static void codeOffset(
  103299. Vdbe *v, /* Generate code into this VM */
  103300. int iOffset, /* Register holding the offset counter */
  103301. int iContinue /* Jump here to skip the current record */
  103302. ){
  103303. if( iOffset>0 ){
  103304. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  103305. VdbeComment((v, "OFFSET"));
  103306. }
  103307. }
  103308. /*
  103309. ** Add code that will check to make sure the N registers starting at iMem
  103310. ** form a distinct entry. iTab is a sorting index that holds previously
  103311. ** seen combinations of the N values. A new entry is made in iTab
  103312. ** if the current N values are new.
  103313. **
  103314. ** A jump to addrRepeat is made and the N+1 values are popped from the
  103315. ** stack if the top N elements are not distinct.
  103316. */
  103317. static void codeDistinct(
  103318. Parse *pParse, /* Parsing and code generating context */
  103319. int iTab, /* A sorting index used to test for distinctness */
  103320. int addrRepeat, /* Jump to here if not distinct */
  103321. int N, /* Number of elements */
  103322. int iMem /* First element */
  103323. ){
  103324. Vdbe *v;
  103325. int r1;
  103326. v = pParse->pVdbe;
  103327. r1 = sqlite3GetTempReg(pParse);
  103328. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  103329. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  103330. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  103331. sqlite3ReleaseTempReg(pParse, r1);
  103332. }
  103333. #ifndef SQLITE_OMIT_SUBQUERY
  103334. /*
  103335. ** Generate an error message when a SELECT is used within a subexpression
  103336. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  103337. ** column. We do this in a subroutine because the error used to occur
  103338. ** in multiple places. (The error only occurs in one place now, but we
  103339. ** retain the subroutine to minimize code disruption.)
  103340. */
  103341. static int checkForMultiColumnSelectError(
  103342. Parse *pParse, /* Parse context. */
  103343. SelectDest *pDest, /* Destination of SELECT results */
  103344. int nExpr /* Number of result columns returned by SELECT */
  103345. ){
  103346. int eDest = pDest->eDest;
  103347. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  103348. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  103349. "a SELECT that is part of an expression");
  103350. return 1;
  103351. }else{
  103352. return 0;
  103353. }
  103354. }
  103355. #endif
  103356. /*
  103357. ** This routine generates the code for the inside of the inner loop
  103358. ** of a SELECT.
  103359. **
  103360. ** If srcTab is negative, then the pEList expressions
  103361. ** are evaluated in order to get the data for this row. If srcTab is
  103362. ** zero or more, then data is pulled from srcTab and pEList is used only
  103363. ** to get number columns and the datatype for each column.
  103364. */
  103365. static void selectInnerLoop(
  103366. Parse *pParse, /* The parser context */
  103367. Select *p, /* The complete select statement being coded */
  103368. ExprList *pEList, /* List of values being extracted */
  103369. int srcTab, /* Pull data from this table */
  103370. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  103371. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  103372. SelectDest *pDest, /* How to dispose of the results */
  103373. int iContinue, /* Jump here to continue with next row */
  103374. int iBreak /* Jump here to break out of the inner loop */
  103375. ){
  103376. Vdbe *v = pParse->pVdbe;
  103377. int i;
  103378. int hasDistinct; /* True if the DISTINCT keyword is present */
  103379. int regResult; /* Start of memory holding result set */
  103380. int eDest = pDest->eDest; /* How to dispose of results */
  103381. int iParm = pDest->iSDParm; /* First argument to disposal method */
  103382. int nResultCol; /* Number of result columns */
  103383. int nPrefixReg = 0; /* Number of extra registers before regResult */
  103384. assert( v );
  103385. assert( pEList!=0 );
  103386. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  103387. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  103388. if( pSort==0 && !hasDistinct ){
  103389. assert( iContinue!=0 );
  103390. codeOffset(v, p->iOffset, iContinue);
  103391. }
  103392. /* Pull the requested columns.
  103393. */
  103394. nResultCol = pEList->nExpr;
  103395. if( pDest->iSdst==0 ){
  103396. if( pSort ){
  103397. nPrefixReg = pSort->pOrderBy->nExpr;
  103398. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  103399. pParse->nMem += nPrefixReg;
  103400. }
  103401. pDest->iSdst = pParse->nMem+1;
  103402. pParse->nMem += nResultCol;
  103403. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  103404. /* This is an error condition that can result, for example, when a SELECT
  103405. ** on the right-hand side of an INSERT contains more result columns than
  103406. ** there are columns in the table on the left. The error will be caught
  103407. ** and reported later. But we need to make sure enough memory is allocated
  103408. ** to avoid other spurious errors in the meantime. */
  103409. pParse->nMem += nResultCol;
  103410. }
  103411. pDest->nSdst = nResultCol;
  103412. regResult = pDest->iSdst;
  103413. if( srcTab>=0 ){
  103414. for(i=0; i<nResultCol; i++){
  103415. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  103416. VdbeComment((v, "%s", pEList->a[i].zName));
  103417. }
  103418. }else if( eDest!=SRT_Exists ){
  103419. /* If the destination is an EXISTS(...) expression, the actual
  103420. ** values returned by the SELECT are not required.
  103421. */
  103422. u8 ecelFlags;
  103423. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  103424. ecelFlags = SQLITE_ECEL_DUP;
  103425. }else{
  103426. ecelFlags = 0;
  103427. }
  103428. sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
  103429. }
  103430. /* If the DISTINCT keyword was present on the SELECT statement
  103431. ** and this row has been seen before, then do not make this row
  103432. ** part of the result.
  103433. */
  103434. if( hasDistinct ){
  103435. switch( pDistinct->eTnctType ){
  103436. case WHERE_DISTINCT_ORDERED: {
  103437. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  103438. int iJump; /* Jump destination */
  103439. int regPrev; /* Previous row content */
  103440. /* Allocate space for the previous row */
  103441. regPrev = pParse->nMem+1;
  103442. pParse->nMem += nResultCol;
  103443. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  103444. ** sets the MEM_Cleared bit on the first register of the
  103445. ** previous value. This will cause the OP_Ne below to always
  103446. ** fail on the first iteration of the loop even if the first
  103447. ** row is all NULLs.
  103448. */
  103449. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  103450. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  103451. pOp->opcode = OP_Null;
  103452. pOp->p1 = 1;
  103453. pOp->p2 = regPrev;
  103454. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  103455. for(i=0; i<nResultCol; i++){
  103456. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  103457. if( i<nResultCol-1 ){
  103458. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  103459. VdbeCoverage(v);
  103460. }else{
  103461. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  103462. VdbeCoverage(v);
  103463. }
  103464. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  103465. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  103466. }
  103467. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  103468. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  103469. break;
  103470. }
  103471. case WHERE_DISTINCT_UNIQUE: {
  103472. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  103473. break;
  103474. }
  103475. default: {
  103476. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  103477. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  103478. regResult);
  103479. break;
  103480. }
  103481. }
  103482. if( pSort==0 ){
  103483. codeOffset(v, p->iOffset, iContinue);
  103484. }
  103485. }
  103486. switch( eDest ){
  103487. /* In this mode, write each query result to the key of the temporary
  103488. ** table iParm.
  103489. */
  103490. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  103491. case SRT_Union: {
  103492. int r1;
  103493. r1 = sqlite3GetTempReg(pParse);
  103494. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  103495. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  103496. sqlite3ReleaseTempReg(pParse, r1);
  103497. break;
  103498. }
  103499. /* Construct a record from the query result, but instead of
  103500. ** saving that record, use it as a key to delete elements from
  103501. ** the temporary table iParm.
  103502. */
  103503. case SRT_Except: {
  103504. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  103505. break;
  103506. }
  103507. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  103508. /* Store the result as data using a unique key.
  103509. */
  103510. case SRT_Fifo:
  103511. case SRT_DistFifo:
  103512. case SRT_Table:
  103513. case SRT_EphemTab: {
  103514. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  103515. testcase( eDest==SRT_Table );
  103516. testcase( eDest==SRT_EphemTab );
  103517. testcase( eDest==SRT_Fifo );
  103518. testcase( eDest==SRT_DistFifo );
  103519. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  103520. #ifndef SQLITE_OMIT_CTE
  103521. if( eDest==SRT_DistFifo ){
  103522. /* If the destination is DistFifo, then cursor (iParm+1) is open
  103523. ** on an ephemeral index. If the current row is already present
  103524. ** in the index, do not write it to the output. If not, add the
  103525. ** current row to the index and proceed with writing it to the
  103526. ** output table as well. */
  103527. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  103528. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  103529. VdbeCoverage(v);
  103530. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
  103531. assert( pSort==0 );
  103532. }
  103533. #endif
  103534. if( pSort ){
  103535. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
  103536. }else{
  103537. int r2 = sqlite3GetTempReg(pParse);
  103538. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  103539. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  103540. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  103541. sqlite3ReleaseTempReg(pParse, r2);
  103542. }
  103543. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  103544. break;
  103545. }
  103546. #ifndef SQLITE_OMIT_SUBQUERY
  103547. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  103548. ** then there should be a single item on the stack. Write this
  103549. ** item into the set table with bogus data.
  103550. */
  103551. case SRT_Set: {
  103552. assert( nResultCol==1 );
  103553. pDest->affSdst =
  103554. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  103555. if( pSort ){
  103556. /* At first glance you would think we could optimize out the
  103557. ** ORDER BY in this case since the order of entries in the set
  103558. ** does not matter. But there might be a LIMIT clause, in which
  103559. ** case the order does matter */
  103560. pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
  103561. }else{
  103562. int r1 = sqlite3GetTempReg(pParse);
  103563. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  103564. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  103565. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  103566. sqlite3ReleaseTempReg(pParse, r1);
  103567. }
  103568. break;
  103569. }
  103570. /* If any row exist in the result set, record that fact and abort.
  103571. */
  103572. case SRT_Exists: {
  103573. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  103574. /* The LIMIT clause will terminate the loop for us */
  103575. break;
  103576. }
  103577. /* If this is a scalar select that is part of an expression, then
  103578. ** store the results in the appropriate memory cell and break out
  103579. ** of the scan loop.
  103580. */
  103581. case SRT_Mem: {
  103582. assert( nResultCol==1 );
  103583. if( pSort ){
  103584. pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
  103585. }else{
  103586. assert( regResult==iParm );
  103587. /* The LIMIT clause will jump out of the loop for us */
  103588. }
  103589. break;
  103590. }
  103591. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  103592. case SRT_Coroutine: /* Send data to a co-routine */
  103593. case SRT_Output: { /* Return the results */
  103594. testcase( eDest==SRT_Coroutine );
  103595. testcase( eDest==SRT_Output );
  103596. if( pSort ){
  103597. pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
  103598. nPrefixReg);
  103599. }else if( eDest==SRT_Coroutine ){
  103600. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  103601. }else{
  103602. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  103603. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  103604. }
  103605. break;
  103606. }
  103607. #ifndef SQLITE_OMIT_CTE
  103608. /* Write the results into a priority queue that is order according to
  103609. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  103610. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  103611. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  103612. ** final OP_Sequence column. The last column is the record as a blob.
  103613. */
  103614. case SRT_DistQueue:
  103615. case SRT_Queue: {
  103616. int nKey;
  103617. int r1, r2, r3;
  103618. int addrTest = 0;
  103619. ExprList *pSO;
  103620. pSO = pDest->pOrderBy;
  103621. assert( pSO );
  103622. nKey = pSO->nExpr;
  103623. r1 = sqlite3GetTempReg(pParse);
  103624. r2 = sqlite3GetTempRange(pParse, nKey+2);
  103625. r3 = r2+nKey+1;
  103626. if( eDest==SRT_DistQueue ){
  103627. /* If the destination is DistQueue, then cursor (iParm+1) is open
  103628. ** on a second ephemeral index that holds all values every previously
  103629. ** added to the queue. */
  103630. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  103631. regResult, nResultCol);
  103632. VdbeCoverage(v);
  103633. }
  103634. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  103635. if( eDest==SRT_DistQueue ){
  103636. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  103637. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  103638. }
  103639. for(i=0; i<nKey; i++){
  103640. sqlite3VdbeAddOp2(v, OP_SCopy,
  103641. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  103642. r2+i);
  103643. }
  103644. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  103645. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  103646. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  103647. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  103648. sqlite3ReleaseTempReg(pParse, r1);
  103649. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  103650. break;
  103651. }
  103652. #endif /* SQLITE_OMIT_CTE */
  103653. #if !defined(SQLITE_OMIT_TRIGGER)
  103654. /* Discard the results. This is used for SELECT statements inside
  103655. ** the body of a TRIGGER. The purpose of such selects is to call
  103656. ** user-defined functions that have side effects. We do not care
  103657. ** about the actual results of the select.
  103658. */
  103659. default: {
  103660. assert( eDest==SRT_Discard );
  103661. break;
  103662. }
  103663. #endif
  103664. }
  103665. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  103666. ** there is a sorter, in which case the sorter has already limited
  103667. ** the output for us.
  103668. */
  103669. if( pSort==0 && p->iLimit ){
  103670. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  103671. }
  103672. }
  103673. /*
  103674. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  103675. ** X extra columns.
  103676. */
  103677. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  103678. KeyInfo *p = sqlite3DbMallocZero(0,
  103679. sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
  103680. if( p ){
  103681. p->aSortOrder = (u8*)&p->aColl[N+X];
  103682. p->nField = (u16)N;
  103683. p->nXField = (u16)X;
  103684. p->enc = ENC(db);
  103685. p->db = db;
  103686. p->nRef = 1;
  103687. }else{
  103688. db->mallocFailed = 1;
  103689. }
  103690. return p;
  103691. }
  103692. /*
  103693. ** Deallocate a KeyInfo object
  103694. */
  103695. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  103696. if( p ){
  103697. assert( p->nRef>0 );
  103698. p->nRef--;
  103699. if( p->nRef==0 ) sqlite3DbFree(0, p);
  103700. }
  103701. }
  103702. /*
  103703. ** Make a new pointer to a KeyInfo object
  103704. */
  103705. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  103706. if( p ){
  103707. assert( p->nRef>0 );
  103708. p->nRef++;
  103709. }
  103710. return p;
  103711. }
  103712. #ifdef SQLITE_DEBUG
  103713. /*
  103714. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  103715. ** can only be changed if this is just a single reference to the object.
  103716. **
  103717. ** This routine is used only inside of assert() statements.
  103718. */
  103719. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  103720. #endif /* SQLITE_DEBUG */
  103721. /*
  103722. ** Given an expression list, generate a KeyInfo structure that records
  103723. ** the collating sequence for each expression in that expression list.
  103724. **
  103725. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  103726. ** KeyInfo structure is appropriate for initializing a virtual index to
  103727. ** implement that clause. If the ExprList is the result set of a SELECT
  103728. ** then the KeyInfo structure is appropriate for initializing a virtual
  103729. ** index to implement a DISTINCT test.
  103730. **
  103731. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  103732. ** function is responsible for seeing that this structure is eventually
  103733. ** freed.
  103734. */
  103735. static KeyInfo *keyInfoFromExprList(
  103736. Parse *pParse, /* Parsing context */
  103737. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  103738. int iStart, /* Begin with this column of pList */
  103739. int nExtra /* Add this many extra columns to the end */
  103740. ){
  103741. int nExpr;
  103742. KeyInfo *pInfo;
  103743. struct ExprList_item *pItem;
  103744. sqlite3 *db = pParse->db;
  103745. int i;
  103746. nExpr = pList->nExpr;
  103747. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  103748. if( pInfo ){
  103749. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  103750. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  103751. CollSeq *pColl;
  103752. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  103753. if( !pColl ) pColl = db->pDfltColl;
  103754. pInfo->aColl[i-iStart] = pColl;
  103755. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  103756. }
  103757. }
  103758. return pInfo;
  103759. }
  103760. /*
  103761. ** Name of the connection operator, used for error messages.
  103762. */
  103763. static const char *selectOpName(int id){
  103764. char *z;
  103765. switch( id ){
  103766. case TK_ALL: z = "UNION ALL"; break;
  103767. case TK_INTERSECT: z = "INTERSECT"; break;
  103768. case TK_EXCEPT: z = "EXCEPT"; break;
  103769. default: z = "UNION"; break;
  103770. }
  103771. return z;
  103772. }
  103773. #ifndef SQLITE_OMIT_EXPLAIN
  103774. /*
  103775. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  103776. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  103777. ** where the caption is of the form:
  103778. **
  103779. ** "USE TEMP B-TREE FOR xxx"
  103780. **
  103781. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  103782. ** is determined by the zUsage argument.
  103783. */
  103784. static void explainTempTable(Parse *pParse, const char *zUsage){
  103785. if( pParse->explain==2 ){
  103786. Vdbe *v = pParse->pVdbe;
  103787. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  103788. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  103789. }
  103790. }
  103791. /*
  103792. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  103793. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  103794. ** in sqlite3Select() to assign values to structure member variables that
  103795. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  103796. ** code with #ifndef directives.
  103797. */
  103798. # define explainSetInteger(a, b) a = b
  103799. #else
  103800. /* No-op versions of the explainXXX() functions and macros. */
  103801. # define explainTempTable(y,z)
  103802. # define explainSetInteger(y,z)
  103803. #endif
  103804. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  103805. /*
  103806. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  103807. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  103808. ** where the caption is of one of the two forms:
  103809. **
  103810. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  103811. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  103812. **
  103813. ** where iSub1 and iSub2 are the integers passed as the corresponding
  103814. ** function parameters, and op is the text representation of the parameter
  103815. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  103816. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  103817. ** false, or the second form if it is true.
  103818. */
  103819. static void explainComposite(
  103820. Parse *pParse, /* Parse context */
  103821. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  103822. int iSub1, /* Subquery id 1 */
  103823. int iSub2, /* Subquery id 2 */
  103824. int bUseTmp /* True if a temp table was used */
  103825. ){
  103826. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  103827. if( pParse->explain==2 ){
  103828. Vdbe *v = pParse->pVdbe;
  103829. char *zMsg = sqlite3MPrintf(
  103830. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  103831. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  103832. );
  103833. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  103834. }
  103835. }
  103836. #else
  103837. /* No-op versions of the explainXXX() functions and macros. */
  103838. # define explainComposite(v,w,x,y,z)
  103839. #endif
  103840. /*
  103841. ** If the inner loop was generated using a non-null pOrderBy argument,
  103842. ** then the results were placed in a sorter. After the loop is terminated
  103843. ** we need to run the sorter and output the results. The following
  103844. ** routine generates the code needed to do that.
  103845. */
  103846. static void generateSortTail(
  103847. Parse *pParse, /* Parsing context */
  103848. Select *p, /* The SELECT statement */
  103849. SortCtx *pSort, /* Information on the ORDER BY clause */
  103850. int nColumn, /* Number of columns of data */
  103851. SelectDest *pDest /* Write the sorted results here */
  103852. ){
  103853. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  103854. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  103855. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  103856. int addr;
  103857. int addrOnce = 0;
  103858. int iTab;
  103859. ExprList *pOrderBy = pSort->pOrderBy;
  103860. int eDest = pDest->eDest;
  103861. int iParm = pDest->iSDParm;
  103862. int regRow;
  103863. int regRowid;
  103864. int nKey;
  103865. int iSortTab; /* Sorter cursor to read from */
  103866. int nSortData; /* Trailing values to read from sorter */
  103867. int i;
  103868. int bSeq; /* True if sorter record includes seq. no. */
  103869. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  103870. struct ExprList_item *aOutEx = p->pEList->a;
  103871. #endif
  103872. assert( addrBreak<0 );
  103873. if( pSort->labelBkOut ){
  103874. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  103875. sqlite3VdbeGoto(v, addrBreak);
  103876. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  103877. }
  103878. iTab = pSort->iECursor;
  103879. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  103880. regRowid = 0;
  103881. regRow = pDest->iSdst;
  103882. nSortData = nColumn;
  103883. }else{
  103884. regRowid = sqlite3GetTempReg(pParse);
  103885. regRow = sqlite3GetTempReg(pParse);
  103886. nSortData = 1;
  103887. }
  103888. nKey = pOrderBy->nExpr - pSort->nOBSat;
  103889. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  103890. int regSortOut = ++pParse->nMem;
  103891. iSortTab = pParse->nTab++;
  103892. if( pSort->labelBkOut ){
  103893. addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  103894. }
  103895. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  103896. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  103897. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  103898. VdbeCoverage(v);
  103899. codeOffset(v, p->iOffset, addrContinue);
  103900. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  103901. bSeq = 0;
  103902. }else{
  103903. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  103904. codeOffset(v, p->iOffset, addrContinue);
  103905. iSortTab = iTab;
  103906. bSeq = 1;
  103907. }
  103908. for(i=0; i<nSortData; i++){
  103909. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
  103910. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  103911. }
  103912. switch( eDest ){
  103913. case SRT_EphemTab: {
  103914. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  103915. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  103916. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  103917. break;
  103918. }
  103919. #ifndef SQLITE_OMIT_SUBQUERY
  103920. case SRT_Set: {
  103921. assert( nColumn==1 );
  103922. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  103923. &pDest->affSdst, 1);
  103924. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  103925. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  103926. break;
  103927. }
  103928. case SRT_Mem: {
  103929. assert( nColumn==1 );
  103930. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  103931. /* The LIMIT clause will terminate the loop for us */
  103932. break;
  103933. }
  103934. #endif
  103935. default: {
  103936. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  103937. testcase( eDest==SRT_Output );
  103938. testcase( eDest==SRT_Coroutine );
  103939. if( eDest==SRT_Output ){
  103940. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  103941. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  103942. }else{
  103943. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  103944. }
  103945. break;
  103946. }
  103947. }
  103948. if( regRowid ){
  103949. sqlite3ReleaseTempReg(pParse, regRow);
  103950. sqlite3ReleaseTempReg(pParse, regRowid);
  103951. }
  103952. /* The bottom of the loop
  103953. */
  103954. sqlite3VdbeResolveLabel(v, addrContinue);
  103955. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  103956. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  103957. }else{
  103958. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  103959. }
  103960. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  103961. sqlite3VdbeResolveLabel(v, addrBreak);
  103962. }
  103963. /*
  103964. ** Return a pointer to a string containing the 'declaration type' of the
  103965. ** expression pExpr. The string may be treated as static by the caller.
  103966. **
  103967. ** Also try to estimate the size of the returned value and return that
  103968. ** result in *pEstWidth.
  103969. **
  103970. ** The declaration type is the exact datatype definition extracted from the
  103971. ** original CREATE TABLE statement if the expression is a column. The
  103972. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  103973. ** is considered a column can be complex in the presence of subqueries. The
  103974. ** result-set expression in all of the following SELECT statements is
  103975. ** considered a column by this function.
  103976. **
  103977. ** SELECT col FROM tbl;
  103978. ** SELECT (SELECT col FROM tbl;
  103979. ** SELECT (SELECT col FROM tbl);
  103980. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  103981. **
  103982. ** The declaration type for any expression other than a column is NULL.
  103983. **
  103984. ** This routine has either 3 or 6 parameters depending on whether or not
  103985. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  103986. */
  103987. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103988. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  103989. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  103990. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  103991. #endif
  103992. static const char *columnTypeImpl(
  103993. NameContext *pNC,
  103994. Expr *pExpr,
  103995. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  103996. const char **pzOrigDb,
  103997. const char **pzOrigTab,
  103998. const char **pzOrigCol,
  103999. #endif
  104000. u8 *pEstWidth
  104001. ){
  104002. char const *zType = 0;
  104003. int j;
  104004. u8 estWidth = 1;
  104005. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104006. char const *zOrigDb = 0;
  104007. char const *zOrigTab = 0;
  104008. char const *zOrigCol = 0;
  104009. #endif
  104010. assert( pExpr!=0 );
  104011. assert( pNC->pSrcList!=0 );
  104012. switch( pExpr->op ){
  104013. case TK_AGG_COLUMN:
  104014. case TK_COLUMN: {
  104015. /* The expression is a column. Locate the table the column is being
  104016. ** extracted from in NameContext.pSrcList. This table may be real
  104017. ** database table or a subquery.
  104018. */
  104019. Table *pTab = 0; /* Table structure column is extracted from */
  104020. Select *pS = 0; /* Select the column is extracted from */
  104021. int iCol = pExpr->iColumn; /* Index of column in pTab */
  104022. testcase( pExpr->op==TK_AGG_COLUMN );
  104023. testcase( pExpr->op==TK_COLUMN );
  104024. while( pNC && !pTab ){
  104025. SrcList *pTabList = pNC->pSrcList;
  104026. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  104027. if( j<pTabList->nSrc ){
  104028. pTab = pTabList->a[j].pTab;
  104029. pS = pTabList->a[j].pSelect;
  104030. }else{
  104031. pNC = pNC->pNext;
  104032. }
  104033. }
  104034. if( pTab==0 ){
  104035. /* At one time, code such as "SELECT new.x" within a trigger would
  104036. ** cause this condition to run. Since then, we have restructured how
  104037. ** trigger code is generated and so this condition is no longer
  104038. ** possible. However, it can still be true for statements like
  104039. ** the following:
  104040. **
  104041. ** CREATE TABLE t1(col INTEGER);
  104042. ** SELECT (SELECT t1.col) FROM FROM t1;
  104043. **
  104044. ** when columnType() is called on the expression "t1.col" in the
  104045. ** sub-select. In this case, set the column type to NULL, even
  104046. ** though it should really be "INTEGER".
  104047. **
  104048. ** This is not a problem, as the column type of "t1.col" is never
  104049. ** used. When columnType() is called on the expression
  104050. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  104051. ** branch below. */
  104052. break;
  104053. }
  104054. assert( pTab && pExpr->pTab==pTab );
  104055. if( pS ){
  104056. /* The "table" is actually a sub-select or a view in the FROM clause
  104057. ** of the SELECT statement. Return the declaration type and origin
  104058. ** data for the result-set column of the sub-select.
  104059. */
  104060. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  104061. /* If iCol is less than zero, then the expression requests the
  104062. ** rowid of the sub-select or view. This expression is legal (see
  104063. ** test case misc2.2.2) - it always evaluates to NULL.
  104064. **
  104065. ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
  104066. ** caught already by name resolution.
  104067. */
  104068. NameContext sNC;
  104069. Expr *p = pS->pEList->a[iCol].pExpr;
  104070. sNC.pSrcList = pS->pSrc;
  104071. sNC.pNext = pNC;
  104072. sNC.pParse = pNC->pParse;
  104073. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  104074. }
  104075. }else if( pTab->pSchema ){
  104076. /* A real table */
  104077. assert( !pS );
  104078. if( iCol<0 ) iCol = pTab->iPKey;
  104079. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  104080. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104081. if( iCol<0 ){
  104082. zType = "INTEGER";
  104083. zOrigCol = "rowid";
  104084. }else{
  104085. zType = pTab->aCol[iCol].zType;
  104086. zOrigCol = pTab->aCol[iCol].zName;
  104087. estWidth = pTab->aCol[iCol].szEst;
  104088. }
  104089. zOrigTab = pTab->zName;
  104090. if( pNC->pParse ){
  104091. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  104092. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  104093. }
  104094. #else
  104095. if( iCol<0 ){
  104096. zType = "INTEGER";
  104097. }else{
  104098. zType = pTab->aCol[iCol].zType;
  104099. estWidth = pTab->aCol[iCol].szEst;
  104100. }
  104101. #endif
  104102. }
  104103. break;
  104104. }
  104105. #ifndef SQLITE_OMIT_SUBQUERY
  104106. case TK_SELECT: {
  104107. /* The expression is a sub-select. Return the declaration type and
  104108. ** origin info for the single column in the result set of the SELECT
  104109. ** statement.
  104110. */
  104111. NameContext sNC;
  104112. Select *pS = pExpr->x.pSelect;
  104113. Expr *p = pS->pEList->a[0].pExpr;
  104114. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  104115. sNC.pSrcList = pS->pSrc;
  104116. sNC.pNext = pNC;
  104117. sNC.pParse = pNC->pParse;
  104118. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  104119. break;
  104120. }
  104121. #endif
  104122. }
  104123. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104124. if( pzOrigDb ){
  104125. assert( pzOrigTab && pzOrigCol );
  104126. *pzOrigDb = zOrigDb;
  104127. *pzOrigTab = zOrigTab;
  104128. *pzOrigCol = zOrigCol;
  104129. }
  104130. #endif
  104131. if( pEstWidth ) *pEstWidth = estWidth;
  104132. return zType;
  104133. }
  104134. /*
  104135. ** Generate code that will tell the VDBE the declaration types of columns
  104136. ** in the result set.
  104137. */
  104138. static void generateColumnTypes(
  104139. Parse *pParse, /* Parser context */
  104140. SrcList *pTabList, /* List of tables */
  104141. ExprList *pEList /* Expressions defining the result set */
  104142. ){
  104143. #ifndef SQLITE_OMIT_DECLTYPE
  104144. Vdbe *v = pParse->pVdbe;
  104145. int i;
  104146. NameContext sNC;
  104147. sNC.pSrcList = pTabList;
  104148. sNC.pParse = pParse;
  104149. for(i=0; i<pEList->nExpr; i++){
  104150. Expr *p = pEList->a[i].pExpr;
  104151. const char *zType;
  104152. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  104153. const char *zOrigDb = 0;
  104154. const char *zOrigTab = 0;
  104155. const char *zOrigCol = 0;
  104156. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  104157. /* The vdbe must make its own copy of the column-type and other
  104158. ** column specific strings, in case the schema is reset before this
  104159. ** virtual machine is deleted.
  104160. */
  104161. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  104162. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  104163. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  104164. #else
  104165. zType = columnType(&sNC, p, 0, 0, 0, 0);
  104166. #endif
  104167. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  104168. }
  104169. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  104170. }
  104171. /*
  104172. ** Generate code that will tell the VDBE the names of columns
  104173. ** in the result set. This information is used to provide the
  104174. ** azCol[] values in the callback.
  104175. */
  104176. static void generateColumnNames(
  104177. Parse *pParse, /* Parser context */
  104178. SrcList *pTabList, /* List of tables */
  104179. ExprList *pEList /* Expressions defining the result set */
  104180. ){
  104181. Vdbe *v = pParse->pVdbe;
  104182. int i, j;
  104183. sqlite3 *db = pParse->db;
  104184. int fullNames, shortNames;
  104185. #ifndef SQLITE_OMIT_EXPLAIN
  104186. /* If this is an EXPLAIN, skip this step */
  104187. if( pParse->explain ){
  104188. return;
  104189. }
  104190. #endif
  104191. if( pParse->colNamesSet || db->mallocFailed ) return;
  104192. assert( v!=0 );
  104193. assert( pTabList!=0 );
  104194. pParse->colNamesSet = 1;
  104195. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  104196. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  104197. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  104198. for(i=0; i<pEList->nExpr; i++){
  104199. Expr *p;
  104200. p = pEList->a[i].pExpr;
  104201. if( NEVER(p==0) ) continue;
  104202. if( pEList->a[i].zName ){
  104203. char *zName = pEList->a[i].zName;
  104204. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  104205. }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
  104206. Table *pTab;
  104207. char *zCol;
  104208. int iCol = p->iColumn;
  104209. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  104210. if( pTabList->a[j].iCursor==p->iTable ) break;
  104211. }
  104212. assert( j<pTabList->nSrc );
  104213. pTab = pTabList->a[j].pTab;
  104214. if( iCol<0 ) iCol = pTab->iPKey;
  104215. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  104216. if( iCol<0 ){
  104217. zCol = "rowid";
  104218. }else{
  104219. zCol = pTab->aCol[iCol].zName;
  104220. }
  104221. if( !shortNames && !fullNames ){
  104222. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  104223. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  104224. }else if( fullNames ){
  104225. char *zName = 0;
  104226. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  104227. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  104228. }else{
  104229. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  104230. }
  104231. }else{
  104232. const char *z = pEList->a[i].zSpan;
  104233. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  104234. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  104235. }
  104236. }
  104237. generateColumnTypes(pParse, pTabList, pEList);
  104238. }
  104239. /*
  104240. ** Given an expression list (which is really the list of expressions
  104241. ** that form the result set of a SELECT statement) compute appropriate
  104242. ** column names for a table that would hold the expression list.
  104243. **
  104244. ** All column names will be unique.
  104245. **
  104246. ** Only the column names are computed. Column.zType, Column.zColl,
  104247. ** and other fields of Column are zeroed.
  104248. **
  104249. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  104250. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  104251. */
  104252. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  104253. Parse *pParse, /* Parsing context */
  104254. ExprList *pEList, /* Expr list from which to derive column names */
  104255. i16 *pnCol, /* Write the number of columns here */
  104256. Column **paCol /* Write the new column list here */
  104257. ){
  104258. sqlite3 *db = pParse->db; /* Database connection */
  104259. int i, j; /* Loop counters */
  104260. u32 cnt; /* Index added to make the name unique */
  104261. Column *aCol, *pCol; /* For looping over result columns */
  104262. int nCol; /* Number of columns in the result set */
  104263. Expr *p; /* Expression for a single result column */
  104264. char *zName; /* Column name */
  104265. int nName; /* Size of name in zName[] */
  104266. Hash ht; /* Hash table of column names */
  104267. sqlite3HashInit(&ht);
  104268. if( pEList ){
  104269. nCol = pEList->nExpr;
  104270. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  104271. testcase( aCol==0 );
  104272. }else{
  104273. nCol = 0;
  104274. aCol = 0;
  104275. }
  104276. assert( nCol==(i16)nCol );
  104277. *pnCol = nCol;
  104278. *paCol = aCol;
  104279. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  104280. /* Get an appropriate name for the column
  104281. */
  104282. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  104283. if( (zName = pEList->a[i].zName)!=0 ){
  104284. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  104285. }else{
  104286. Expr *pColExpr = p; /* The expression that is the result column name */
  104287. Table *pTab; /* Table associated with this expression */
  104288. while( pColExpr->op==TK_DOT ){
  104289. pColExpr = pColExpr->pRight;
  104290. assert( pColExpr!=0 );
  104291. }
  104292. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  104293. /* For columns use the column name name */
  104294. int iCol = pColExpr->iColumn;
  104295. pTab = pColExpr->pTab;
  104296. if( iCol<0 ) iCol = pTab->iPKey;
  104297. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  104298. }else if( pColExpr->op==TK_ID ){
  104299. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  104300. zName = pColExpr->u.zToken;
  104301. }else{
  104302. /* Use the original text of the column expression as its name */
  104303. zName = pEList->a[i].zSpan;
  104304. }
  104305. }
  104306. zName = sqlite3MPrintf(db, "%s", zName);
  104307. /* Make sure the column name is unique. If the name is not unique,
  104308. ** append an integer to the name so that it becomes unique.
  104309. */
  104310. cnt = 0;
  104311. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  104312. nName = sqlite3Strlen30(zName);
  104313. if( nName>0 ){
  104314. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  104315. if( zName[j]==':' ) nName = j;
  104316. }
  104317. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  104318. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  104319. }
  104320. pCol->zName = zName;
  104321. sqlite3ColumnPropertiesFromName(0, pCol);
  104322. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  104323. db->mallocFailed = 1;
  104324. }
  104325. }
  104326. sqlite3HashClear(&ht);
  104327. if( db->mallocFailed ){
  104328. for(j=0; j<i; j++){
  104329. sqlite3DbFree(db, aCol[j].zName);
  104330. }
  104331. sqlite3DbFree(db, aCol);
  104332. *paCol = 0;
  104333. *pnCol = 0;
  104334. return SQLITE_NOMEM;
  104335. }
  104336. return SQLITE_OK;
  104337. }
  104338. /*
  104339. ** Add type and collation information to a column list based on
  104340. ** a SELECT statement.
  104341. **
  104342. ** The column list presumably came from selectColumnNamesFromExprList().
  104343. ** The column list has only names, not types or collations. This
  104344. ** routine goes through and adds the types and collations.
  104345. **
  104346. ** This routine requires that all identifiers in the SELECT
  104347. ** statement be resolved.
  104348. */
  104349. static void selectAddColumnTypeAndCollation(
  104350. Parse *pParse, /* Parsing contexts */
  104351. Table *pTab, /* Add column type information to this table */
  104352. Select *pSelect /* SELECT used to determine types and collations */
  104353. ){
  104354. sqlite3 *db = pParse->db;
  104355. NameContext sNC;
  104356. Column *pCol;
  104357. CollSeq *pColl;
  104358. int i;
  104359. Expr *p;
  104360. struct ExprList_item *a;
  104361. u64 szAll = 0;
  104362. assert( pSelect!=0 );
  104363. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  104364. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  104365. if( db->mallocFailed ) return;
  104366. memset(&sNC, 0, sizeof(sNC));
  104367. sNC.pSrcList = pSelect->pSrc;
  104368. a = pSelect->pEList->a;
  104369. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  104370. p = a[i].pExpr;
  104371. if( pCol->zType==0 ){
  104372. pCol->zType = sqlite3DbStrDup(db,
  104373. columnType(&sNC, p,0,0,0, &pCol->szEst));
  104374. }
  104375. szAll += pCol->szEst;
  104376. pCol->affinity = sqlite3ExprAffinity(p);
  104377. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  104378. pColl = sqlite3ExprCollSeq(pParse, p);
  104379. if( pColl && pCol->zColl==0 ){
  104380. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  104381. }
  104382. }
  104383. pTab->szTabRow = sqlite3LogEst(szAll*4);
  104384. }
  104385. /*
  104386. ** Given a SELECT statement, generate a Table structure that describes
  104387. ** the result set of that SELECT.
  104388. */
  104389. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  104390. Table *pTab;
  104391. sqlite3 *db = pParse->db;
  104392. int savedFlags;
  104393. savedFlags = db->flags;
  104394. db->flags &= ~SQLITE_FullColNames;
  104395. db->flags |= SQLITE_ShortColNames;
  104396. sqlite3SelectPrep(pParse, pSelect, 0);
  104397. if( pParse->nErr ) return 0;
  104398. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  104399. db->flags = savedFlags;
  104400. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  104401. if( pTab==0 ){
  104402. return 0;
  104403. }
  104404. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  104405. ** is disabled */
  104406. assert( db->lookaside.bEnabled==0 );
  104407. pTab->nRef = 1;
  104408. pTab->zName = 0;
  104409. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  104410. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  104411. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  104412. pTab->iPKey = -1;
  104413. if( db->mallocFailed ){
  104414. sqlite3DeleteTable(db, pTab);
  104415. return 0;
  104416. }
  104417. return pTab;
  104418. }
  104419. /*
  104420. ** Get a VDBE for the given parser context. Create a new one if necessary.
  104421. ** If an error occurs, return NULL and leave a message in pParse.
  104422. */
  104423. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  104424. Vdbe *v = pParse->pVdbe;
  104425. if( v==0 ){
  104426. v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  104427. if( v ) sqlite3VdbeAddOp0(v, OP_Init);
  104428. if( pParse->pToplevel==0
  104429. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  104430. ){
  104431. pParse->okConstFactor = 1;
  104432. }
  104433. }
  104434. return v;
  104435. }
  104436. /*
  104437. ** Compute the iLimit and iOffset fields of the SELECT based on the
  104438. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  104439. ** that appear in the original SQL statement after the LIMIT and OFFSET
  104440. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  104441. ** are the integer memory register numbers for counters used to compute
  104442. ** the limit and offset. If there is no limit and/or offset, then
  104443. ** iLimit and iOffset are negative.
  104444. **
  104445. ** This routine changes the values of iLimit and iOffset only if
  104446. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  104447. ** iOffset should have been preset to appropriate default values (zero)
  104448. ** prior to calling this routine.
  104449. **
  104450. ** The iOffset register (if it exists) is initialized to the value
  104451. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  104452. ** iOffset+1 is initialized to LIMIT+OFFSET.
  104453. **
  104454. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  104455. ** redefined. The UNION ALL operator uses this property to force
  104456. ** the reuse of the same limit and offset registers across multiple
  104457. ** SELECT statements.
  104458. */
  104459. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  104460. Vdbe *v = 0;
  104461. int iLimit = 0;
  104462. int iOffset;
  104463. int n;
  104464. if( p->iLimit ) return;
  104465. /*
  104466. ** "LIMIT -1" always shows all rows. There is some
  104467. ** controversy about what the correct behavior should be.
  104468. ** The current implementation interprets "LIMIT 0" to mean
  104469. ** no rows.
  104470. */
  104471. sqlite3ExprCacheClear(pParse);
  104472. assert( p->pOffset==0 || p->pLimit!=0 );
  104473. if( p->pLimit ){
  104474. p->iLimit = iLimit = ++pParse->nMem;
  104475. v = sqlite3GetVdbe(pParse);
  104476. assert( v!=0 );
  104477. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  104478. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  104479. VdbeComment((v, "LIMIT counter"));
  104480. if( n==0 ){
  104481. sqlite3VdbeGoto(v, iBreak);
  104482. }else if( n>=0 && p->nSelectRow>(u64)n ){
  104483. p->nSelectRow = n;
  104484. }
  104485. }else{
  104486. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  104487. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  104488. VdbeComment((v, "LIMIT counter"));
  104489. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  104490. }
  104491. if( p->pOffset ){
  104492. p->iOffset = iOffset = ++pParse->nMem;
  104493. pParse->nMem++; /* Allocate an extra register for limit+offset */
  104494. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  104495. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  104496. VdbeComment((v, "OFFSET counter"));
  104497. sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iOffset, iOffset, 0);
  104498. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  104499. VdbeComment((v, "LIMIT+OFFSET"));
  104500. sqlite3VdbeAddOp3(v, OP_SetIfNotPos, iLimit, iOffset+1, -1);
  104501. }
  104502. }
  104503. }
  104504. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  104505. /*
  104506. ** Return the appropriate collating sequence for the iCol-th column of
  104507. ** the result set for the compound-select statement "p". Return NULL if
  104508. ** the column has no default collating sequence.
  104509. **
  104510. ** The collating sequence for the compound select is taken from the
  104511. ** left-most term of the select that has a collating sequence.
  104512. */
  104513. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  104514. CollSeq *pRet;
  104515. if( p->pPrior ){
  104516. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  104517. }else{
  104518. pRet = 0;
  104519. }
  104520. assert( iCol>=0 );
  104521. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  104522. ** have been thrown during name resolution and we would not have gotten
  104523. ** this far */
  104524. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  104525. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  104526. }
  104527. return pRet;
  104528. }
  104529. /*
  104530. ** The select statement passed as the second parameter is a compound SELECT
  104531. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  104532. ** structure suitable for implementing the ORDER BY.
  104533. **
  104534. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  104535. ** function is responsible for ensuring that this structure is eventually
  104536. ** freed.
  104537. */
  104538. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  104539. ExprList *pOrderBy = p->pOrderBy;
  104540. int nOrderBy = p->pOrderBy->nExpr;
  104541. sqlite3 *db = pParse->db;
  104542. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  104543. if( pRet ){
  104544. int i;
  104545. for(i=0; i<nOrderBy; i++){
  104546. struct ExprList_item *pItem = &pOrderBy->a[i];
  104547. Expr *pTerm = pItem->pExpr;
  104548. CollSeq *pColl;
  104549. if( pTerm->flags & EP_Collate ){
  104550. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  104551. }else{
  104552. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  104553. if( pColl==0 ) pColl = db->pDfltColl;
  104554. pOrderBy->a[i].pExpr =
  104555. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  104556. }
  104557. assert( sqlite3KeyInfoIsWriteable(pRet) );
  104558. pRet->aColl[i] = pColl;
  104559. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  104560. }
  104561. }
  104562. return pRet;
  104563. }
  104564. #ifndef SQLITE_OMIT_CTE
  104565. /*
  104566. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  104567. ** query of the form:
  104568. **
  104569. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  104570. ** \___________/ \_______________/
  104571. ** p->pPrior p
  104572. **
  104573. **
  104574. ** There is exactly one reference to the recursive-table in the FROM clause
  104575. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  104576. **
  104577. ** The setup-query runs once to generate an initial set of rows that go
  104578. ** into a Queue table. Rows are extracted from the Queue table one by
  104579. ** one. Each row extracted from Queue is output to pDest. Then the single
  104580. ** extracted row (now in the iCurrent table) becomes the content of the
  104581. ** recursive-table for a recursive-query run. The output of the recursive-query
  104582. ** is added back into the Queue table. Then another row is extracted from Queue
  104583. ** and the iteration continues until the Queue table is empty.
  104584. **
  104585. ** If the compound query operator is UNION then no duplicate rows are ever
  104586. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  104587. ** that have ever been inserted into Queue and causes duplicates to be
  104588. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  104589. **
  104590. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  104591. ** ORDER BY order and the first entry is extracted for each cycle. Without
  104592. ** an ORDER BY, the Queue table is just a FIFO.
  104593. **
  104594. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  104595. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  104596. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  104597. ** with a positive value, then the first OFFSET outputs are discarded rather
  104598. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  104599. ** rows have been skipped.
  104600. */
  104601. static void generateWithRecursiveQuery(
  104602. Parse *pParse, /* Parsing context */
  104603. Select *p, /* The recursive SELECT to be coded */
  104604. SelectDest *pDest /* What to do with query results */
  104605. ){
  104606. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  104607. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  104608. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  104609. Select *pSetup = p->pPrior; /* The setup query */
  104610. int addrTop; /* Top of the loop */
  104611. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  104612. int iCurrent = 0; /* The Current table */
  104613. int regCurrent; /* Register holding Current table */
  104614. int iQueue; /* The Queue table */
  104615. int iDistinct = 0; /* To ensure unique results if UNION */
  104616. int eDest = SRT_Fifo; /* How to write to Queue */
  104617. SelectDest destQueue; /* SelectDest targetting the Queue table */
  104618. int i; /* Loop counter */
  104619. int rc; /* Result code */
  104620. ExprList *pOrderBy; /* The ORDER BY clause */
  104621. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  104622. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  104623. /* Obtain authorization to do a recursive query */
  104624. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  104625. /* Process the LIMIT and OFFSET clauses, if they exist */
  104626. addrBreak = sqlite3VdbeMakeLabel(v);
  104627. computeLimitRegisters(pParse, p, addrBreak);
  104628. pLimit = p->pLimit;
  104629. pOffset = p->pOffset;
  104630. regLimit = p->iLimit;
  104631. regOffset = p->iOffset;
  104632. p->pLimit = p->pOffset = 0;
  104633. p->iLimit = p->iOffset = 0;
  104634. pOrderBy = p->pOrderBy;
  104635. /* Locate the cursor number of the Current table */
  104636. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  104637. if( pSrc->a[i].fg.isRecursive ){
  104638. iCurrent = pSrc->a[i].iCursor;
  104639. break;
  104640. }
  104641. }
  104642. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  104643. ** the Distinct table must be exactly one greater than Queue in order
  104644. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  104645. iQueue = pParse->nTab++;
  104646. if( p->op==TK_UNION ){
  104647. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  104648. iDistinct = pParse->nTab++;
  104649. }else{
  104650. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  104651. }
  104652. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  104653. /* Allocate cursors for Current, Queue, and Distinct. */
  104654. regCurrent = ++pParse->nMem;
  104655. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  104656. if( pOrderBy ){
  104657. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  104658. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  104659. (char*)pKeyInfo, P4_KEYINFO);
  104660. destQueue.pOrderBy = pOrderBy;
  104661. }else{
  104662. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  104663. }
  104664. VdbeComment((v, "Queue table"));
  104665. if( iDistinct ){
  104666. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  104667. p->selFlags |= SF_UsesEphemeral;
  104668. }
  104669. /* Detach the ORDER BY clause from the compound SELECT */
  104670. p->pOrderBy = 0;
  104671. /* Store the results of the setup-query in Queue. */
  104672. pSetup->pNext = 0;
  104673. rc = sqlite3Select(pParse, pSetup, &destQueue);
  104674. pSetup->pNext = p;
  104675. if( rc ) goto end_of_recursive_query;
  104676. /* Find the next row in the Queue and output that row */
  104677. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  104678. /* Transfer the next row in Queue over to Current */
  104679. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  104680. if( pOrderBy ){
  104681. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  104682. }else{
  104683. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  104684. }
  104685. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  104686. /* Output the single row in Current */
  104687. addrCont = sqlite3VdbeMakeLabel(v);
  104688. codeOffset(v, regOffset, addrCont);
  104689. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  104690. 0, 0, pDest, addrCont, addrBreak);
  104691. if( regLimit ){
  104692. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  104693. VdbeCoverage(v);
  104694. }
  104695. sqlite3VdbeResolveLabel(v, addrCont);
  104696. /* Execute the recursive SELECT taking the single row in Current as
  104697. ** the value for the recursive-table. Store the results in the Queue.
  104698. */
  104699. if( p->selFlags & SF_Aggregate ){
  104700. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  104701. }else{
  104702. p->pPrior = 0;
  104703. sqlite3Select(pParse, p, &destQueue);
  104704. assert( p->pPrior==0 );
  104705. p->pPrior = pSetup;
  104706. }
  104707. /* Keep running the loop until the Queue is empty */
  104708. sqlite3VdbeGoto(v, addrTop);
  104709. sqlite3VdbeResolveLabel(v, addrBreak);
  104710. end_of_recursive_query:
  104711. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  104712. p->pOrderBy = pOrderBy;
  104713. p->pLimit = pLimit;
  104714. p->pOffset = pOffset;
  104715. return;
  104716. }
  104717. #endif /* SQLITE_OMIT_CTE */
  104718. /* Forward references */
  104719. static int multiSelectOrderBy(
  104720. Parse *pParse, /* Parsing context */
  104721. Select *p, /* The right-most of SELECTs to be coded */
  104722. SelectDest *pDest /* What to do with query results */
  104723. );
  104724. /*
  104725. ** Handle the special case of a compound-select that originates from a
  104726. ** VALUES clause. By handling this as a special case, we avoid deep
  104727. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  104728. ** on a VALUES clause.
  104729. **
  104730. ** Because the Select object originates from a VALUES clause:
  104731. ** (1) It has no LIMIT or OFFSET
  104732. ** (2) All terms are UNION ALL
  104733. ** (3) There is no ORDER BY clause
  104734. */
  104735. static int multiSelectValues(
  104736. Parse *pParse, /* Parsing context */
  104737. Select *p, /* The right-most of SELECTs to be coded */
  104738. SelectDest *pDest /* What to do with query results */
  104739. ){
  104740. Select *pPrior;
  104741. int nRow = 1;
  104742. int rc = 0;
  104743. assert( p->selFlags & SF_MultiValue );
  104744. do{
  104745. assert( p->selFlags & SF_Values );
  104746. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  104747. assert( p->pLimit==0 );
  104748. assert( p->pOffset==0 );
  104749. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  104750. if( p->pPrior==0 ) break;
  104751. assert( p->pPrior->pNext==p );
  104752. p = p->pPrior;
  104753. nRow++;
  104754. }while(1);
  104755. while( p ){
  104756. pPrior = p->pPrior;
  104757. p->pPrior = 0;
  104758. rc = sqlite3Select(pParse, p, pDest);
  104759. p->pPrior = pPrior;
  104760. if( rc ) break;
  104761. p->nSelectRow = nRow;
  104762. p = p->pNext;
  104763. }
  104764. return rc;
  104765. }
  104766. /*
  104767. ** This routine is called to process a compound query form from
  104768. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  104769. ** INTERSECT
  104770. **
  104771. ** "p" points to the right-most of the two queries. the query on the
  104772. ** left is p->pPrior. The left query could also be a compound query
  104773. ** in which case this routine will be called recursively.
  104774. **
  104775. ** The results of the total query are to be written into a destination
  104776. ** of type eDest with parameter iParm.
  104777. **
  104778. ** Example 1: Consider a three-way compound SQL statement.
  104779. **
  104780. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  104781. **
  104782. ** This statement is parsed up as follows:
  104783. **
  104784. ** SELECT c FROM t3
  104785. ** |
  104786. ** `-----> SELECT b FROM t2
  104787. ** |
  104788. ** `------> SELECT a FROM t1
  104789. **
  104790. ** The arrows in the diagram above represent the Select.pPrior pointer.
  104791. ** So if this routine is called with p equal to the t3 query, then
  104792. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  104793. **
  104794. ** Notice that because of the way SQLite parses compound SELECTs, the
  104795. ** individual selects always group from left to right.
  104796. */
  104797. static int multiSelect(
  104798. Parse *pParse, /* Parsing context */
  104799. Select *p, /* The right-most of SELECTs to be coded */
  104800. SelectDest *pDest /* What to do with query results */
  104801. ){
  104802. int rc = SQLITE_OK; /* Success code from a subroutine */
  104803. Select *pPrior; /* Another SELECT immediately to our left */
  104804. Vdbe *v; /* Generate code to this VDBE */
  104805. SelectDest dest; /* Alternative data destination */
  104806. Select *pDelete = 0; /* Chain of simple selects to delete */
  104807. sqlite3 *db; /* Database connection */
  104808. #ifndef SQLITE_OMIT_EXPLAIN
  104809. int iSub1 = 0; /* EQP id of left-hand query */
  104810. int iSub2 = 0; /* EQP id of right-hand query */
  104811. #endif
  104812. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  104813. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  104814. */
  104815. assert( p && p->pPrior ); /* Calling function guarantees this much */
  104816. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  104817. db = pParse->db;
  104818. pPrior = p->pPrior;
  104819. dest = *pDest;
  104820. if( pPrior->pOrderBy ){
  104821. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  104822. selectOpName(p->op));
  104823. rc = 1;
  104824. goto multi_select_end;
  104825. }
  104826. if( pPrior->pLimit ){
  104827. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  104828. selectOpName(p->op));
  104829. rc = 1;
  104830. goto multi_select_end;
  104831. }
  104832. v = sqlite3GetVdbe(pParse);
  104833. assert( v!=0 ); /* The VDBE already created by calling function */
  104834. /* Create the destination temporary table if necessary
  104835. */
  104836. if( dest.eDest==SRT_EphemTab ){
  104837. assert( p->pEList );
  104838. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  104839. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  104840. dest.eDest = SRT_Table;
  104841. }
  104842. /* Special handling for a compound-select that originates as a VALUES clause.
  104843. */
  104844. if( p->selFlags & SF_MultiValue ){
  104845. rc = multiSelectValues(pParse, p, &dest);
  104846. goto multi_select_end;
  104847. }
  104848. /* Make sure all SELECTs in the statement have the same number of elements
  104849. ** in their result sets.
  104850. */
  104851. assert( p->pEList && pPrior->pEList );
  104852. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  104853. #ifndef SQLITE_OMIT_CTE
  104854. if( p->selFlags & SF_Recursive ){
  104855. generateWithRecursiveQuery(pParse, p, &dest);
  104856. }else
  104857. #endif
  104858. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  104859. */
  104860. if( p->pOrderBy ){
  104861. return multiSelectOrderBy(pParse, p, pDest);
  104862. }else
  104863. /* Generate code for the left and right SELECT statements.
  104864. */
  104865. switch( p->op ){
  104866. case TK_ALL: {
  104867. int addr = 0;
  104868. int nLimit;
  104869. assert( !pPrior->pLimit );
  104870. pPrior->iLimit = p->iLimit;
  104871. pPrior->iOffset = p->iOffset;
  104872. pPrior->pLimit = p->pLimit;
  104873. pPrior->pOffset = p->pOffset;
  104874. explainSetInteger(iSub1, pParse->iNextSelectId);
  104875. rc = sqlite3Select(pParse, pPrior, &dest);
  104876. p->pLimit = 0;
  104877. p->pOffset = 0;
  104878. if( rc ){
  104879. goto multi_select_end;
  104880. }
  104881. p->pPrior = 0;
  104882. p->iLimit = pPrior->iLimit;
  104883. p->iOffset = pPrior->iOffset;
  104884. if( p->iLimit ){
  104885. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  104886. VdbeComment((v, "Jump ahead if LIMIT reached"));
  104887. if( p->iOffset ){
  104888. sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iOffset, p->iOffset, 0);
  104889. sqlite3VdbeAddOp3(v, OP_Add, p->iLimit, p->iOffset, p->iOffset+1);
  104890. sqlite3VdbeAddOp3(v, OP_SetIfNotPos, p->iLimit, p->iOffset+1, -1);
  104891. }
  104892. }
  104893. explainSetInteger(iSub2, pParse->iNextSelectId);
  104894. rc = sqlite3Select(pParse, p, &dest);
  104895. testcase( rc!=SQLITE_OK );
  104896. pDelete = p->pPrior;
  104897. p->pPrior = pPrior;
  104898. p->nSelectRow += pPrior->nSelectRow;
  104899. if( pPrior->pLimit
  104900. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  104901. && nLimit>0 && p->nSelectRow > (u64)nLimit
  104902. ){
  104903. p->nSelectRow = nLimit;
  104904. }
  104905. if( addr ){
  104906. sqlite3VdbeJumpHere(v, addr);
  104907. }
  104908. break;
  104909. }
  104910. case TK_EXCEPT:
  104911. case TK_UNION: {
  104912. int unionTab; /* Cursor number of the temporary table holding result */
  104913. u8 op = 0; /* One of the SRT_ operations to apply to self */
  104914. int priorOp; /* The SRT_ operation to apply to prior selects */
  104915. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  104916. int addr;
  104917. SelectDest uniondest;
  104918. testcase( p->op==TK_EXCEPT );
  104919. testcase( p->op==TK_UNION );
  104920. priorOp = SRT_Union;
  104921. if( dest.eDest==priorOp ){
  104922. /* We can reuse a temporary table generated by a SELECT to our
  104923. ** right.
  104924. */
  104925. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  104926. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  104927. unionTab = dest.iSDParm;
  104928. }else{
  104929. /* We will need to create our own temporary table to hold the
  104930. ** intermediate results.
  104931. */
  104932. unionTab = pParse->nTab++;
  104933. assert( p->pOrderBy==0 );
  104934. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  104935. assert( p->addrOpenEphm[0] == -1 );
  104936. p->addrOpenEphm[0] = addr;
  104937. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  104938. assert( p->pEList );
  104939. }
  104940. /* Code the SELECT statements to our left
  104941. */
  104942. assert( !pPrior->pOrderBy );
  104943. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  104944. explainSetInteger(iSub1, pParse->iNextSelectId);
  104945. rc = sqlite3Select(pParse, pPrior, &uniondest);
  104946. if( rc ){
  104947. goto multi_select_end;
  104948. }
  104949. /* Code the current SELECT statement
  104950. */
  104951. if( p->op==TK_EXCEPT ){
  104952. op = SRT_Except;
  104953. }else{
  104954. assert( p->op==TK_UNION );
  104955. op = SRT_Union;
  104956. }
  104957. p->pPrior = 0;
  104958. pLimit = p->pLimit;
  104959. p->pLimit = 0;
  104960. pOffset = p->pOffset;
  104961. p->pOffset = 0;
  104962. uniondest.eDest = op;
  104963. explainSetInteger(iSub2, pParse->iNextSelectId);
  104964. rc = sqlite3Select(pParse, p, &uniondest);
  104965. testcase( rc!=SQLITE_OK );
  104966. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  104967. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  104968. sqlite3ExprListDelete(db, p->pOrderBy);
  104969. pDelete = p->pPrior;
  104970. p->pPrior = pPrior;
  104971. p->pOrderBy = 0;
  104972. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  104973. sqlite3ExprDelete(db, p->pLimit);
  104974. p->pLimit = pLimit;
  104975. p->pOffset = pOffset;
  104976. p->iLimit = 0;
  104977. p->iOffset = 0;
  104978. /* Convert the data in the temporary table into whatever form
  104979. ** it is that we currently need.
  104980. */
  104981. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  104982. if( dest.eDest!=priorOp ){
  104983. int iCont, iBreak, iStart;
  104984. assert( p->pEList );
  104985. if( dest.eDest==SRT_Output ){
  104986. Select *pFirst = p;
  104987. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  104988. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  104989. }
  104990. iBreak = sqlite3VdbeMakeLabel(v);
  104991. iCont = sqlite3VdbeMakeLabel(v);
  104992. computeLimitRegisters(pParse, p, iBreak);
  104993. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  104994. iStart = sqlite3VdbeCurrentAddr(v);
  104995. selectInnerLoop(pParse, p, p->pEList, unionTab,
  104996. 0, 0, &dest, iCont, iBreak);
  104997. sqlite3VdbeResolveLabel(v, iCont);
  104998. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  104999. sqlite3VdbeResolveLabel(v, iBreak);
  105000. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  105001. }
  105002. break;
  105003. }
  105004. default: assert( p->op==TK_INTERSECT ); {
  105005. int tab1, tab2;
  105006. int iCont, iBreak, iStart;
  105007. Expr *pLimit, *pOffset;
  105008. int addr;
  105009. SelectDest intersectdest;
  105010. int r1;
  105011. /* INTERSECT is different from the others since it requires
  105012. ** two temporary tables. Hence it has its own case. Begin
  105013. ** by allocating the tables we will need.
  105014. */
  105015. tab1 = pParse->nTab++;
  105016. tab2 = pParse->nTab++;
  105017. assert( p->pOrderBy==0 );
  105018. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  105019. assert( p->addrOpenEphm[0] == -1 );
  105020. p->addrOpenEphm[0] = addr;
  105021. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  105022. assert( p->pEList );
  105023. /* Code the SELECTs to our left into temporary table "tab1".
  105024. */
  105025. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  105026. explainSetInteger(iSub1, pParse->iNextSelectId);
  105027. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  105028. if( rc ){
  105029. goto multi_select_end;
  105030. }
  105031. /* Code the current SELECT into temporary table "tab2"
  105032. */
  105033. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  105034. assert( p->addrOpenEphm[1] == -1 );
  105035. p->addrOpenEphm[1] = addr;
  105036. p->pPrior = 0;
  105037. pLimit = p->pLimit;
  105038. p->pLimit = 0;
  105039. pOffset = p->pOffset;
  105040. p->pOffset = 0;
  105041. intersectdest.iSDParm = tab2;
  105042. explainSetInteger(iSub2, pParse->iNextSelectId);
  105043. rc = sqlite3Select(pParse, p, &intersectdest);
  105044. testcase( rc!=SQLITE_OK );
  105045. pDelete = p->pPrior;
  105046. p->pPrior = pPrior;
  105047. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  105048. sqlite3ExprDelete(db, p->pLimit);
  105049. p->pLimit = pLimit;
  105050. p->pOffset = pOffset;
  105051. /* Generate code to take the intersection of the two temporary
  105052. ** tables.
  105053. */
  105054. assert( p->pEList );
  105055. if( dest.eDest==SRT_Output ){
  105056. Select *pFirst = p;
  105057. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  105058. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  105059. }
  105060. iBreak = sqlite3VdbeMakeLabel(v);
  105061. iCont = sqlite3VdbeMakeLabel(v);
  105062. computeLimitRegisters(pParse, p, iBreak);
  105063. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  105064. r1 = sqlite3GetTempReg(pParse);
  105065. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  105066. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  105067. sqlite3ReleaseTempReg(pParse, r1);
  105068. selectInnerLoop(pParse, p, p->pEList, tab1,
  105069. 0, 0, &dest, iCont, iBreak);
  105070. sqlite3VdbeResolveLabel(v, iCont);
  105071. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  105072. sqlite3VdbeResolveLabel(v, iBreak);
  105073. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  105074. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  105075. break;
  105076. }
  105077. }
  105078. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  105079. /* Compute collating sequences used by
  105080. ** temporary tables needed to implement the compound select.
  105081. ** Attach the KeyInfo structure to all temporary tables.
  105082. **
  105083. ** This section is run by the right-most SELECT statement only.
  105084. ** SELECT statements to the left always skip this part. The right-most
  105085. ** SELECT might also skip this part if it has no ORDER BY clause and
  105086. ** no temp tables are required.
  105087. */
  105088. if( p->selFlags & SF_UsesEphemeral ){
  105089. int i; /* Loop counter */
  105090. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  105091. Select *pLoop; /* For looping through SELECT statements */
  105092. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  105093. int nCol; /* Number of columns in result set */
  105094. assert( p->pNext==0 );
  105095. nCol = p->pEList->nExpr;
  105096. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  105097. if( !pKeyInfo ){
  105098. rc = SQLITE_NOMEM;
  105099. goto multi_select_end;
  105100. }
  105101. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  105102. *apColl = multiSelectCollSeq(pParse, p, i);
  105103. if( 0==*apColl ){
  105104. *apColl = db->pDfltColl;
  105105. }
  105106. }
  105107. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  105108. for(i=0; i<2; i++){
  105109. int addr = pLoop->addrOpenEphm[i];
  105110. if( addr<0 ){
  105111. /* If [0] is unused then [1] is also unused. So we can
  105112. ** always safely abort as soon as the first unused slot is found */
  105113. assert( pLoop->addrOpenEphm[1]<0 );
  105114. break;
  105115. }
  105116. sqlite3VdbeChangeP2(v, addr, nCol);
  105117. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  105118. P4_KEYINFO);
  105119. pLoop->addrOpenEphm[i] = -1;
  105120. }
  105121. }
  105122. sqlite3KeyInfoUnref(pKeyInfo);
  105123. }
  105124. multi_select_end:
  105125. pDest->iSdst = dest.iSdst;
  105126. pDest->nSdst = dest.nSdst;
  105127. sqlite3SelectDelete(db, pDelete);
  105128. return rc;
  105129. }
  105130. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  105131. /*
  105132. ** Error message for when two or more terms of a compound select have different
  105133. ** size result sets.
  105134. */
  105135. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  105136. if( p->selFlags & SF_Values ){
  105137. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  105138. }else{
  105139. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  105140. " do not have the same number of result columns", selectOpName(p->op));
  105141. }
  105142. }
  105143. /*
  105144. ** Code an output subroutine for a coroutine implementation of a
  105145. ** SELECT statment.
  105146. **
  105147. ** The data to be output is contained in pIn->iSdst. There are
  105148. ** pIn->nSdst columns to be output. pDest is where the output should
  105149. ** be sent.
  105150. **
  105151. ** regReturn is the number of the register holding the subroutine
  105152. ** return address.
  105153. **
  105154. ** If regPrev>0 then it is the first register in a vector that
  105155. ** records the previous output. mem[regPrev] is a flag that is false
  105156. ** if there has been no previous output. If regPrev>0 then code is
  105157. ** generated to suppress duplicates. pKeyInfo is used for comparing
  105158. ** keys.
  105159. **
  105160. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  105161. ** iBreak.
  105162. */
  105163. static int generateOutputSubroutine(
  105164. Parse *pParse, /* Parsing context */
  105165. Select *p, /* The SELECT statement */
  105166. SelectDest *pIn, /* Coroutine supplying data */
  105167. SelectDest *pDest, /* Where to send the data */
  105168. int regReturn, /* The return address register */
  105169. int regPrev, /* Previous result register. No uniqueness if 0 */
  105170. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  105171. int iBreak /* Jump here if we hit the LIMIT */
  105172. ){
  105173. Vdbe *v = pParse->pVdbe;
  105174. int iContinue;
  105175. int addr;
  105176. addr = sqlite3VdbeCurrentAddr(v);
  105177. iContinue = sqlite3VdbeMakeLabel(v);
  105178. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  105179. */
  105180. if( regPrev ){
  105181. int addr1, addr2;
  105182. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  105183. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  105184. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  105185. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  105186. sqlite3VdbeJumpHere(v, addr1);
  105187. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  105188. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  105189. }
  105190. if( pParse->db->mallocFailed ) return 0;
  105191. /* Suppress the first OFFSET entries if there is an OFFSET clause
  105192. */
  105193. codeOffset(v, p->iOffset, iContinue);
  105194. assert( pDest->eDest!=SRT_Exists );
  105195. assert( pDest->eDest!=SRT_Table );
  105196. switch( pDest->eDest ){
  105197. /* Store the result as data using a unique key.
  105198. */
  105199. case SRT_EphemTab: {
  105200. int r1 = sqlite3GetTempReg(pParse);
  105201. int r2 = sqlite3GetTempReg(pParse);
  105202. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  105203. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  105204. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  105205. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  105206. sqlite3ReleaseTempReg(pParse, r2);
  105207. sqlite3ReleaseTempReg(pParse, r1);
  105208. break;
  105209. }
  105210. #ifndef SQLITE_OMIT_SUBQUERY
  105211. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  105212. ** then there should be a single item on the stack. Write this
  105213. ** item into the set table with bogus data.
  105214. */
  105215. case SRT_Set: {
  105216. int r1;
  105217. assert( pIn->nSdst==1 || pParse->nErr>0 );
  105218. pDest->affSdst =
  105219. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  105220. r1 = sqlite3GetTempReg(pParse);
  105221. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  105222. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  105223. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  105224. sqlite3ReleaseTempReg(pParse, r1);
  105225. break;
  105226. }
  105227. /* If this is a scalar select that is part of an expression, then
  105228. ** store the results in the appropriate memory cell and break out
  105229. ** of the scan loop.
  105230. */
  105231. case SRT_Mem: {
  105232. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  105233. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  105234. /* The LIMIT clause will jump out of the loop for us */
  105235. break;
  105236. }
  105237. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  105238. /* The results are stored in a sequence of registers
  105239. ** starting at pDest->iSdst. Then the co-routine yields.
  105240. */
  105241. case SRT_Coroutine: {
  105242. if( pDest->iSdst==0 ){
  105243. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  105244. pDest->nSdst = pIn->nSdst;
  105245. }
  105246. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  105247. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  105248. break;
  105249. }
  105250. /* If none of the above, then the result destination must be
  105251. ** SRT_Output. This routine is never called with any other
  105252. ** destination other than the ones handled above or SRT_Output.
  105253. **
  105254. ** For SRT_Output, results are stored in a sequence of registers.
  105255. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  105256. ** return the next row of result.
  105257. */
  105258. default: {
  105259. assert( pDest->eDest==SRT_Output );
  105260. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  105261. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  105262. break;
  105263. }
  105264. }
  105265. /* Jump to the end of the loop if the LIMIT is reached.
  105266. */
  105267. if( p->iLimit ){
  105268. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  105269. }
  105270. /* Generate the subroutine return
  105271. */
  105272. sqlite3VdbeResolveLabel(v, iContinue);
  105273. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  105274. return addr;
  105275. }
  105276. /*
  105277. ** Alternative compound select code generator for cases when there
  105278. ** is an ORDER BY clause.
  105279. **
  105280. ** We assume a query of the following form:
  105281. **
  105282. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  105283. **
  105284. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  105285. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  105286. ** co-routines. Then run the co-routines in parallel and merge the results
  105287. ** into the output. In addition to the two coroutines (called selectA and
  105288. ** selectB) there are 7 subroutines:
  105289. **
  105290. ** outA: Move the output of the selectA coroutine into the output
  105291. ** of the compound query.
  105292. **
  105293. ** outB: Move the output of the selectB coroutine into the output
  105294. ** of the compound query. (Only generated for UNION and
  105295. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  105296. ** appears only in B.)
  105297. **
  105298. ** AltB: Called when there is data from both coroutines and A<B.
  105299. **
  105300. ** AeqB: Called when there is data from both coroutines and A==B.
  105301. **
  105302. ** AgtB: Called when there is data from both coroutines and A>B.
  105303. **
  105304. ** EofA: Called when data is exhausted from selectA.
  105305. **
  105306. ** EofB: Called when data is exhausted from selectB.
  105307. **
  105308. ** The implementation of the latter five subroutines depend on which
  105309. ** <operator> is used:
  105310. **
  105311. **
  105312. ** UNION ALL UNION EXCEPT INTERSECT
  105313. ** ------------- ----------------- -------------- -----------------
  105314. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  105315. **
  105316. ** AeqB: outA, nextA nextA nextA outA, nextA
  105317. **
  105318. ** AgtB: outB, nextB outB, nextB nextB nextB
  105319. **
  105320. ** EofA: outB, nextB outB, nextB halt halt
  105321. **
  105322. ** EofB: outA, nextA outA, nextA outA, nextA halt
  105323. **
  105324. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  105325. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  105326. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  105327. ** following nextX causes a jump to the end of the select processing.
  105328. **
  105329. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  105330. ** within the output subroutine. The regPrev register set holds the previously
  105331. ** output value. A comparison is made against this value and the output
  105332. ** is skipped if the next results would be the same as the previous.
  105333. **
  105334. ** The implementation plan is to implement the two coroutines and seven
  105335. ** subroutines first, then put the control logic at the bottom. Like this:
  105336. **
  105337. ** goto Init
  105338. ** coA: coroutine for left query (A)
  105339. ** coB: coroutine for right query (B)
  105340. ** outA: output one row of A
  105341. ** outB: output one row of B (UNION and UNION ALL only)
  105342. ** EofA: ...
  105343. ** EofB: ...
  105344. ** AltB: ...
  105345. ** AeqB: ...
  105346. ** AgtB: ...
  105347. ** Init: initialize coroutine registers
  105348. ** yield coA
  105349. ** if eof(A) goto EofA
  105350. ** yield coB
  105351. ** if eof(B) goto EofB
  105352. ** Cmpr: Compare A, B
  105353. ** Jump AltB, AeqB, AgtB
  105354. ** End: ...
  105355. **
  105356. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  105357. ** actually called using Gosub and they do not Return. EofA and EofB loop
  105358. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  105359. ** and AgtB jump to either L2 or to one of EofA or EofB.
  105360. */
  105361. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  105362. static int multiSelectOrderBy(
  105363. Parse *pParse, /* Parsing context */
  105364. Select *p, /* The right-most of SELECTs to be coded */
  105365. SelectDest *pDest /* What to do with query results */
  105366. ){
  105367. int i, j; /* Loop counters */
  105368. Select *pPrior; /* Another SELECT immediately to our left */
  105369. Vdbe *v; /* Generate code to this VDBE */
  105370. SelectDest destA; /* Destination for coroutine A */
  105371. SelectDest destB; /* Destination for coroutine B */
  105372. int regAddrA; /* Address register for select-A coroutine */
  105373. int regAddrB; /* Address register for select-B coroutine */
  105374. int addrSelectA; /* Address of the select-A coroutine */
  105375. int addrSelectB; /* Address of the select-B coroutine */
  105376. int regOutA; /* Address register for the output-A subroutine */
  105377. int regOutB; /* Address register for the output-B subroutine */
  105378. int addrOutA; /* Address of the output-A subroutine */
  105379. int addrOutB = 0; /* Address of the output-B subroutine */
  105380. int addrEofA; /* Address of the select-A-exhausted subroutine */
  105381. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  105382. int addrEofB; /* Address of the select-B-exhausted subroutine */
  105383. int addrAltB; /* Address of the A<B subroutine */
  105384. int addrAeqB; /* Address of the A==B subroutine */
  105385. int addrAgtB; /* Address of the A>B subroutine */
  105386. int regLimitA; /* Limit register for select-A */
  105387. int regLimitB; /* Limit register for select-A */
  105388. int regPrev; /* A range of registers to hold previous output */
  105389. int savedLimit; /* Saved value of p->iLimit */
  105390. int savedOffset; /* Saved value of p->iOffset */
  105391. int labelCmpr; /* Label for the start of the merge algorithm */
  105392. int labelEnd; /* Label for the end of the overall SELECT stmt */
  105393. int addr1; /* Jump instructions that get retargetted */
  105394. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  105395. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  105396. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  105397. sqlite3 *db; /* Database connection */
  105398. ExprList *pOrderBy; /* The ORDER BY clause */
  105399. int nOrderBy; /* Number of terms in the ORDER BY clause */
  105400. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  105401. #ifndef SQLITE_OMIT_EXPLAIN
  105402. int iSub1; /* EQP id of left-hand query */
  105403. int iSub2; /* EQP id of right-hand query */
  105404. #endif
  105405. assert( p->pOrderBy!=0 );
  105406. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  105407. db = pParse->db;
  105408. v = pParse->pVdbe;
  105409. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  105410. labelEnd = sqlite3VdbeMakeLabel(v);
  105411. labelCmpr = sqlite3VdbeMakeLabel(v);
  105412. /* Patch up the ORDER BY clause
  105413. */
  105414. op = p->op;
  105415. pPrior = p->pPrior;
  105416. assert( pPrior->pOrderBy==0 );
  105417. pOrderBy = p->pOrderBy;
  105418. assert( pOrderBy );
  105419. nOrderBy = pOrderBy->nExpr;
  105420. /* For operators other than UNION ALL we have to make sure that
  105421. ** the ORDER BY clause covers every term of the result set. Add
  105422. ** terms to the ORDER BY clause as necessary.
  105423. */
  105424. if( op!=TK_ALL ){
  105425. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  105426. struct ExprList_item *pItem;
  105427. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  105428. assert( pItem->u.x.iOrderByCol>0 );
  105429. if( pItem->u.x.iOrderByCol==i ) break;
  105430. }
  105431. if( j==nOrderBy ){
  105432. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  105433. if( pNew==0 ) return SQLITE_NOMEM;
  105434. pNew->flags |= EP_IntValue;
  105435. pNew->u.iValue = i;
  105436. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  105437. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  105438. }
  105439. }
  105440. }
  105441. /* Compute the comparison permutation and keyinfo that is used with
  105442. ** the permutation used to determine if the next
  105443. ** row of results comes from selectA or selectB. Also add explicit
  105444. ** collations to the ORDER BY clause terms so that when the subqueries
  105445. ** to the right and the left are evaluated, they use the correct
  105446. ** collation.
  105447. */
  105448. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  105449. if( aPermute ){
  105450. struct ExprList_item *pItem;
  105451. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  105452. assert( pItem->u.x.iOrderByCol>0 );
  105453. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  105454. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  105455. }
  105456. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  105457. }else{
  105458. pKeyMerge = 0;
  105459. }
  105460. /* Reattach the ORDER BY clause to the query.
  105461. */
  105462. p->pOrderBy = pOrderBy;
  105463. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  105464. /* Allocate a range of temporary registers and the KeyInfo needed
  105465. ** for the logic that removes duplicate result rows when the
  105466. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  105467. */
  105468. if( op==TK_ALL ){
  105469. regPrev = 0;
  105470. }else{
  105471. int nExpr = p->pEList->nExpr;
  105472. assert( nOrderBy>=nExpr || db->mallocFailed );
  105473. regPrev = pParse->nMem+1;
  105474. pParse->nMem += nExpr+1;
  105475. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  105476. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  105477. if( pKeyDup ){
  105478. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  105479. for(i=0; i<nExpr; i++){
  105480. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  105481. pKeyDup->aSortOrder[i] = 0;
  105482. }
  105483. }
  105484. }
  105485. /* Separate the left and the right query from one another
  105486. */
  105487. p->pPrior = 0;
  105488. pPrior->pNext = 0;
  105489. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  105490. if( pPrior->pPrior==0 ){
  105491. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  105492. }
  105493. /* Compute the limit registers */
  105494. computeLimitRegisters(pParse, p, labelEnd);
  105495. if( p->iLimit && op==TK_ALL ){
  105496. regLimitA = ++pParse->nMem;
  105497. regLimitB = ++pParse->nMem;
  105498. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  105499. regLimitA);
  105500. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  105501. }else{
  105502. regLimitA = regLimitB = 0;
  105503. }
  105504. sqlite3ExprDelete(db, p->pLimit);
  105505. p->pLimit = 0;
  105506. sqlite3ExprDelete(db, p->pOffset);
  105507. p->pOffset = 0;
  105508. regAddrA = ++pParse->nMem;
  105509. regAddrB = ++pParse->nMem;
  105510. regOutA = ++pParse->nMem;
  105511. regOutB = ++pParse->nMem;
  105512. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  105513. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  105514. /* Generate a coroutine to evaluate the SELECT statement to the
  105515. ** left of the compound operator - the "A" select.
  105516. */
  105517. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  105518. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  105519. VdbeComment((v, "left SELECT"));
  105520. pPrior->iLimit = regLimitA;
  105521. explainSetInteger(iSub1, pParse->iNextSelectId);
  105522. sqlite3Select(pParse, pPrior, &destA);
  105523. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
  105524. sqlite3VdbeJumpHere(v, addr1);
  105525. /* Generate a coroutine to evaluate the SELECT statement on
  105526. ** the right - the "B" select
  105527. */
  105528. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  105529. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  105530. VdbeComment((v, "right SELECT"));
  105531. savedLimit = p->iLimit;
  105532. savedOffset = p->iOffset;
  105533. p->iLimit = regLimitB;
  105534. p->iOffset = 0;
  105535. explainSetInteger(iSub2, pParse->iNextSelectId);
  105536. sqlite3Select(pParse, p, &destB);
  105537. p->iLimit = savedLimit;
  105538. p->iOffset = savedOffset;
  105539. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
  105540. /* Generate a subroutine that outputs the current row of the A
  105541. ** select as the next output row of the compound select.
  105542. */
  105543. VdbeNoopComment((v, "Output routine for A"));
  105544. addrOutA = generateOutputSubroutine(pParse,
  105545. p, &destA, pDest, regOutA,
  105546. regPrev, pKeyDup, labelEnd);
  105547. /* Generate a subroutine that outputs the current row of the B
  105548. ** select as the next output row of the compound select.
  105549. */
  105550. if( op==TK_ALL || op==TK_UNION ){
  105551. VdbeNoopComment((v, "Output routine for B"));
  105552. addrOutB = generateOutputSubroutine(pParse,
  105553. p, &destB, pDest, regOutB,
  105554. regPrev, pKeyDup, labelEnd);
  105555. }
  105556. sqlite3KeyInfoUnref(pKeyDup);
  105557. /* Generate a subroutine to run when the results from select A
  105558. ** are exhausted and only data in select B remains.
  105559. */
  105560. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  105561. addrEofA_noB = addrEofA = labelEnd;
  105562. }else{
  105563. VdbeNoopComment((v, "eof-A subroutine"));
  105564. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  105565. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  105566. VdbeCoverage(v);
  105567. sqlite3VdbeGoto(v, addrEofA);
  105568. p->nSelectRow += pPrior->nSelectRow;
  105569. }
  105570. /* Generate a subroutine to run when the results from select B
  105571. ** are exhausted and only data in select A remains.
  105572. */
  105573. if( op==TK_INTERSECT ){
  105574. addrEofB = addrEofA;
  105575. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  105576. }else{
  105577. VdbeNoopComment((v, "eof-B subroutine"));
  105578. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  105579. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  105580. sqlite3VdbeGoto(v, addrEofB);
  105581. }
  105582. /* Generate code to handle the case of A<B
  105583. */
  105584. VdbeNoopComment((v, "A-lt-B subroutine"));
  105585. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  105586. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  105587. sqlite3VdbeGoto(v, labelCmpr);
  105588. /* Generate code to handle the case of A==B
  105589. */
  105590. if( op==TK_ALL ){
  105591. addrAeqB = addrAltB;
  105592. }else if( op==TK_INTERSECT ){
  105593. addrAeqB = addrAltB;
  105594. addrAltB++;
  105595. }else{
  105596. VdbeNoopComment((v, "A-eq-B subroutine"));
  105597. addrAeqB =
  105598. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  105599. sqlite3VdbeGoto(v, labelCmpr);
  105600. }
  105601. /* Generate code to handle the case of A>B
  105602. */
  105603. VdbeNoopComment((v, "A-gt-B subroutine"));
  105604. addrAgtB = sqlite3VdbeCurrentAddr(v);
  105605. if( op==TK_ALL || op==TK_UNION ){
  105606. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  105607. }
  105608. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  105609. sqlite3VdbeGoto(v, labelCmpr);
  105610. /* This code runs once to initialize everything.
  105611. */
  105612. sqlite3VdbeJumpHere(v, addr1);
  105613. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  105614. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  105615. /* Implement the main merge loop
  105616. */
  105617. sqlite3VdbeResolveLabel(v, labelCmpr);
  105618. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  105619. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  105620. (char*)pKeyMerge, P4_KEYINFO);
  105621. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  105622. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  105623. /* Jump to the this point in order to terminate the query.
  105624. */
  105625. sqlite3VdbeResolveLabel(v, labelEnd);
  105626. /* Set the number of output columns
  105627. */
  105628. if( pDest->eDest==SRT_Output ){
  105629. Select *pFirst = pPrior;
  105630. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  105631. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  105632. }
  105633. /* Reassembly the compound query so that it will be freed correctly
  105634. ** by the calling function */
  105635. if( p->pPrior ){
  105636. sqlite3SelectDelete(db, p->pPrior);
  105637. }
  105638. p->pPrior = pPrior;
  105639. pPrior->pNext = p;
  105640. /*** TBD: Insert subroutine calls to close cursors on incomplete
  105641. **** subqueries ****/
  105642. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  105643. return pParse->nErr!=0;
  105644. }
  105645. #endif
  105646. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  105647. /* Forward Declarations */
  105648. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  105649. static void substSelect(sqlite3*, Select *, int, ExprList*, int);
  105650. /*
  105651. ** Scan through the expression pExpr. Replace every reference to
  105652. ** a column in table number iTable with a copy of the iColumn-th
  105653. ** entry in pEList. (But leave references to the ROWID column
  105654. ** unchanged.)
  105655. **
  105656. ** This routine is part of the flattening procedure. A subquery
  105657. ** whose result set is defined by pEList appears as entry in the
  105658. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  105659. ** FORM clause entry is iTable. This routine make the necessary
  105660. ** changes to pExpr so that it refers directly to the source table
  105661. ** of the subquery rather the result set of the subquery.
  105662. */
  105663. static Expr *substExpr(
  105664. sqlite3 *db, /* Report malloc errors to this connection */
  105665. Expr *pExpr, /* Expr in which substitution occurs */
  105666. int iTable, /* Table to be substituted */
  105667. ExprList *pEList /* Substitute expressions */
  105668. ){
  105669. if( pExpr==0 ) return 0;
  105670. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  105671. if( pExpr->iColumn<0 ){
  105672. pExpr->op = TK_NULL;
  105673. }else{
  105674. Expr *pNew;
  105675. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  105676. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  105677. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  105678. sqlite3ExprDelete(db, pExpr);
  105679. pExpr = pNew;
  105680. }
  105681. }else{
  105682. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  105683. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  105684. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  105685. substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
  105686. }else{
  105687. substExprList(db, pExpr->x.pList, iTable, pEList);
  105688. }
  105689. }
  105690. return pExpr;
  105691. }
  105692. static void substExprList(
  105693. sqlite3 *db, /* Report malloc errors here */
  105694. ExprList *pList, /* List to scan and in which to make substitutes */
  105695. int iTable, /* Table to be substituted */
  105696. ExprList *pEList /* Substitute values */
  105697. ){
  105698. int i;
  105699. if( pList==0 ) return;
  105700. for(i=0; i<pList->nExpr; i++){
  105701. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  105702. }
  105703. }
  105704. static void substSelect(
  105705. sqlite3 *db, /* Report malloc errors here */
  105706. Select *p, /* SELECT statement in which to make substitutions */
  105707. int iTable, /* Table to be replaced */
  105708. ExprList *pEList, /* Substitute values */
  105709. int doPrior /* Do substitutes on p->pPrior too */
  105710. ){
  105711. SrcList *pSrc;
  105712. struct SrcList_item *pItem;
  105713. int i;
  105714. if( !p ) return;
  105715. do{
  105716. substExprList(db, p->pEList, iTable, pEList);
  105717. substExprList(db, p->pGroupBy, iTable, pEList);
  105718. substExprList(db, p->pOrderBy, iTable, pEList);
  105719. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  105720. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  105721. pSrc = p->pSrc;
  105722. assert( pSrc!=0 );
  105723. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  105724. substSelect(db, pItem->pSelect, iTable, pEList, 1);
  105725. if( pItem->fg.isTabFunc ){
  105726. substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
  105727. }
  105728. }
  105729. }while( doPrior && (p = p->pPrior)!=0 );
  105730. }
  105731. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  105732. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  105733. /*
  105734. ** This routine attempts to flatten subqueries as a performance optimization.
  105735. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  105736. **
  105737. ** To understand the concept of flattening, consider the following
  105738. ** query:
  105739. **
  105740. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  105741. **
  105742. ** The default way of implementing this query is to execute the
  105743. ** subquery first and store the results in a temporary table, then
  105744. ** run the outer query on that temporary table. This requires two
  105745. ** passes over the data. Furthermore, because the temporary table
  105746. ** has no indices, the WHERE clause on the outer query cannot be
  105747. ** optimized.
  105748. **
  105749. ** This routine attempts to rewrite queries such as the above into
  105750. ** a single flat select, like this:
  105751. **
  105752. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  105753. **
  105754. ** The code generated for this simplification gives the same result
  105755. ** but only has to scan the data once. And because indices might
  105756. ** exist on the table t1, a complete scan of the data might be
  105757. ** avoided.
  105758. **
  105759. ** Flattening is only attempted if all of the following are true:
  105760. **
  105761. ** (1) The subquery and the outer query do not both use aggregates.
  105762. **
  105763. ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
  105764. ** and (2b) the outer query does not use subqueries other than the one
  105765. ** FROM-clause subquery that is a candidate for flattening. (2b is
  105766. ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
  105767. **
  105768. ** (3) The subquery is not the right operand of a left outer join
  105769. ** (Originally ticket #306. Strengthened by ticket #3300)
  105770. **
  105771. ** (4) The subquery is not DISTINCT.
  105772. **
  105773. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  105774. ** sub-queries that were excluded from this optimization. Restriction
  105775. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  105776. **
  105777. ** (6) The subquery does not use aggregates or the outer query is not
  105778. ** DISTINCT.
  105779. **
  105780. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  105781. ** A FROM clause, consider adding a FROM close with the special
  105782. ** table sqlite_once that consists of a single row containing a
  105783. ** single NULL.
  105784. **
  105785. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  105786. **
  105787. ** (9) The subquery does not use LIMIT or the outer query does not use
  105788. ** aggregates.
  105789. **
  105790. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  105791. ** accidently carried the comment forward until 2014-09-15. Original
  105792. ** text: "The subquery does not use aggregates or the outer query
  105793. ** does not use LIMIT."
  105794. **
  105795. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  105796. **
  105797. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  105798. ** a separate restriction deriving from ticket #350.
  105799. **
  105800. ** (13) The subquery and outer query do not both use LIMIT.
  105801. **
  105802. ** (14) The subquery does not use OFFSET.
  105803. **
  105804. ** (15) The outer query is not part of a compound select or the
  105805. ** subquery does not have a LIMIT clause.
  105806. ** (See ticket #2339 and ticket [02a8e81d44]).
  105807. **
  105808. ** (16) The outer query is not an aggregate or the subquery does
  105809. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  105810. ** until we introduced the group_concat() function.
  105811. **
  105812. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  105813. ** compound clause made up entirely of non-aggregate queries, and
  105814. ** the parent query:
  105815. **
  105816. ** * is not itself part of a compound select,
  105817. ** * is not an aggregate or DISTINCT query, and
  105818. ** * is not a join
  105819. **
  105820. ** The parent and sub-query may contain WHERE clauses. Subject to
  105821. ** rules (11), (13) and (14), they may also contain ORDER BY,
  105822. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  105823. ** operator other than UNION ALL because all the other compound
  105824. ** operators have an implied DISTINCT which is disallowed by
  105825. ** restriction (4).
  105826. **
  105827. ** Also, each component of the sub-query must return the same number
  105828. ** of result columns. This is actually a requirement for any compound
  105829. ** SELECT statement, but all the code here does is make sure that no
  105830. ** such (illegal) sub-query is flattened. The caller will detect the
  105831. ** syntax error and return a detailed message.
  105832. **
  105833. ** (18) If the sub-query is a compound select, then all terms of the
  105834. ** ORDER by clause of the parent must be simple references to
  105835. ** columns of the sub-query.
  105836. **
  105837. ** (19) The subquery does not use LIMIT or the outer query does not
  105838. ** have a WHERE clause.
  105839. **
  105840. ** (20) If the sub-query is a compound select, then it must not use
  105841. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  105842. ** somewhat by saying that the terms of the ORDER BY clause must
  105843. ** appear as unmodified result columns in the outer query. But we
  105844. ** have other optimizations in mind to deal with that case.
  105845. **
  105846. ** (21) The subquery does not use LIMIT or the outer query is not
  105847. ** DISTINCT. (See ticket [752e1646fc]).
  105848. **
  105849. ** (22) The subquery is not a recursive CTE.
  105850. **
  105851. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  105852. ** compound query. This restriction is because transforming the
  105853. ** parent to a compound query confuses the code that handles
  105854. ** recursive queries in multiSelect().
  105855. **
  105856. ** (24) The subquery is not an aggregate that uses the built-in min() or
  105857. ** or max() functions. (Without this restriction, a query like:
  105858. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  105859. ** return the value X for which Y was maximal.)
  105860. **
  105861. **
  105862. ** In this routine, the "p" parameter is a pointer to the outer query.
  105863. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  105864. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  105865. **
  105866. ** If flattening is not attempted, this routine is a no-op and returns 0.
  105867. ** If flattening is attempted this routine returns 1.
  105868. **
  105869. ** All of the expression analysis must occur on both the outer query and
  105870. ** the subquery before this routine runs.
  105871. */
  105872. static int flattenSubquery(
  105873. Parse *pParse, /* Parsing context */
  105874. Select *p, /* The parent or outer SELECT statement */
  105875. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  105876. int isAgg, /* True if outer SELECT uses aggregate functions */
  105877. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  105878. ){
  105879. const char *zSavedAuthContext = pParse->zAuthContext;
  105880. Select *pParent; /* Current UNION ALL term of the other query */
  105881. Select *pSub; /* The inner query or "subquery" */
  105882. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  105883. SrcList *pSrc; /* The FROM clause of the outer query */
  105884. SrcList *pSubSrc; /* The FROM clause of the subquery */
  105885. ExprList *pList; /* The result set of the outer query */
  105886. int iParent; /* VDBE cursor number of the pSub result set temp table */
  105887. int i; /* Loop counter */
  105888. Expr *pWhere; /* The WHERE clause */
  105889. struct SrcList_item *pSubitem; /* The subquery */
  105890. sqlite3 *db = pParse->db;
  105891. /* Check to see if flattening is permitted. Return 0 if not.
  105892. */
  105893. assert( p!=0 );
  105894. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  105895. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  105896. pSrc = p->pSrc;
  105897. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  105898. pSubitem = &pSrc->a[iFrom];
  105899. iParent = pSubitem->iCursor;
  105900. pSub = pSubitem->pSelect;
  105901. assert( pSub!=0 );
  105902. if( subqueryIsAgg ){
  105903. if( isAgg ) return 0; /* Restriction (1) */
  105904. if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
  105905. if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
  105906. || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
  105907. || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
  105908. ){
  105909. return 0; /* Restriction (2b) */
  105910. }
  105911. }
  105912. pSubSrc = pSub->pSrc;
  105913. assert( pSubSrc );
  105914. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  105915. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  105916. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  105917. ** became arbitrary expressions, we were forced to add restrictions (13)
  105918. ** and (14). */
  105919. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  105920. if( pSub->pOffset ) return 0; /* Restriction (14) */
  105921. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  105922. return 0; /* Restriction (15) */
  105923. }
  105924. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  105925. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  105926. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  105927. return 0; /* Restrictions (8)(9) */
  105928. }
  105929. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  105930. return 0; /* Restriction (6) */
  105931. }
  105932. if( p->pOrderBy && pSub->pOrderBy ){
  105933. return 0; /* Restriction (11) */
  105934. }
  105935. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  105936. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  105937. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  105938. return 0; /* Restriction (21) */
  105939. }
  105940. testcase( pSub->selFlags & SF_Recursive );
  105941. testcase( pSub->selFlags & SF_MinMaxAgg );
  105942. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  105943. return 0; /* Restrictions (22) and (24) */
  105944. }
  105945. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  105946. return 0; /* Restriction (23) */
  105947. }
  105948. /* OBSOLETE COMMENT 1:
  105949. ** Restriction 3: If the subquery is a join, make sure the subquery is
  105950. ** not used as the right operand of an outer join. Examples of why this
  105951. ** is not allowed:
  105952. **
  105953. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  105954. **
  105955. ** If we flatten the above, we would get
  105956. **
  105957. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  105958. **
  105959. ** which is not at all the same thing.
  105960. **
  105961. ** OBSOLETE COMMENT 2:
  105962. ** Restriction 12: If the subquery is the right operand of a left outer
  105963. ** join, make sure the subquery has no WHERE clause.
  105964. ** An examples of why this is not allowed:
  105965. **
  105966. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  105967. **
  105968. ** If we flatten the above, we would get
  105969. **
  105970. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  105971. **
  105972. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  105973. ** effectively converts the OUTER JOIN into an INNER JOIN.
  105974. **
  105975. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  105976. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  105977. ** is fraught with danger. Best to avoid the whole thing. If the
  105978. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  105979. */
  105980. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  105981. return 0;
  105982. }
  105983. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  105984. ** use only the UNION ALL operator. And none of the simple select queries
  105985. ** that make up the compound SELECT are allowed to be aggregate or distinct
  105986. ** queries.
  105987. */
  105988. if( pSub->pPrior ){
  105989. if( pSub->pOrderBy ){
  105990. return 0; /* Restriction 20 */
  105991. }
  105992. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  105993. return 0;
  105994. }
  105995. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  105996. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  105997. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  105998. assert( pSub->pSrc!=0 );
  105999. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  106000. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  106001. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  106002. || pSub1->pSrc->nSrc<1
  106003. ){
  106004. return 0;
  106005. }
  106006. testcase( pSub1->pSrc->nSrc>1 );
  106007. }
  106008. /* Restriction 18. */
  106009. if( p->pOrderBy ){
  106010. int ii;
  106011. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  106012. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  106013. }
  106014. }
  106015. }
  106016. /***** If we reach this point, flattening is permitted. *****/
  106017. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  106018. pSub->zSelName, pSub, iFrom));
  106019. /* Authorize the subquery */
  106020. pParse->zAuthContext = pSubitem->zName;
  106021. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  106022. testcase( i==SQLITE_DENY );
  106023. pParse->zAuthContext = zSavedAuthContext;
  106024. /* If the sub-query is a compound SELECT statement, then (by restrictions
  106025. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  106026. ** be of the form:
  106027. **
  106028. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  106029. **
  106030. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  106031. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  106032. ** OFFSET clauses and joins them to the left-hand-side of the original
  106033. ** using UNION ALL operators. In this case N is the number of simple
  106034. ** select statements in the compound sub-query.
  106035. **
  106036. ** Example:
  106037. **
  106038. ** SELECT a+1 FROM (
  106039. ** SELECT x FROM tab
  106040. ** UNION ALL
  106041. ** SELECT y FROM tab
  106042. ** UNION ALL
  106043. ** SELECT abs(z*2) FROM tab2
  106044. ** ) WHERE a!=5 ORDER BY 1
  106045. **
  106046. ** Transformed into:
  106047. **
  106048. ** SELECT x+1 FROM tab WHERE x+1!=5
  106049. ** UNION ALL
  106050. ** SELECT y+1 FROM tab WHERE y+1!=5
  106051. ** UNION ALL
  106052. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  106053. ** ORDER BY 1
  106054. **
  106055. ** We call this the "compound-subquery flattening".
  106056. */
  106057. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  106058. Select *pNew;
  106059. ExprList *pOrderBy = p->pOrderBy;
  106060. Expr *pLimit = p->pLimit;
  106061. Expr *pOffset = p->pOffset;
  106062. Select *pPrior = p->pPrior;
  106063. p->pOrderBy = 0;
  106064. p->pSrc = 0;
  106065. p->pPrior = 0;
  106066. p->pLimit = 0;
  106067. p->pOffset = 0;
  106068. pNew = sqlite3SelectDup(db, p, 0);
  106069. sqlite3SelectSetName(pNew, pSub->zSelName);
  106070. p->pOffset = pOffset;
  106071. p->pLimit = pLimit;
  106072. p->pOrderBy = pOrderBy;
  106073. p->pSrc = pSrc;
  106074. p->op = TK_ALL;
  106075. if( pNew==0 ){
  106076. p->pPrior = pPrior;
  106077. }else{
  106078. pNew->pPrior = pPrior;
  106079. if( pPrior ) pPrior->pNext = pNew;
  106080. pNew->pNext = p;
  106081. p->pPrior = pNew;
  106082. SELECTTRACE(2,pParse,p,
  106083. ("compound-subquery flattener creates %s.%p as peer\n",
  106084. pNew->zSelName, pNew));
  106085. }
  106086. if( db->mallocFailed ) return 1;
  106087. }
  106088. /* Begin flattening the iFrom-th entry of the FROM clause
  106089. ** in the outer query.
  106090. */
  106091. pSub = pSub1 = pSubitem->pSelect;
  106092. /* Delete the transient table structure associated with the
  106093. ** subquery
  106094. */
  106095. sqlite3DbFree(db, pSubitem->zDatabase);
  106096. sqlite3DbFree(db, pSubitem->zName);
  106097. sqlite3DbFree(db, pSubitem->zAlias);
  106098. pSubitem->zDatabase = 0;
  106099. pSubitem->zName = 0;
  106100. pSubitem->zAlias = 0;
  106101. pSubitem->pSelect = 0;
  106102. /* Defer deleting the Table object associated with the
  106103. ** subquery until code generation is
  106104. ** complete, since there may still exist Expr.pTab entries that
  106105. ** refer to the subquery even after flattening. Ticket #3346.
  106106. **
  106107. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  106108. */
  106109. if( ALWAYS(pSubitem->pTab!=0) ){
  106110. Table *pTabToDel = pSubitem->pTab;
  106111. if( pTabToDel->nRef==1 ){
  106112. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  106113. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  106114. pToplevel->pZombieTab = pTabToDel;
  106115. }else{
  106116. pTabToDel->nRef--;
  106117. }
  106118. pSubitem->pTab = 0;
  106119. }
  106120. /* The following loop runs once for each term in a compound-subquery
  106121. ** flattening (as described above). If we are doing a different kind
  106122. ** of flattening - a flattening other than a compound-subquery flattening -
  106123. ** then this loop only runs once.
  106124. **
  106125. ** This loop moves all of the FROM elements of the subquery into the
  106126. ** the FROM clause of the outer query. Before doing this, remember
  106127. ** the cursor number for the original outer query FROM element in
  106128. ** iParent. The iParent cursor will never be used. Subsequent code
  106129. ** will scan expressions looking for iParent references and replace
  106130. ** those references with expressions that resolve to the subquery FROM
  106131. ** elements we are now copying in.
  106132. */
  106133. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  106134. int nSubSrc;
  106135. u8 jointype = 0;
  106136. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  106137. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  106138. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  106139. if( pSrc ){
  106140. assert( pParent==p ); /* First time through the loop */
  106141. jointype = pSubitem->fg.jointype;
  106142. }else{
  106143. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  106144. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  106145. if( pSrc==0 ){
  106146. assert( db->mallocFailed );
  106147. break;
  106148. }
  106149. }
  106150. /* The subquery uses a single slot of the FROM clause of the outer
  106151. ** query. If the subquery has more than one element in its FROM clause,
  106152. ** then expand the outer query to make space for it to hold all elements
  106153. ** of the subquery.
  106154. **
  106155. ** Example:
  106156. **
  106157. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  106158. **
  106159. ** The outer query has 3 slots in its FROM clause. One slot of the
  106160. ** outer query (the middle slot) is used by the subquery. The next
  106161. ** block of code will expand the outer query FROM clause to 4 slots.
  106162. ** The middle slot is expanded to two slots in order to make space
  106163. ** for the two elements in the FROM clause of the subquery.
  106164. */
  106165. if( nSubSrc>1 ){
  106166. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  106167. if( db->mallocFailed ){
  106168. break;
  106169. }
  106170. }
  106171. /* Transfer the FROM clause terms from the subquery into the
  106172. ** outer query.
  106173. */
  106174. for(i=0; i<nSubSrc; i++){
  106175. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  106176. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  106177. pSrc->a[i+iFrom] = pSubSrc->a[i];
  106178. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  106179. }
  106180. pSrc->a[iFrom].fg.jointype = jointype;
  106181. /* Now begin substituting subquery result set expressions for
  106182. ** references to the iParent in the outer query.
  106183. **
  106184. ** Example:
  106185. **
  106186. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  106187. ** \ \_____________ subquery __________/ /
  106188. ** \_____________________ outer query ______________________________/
  106189. **
  106190. ** We look at every expression in the outer query and every place we see
  106191. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  106192. */
  106193. pList = pParent->pEList;
  106194. for(i=0; i<pList->nExpr; i++){
  106195. if( pList->a[i].zName==0 ){
  106196. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  106197. sqlite3Dequote(zName);
  106198. pList->a[i].zName = zName;
  106199. }
  106200. }
  106201. if( pSub->pOrderBy ){
  106202. /* At this point, any non-zero iOrderByCol values indicate that the
  106203. ** ORDER BY column expression is identical to the iOrderByCol'th
  106204. ** expression returned by SELECT statement pSub. Since these values
  106205. ** do not necessarily correspond to columns in SELECT statement pParent,
  106206. ** zero them before transfering the ORDER BY clause.
  106207. **
  106208. ** Not doing this may cause an error if a subsequent call to this
  106209. ** function attempts to flatten a compound sub-query into pParent
  106210. ** (the only way this can happen is if the compound sub-query is
  106211. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  106212. ExprList *pOrderBy = pSub->pOrderBy;
  106213. for(i=0; i<pOrderBy->nExpr; i++){
  106214. pOrderBy->a[i].u.x.iOrderByCol = 0;
  106215. }
  106216. assert( pParent->pOrderBy==0 );
  106217. assert( pSub->pPrior==0 );
  106218. pParent->pOrderBy = pOrderBy;
  106219. pSub->pOrderBy = 0;
  106220. }
  106221. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  106222. if( subqueryIsAgg ){
  106223. assert( pParent->pHaving==0 );
  106224. pParent->pHaving = pParent->pWhere;
  106225. pParent->pWhere = pWhere;
  106226. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  106227. sqlite3ExprDup(db, pSub->pHaving, 0));
  106228. assert( pParent->pGroupBy==0 );
  106229. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  106230. }else{
  106231. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  106232. }
  106233. substSelect(db, pParent, iParent, pSub->pEList, 0);
  106234. /* The flattened query is distinct if either the inner or the
  106235. ** outer query is distinct.
  106236. */
  106237. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  106238. /*
  106239. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  106240. **
  106241. ** One is tempted to try to add a and b to combine the limits. But this
  106242. ** does not work if either limit is negative.
  106243. */
  106244. if( pSub->pLimit ){
  106245. pParent->pLimit = pSub->pLimit;
  106246. pSub->pLimit = 0;
  106247. }
  106248. }
  106249. /* Finially, delete what is left of the subquery and return
  106250. ** success.
  106251. */
  106252. sqlite3SelectDelete(db, pSub1);
  106253. #if SELECTTRACE_ENABLED
  106254. if( sqlite3SelectTrace & 0x100 ){
  106255. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  106256. sqlite3TreeViewSelect(0, p, 0);
  106257. }
  106258. #endif
  106259. return 1;
  106260. }
  106261. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  106262. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  106263. /*
  106264. ** Make copies of relevant WHERE clause terms of the outer query into
  106265. ** the WHERE clause of subquery. Example:
  106266. **
  106267. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  106268. **
  106269. ** Transformed into:
  106270. **
  106271. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  106272. ** WHERE x=5 AND y=10;
  106273. **
  106274. ** The hope is that the terms added to the inner query will make it more
  106275. ** efficient.
  106276. **
  106277. ** Do not attempt this optimization if:
  106278. **
  106279. ** (1) The inner query is an aggregate. (In that case, we'd really want
  106280. ** to copy the outer WHERE-clause terms onto the HAVING clause of the
  106281. ** inner query. But they probably won't help there so do not bother.)
  106282. **
  106283. ** (2) The inner query is the recursive part of a common table expression.
  106284. **
  106285. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  106286. ** close would change the meaning of the LIMIT).
  106287. **
  106288. ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
  106289. ** enforces this restriction since this routine does not have enough
  106290. ** information to know.)
  106291. **
  106292. ** (5) The WHERE clause expression originates in the ON or USING clause
  106293. ** of a LEFT JOIN.
  106294. **
  106295. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  106296. ** terms are duplicated into the subquery.
  106297. */
  106298. static int pushDownWhereTerms(
  106299. sqlite3 *db, /* The database connection (for malloc()) */
  106300. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  106301. Expr *pWhere, /* The WHERE clause of the outer query */
  106302. int iCursor /* Cursor number of the subquery */
  106303. ){
  106304. Expr *pNew;
  106305. int nChng = 0;
  106306. if( pWhere==0 ) return 0;
  106307. if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
  106308. return 0; /* restrictions (1) and (2) */
  106309. }
  106310. if( pSubq->pLimit!=0 ){
  106311. return 0; /* restriction (3) */
  106312. }
  106313. while( pWhere->op==TK_AND ){
  106314. nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
  106315. pWhere = pWhere->pLeft;
  106316. }
  106317. if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
  106318. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  106319. nChng++;
  106320. while( pSubq ){
  106321. pNew = sqlite3ExprDup(db, pWhere, 0);
  106322. pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
  106323. pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
  106324. pSubq = pSubq->pPrior;
  106325. }
  106326. }
  106327. return nChng;
  106328. }
  106329. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  106330. /*
  106331. ** Based on the contents of the AggInfo structure indicated by the first
  106332. ** argument, this function checks if the following are true:
  106333. **
  106334. ** * the query contains just a single aggregate function,
  106335. ** * the aggregate function is either min() or max(), and
  106336. ** * the argument to the aggregate function is a column value.
  106337. **
  106338. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  106339. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  106340. ** list of arguments passed to the aggregate before returning.
  106341. **
  106342. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  106343. ** WHERE_ORDERBY_NORMAL is returned.
  106344. */
  106345. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  106346. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  106347. *ppMinMax = 0;
  106348. if( pAggInfo->nFunc==1 ){
  106349. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  106350. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  106351. assert( pExpr->op==TK_AGG_FUNCTION );
  106352. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  106353. const char *zFunc = pExpr->u.zToken;
  106354. if( sqlite3StrICmp(zFunc, "min")==0 ){
  106355. eRet = WHERE_ORDERBY_MIN;
  106356. *ppMinMax = pEList;
  106357. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  106358. eRet = WHERE_ORDERBY_MAX;
  106359. *ppMinMax = pEList;
  106360. }
  106361. }
  106362. }
  106363. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  106364. return eRet;
  106365. }
  106366. /*
  106367. ** The select statement passed as the first argument is an aggregate query.
  106368. ** The second argument is the associated aggregate-info object. This
  106369. ** function tests if the SELECT is of the form:
  106370. **
  106371. ** SELECT count(*) FROM <tbl>
  106372. **
  106373. ** where table is a database table, not a sub-select or view. If the query
  106374. ** does match this pattern, then a pointer to the Table object representing
  106375. ** <tbl> is returned. Otherwise, 0 is returned.
  106376. */
  106377. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  106378. Table *pTab;
  106379. Expr *pExpr;
  106380. assert( !p->pGroupBy );
  106381. if( p->pWhere || p->pEList->nExpr!=1
  106382. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  106383. ){
  106384. return 0;
  106385. }
  106386. pTab = p->pSrc->a[0].pTab;
  106387. pExpr = p->pEList->a[0].pExpr;
  106388. assert( pTab && !pTab->pSelect && pExpr );
  106389. if( IsVirtual(pTab) ) return 0;
  106390. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  106391. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  106392. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  106393. if( pExpr->flags&EP_Distinct ) return 0;
  106394. return pTab;
  106395. }
  106396. /*
  106397. ** If the source-list item passed as an argument was augmented with an
  106398. ** INDEXED BY clause, then try to locate the specified index. If there
  106399. ** was such a clause and the named index cannot be found, return
  106400. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  106401. ** pFrom->pIndex and return SQLITE_OK.
  106402. */
  106403. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  106404. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  106405. Table *pTab = pFrom->pTab;
  106406. char *zIndexedBy = pFrom->u1.zIndexedBy;
  106407. Index *pIdx;
  106408. for(pIdx=pTab->pIndex;
  106409. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  106410. pIdx=pIdx->pNext
  106411. );
  106412. if( !pIdx ){
  106413. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  106414. pParse->checkSchema = 1;
  106415. return SQLITE_ERROR;
  106416. }
  106417. pFrom->pIBIndex = pIdx;
  106418. }
  106419. return SQLITE_OK;
  106420. }
  106421. /*
  106422. ** Detect compound SELECT statements that use an ORDER BY clause with
  106423. ** an alternative collating sequence.
  106424. **
  106425. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  106426. **
  106427. ** These are rewritten as a subquery:
  106428. **
  106429. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  106430. ** ORDER BY ... COLLATE ...
  106431. **
  106432. ** This transformation is necessary because the multiSelectOrderBy() routine
  106433. ** above that generates the code for a compound SELECT with an ORDER BY clause
  106434. ** uses a merge algorithm that requires the same collating sequence on the
  106435. ** result columns as on the ORDER BY clause. See ticket
  106436. ** http://www.sqlite.org/src/info/6709574d2a
  106437. **
  106438. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  106439. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  106440. ** there are COLLATE terms in the ORDER BY.
  106441. */
  106442. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  106443. int i;
  106444. Select *pNew;
  106445. Select *pX;
  106446. sqlite3 *db;
  106447. struct ExprList_item *a;
  106448. SrcList *pNewSrc;
  106449. Parse *pParse;
  106450. Token dummy;
  106451. if( p->pPrior==0 ) return WRC_Continue;
  106452. if( p->pOrderBy==0 ) return WRC_Continue;
  106453. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  106454. if( pX==0 ) return WRC_Continue;
  106455. a = p->pOrderBy->a;
  106456. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  106457. if( a[i].pExpr->flags & EP_Collate ) break;
  106458. }
  106459. if( i<0 ) return WRC_Continue;
  106460. /* If we reach this point, that means the transformation is required. */
  106461. pParse = pWalker->pParse;
  106462. db = pParse->db;
  106463. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  106464. if( pNew==0 ) return WRC_Abort;
  106465. memset(&dummy, 0, sizeof(dummy));
  106466. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  106467. if( pNewSrc==0 ) return WRC_Abort;
  106468. *pNew = *p;
  106469. p->pSrc = pNewSrc;
  106470. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  106471. p->op = TK_SELECT;
  106472. p->pWhere = 0;
  106473. pNew->pGroupBy = 0;
  106474. pNew->pHaving = 0;
  106475. pNew->pOrderBy = 0;
  106476. p->pPrior = 0;
  106477. p->pNext = 0;
  106478. p->pWith = 0;
  106479. p->selFlags &= ~SF_Compound;
  106480. assert( (p->selFlags & SF_Converted)==0 );
  106481. p->selFlags |= SF_Converted;
  106482. assert( pNew->pPrior!=0 );
  106483. pNew->pPrior->pNext = pNew;
  106484. pNew->pLimit = 0;
  106485. pNew->pOffset = 0;
  106486. return WRC_Continue;
  106487. }
  106488. /*
  106489. ** Check to see if the FROM clause term pFrom has table-valued function
  106490. ** arguments. If it does, leave an error message in pParse and return
  106491. ** non-zero, since pFrom is not allowed to be a table-valued function.
  106492. */
  106493. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  106494. if( pFrom->fg.isTabFunc ){
  106495. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  106496. return 1;
  106497. }
  106498. return 0;
  106499. }
  106500. #ifndef SQLITE_OMIT_CTE
  106501. /*
  106502. ** Argument pWith (which may be NULL) points to a linked list of nested
  106503. ** WITH contexts, from inner to outermost. If the table identified by
  106504. ** FROM clause element pItem is really a common-table-expression (CTE)
  106505. ** then return a pointer to the CTE definition for that table. Otherwise
  106506. ** return NULL.
  106507. **
  106508. ** If a non-NULL value is returned, set *ppContext to point to the With
  106509. ** object that the returned CTE belongs to.
  106510. */
  106511. static struct Cte *searchWith(
  106512. With *pWith, /* Current innermost WITH clause */
  106513. struct SrcList_item *pItem, /* FROM clause element to resolve */
  106514. With **ppContext /* OUT: WITH clause return value belongs to */
  106515. ){
  106516. const char *zName;
  106517. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  106518. With *p;
  106519. for(p=pWith; p; p=p->pOuter){
  106520. int i;
  106521. for(i=0; i<p->nCte; i++){
  106522. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  106523. *ppContext = p;
  106524. return &p->a[i];
  106525. }
  106526. }
  106527. }
  106528. }
  106529. return 0;
  106530. }
  106531. /* The code generator maintains a stack of active WITH clauses
  106532. ** with the inner-most WITH clause being at the top of the stack.
  106533. **
  106534. ** This routine pushes the WITH clause passed as the second argument
  106535. ** onto the top of the stack. If argument bFree is true, then this
  106536. ** WITH clause will never be popped from the stack. In this case it
  106537. ** should be freed along with the Parse object. In other cases, when
  106538. ** bFree==0, the With object will be freed along with the SELECT
  106539. ** statement with which it is associated.
  106540. */
  106541. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  106542. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  106543. if( pWith ){
  106544. assert( pParse->pWith!=pWith );
  106545. pWith->pOuter = pParse->pWith;
  106546. pParse->pWith = pWith;
  106547. if( bFree ) pParse->pWithToFree = pWith;
  106548. }
  106549. }
  106550. /*
  106551. ** This function checks if argument pFrom refers to a CTE declared by
  106552. ** a WITH clause on the stack currently maintained by the parser. And,
  106553. ** if currently processing a CTE expression, if it is a recursive
  106554. ** reference to the current CTE.
  106555. **
  106556. ** If pFrom falls into either of the two categories above, pFrom->pTab
  106557. ** and other fields are populated accordingly. The caller should check
  106558. ** (pFrom->pTab!=0) to determine whether or not a successful match
  106559. ** was found.
  106560. **
  106561. ** Whether or not a match is found, SQLITE_OK is returned if no error
  106562. ** occurs. If an error does occur, an error message is stored in the
  106563. ** parser and some error code other than SQLITE_OK returned.
  106564. */
  106565. static int withExpand(
  106566. Walker *pWalker,
  106567. struct SrcList_item *pFrom
  106568. ){
  106569. Parse *pParse = pWalker->pParse;
  106570. sqlite3 *db = pParse->db;
  106571. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  106572. With *pWith; /* WITH clause that pCte belongs to */
  106573. assert( pFrom->pTab==0 );
  106574. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  106575. if( pCte ){
  106576. Table *pTab;
  106577. ExprList *pEList;
  106578. Select *pSel;
  106579. Select *pLeft; /* Left-most SELECT statement */
  106580. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  106581. With *pSavedWith; /* Initial value of pParse->pWith */
  106582. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  106583. ** recursive reference to CTE pCte. Leave an error in pParse and return
  106584. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  106585. ** In this case, proceed. */
  106586. if( pCte->zCteErr ){
  106587. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  106588. return SQLITE_ERROR;
  106589. }
  106590. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  106591. assert( pFrom->pTab==0 );
  106592. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  106593. if( pTab==0 ) return WRC_Abort;
  106594. pTab->nRef = 1;
  106595. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  106596. pTab->iPKey = -1;
  106597. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  106598. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  106599. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  106600. if( db->mallocFailed ) return SQLITE_NOMEM;
  106601. assert( pFrom->pSelect );
  106602. /* Check if this is a recursive CTE. */
  106603. pSel = pFrom->pSelect;
  106604. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  106605. if( bMayRecursive ){
  106606. int i;
  106607. SrcList *pSrc = pFrom->pSelect->pSrc;
  106608. for(i=0; i<pSrc->nSrc; i++){
  106609. struct SrcList_item *pItem = &pSrc->a[i];
  106610. if( pItem->zDatabase==0
  106611. && pItem->zName!=0
  106612. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  106613. ){
  106614. pItem->pTab = pTab;
  106615. pItem->fg.isRecursive = 1;
  106616. pTab->nRef++;
  106617. pSel->selFlags |= SF_Recursive;
  106618. }
  106619. }
  106620. }
  106621. /* Only one recursive reference is permitted. */
  106622. if( pTab->nRef>2 ){
  106623. sqlite3ErrorMsg(
  106624. pParse, "multiple references to recursive table: %s", pCte->zName
  106625. );
  106626. return SQLITE_ERROR;
  106627. }
  106628. assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
  106629. pCte->zCteErr = "circular reference: %s";
  106630. pSavedWith = pParse->pWith;
  106631. pParse->pWith = pWith;
  106632. sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
  106633. pParse->pWith = pWith;
  106634. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  106635. pEList = pLeft->pEList;
  106636. if( pCte->pCols ){
  106637. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  106638. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  106639. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  106640. );
  106641. pParse->pWith = pSavedWith;
  106642. return SQLITE_ERROR;
  106643. }
  106644. pEList = pCte->pCols;
  106645. }
  106646. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  106647. if( bMayRecursive ){
  106648. if( pSel->selFlags & SF_Recursive ){
  106649. pCte->zCteErr = "multiple recursive references: %s";
  106650. }else{
  106651. pCte->zCteErr = "recursive reference in a subquery: %s";
  106652. }
  106653. sqlite3WalkSelect(pWalker, pSel);
  106654. }
  106655. pCte->zCteErr = 0;
  106656. pParse->pWith = pSavedWith;
  106657. }
  106658. return SQLITE_OK;
  106659. }
  106660. #endif
  106661. #ifndef SQLITE_OMIT_CTE
  106662. /*
  106663. ** If the SELECT passed as the second argument has an associated WITH
  106664. ** clause, pop it from the stack stored as part of the Parse object.
  106665. **
  106666. ** This function is used as the xSelectCallback2() callback by
  106667. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  106668. ** names and other FROM clause elements.
  106669. */
  106670. static void selectPopWith(Walker *pWalker, Select *p){
  106671. Parse *pParse = pWalker->pParse;
  106672. With *pWith = findRightmost(p)->pWith;
  106673. if( pWith!=0 ){
  106674. assert( pParse->pWith==pWith );
  106675. pParse->pWith = pWith->pOuter;
  106676. }
  106677. }
  106678. #else
  106679. #define selectPopWith 0
  106680. #endif
  106681. /*
  106682. ** This routine is a Walker callback for "expanding" a SELECT statement.
  106683. ** "Expanding" means to do the following:
  106684. **
  106685. ** (1) Make sure VDBE cursor numbers have been assigned to every
  106686. ** element of the FROM clause.
  106687. **
  106688. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  106689. ** defines FROM clause. When views appear in the FROM clause,
  106690. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  106691. ** that implements the view. A copy is made of the view's SELECT
  106692. ** statement so that we can freely modify or delete that statement
  106693. ** without worrying about messing up the persistent representation
  106694. ** of the view.
  106695. **
  106696. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  106697. ** on joins and the ON and USING clause of joins.
  106698. **
  106699. ** (4) Scan the list of columns in the result set (pEList) looking
  106700. ** for instances of the "*" operator or the TABLE.* operator.
  106701. ** If found, expand each "*" to be every column in every table
  106702. ** and TABLE.* to be every column in TABLE.
  106703. **
  106704. */
  106705. static int selectExpander(Walker *pWalker, Select *p){
  106706. Parse *pParse = pWalker->pParse;
  106707. int i, j, k;
  106708. SrcList *pTabList;
  106709. ExprList *pEList;
  106710. struct SrcList_item *pFrom;
  106711. sqlite3 *db = pParse->db;
  106712. Expr *pE, *pRight, *pExpr;
  106713. u16 selFlags = p->selFlags;
  106714. p->selFlags |= SF_Expanded;
  106715. if( db->mallocFailed ){
  106716. return WRC_Abort;
  106717. }
  106718. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  106719. return WRC_Prune;
  106720. }
  106721. pTabList = p->pSrc;
  106722. pEList = p->pEList;
  106723. if( pWalker->xSelectCallback2==selectPopWith ){
  106724. sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
  106725. }
  106726. /* Make sure cursor numbers have been assigned to all entries in
  106727. ** the FROM clause of the SELECT statement.
  106728. */
  106729. sqlite3SrcListAssignCursors(pParse, pTabList);
  106730. /* Look up every table named in the FROM clause of the select. If
  106731. ** an entry of the FROM clause is a subquery instead of a table or view,
  106732. ** then create a transient table structure to describe the subquery.
  106733. */
  106734. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  106735. Table *pTab;
  106736. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  106737. if( pFrom->fg.isRecursive ) continue;
  106738. assert( pFrom->pTab==0 );
  106739. #ifndef SQLITE_OMIT_CTE
  106740. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  106741. if( pFrom->pTab ) {} else
  106742. #endif
  106743. if( pFrom->zName==0 ){
  106744. #ifndef SQLITE_OMIT_SUBQUERY
  106745. Select *pSel = pFrom->pSelect;
  106746. /* A sub-query in the FROM clause of a SELECT */
  106747. assert( pSel!=0 );
  106748. assert( pFrom->pTab==0 );
  106749. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  106750. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  106751. if( pTab==0 ) return WRC_Abort;
  106752. pTab->nRef = 1;
  106753. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  106754. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  106755. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  106756. pTab->iPKey = -1;
  106757. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  106758. pTab->tabFlags |= TF_Ephemeral;
  106759. #endif
  106760. }else{
  106761. /* An ordinary table or view name in the FROM clause */
  106762. assert( pFrom->pTab==0 );
  106763. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  106764. if( pTab==0 ) return WRC_Abort;
  106765. if( pTab->nRef==0xffff ){
  106766. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  106767. pTab->zName);
  106768. pFrom->pTab = 0;
  106769. return WRC_Abort;
  106770. }
  106771. pTab->nRef++;
  106772. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  106773. return WRC_Abort;
  106774. }
  106775. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  106776. if( IsVirtual(pTab) || pTab->pSelect ){
  106777. i16 nCol;
  106778. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  106779. assert( pFrom->pSelect==0 );
  106780. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  106781. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  106782. nCol = pTab->nCol;
  106783. pTab->nCol = -1;
  106784. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  106785. pTab->nCol = nCol;
  106786. }
  106787. #endif
  106788. }
  106789. /* Locate the index named by the INDEXED BY clause, if any. */
  106790. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  106791. return WRC_Abort;
  106792. }
  106793. }
  106794. /* Process NATURAL keywords, and ON and USING clauses of joins.
  106795. */
  106796. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  106797. return WRC_Abort;
  106798. }
  106799. /* For every "*" that occurs in the column list, insert the names of
  106800. ** all columns in all tables. And for every TABLE.* insert the names
  106801. ** of all columns in TABLE. The parser inserted a special expression
  106802. ** with the TK_ASTERISK operator for each "*" that it found in the column
  106803. ** list. The following code just has to locate the TK_ASTERISK
  106804. ** expressions and expand each one to the list of all columns in
  106805. ** all tables.
  106806. **
  106807. ** The first loop just checks to see if there are any "*" operators
  106808. ** that need expanding.
  106809. */
  106810. for(k=0; k<pEList->nExpr; k++){
  106811. pE = pEList->a[k].pExpr;
  106812. if( pE->op==TK_ASTERISK ) break;
  106813. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  106814. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  106815. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  106816. }
  106817. if( k<pEList->nExpr ){
  106818. /*
  106819. ** If we get here it means the result set contains one or more "*"
  106820. ** operators that need to be expanded. Loop through each expression
  106821. ** in the result set and expand them one by one.
  106822. */
  106823. struct ExprList_item *a = pEList->a;
  106824. ExprList *pNew = 0;
  106825. int flags = pParse->db->flags;
  106826. int longNames = (flags & SQLITE_FullColNames)!=0
  106827. && (flags & SQLITE_ShortColNames)==0;
  106828. for(k=0; k<pEList->nExpr; k++){
  106829. pE = a[k].pExpr;
  106830. pRight = pE->pRight;
  106831. assert( pE->op!=TK_DOT || pRight!=0 );
  106832. if( pE->op!=TK_ASTERISK
  106833. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  106834. ){
  106835. /* This particular expression does not need to be expanded.
  106836. */
  106837. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  106838. if( pNew ){
  106839. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  106840. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  106841. a[k].zName = 0;
  106842. a[k].zSpan = 0;
  106843. }
  106844. a[k].pExpr = 0;
  106845. }else{
  106846. /* This expression is a "*" or a "TABLE.*" and needs to be
  106847. ** expanded. */
  106848. int tableSeen = 0; /* Set to 1 when TABLE matches */
  106849. char *zTName = 0; /* text of name of TABLE */
  106850. if( pE->op==TK_DOT ){
  106851. assert( pE->pLeft!=0 );
  106852. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  106853. zTName = pE->pLeft->u.zToken;
  106854. }
  106855. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  106856. Table *pTab = pFrom->pTab;
  106857. Select *pSub = pFrom->pSelect;
  106858. char *zTabName = pFrom->zAlias;
  106859. const char *zSchemaName = 0;
  106860. int iDb;
  106861. if( zTabName==0 ){
  106862. zTabName = pTab->zName;
  106863. }
  106864. if( db->mallocFailed ) break;
  106865. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  106866. pSub = 0;
  106867. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  106868. continue;
  106869. }
  106870. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  106871. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  106872. }
  106873. for(j=0; j<pTab->nCol; j++){
  106874. char *zName = pTab->aCol[j].zName;
  106875. char *zColname; /* The computed column name */
  106876. char *zToFree; /* Malloced string that needs to be freed */
  106877. Token sColname; /* Computed column name as a token */
  106878. assert( zName );
  106879. if( zTName && pSub
  106880. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  106881. ){
  106882. continue;
  106883. }
  106884. /* If a column is marked as 'hidden', omit it from the expanded
  106885. ** result-set list unless the SELECT has the SF_IncludeHidden
  106886. ** bit set.
  106887. */
  106888. if( (p->selFlags & SF_IncludeHidden)==0
  106889. && IsHiddenColumn(&pTab->aCol[j])
  106890. ){
  106891. continue;
  106892. }
  106893. tableSeen = 1;
  106894. if( i>0 && zTName==0 ){
  106895. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  106896. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  106897. ){
  106898. /* In a NATURAL join, omit the join columns from the
  106899. ** table to the right of the join */
  106900. continue;
  106901. }
  106902. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  106903. /* In a join with a USING clause, omit columns in the
  106904. ** using clause from the table on the right. */
  106905. continue;
  106906. }
  106907. }
  106908. pRight = sqlite3Expr(db, TK_ID, zName);
  106909. zColname = zName;
  106910. zToFree = 0;
  106911. if( longNames || pTabList->nSrc>1 ){
  106912. Expr *pLeft;
  106913. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  106914. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  106915. if( zSchemaName ){
  106916. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  106917. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  106918. }
  106919. if( longNames ){
  106920. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  106921. zToFree = zColname;
  106922. }
  106923. }else{
  106924. pExpr = pRight;
  106925. }
  106926. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  106927. sColname.z = zColname;
  106928. sColname.n = sqlite3Strlen30(zColname);
  106929. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  106930. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  106931. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  106932. if( pSub ){
  106933. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  106934. testcase( pX->zSpan==0 );
  106935. }else{
  106936. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  106937. zSchemaName, zTabName, zColname);
  106938. testcase( pX->zSpan==0 );
  106939. }
  106940. pX->bSpanIsTab = 1;
  106941. }
  106942. sqlite3DbFree(db, zToFree);
  106943. }
  106944. }
  106945. if( !tableSeen ){
  106946. if( zTName ){
  106947. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  106948. }else{
  106949. sqlite3ErrorMsg(pParse, "no tables specified");
  106950. }
  106951. }
  106952. }
  106953. }
  106954. sqlite3ExprListDelete(db, pEList);
  106955. p->pEList = pNew;
  106956. }
  106957. #if SQLITE_MAX_COLUMN
  106958. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  106959. sqlite3ErrorMsg(pParse, "too many columns in result set");
  106960. return WRC_Abort;
  106961. }
  106962. #endif
  106963. return WRC_Continue;
  106964. }
  106965. /*
  106966. ** No-op routine for the parse-tree walker.
  106967. **
  106968. ** When this routine is the Walker.xExprCallback then expression trees
  106969. ** are walked without any actions being taken at each node. Presumably,
  106970. ** when this routine is used for Walker.xExprCallback then
  106971. ** Walker.xSelectCallback is set to do something useful for every
  106972. ** subquery in the parser tree.
  106973. */
  106974. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  106975. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  106976. return WRC_Continue;
  106977. }
  106978. /*
  106979. ** This routine "expands" a SELECT statement and all of its subqueries.
  106980. ** For additional information on what it means to "expand" a SELECT
  106981. ** statement, see the comment on the selectExpand worker callback above.
  106982. **
  106983. ** Expanding a SELECT statement is the first step in processing a
  106984. ** SELECT statement. The SELECT statement must be expanded before
  106985. ** name resolution is performed.
  106986. **
  106987. ** If anything goes wrong, an error message is written into pParse.
  106988. ** The calling function can detect the problem by looking at pParse->nErr
  106989. ** and/or pParse->db->mallocFailed.
  106990. */
  106991. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  106992. Walker w;
  106993. memset(&w, 0, sizeof(w));
  106994. w.xExprCallback = sqlite3ExprWalkNoop;
  106995. w.pParse = pParse;
  106996. if( pParse->hasCompound ){
  106997. w.xSelectCallback = convertCompoundSelectToSubquery;
  106998. sqlite3WalkSelect(&w, pSelect);
  106999. }
  107000. w.xSelectCallback = selectExpander;
  107001. if( (pSelect->selFlags & SF_MultiValue)==0 ){
  107002. w.xSelectCallback2 = selectPopWith;
  107003. }
  107004. sqlite3WalkSelect(&w, pSelect);
  107005. }
  107006. #ifndef SQLITE_OMIT_SUBQUERY
  107007. /*
  107008. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  107009. ** interface.
  107010. **
  107011. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  107012. ** information to the Table structure that represents the result set
  107013. ** of that subquery.
  107014. **
  107015. ** The Table structure that represents the result set was constructed
  107016. ** by selectExpander() but the type and collation information was omitted
  107017. ** at that point because identifiers had not yet been resolved. This
  107018. ** routine is called after identifier resolution.
  107019. */
  107020. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  107021. Parse *pParse;
  107022. int i;
  107023. SrcList *pTabList;
  107024. struct SrcList_item *pFrom;
  107025. assert( p->selFlags & SF_Resolved );
  107026. assert( (p->selFlags & SF_HasTypeInfo)==0 );
  107027. p->selFlags |= SF_HasTypeInfo;
  107028. pParse = pWalker->pParse;
  107029. pTabList = p->pSrc;
  107030. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  107031. Table *pTab = pFrom->pTab;
  107032. assert( pTab!=0 );
  107033. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  107034. /* A sub-query in the FROM clause of a SELECT */
  107035. Select *pSel = pFrom->pSelect;
  107036. if( pSel ){
  107037. while( pSel->pPrior ) pSel = pSel->pPrior;
  107038. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  107039. }
  107040. }
  107041. }
  107042. }
  107043. #endif
  107044. /*
  107045. ** This routine adds datatype and collating sequence information to
  107046. ** the Table structures of all FROM-clause subqueries in a
  107047. ** SELECT statement.
  107048. **
  107049. ** Use this routine after name resolution.
  107050. */
  107051. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  107052. #ifndef SQLITE_OMIT_SUBQUERY
  107053. Walker w;
  107054. memset(&w, 0, sizeof(w));
  107055. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  107056. w.xExprCallback = sqlite3ExprWalkNoop;
  107057. w.pParse = pParse;
  107058. sqlite3WalkSelect(&w, pSelect);
  107059. #endif
  107060. }
  107061. /*
  107062. ** This routine sets up a SELECT statement for processing. The
  107063. ** following is accomplished:
  107064. **
  107065. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  107066. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  107067. ** * ON and USING clauses are shifted into WHERE statements
  107068. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  107069. ** * Identifiers in expression are matched to tables.
  107070. **
  107071. ** This routine acts recursively on all subqueries within the SELECT.
  107072. */
  107073. SQLITE_PRIVATE void sqlite3SelectPrep(
  107074. Parse *pParse, /* The parser context */
  107075. Select *p, /* The SELECT statement being coded. */
  107076. NameContext *pOuterNC /* Name context for container */
  107077. ){
  107078. sqlite3 *db;
  107079. if( NEVER(p==0) ) return;
  107080. db = pParse->db;
  107081. if( db->mallocFailed ) return;
  107082. if( p->selFlags & SF_HasTypeInfo ) return;
  107083. sqlite3SelectExpand(pParse, p);
  107084. if( pParse->nErr || db->mallocFailed ) return;
  107085. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  107086. if( pParse->nErr || db->mallocFailed ) return;
  107087. sqlite3SelectAddTypeInfo(pParse, p);
  107088. }
  107089. /*
  107090. ** Reset the aggregate accumulator.
  107091. **
  107092. ** The aggregate accumulator is a set of memory cells that hold
  107093. ** intermediate results while calculating an aggregate. This
  107094. ** routine generates code that stores NULLs in all of those memory
  107095. ** cells.
  107096. */
  107097. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  107098. Vdbe *v = pParse->pVdbe;
  107099. int i;
  107100. struct AggInfo_func *pFunc;
  107101. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  107102. if( nReg==0 ) return;
  107103. #ifdef SQLITE_DEBUG
  107104. /* Verify that all AggInfo registers are within the range specified by
  107105. ** AggInfo.mnReg..AggInfo.mxReg */
  107106. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  107107. for(i=0; i<pAggInfo->nColumn; i++){
  107108. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  107109. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  107110. }
  107111. for(i=0; i<pAggInfo->nFunc; i++){
  107112. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  107113. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  107114. }
  107115. #endif
  107116. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  107117. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  107118. if( pFunc->iDistinct>=0 ){
  107119. Expr *pE = pFunc->pExpr;
  107120. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  107121. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  107122. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  107123. "argument");
  107124. pFunc->iDistinct = -1;
  107125. }else{
  107126. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  107127. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  107128. (char*)pKeyInfo, P4_KEYINFO);
  107129. }
  107130. }
  107131. }
  107132. }
  107133. /*
  107134. ** Invoke the OP_AggFinalize opcode for every aggregate function
  107135. ** in the AggInfo structure.
  107136. */
  107137. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  107138. Vdbe *v = pParse->pVdbe;
  107139. int i;
  107140. struct AggInfo_func *pF;
  107141. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  107142. ExprList *pList = pF->pExpr->x.pList;
  107143. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  107144. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  107145. (void*)pF->pFunc, P4_FUNCDEF);
  107146. }
  107147. }
  107148. /*
  107149. ** Update the accumulator memory cells for an aggregate based on
  107150. ** the current cursor position.
  107151. */
  107152. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  107153. Vdbe *v = pParse->pVdbe;
  107154. int i;
  107155. int regHit = 0;
  107156. int addrHitTest = 0;
  107157. struct AggInfo_func *pF;
  107158. struct AggInfo_col *pC;
  107159. pAggInfo->directMode = 1;
  107160. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  107161. int nArg;
  107162. int addrNext = 0;
  107163. int regAgg;
  107164. ExprList *pList = pF->pExpr->x.pList;
  107165. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  107166. if( pList ){
  107167. nArg = pList->nExpr;
  107168. regAgg = sqlite3GetTempRange(pParse, nArg);
  107169. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  107170. }else{
  107171. nArg = 0;
  107172. regAgg = 0;
  107173. }
  107174. if( pF->iDistinct>=0 ){
  107175. addrNext = sqlite3VdbeMakeLabel(v);
  107176. testcase( nArg==0 ); /* Error condition */
  107177. testcase( nArg>1 ); /* Also an error */
  107178. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  107179. }
  107180. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  107181. CollSeq *pColl = 0;
  107182. struct ExprList_item *pItem;
  107183. int j;
  107184. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  107185. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  107186. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  107187. }
  107188. if( !pColl ){
  107189. pColl = pParse->db->pDfltColl;
  107190. }
  107191. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  107192. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  107193. }
  107194. sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
  107195. (void*)pF->pFunc, P4_FUNCDEF);
  107196. sqlite3VdbeChangeP5(v, (u8)nArg);
  107197. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  107198. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  107199. if( addrNext ){
  107200. sqlite3VdbeResolveLabel(v, addrNext);
  107201. sqlite3ExprCacheClear(pParse);
  107202. }
  107203. }
  107204. /* Before populating the accumulator registers, clear the column cache.
  107205. ** Otherwise, if any of the required column values are already present
  107206. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  107207. ** to pC->iMem. But by the time the value is used, the original register
  107208. ** may have been used, invalidating the underlying buffer holding the
  107209. ** text or blob value. See ticket [883034dcb5].
  107210. **
  107211. ** Another solution would be to change the OP_SCopy used to copy cached
  107212. ** values to an OP_Copy.
  107213. */
  107214. if( regHit ){
  107215. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  107216. }
  107217. sqlite3ExprCacheClear(pParse);
  107218. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  107219. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  107220. }
  107221. pAggInfo->directMode = 0;
  107222. sqlite3ExprCacheClear(pParse);
  107223. if( addrHitTest ){
  107224. sqlite3VdbeJumpHere(v, addrHitTest);
  107225. }
  107226. }
  107227. /*
  107228. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  107229. ** count(*) query ("SELECT count(*) FROM pTab").
  107230. */
  107231. #ifndef SQLITE_OMIT_EXPLAIN
  107232. static void explainSimpleCount(
  107233. Parse *pParse, /* Parse context */
  107234. Table *pTab, /* Table being queried */
  107235. Index *pIdx /* Index used to optimize scan, or NULL */
  107236. ){
  107237. if( pParse->explain==2 ){
  107238. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  107239. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  107240. pTab->zName,
  107241. bCover ? " USING COVERING INDEX " : "",
  107242. bCover ? pIdx->zName : ""
  107243. );
  107244. sqlite3VdbeAddOp4(
  107245. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  107246. );
  107247. }
  107248. }
  107249. #else
  107250. # define explainSimpleCount(a,b,c)
  107251. #endif
  107252. /*
  107253. ** Generate code for the SELECT statement given in the p argument.
  107254. **
  107255. ** The results are returned according to the SelectDest structure.
  107256. ** See comments in sqliteInt.h for further information.
  107257. **
  107258. ** This routine returns the number of errors. If any errors are
  107259. ** encountered, then an appropriate error message is left in
  107260. ** pParse->zErrMsg.
  107261. **
  107262. ** This routine does NOT free the Select structure passed in. The
  107263. ** calling function needs to do that.
  107264. */
  107265. SQLITE_PRIVATE int sqlite3Select(
  107266. Parse *pParse, /* The parser context */
  107267. Select *p, /* The SELECT statement being coded. */
  107268. SelectDest *pDest /* What to do with the query results */
  107269. ){
  107270. int i, j; /* Loop counters */
  107271. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  107272. Vdbe *v; /* The virtual machine under construction */
  107273. int isAgg; /* True for select lists like "count(*)" */
  107274. ExprList *pEList = 0; /* List of columns to extract. */
  107275. SrcList *pTabList; /* List of tables to select from */
  107276. Expr *pWhere; /* The WHERE clause. May be NULL */
  107277. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  107278. Expr *pHaving; /* The HAVING clause. May be NULL */
  107279. int rc = 1; /* Value to return from this function */
  107280. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  107281. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  107282. AggInfo sAggInfo; /* Information used by aggregate queries */
  107283. int iEnd; /* Address of the end of the query */
  107284. sqlite3 *db; /* The database connection */
  107285. #ifndef SQLITE_OMIT_EXPLAIN
  107286. int iRestoreSelectId = pParse->iSelectId;
  107287. pParse->iSelectId = pParse->iNextSelectId++;
  107288. #endif
  107289. db = pParse->db;
  107290. if( p==0 || db->mallocFailed || pParse->nErr ){
  107291. return 1;
  107292. }
  107293. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  107294. memset(&sAggInfo, 0, sizeof(sAggInfo));
  107295. #if SELECTTRACE_ENABLED
  107296. pParse->nSelectIndent++;
  107297. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  107298. if( sqlite3SelectTrace & 0x100 ){
  107299. sqlite3TreeViewSelect(0, p, 0);
  107300. }
  107301. #endif
  107302. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  107303. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  107304. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  107305. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  107306. if( IgnorableOrderby(pDest) ){
  107307. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  107308. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  107309. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  107310. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  107311. /* If ORDER BY makes no difference in the output then neither does
  107312. ** DISTINCT so it can be removed too. */
  107313. sqlite3ExprListDelete(db, p->pOrderBy);
  107314. p->pOrderBy = 0;
  107315. p->selFlags &= ~SF_Distinct;
  107316. }
  107317. sqlite3SelectPrep(pParse, p, 0);
  107318. memset(&sSort, 0, sizeof(sSort));
  107319. sSort.pOrderBy = p->pOrderBy;
  107320. pTabList = p->pSrc;
  107321. if( pParse->nErr || db->mallocFailed ){
  107322. goto select_end;
  107323. }
  107324. assert( p->pEList!=0 );
  107325. isAgg = (p->selFlags & SF_Aggregate)!=0;
  107326. #if SELECTTRACE_ENABLED
  107327. if( sqlite3SelectTrace & 0x100 ){
  107328. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  107329. sqlite3TreeViewSelect(0, p, 0);
  107330. }
  107331. #endif
  107332. /* If writing to memory or generating a set
  107333. ** only a single column may be output.
  107334. */
  107335. #ifndef SQLITE_OMIT_SUBQUERY
  107336. if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
  107337. goto select_end;
  107338. }
  107339. #endif
  107340. /* Try to flatten subqueries in the FROM clause up into the main query
  107341. */
  107342. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  107343. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  107344. struct SrcList_item *pItem = &pTabList->a[i];
  107345. Select *pSub = pItem->pSelect;
  107346. int isAggSub;
  107347. Table *pTab = pItem->pTab;
  107348. if( pSub==0 ) continue;
  107349. /* Catch mismatch in the declared columns of a view and the number of
  107350. ** columns in the SELECT on the RHS */
  107351. if( pTab->nCol!=pSub->pEList->nExpr ){
  107352. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  107353. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  107354. goto select_end;
  107355. }
  107356. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  107357. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  107358. /* This subquery can be absorbed into its parent. */
  107359. if( isAggSub ){
  107360. isAgg = 1;
  107361. p->selFlags |= SF_Aggregate;
  107362. }
  107363. i = -1;
  107364. }
  107365. pTabList = p->pSrc;
  107366. if( db->mallocFailed ) goto select_end;
  107367. if( !IgnorableOrderby(pDest) ){
  107368. sSort.pOrderBy = p->pOrderBy;
  107369. }
  107370. }
  107371. #endif
  107372. /* Get a pointer the VDBE under construction, allocating a new VDBE if one
  107373. ** does not already exist */
  107374. v = sqlite3GetVdbe(pParse);
  107375. if( v==0 ) goto select_end;
  107376. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  107377. /* Handle compound SELECT statements using the separate multiSelect()
  107378. ** procedure.
  107379. */
  107380. if( p->pPrior ){
  107381. rc = multiSelect(pParse, p, pDest);
  107382. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  107383. #if SELECTTRACE_ENABLED
  107384. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  107385. pParse->nSelectIndent--;
  107386. #endif
  107387. return rc;
  107388. }
  107389. #endif
  107390. /* Generate code for all sub-queries in the FROM clause
  107391. */
  107392. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  107393. for(i=0; i<pTabList->nSrc; i++){
  107394. struct SrcList_item *pItem = &pTabList->a[i];
  107395. SelectDest dest;
  107396. Select *pSub = pItem->pSelect;
  107397. if( pSub==0 ) continue;
  107398. /* Sometimes the code for a subquery will be generated more than
  107399. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  107400. ** for example. In that case, do not regenerate the code to manifest
  107401. ** a view or the co-routine to implement a view. The first instance
  107402. ** is sufficient, though the subroutine to manifest the view does need
  107403. ** to be invoked again. */
  107404. if( pItem->addrFillSub ){
  107405. if( pItem->fg.viaCoroutine==0 ){
  107406. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  107407. }
  107408. continue;
  107409. }
  107410. /* Increment Parse.nHeight by the height of the largest expression
  107411. ** tree referred to by this, the parent select. The child select
  107412. ** may contain expression trees of at most
  107413. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  107414. ** more conservative than necessary, but much easier than enforcing
  107415. ** an exact limit.
  107416. */
  107417. pParse->nHeight += sqlite3SelectExprHeight(p);
  107418. /* Make copies of constant WHERE-clause terms in the outer query down
  107419. ** inside the subquery. This can help the subquery to run more efficiently.
  107420. */
  107421. if( (pItem->fg.jointype & JT_OUTER)==0
  107422. && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
  107423. ){
  107424. #if SELECTTRACE_ENABLED
  107425. if( sqlite3SelectTrace & 0x100 ){
  107426. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  107427. sqlite3TreeViewSelect(0, p, 0);
  107428. }
  107429. #endif
  107430. }
  107431. /* Generate code to implement the subquery
  107432. */
  107433. if( pTabList->nSrc==1
  107434. && (p->selFlags & SF_All)==0
  107435. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  107436. ){
  107437. /* Implement a co-routine that will return a single row of the result
  107438. ** set on each invocation.
  107439. */
  107440. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  107441. pItem->regReturn = ++pParse->nMem;
  107442. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  107443. VdbeComment((v, "%s", pItem->pTab->zName));
  107444. pItem->addrFillSub = addrTop;
  107445. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  107446. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  107447. sqlite3Select(pParse, pSub, &dest);
  107448. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  107449. pItem->fg.viaCoroutine = 1;
  107450. pItem->regResult = dest.iSdst;
  107451. sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
  107452. sqlite3VdbeJumpHere(v, addrTop-1);
  107453. sqlite3ClearTempRegCache(pParse);
  107454. }else{
  107455. /* Generate a subroutine that will fill an ephemeral table with
  107456. ** the content of this subquery. pItem->addrFillSub will point
  107457. ** to the address of the generated subroutine. pItem->regReturn
  107458. ** is a register allocated to hold the subroutine return address
  107459. */
  107460. int topAddr;
  107461. int onceAddr = 0;
  107462. int retAddr;
  107463. assert( pItem->addrFillSub==0 );
  107464. pItem->regReturn = ++pParse->nMem;
  107465. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  107466. pItem->addrFillSub = topAddr+1;
  107467. if( pItem->fg.isCorrelated==0 ){
  107468. /* If the subquery is not correlated and if we are not inside of
  107469. ** a trigger, then we only need to compute the value of the subquery
  107470. ** once. */
  107471. onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  107472. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  107473. }else{
  107474. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  107475. }
  107476. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  107477. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  107478. sqlite3Select(pParse, pSub, &dest);
  107479. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  107480. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  107481. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  107482. VdbeComment((v, "end %s", pItem->pTab->zName));
  107483. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  107484. sqlite3ClearTempRegCache(pParse);
  107485. }
  107486. if( db->mallocFailed ) goto select_end;
  107487. pParse->nHeight -= sqlite3SelectExprHeight(p);
  107488. }
  107489. #endif
  107490. /* Various elements of the SELECT copied into local variables for
  107491. ** convenience */
  107492. pEList = p->pEList;
  107493. pWhere = p->pWhere;
  107494. pGroupBy = p->pGroupBy;
  107495. pHaving = p->pHaving;
  107496. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  107497. #if SELECTTRACE_ENABLED
  107498. if( sqlite3SelectTrace & 0x400 ){
  107499. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  107500. sqlite3TreeViewSelect(0, p, 0);
  107501. }
  107502. #endif
  107503. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  107504. ** if the select-list is the same as the ORDER BY list, then this query
  107505. ** can be rewritten as a GROUP BY. In other words, this:
  107506. **
  107507. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  107508. **
  107509. ** is transformed to:
  107510. **
  107511. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  107512. **
  107513. ** The second form is preferred as a single index (or temp-table) may be
  107514. ** used for both the ORDER BY and DISTINCT processing. As originally
  107515. ** written the query must use a temp-table for at least one of the ORDER
  107516. ** BY and DISTINCT, and an index or separate temp-table for the other.
  107517. */
  107518. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  107519. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  107520. ){
  107521. p->selFlags &= ~SF_Distinct;
  107522. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  107523. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  107524. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  107525. ** original setting of the SF_Distinct flag, not the current setting */
  107526. assert( sDistinct.isTnct );
  107527. }
  107528. /* If there is an ORDER BY clause, then create an ephemeral index to
  107529. ** do the sorting. But this sorting ephemeral index might end up
  107530. ** being unused if the data can be extracted in pre-sorted order.
  107531. ** If that is the case, then the OP_OpenEphemeral instruction will be
  107532. ** changed to an OP_Noop once we figure out that the sorting index is
  107533. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  107534. ** that change.
  107535. */
  107536. if( sSort.pOrderBy ){
  107537. KeyInfo *pKeyInfo;
  107538. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  107539. sSort.iECursor = pParse->nTab++;
  107540. sSort.addrSortIndex =
  107541. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  107542. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  107543. (char*)pKeyInfo, P4_KEYINFO
  107544. );
  107545. }else{
  107546. sSort.addrSortIndex = -1;
  107547. }
  107548. /* If the output is destined for a temporary table, open that table.
  107549. */
  107550. if( pDest->eDest==SRT_EphemTab ){
  107551. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  107552. }
  107553. /* Set the limiter.
  107554. */
  107555. iEnd = sqlite3VdbeMakeLabel(v);
  107556. p->nSelectRow = LARGEST_INT64;
  107557. computeLimitRegisters(pParse, p, iEnd);
  107558. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  107559. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  107560. sSort.sortFlags |= SORTFLAG_UseSorter;
  107561. }
  107562. /* Open an ephemeral index to use for the distinct set.
  107563. */
  107564. if( p->selFlags & SF_Distinct ){
  107565. sDistinct.tabTnct = pParse->nTab++;
  107566. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  107567. sDistinct.tabTnct, 0, 0,
  107568. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  107569. P4_KEYINFO);
  107570. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  107571. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  107572. }else{
  107573. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  107574. }
  107575. if( !isAgg && pGroupBy==0 ){
  107576. /* No aggregate functions and no GROUP BY clause */
  107577. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  107578. /* Begin the database scan. */
  107579. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  107580. p->pEList, wctrlFlags, 0);
  107581. if( pWInfo==0 ) goto select_end;
  107582. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  107583. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  107584. }
  107585. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  107586. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  107587. }
  107588. if( sSort.pOrderBy ){
  107589. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  107590. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  107591. sSort.pOrderBy = 0;
  107592. }
  107593. }
  107594. /* If sorting index that was created by a prior OP_OpenEphemeral
  107595. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  107596. ** into an OP_Noop.
  107597. */
  107598. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  107599. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  107600. }
  107601. /* Use the standard inner loop. */
  107602. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  107603. sqlite3WhereContinueLabel(pWInfo),
  107604. sqlite3WhereBreakLabel(pWInfo));
  107605. /* End the database scan loop.
  107606. */
  107607. sqlite3WhereEnd(pWInfo);
  107608. }else{
  107609. /* This case when there exist aggregate functions or a GROUP BY clause
  107610. ** or both */
  107611. NameContext sNC; /* Name context for processing aggregate information */
  107612. int iAMem; /* First Mem address for storing current GROUP BY */
  107613. int iBMem; /* First Mem address for previous GROUP BY */
  107614. int iUseFlag; /* Mem address holding flag indicating that at least
  107615. ** one row of the input to the aggregator has been
  107616. ** processed */
  107617. int iAbortFlag; /* Mem address which causes query abort if positive */
  107618. int groupBySort; /* Rows come from source in GROUP BY order */
  107619. int addrEnd; /* End of processing for this SELECT */
  107620. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  107621. int sortOut = 0; /* Output register from the sorter */
  107622. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  107623. /* Remove any and all aliases between the result set and the
  107624. ** GROUP BY clause.
  107625. */
  107626. if( pGroupBy ){
  107627. int k; /* Loop counter */
  107628. struct ExprList_item *pItem; /* For looping over expression in a list */
  107629. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  107630. pItem->u.x.iAlias = 0;
  107631. }
  107632. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  107633. pItem->u.x.iAlias = 0;
  107634. }
  107635. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  107636. }else{
  107637. p->nSelectRow = 1;
  107638. }
  107639. /* If there is both a GROUP BY and an ORDER BY clause and they are
  107640. ** identical, then it may be possible to disable the ORDER BY clause
  107641. ** on the grounds that the GROUP BY will cause elements to come out
  107642. ** in the correct order. It also may not - the GROUP BY might use a
  107643. ** database index that causes rows to be grouped together as required
  107644. ** but not actually sorted. Either way, record the fact that the
  107645. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  107646. ** variable. */
  107647. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  107648. orderByGrp = 1;
  107649. }
  107650. /* Create a label to jump to when we want to abort the query */
  107651. addrEnd = sqlite3VdbeMakeLabel(v);
  107652. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  107653. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  107654. ** SELECT statement.
  107655. */
  107656. memset(&sNC, 0, sizeof(sNC));
  107657. sNC.pParse = pParse;
  107658. sNC.pSrcList = pTabList;
  107659. sNC.pAggInfo = &sAggInfo;
  107660. sAggInfo.mnReg = pParse->nMem+1;
  107661. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  107662. sAggInfo.pGroupBy = pGroupBy;
  107663. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  107664. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  107665. if( pHaving ){
  107666. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  107667. }
  107668. sAggInfo.nAccumulator = sAggInfo.nColumn;
  107669. for(i=0; i<sAggInfo.nFunc; i++){
  107670. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  107671. sNC.ncFlags |= NC_InAggFunc;
  107672. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  107673. sNC.ncFlags &= ~NC_InAggFunc;
  107674. }
  107675. sAggInfo.mxReg = pParse->nMem;
  107676. if( db->mallocFailed ) goto select_end;
  107677. /* Processing for aggregates with GROUP BY is very different and
  107678. ** much more complex than aggregates without a GROUP BY.
  107679. */
  107680. if( pGroupBy ){
  107681. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  107682. int addr1; /* A-vs-B comparision jump */
  107683. int addrOutputRow; /* Start of subroutine that outputs a result row */
  107684. int regOutputRow; /* Return address register for output subroutine */
  107685. int addrSetAbort; /* Set the abort flag and return */
  107686. int addrTopOfLoop; /* Top of the input loop */
  107687. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  107688. int addrReset; /* Subroutine for resetting the accumulator */
  107689. int regReset; /* Return address register for reset subroutine */
  107690. /* If there is a GROUP BY clause we might need a sorting index to
  107691. ** implement it. Allocate that sorting index now. If it turns out
  107692. ** that we do not need it after all, the OP_SorterOpen instruction
  107693. ** will be converted into a Noop.
  107694. */
  107695. sAggInfo.sortingIdx = pParse->nTab++;
  107696. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  107697. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  107698. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  107699. 0, (char*)pKeyInfo, P4_KEYINFO);
  107700. /* Initialize memory locations used by GROUP BY aggregate processing
  107701. */
  107702. iUseFlag = ++pParse->nMem;
  107703. iAbortFlag = ++pParse->nMem;
  107704. regOutputRow = ++pParse->nMem;
  107705. addrOutputRow = sqlite3VdbeMakeLabel(v);
  107706. regReset = ++pParse->nMem;
  107707. addrReset = sqlite3VdbeMakeLabel(v);
  107708. iAMem = pParse->nMem + 1;
  107709. pParse->nMem += pGroupBy->nExpr;
  107710. iBMem = pParse->nMem + 1;
  107711. pParse->nMem += pGroupBy->nExpr;
  107712. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  107713. VdbeComment((v, "clear abort flag"));
  107714. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  107715. VdbeComment((v, "indicate accumulator empty"));
  107716. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  107717. /* Begin a loop that will extract all source rows in GROUP BY order.
  107718. ** This might involve two separate loops with an OP_Sort in between, or
  107719. ** it might be a single loop that uses an index to extract information
  107720. ** in the right order to begin with.
  107721. */
  107722. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  107723. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  107724. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  107725. );
  107726. if( pWInfo==0 ) goto select_end;
  107727. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  107728. /* The optimizer is able to deliver rows in group by order so
  107729. ** we do not have to sort. The OP_OpenEphemeral table will be
  107730. ** cancelled later because we still need to use the pKeyInfo
  107731. */
  107732. groupBySort = 0;
  107733. }else{
  107734. /* Rows are coming out in undetermined order. We have to push
  107735. ** each row into a sorting index, terminate the first loop,
  107736. ** then loop over the sorting index in order to get the output
  107737. ** in sorted order
  107738. */
  107739. int regBase;
  107740. int regRecord;
  107741. int nCol;
  107742. int nGroupBy;
  107743. explainTempTable(pParse,
  107744. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  107745. "DISTINCT" : "GROUP BY");
  107746. groupBySort = 1;
  107747. nGroupBy = pGroupBy->nExpr;
  107748. nCol = nGroupBy;
  107749. j = nGroupBy;
  107750. for(i=0; i<sAggInfo.nColumn; i++){
  107751. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  107752. nCol++;
  107753. j++;
  107754. }
  107755. }
  107756. regBase = sqlite3GetTempRange(pParse, nCol);
  107757. sqlite3ExprCacheClear(pParse);
  107758. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  107759. j = nGroupBy;
  107760. for(i=0; i<sAggInfo.nColumn; i++){
  107761. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  107762. if( pCol->iSorterColumn>=j ){
  107763. int r1 = j + regBase;
  107764. sqlite3ExprCodeGetColumnToReg(pParse,
  107765. pCol->pTab, pCol->iColumn, pCol->iTable, r1);
  107766. j++;
  107767. }
  107768. }
  107769. regRecord = sqlite3GetTempReg(pParse);
  107770. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  107771. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  107772. sqlite3ReleaseTempReg(pParse, regRecord);
  107773. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  107774. sqlite3WhereEnd(pWInfo);
  107775. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  107776. sortOut = sqlite3GetTempReg(pParse);
  107777. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  107778. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  107779. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  107780. sAggInfo.useSortingIdx = 1;
  107781. sqlite3ExprCacheClear(pParse);
  107782. }
  107783. /* If the index or temporary table used by the GROUP BY sort
  107784. ** will naturally deliver rows in the order required by the ORDER BY
  107785. ** clause, cancel the ephemeral table open coded earlier.
  107786. **
  107787. ** This is an optimization - the correct answer should result regardless.
  107788. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  107789. ** disable this optimization for testing purposes. */
  107790. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  107791. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  107792. ){
  107793. sSort.pOrderBy = 0;
  107794. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  107795. }
  107796. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  107797. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  107798. ** Then compare the current GROUP BY terms against the GROUP BY terms
  107799. ** from the previous row currently stored in a0, a1, a2...
  107800. */
  107801. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  107802. sqlite3ExprCacheClear(pParse);
  107803. if( groupBySort ){
  107804. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  107805. sortOut, sortPTab);
  107806. }
  107807. for(j=0; j<pGroupBy->nExpr; j++){
  107808. if( groupBySort ){
  107809. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  107810. }else{
  107811. sAggInfo.directMode = 1;
  107812. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  107813. }
  107814. }
  107815. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  107816. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  107817. addr1 = sqlite3VdbeCurrentAddr(v);
  107818. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  107819. /* Generate code that runs whenever the GROUP BY changes.
  107820. ** Changes in the GROUP BY are detected by the previous code
  107821. ** block. If there were no changes, this block is skipped.
  107822. **
  107823. ** This code copies current group by terms in b0,b1,b2,...
  107824. ** over to a0,a1,a2. It then calls the output subroutine
  107825. ** and resets the aggregate accumulator registers in preparation
  107826. ** for the next GROUP BY batch.
  107827. */
  107828. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  107829. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  107830. VdbeComment((v, "output one row"));
  107831. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  107832. VdbeComment((v, "check abort flag"));
  107833. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  107834. VdbeComment((v, "reset accumulator"));
  107835. /* Update the aggregate accumulators based on the content of
  107836. ** the current row
  107837. */
  107838. sqlite3VdbeJumpHere(v, addr1);
  107839. updateAccumulator(pParse, &sAggInfo);
  107840. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  107841. VdbeComment((v, "indicate data in accumulator"));
  107842. /* End of the loop
  107843. */
  107844. if( groupBySort ){
  107845. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  107846. VdbeCoverage(v);
  107847. }else{
  107848. sqlite3WhereEnd(pWInfo);
  107849. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  107850. }
  107851. /* Output the final row of result
  107852. */
  107853. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  107854. VdbeComment((v, "output final row"));
  107855. /* Jump over the subroutines
  107856. */
  107857. sqlite3VdbeGoto(v, addrEnd);
  107858. /* Generate a subroutine that outputs a single row of the result
  107859. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  107860. ** is less than or equal to zero, the subroutine is a no-op. If
  107861. ** the processing calls for the query to abort, this subroutine
  107862. ** increments the iAbortFlag memory location before returning in
  107863. ** order to signal the caller to abort.
  107864. */
  107865. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  107866. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  107867. VdbeComment((v, "set abort flag"));
  107868. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  107869. sqlite3VdbeResolveLabel(v, addrOutputRow);
  107870. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  107871. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  107872. VdbeCoverage(v);
  107873. VdbeComment((v, "Groupby result generator entry point"));
  107874. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  107875. finalizeAggFunctions(pParse, &sAggInfo);
  107876. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  107877. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  107878. &sDistinct, pDest,
  107879. addrOutputRow+1, addrSetAbort);
  107880. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  107881. VdbeComment((v, "end groupby result generator"));
  107882. /* Generate a subroutine that will reset the group-by accumulator
  107883. */
  107884. sqlite3VdbeResolveLabel(v, addrReset);
  107885. resetAccumulator(pParse, &sAggInfo);
  107886. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  107887. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  107888. else {
  107889. ExprList *pDel = 0;
  107890. #ifndef SQLITE_OMIT_BTREECOUNT
  107891. Table *pTab;
  107892. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  107893. /* If isSimpleCount() returns a pointer to a Table structure, then
  107894. ** the SQL statement is of the form:
  107895. **
  107896. ** SELECT count(*) FROM <tbl>
  107897. **
  107898. ** where the Table structure returned represents table <tbl>.
  107899. **
  107900. ** This statement is so common that it is optimized specially. The
  107901. ** OP_Count instruction is executed either on the intkey table that
  107902. ** contains the data for table <tbl> or on one of its indexes. It
  107903. ** is better to execute the op on an index, as indexes are almost
  107904. ** always spread across less pages than their corresponding tables.
  107905. */
  107906. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  107907. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  107908. Index *pIdx; /* Iterator variable */
  107909. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  107910. Index *pBest = 0; /* Best index found so far */
  107911. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  107912. sqlite3CodeVerifySchema(pParse, iDb);
  107913. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  107914. /* Search for the index that has the lowest scan cost.
  107915. **
  107916. ** (2011-04-15) Do not do a full scan of an unordered index.
  107917. **
  107918. ** (2013-10-03) Do not count the entries in a partial index.
  107919. **
  107920. ** In practice the KeyInfo structure will not be used. It is only
  107921. ** passed to keep OP_OpenRead happy.
  107922. */
  107923. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  107924. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107925. if( pIdx->bUnordered==0
  107926. && pIdx->szIdxRow<pTab->szTabRow
  107927. && pIdx->pPartIdxWhere==0
  107928. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  107929. ){
  107930. pBest = pIdx;
  107931. }
  107932. }
  107933. if( pBest ){
  107934. iRoot = pBest->tnum;
  107935. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  107936. }
  107937. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  107938. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  107939. if( pKeyInfo ){
  107940. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  107941. }
  107942. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  107943. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  107944. explainSimpleCount(pParse, pTab, pBest);
  107945. }else
  107946. #endif /* SQLITE_OMIT_BTREECOUNT */
  107947. {
  107948. /* Check if the query is of one of the following forms:
  107949. **
  107950. ** SELECT min(x) FROM ...
  107951. ** SELECT max(x) FROM ...
  107952. **
  107953. ** If it is, then ask the code in where.c to attempt to sort results
  107954. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  107955. ** If where.c is able to produce results sorted in this order, then
  107956. ** add vdbe code to break out of the processing loop after the
  107957. ** first iteration (since the first iteration of the loop is
  107958. ** guaranteed to operate on the row with the minimum or maximum
  107959. ** value of x, the only row required).
  107960. **
  107961. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  107962. ** modify behavior as follows:
  107963. **
  107964. ** + If the query is a "SELECT min(x)", then the loop coded by
  107965. ** where.c should not iterate over any values with a NULL value
  107966. ** for x.
  107967. **
  107968. ** + The optimizer code in where.c (the thing that decides which
  107969. ** index or indices to use) should place a different priority on
  107970. ** satisfying the 'ORDER BY' clause than it does in other cases.
  107971. ** Refer to code and comments in where.c for details.
  107972. */
  107973. ExprList *pMinMax = 0;
  107974. u8 flag = WHERE_ORDERBY_NORMAL;
  107975. assert( p->pGroupBy==0 );
  107976. assert( flag==0 );
  107977. if( p->pHaving==0 ){
  107978. flag = minMaxQuery(&sAggInfo, &pMinMax);
  107979. }
  107980. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  107981. if( flag ){
  107982. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  107983. pDel = pMinMax;
  107984. if( pMinMax && !db->mallocFailed ){
  107985. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  107986. pMinMax->a[0].pExpr->op = TK_COLUMN;
  107987. }
  107988. }
  107989. /* This case runs if the aggregate has no GROUP BY clause. The
  107990. ** processing is much simpler since there is only a single row
  107991. ** of output.
  107992. */
  107993. resetAccumulator(pParse, &sAggInfo);
  107994. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  107995. if( pWInfo==0 ){
  107996. sqlite3ExprListDelete(db, pDel);
  107997. goto select_end;
  107998. }
  107999. updateAccumulator(pParse, &sAggInfo);
  108000. assert( pMinMax==0 || pMinMax->nExpr==1 );
  108001. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  108002. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  108003. VdbeComment((v, "%s() by index",
  108004. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  108005. }
  108006. sqlite3WhereEnd(pWInfo);
  108007. finalizeAggFunctions(pParse, &sAggInfo);
  108008. }
  108009. sSort.pOrderBy = 0;
  108010. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  108011. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  108012. pDest, addrEnd, addrEnd);
  108013. sqlite3ExprListDelete(db, pDel);
  108014. }
  108015. sqlite3VdbeResolveLabel(v, addrEnd);
  108016. } /* endif aggregate query */
  108017. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  108018. explainTempTable(pParse, "DISTINCT");
  108019. }
  108020. /* If there is an ORDER BY clause, then we need to sort the results
  108021. ** and send them to the callback one by one.
  108022. */
  108023. if( sSort.pOrderBy ){
  108024. explainTempTable(pParse,
  108025. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  108026. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  108027. }
  108028. /* Jump here to skip this query
  108029. */
  108030. sqlite3VdbeResolveLabel(v, iEnd);
  108031. /* The SELECT has been coded. If there is an error in the Parse structure,
  108032. ** set the return code to 1. Otherwise 0. */
  108033. rc = (pParse->nErr>0);
  108034. /* Control jumps to here if an error is encountered above, or upon
  108035. ** successful coding of the SELECT.
  108036. */
  108037. select_end:
  108038. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  108039. /* Identify column names if results of the SELECT are to be output.
  108040. */
  108041. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  108042. generateColumnNames(pParse, pTabList, pEList);
  108043. }
  108044. sqlite3DbFree(db, sAggInfo.aCol);
  108045. sqlite3DbFree(db, sAggInfo.aFunc);
  108046. #if SELECTTRACE_ENABLED
  108047. SELECTTRACE(1,pParse,p,("end processing\n"));
  108048. pParse->nSelectIndent--;
  108049. #endif
  108050. return rc;
  108051. }
  108052. /************** End of select.c **********************************************/
  108053. /************** Begin file table.c *******************************************/
  108054. /*
  108055. ** 2001 September 15
  108056. **
  108057. ** The author disclaims copyright to this source code. In place of
  108058. ** a legal notice, here is a blessing:
  108059. **
  108060. ** May you do good and not evil.
  108061. ** May you find forgiveness for yourself and forgive others.
  108062. ** May you share freely, never taking more than you give.
  108063. **
  108064. *************************************************************************
  108065. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  108066. ** interface routines. These are just wrappers around the main
  108067. ** interface routine of sqlite3_exec().
  108068. **
  108069. ** These routines are in a separate files so that they will not be linked
  108070. ** if they are not used.
  108071. */
  108072. /* #include "sqliteInt.h" */
  108073. /* #include <stdlib.h> */
  108074. /* #include <string.h> */
  108075. #ifndef SQLITE_OMIT_GET_TABLE
  108076. /*
  108077. ** This structure is used to pass data from sqlite3_get_table() through
  108078. ** to the callback function is uses to build the result.
  108079. */
  108080. typedef struct TabResult {
  108081. char **azResult; /* Accumulated output */
  108082. char *zErrMsg; /* Error message text, if an error occurs */
  108083. u32 nAlloc; /* Slots allocated for azResult[] */
  108084. u32 nRow; /* Number of rows in the result */
  108085. u32 nColumn; /* Number of columns in the result */
  108086. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  108087. int rc; /* Return code from sqlite3_exec() */
  108088. } TabResult;
  108089. /*
  108090. ** This routine is called once for each row in the result table. Its job
  108091. ** is to fill in the TabResult structure appropriately, allocating new
  108092. ** memory as necessary.
  108093. */
  108094. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  108095. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  108096. int need; /* Slots needed in p->azResult[] */
  108097. int i; /* Loop counter */
  108098. char *z; /* A single column of result */
  108099. /* Make sure there is enough space in p->azResult to hold everything
  108100. ** we need to remember from this invocation of the callback.
  108101. */
  108102. if( p->nRow==0 && argv!=0 ){
  108103. need = nCol*2;
  108104. }else{
  108105. need = nCol;
  108106. }
  108107. if( p->nData + need > p->nAlloc ){
  108108. char **azNew;
  108109. p->nAlloc = p->nAlloc*2 + need;
  108110. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  108111. if( azNew==0 ) goto malloc_failed;
  108112. p->azResult = azNew;
  108113. }
  108114. /* If this is the first row, then generate an extra row containing
  108115. ** the names of all columns.
  108116. */
  108117. if( p->nRow==0 ){
  108118. p->nColumn = nCol;
  108119. for(i=0; i<nCol; i++){
  108120. z = sqlite3_mprintf("%s", colv[i]);
  108121. if( z==0 ) goto malloc_failed;
  108122. p->azResult[p->nData++] = z;
  108123. }
  108124. }else if( (int)p->nColumn!=nCol ){
  108125. sqlite3_free(p->zErrMsg);
  108126. p->zErrMsg = sqlite3_mprintf(
  108127. "sqlite3_get_table() called with two or more incompatible queries"
  108128. );
  108129. p->rc = SQLITE_ERROR;
  108130. return 1;
  108131. }
  108132. /* Copy over the row data
  108133. */
  108134. if( argv!=0 ){
  108135. for(i=0; i<nCol; i++){
  108136. if( argv[i]==0 ){
  108137. z = 0;
  108138. }else{
  108139. int n = sqlite3Strlen30(argv[i])+1;
  108140. z = sqlite3_malloc64( n );
  108141. if( z==0 ) goto malloc_failed;
  108142. memcpy(z, argv[i], n);
  108143. }
  108144. p->azResult[p->nData++] = z;
  108145. }
  108146. p->nRow++;
  108147. }
  108148. return 0;
  108149. malloc_failed:
  108150. p->rc = SQLITE_NOMEM;
  108151. return 1;
  108152. }
  108153. /*
  108154. ** Query the database. But instead of invoking a callback for each row,
  108155. ** malloc() for space to hold the result and return the entire results
  108156. ** at the conclusion of the call.
  108157. **
  108158. ** The result that is written to ***pazResult is held in memory obtained
  108159. ** from malloc(). But the caller cannot free this memory directly.
  108160. ** Instead, the entire table should be passed to sqlite3_free_table() when
  108161. ** the calling procedure is finished using it.
  108162. */
  108163. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  108164. sqlite3 *db, /* The database on which the SQL executes */
  108165. const char *zSql, /* The SQL to be executed */
  108166. char ***pazResult, /* Write the result table here */
  108167. int *pnRow, /* Write the number of rows in the result here */
  108168. int *pnColumn, /* Write the number of columns of result here */
  108169. char **pzErrMsg /* Write error messages here */
  108170. ){
  108171. int rc;
  108172. TabResult res;
  108173. #ifdef SQLITE_ENABLE_API_ARMOR
  108174. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  108175. #endif
  108176. *pazResult = 0;
  108177. if( pnColumn ) *pnColumn = 0;
  108178. if( pnRow ) *pnRow = 0;
  108179. if( pzErrMsg ) *pzErrMsg = 0;
  108180. res.zErrMsg = 0;
  108181. res.nRow = 0;
  108182. res.nColumn = 0;
  108183. res.nData = 1;
  108184. res.nAlloc = 20;
  108185. res.rc = SQLITE_OK;
  108186. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  108187. if( res.azResult==0 ){
  108188. db->errCode = SQLITE_NOMEM;
  108189. return SQLITE_NOMEM;
  108190. }
  108191. res.azResult[0] = 0;
  108192. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  108193. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  108194. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  108195. if( (rc&0xff)==SQLITE_ABORT ){
  108196. sqlite3_free_table(&res.azResult[1]);
  108197. if( res.zErrMsg ){
  108198. if( pzErrMsg ){
  108199. sqlite3_free(*pzErrMsg);
  108200. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  108201. }
  108202. sqlite3_free(res.zErrMsg);
  108203. }
  108204. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  108205. return res.rc;
  108206. }
  108207. sqlite3_free(res.zErrMsg);
  108208. if( rc!=SQLITE_OK ){
  108209. sqlite3_free_table(&res.azResult[1]);
  108210. return rc;
  108211. }
  108212. if( res.nAlloc>res.nData ){
  108213. char **azNew;
  108214. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  108215. if( azNew==0 ){
  108216. sqlite3_free_table(&res.azResult[1]);
  108217. db->errCode = SQLITE_NOMEM;
  108218. return SQLITE_NOMEM;
  108219. }
  108220. res.azResult = azNew;
  108221. }
  108222. *pazResult = &res.azResult[1];
  108223. if( pnColumn ) *pnColumn = res.nColumn;
  108224. if( pnRow ) *pnRow = res.nRow;
  108225. return rc;
  108226. }
  108227. /*
  108228. ** This routine frees the space the sqlite3_get_table() malloced.
  108229. */
  108230. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
  108231. char **azResult /* Result returned from sqlite3_get_table() */
  108232. ){
  108233. if( azResult ){
  108234. int i, n;
  108235. azResult--;
  108236. assert( azResult!=0 );
  108237. n = SQLITE_PTR_TO_INT(azResult[0]);
  108238. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  108239. sqlite3_free(azResult);
  108240. }
  108241. }
  108242. #endif /* SQLITE_OMIT_GET_TABLE */
  108243. /************** End of table.c ***********************************************/
  108244. /************** Begin file trigger.c *****************************************/
  108245. /*
  108246. **
  108247. ** The author disclaims copyright to this source code. In place of
  108248. ** a legal notice, here is a blessing:
  108249. **
  108250. ** May you do good and not evil.
  108251. ** May you find forgiveness for yourself and forgive others.
  108252. ** May you share freely, never taking more than you give.
  108253. **
  108254. *************************************************************************
  108255. ** This file contains the implementation for TRIGGERs
  108256. */
  108257. /* #include "sqliteInt.h" */
  108258. #ifndef SQLITE_OMIT_TRIGGER
  108259. /*
  108260. ** Delete a linked list of TriggerStep structures.
  108261. */
  108262. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  108263. while( pTriggerStep ){
  108264. TriggerStep * pTmp = pTriggerStep;
  108265. pTriggerStep = pTriggerStep->pNext;
  108266. sqlite3ExprDelete(db, pTmp->pWhere);
  108267. sqlite3ExprListDelete(db, pTmp->pExprList);
  108268. sqlite3SelectDelete(db, pTmp->pSelect);
  108269. sqlite3IdListDelete(db, pTmp->pIdList);
  108270. sqlite3DbFree(db, pTmp);
  108271. }
  108272. }
  108273. /*
  108274. ** Given table pTab, return a list of all the triggers attached to
  108275. ** the table. The list is connected by Trigger.pNext pointers.
  108276. **
  108277. ** All of the triggers on pTab that are in the same database as pTab
  108278. ** are already attached to pTab->pTrigger. But there might be additional
  108279. ** triggers on pTab in the TEMP schema. This routine prepends all
  108280. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  108281. ** and returns the combined list.
  108282. **
  108283. ** To state it another way: This routine returns a list of all triggers
  108284. ** that fire off of pTab. The list will include any TEMP triggers on
  108285. ** pTab as well as the triggers lised in pTab->pTrigger.
  108286. */
  108287. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  108288. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  108289. Trigger *pList = 0; /* List of triggers to return */
  108290. if( pParse->disableTriggers ){
  108291. return 0;
  108292. }
  108293. if( pTmpSchema!=pTab->pSchema ){
  108294. HashElem *p;
  108295. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  108296. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  108297. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  108298. if( pTrig->pTabSchema==pTab->pSchema
  108299. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  108300. ){
  108301. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  108302. pList = pTrig;
  108303. }
  108304. }
  108305. }
  108306. return (pList ? pList : pTab->pTrigger);
  108307. }
  108308. /*
  108309. ** This is called by the parser when it sees a CREATE TRIGGER statement
  108310. ** up to the point of the BEGIN before the trigger actions. A Trigger
  108311. ** structure is generated based on the information available and stored
  108312. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  108313. ** sqlite3FinishTrigger() function is called to complete the trigger
  108314. ** construction process.
  108315. */
  108316. SQLITE_PRIVATE void sqlite3BeginTrigger(
  108317. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  108318. Token *pName1, /* The name of the trigger */
  108319. Token *pName2, /* The name of the trigger */
  108320. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  108321. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  108322. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  108323. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  108324. Expr *pWhen, /* WHEN clause */
  108325. int isTemp, /* True if the TEMPORARY keyword is present */
  108326. int noErr /* Suppress errors if the trigger already exists */
  108327. ){
  108328. Trigger *pTrigger = 0; /* The new trigger */
  108329. Table *pTab; /* Table that the trigger fires off of */
  108330. char *zName = 0; /* Name of the trigger */
  108331. sqlite3 *db = pParse->db; /* The database connection */
  108332. int iDb; /* The database to store the trigger in */
  108333. Token *pName; /* The unqualified db name */
  108334. DbFixer sFix; /* State vector for the DB fixer */
  108335. int iTabDb; /* Index of the database holding pTab */
  108336. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  108337. assert( pName2!=0 );
  108338. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  108339. assert( op>0 && op<0xff );
  108340. if( isTemp ){
  108341. /* If TEMP was specified, then the trigger name may not be qualified. */
  108342. if( pName2->n>0 ){
  108343. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  108344. goto trigger_cleanup;
  108345. }
  108346. iDb = 1;
  108347. pName = pName1;
  108348. }else{
  108349. /* Figure out the db that the trigger will be created in */
  108350. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  108351. if( iDb<0 ){
  108352. goto trigger_cleanup;
  108353. }
  108354. }
  108355. if( !pTableName || db->mallocFailed ){
  108356. goto trigger_cleanup;
  108357. }
  108358. /* A long-standing parser bug is that this syntax was allowed:
  108359. **
  108360. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  108361. ** ^^^^^^^^
  108362. **
  108363. ** To maintain backwards compatibility, ignore the database
  108364. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  108365. */
  108366. if( db->init.busy && iDb!=1 ){
  108367. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  108368. pTableName->a[0].zDatabase = 0;
  108369. }
  108370. /* If the trigger name was unqualified, and the table is a temp table,
  108371. ** then set iDb to 1 to create the trigger in the temporary database.
  108372. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  108373. ** exist, the error is caught by the block below.
  108374. */
  108375. pTab = sqlite3SrcListLookup(pParse, pTableName);
  108376. if( db->init.busy==0 && pName2->n==0 && pTab
  108377. && pTab->pSchema==db->aDb[1].pSchema ){
  108378. iDb = 1;
  108379. }
  108380. /* Ensure the table name matches database name and that the table exists */
  108381. if( db->mallocFailed ) goto trigger_cleanup;
  108382. assert( pTableName->nSrc==1 );
  108383. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  108384. if( sqlite3FixSrcList(&sFix, pTableName) ){
  108385. goto trigger_cleanup;
  108386. }
  108387. pTab = sqlite3SrcListLookup(pParse, pTableName);
  108388. if( !pTab ){
  108389. /* The table does not exist. */
  108390. if( db->init.iDb==1 ){
  108391. /* Ticket #3810.
  108392. ** Normally, whenever a table is dropped, all associated triggers are
  108393. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  108394. ** and the table is dropped by a different database connection, the
  108395. ** trigger is not visible to the database connection that does the
  108396. ** drop so the trigger cannot be dropped. This results in an
  108397. ** "orphaned trigger" - a trigger whose associated table is missing.
  108398. */
  108399. db->init.orphanTrigger = 1;
  108400. }
  108401. goto trigger_cleanup;
  108402. }
  108403. if( IsVirtual(pTab) ){
  108404. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  108405. goto trigger_cleanup;
  108406. }
  108407. /* Check that the trigger name is not reserved and that no trigger of the
  108408. ** specified name exists */
  108409. zName = sqlite3NameFromToken(db, pName);
  108410. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  108411. goto trigger_cleanup;
  108412. }
  108413. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  108414. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  108415. if( !noErr ){
  108416. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  108417. }else{
  108418. assert( !db->init.busy );
  108419. sqlite3CodeVerifySchema(pParse, iDb);
  108420. }
  108421. goto trigger_cleanup;
  108422. }
  108423. /* Do not create a trigger on a system table */
  108424. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  108425. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  108426. goto trigger_cleanup;
  108427. }
  108428. /* INSTEAD of triggers are only for views and views only support INSTEAD
  108429. ** of triggers.
  108430. */
  108431. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  108432. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  108433. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  108434. goto trigger_cleanup;
  108435. }
  108436. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  108437. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  108438. " trigger on table: %S", pTableName, 0);
  108439. goto trigger_cleanup;
  108440. }
  108441. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  108442. #ifndef SQLITE_OMIT_AUTHORIZATION
  108443. {
  108444. int code = SQLITE_CREATE_TRIGGER;
  108445. const char *zDb = db->aDb[iTabDb].zName;
  108446. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  108447. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  108448. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  108449. goto trigger_cleanup;
  108450. }
  108451. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  108452. goto trigger_cleanup;
  108453. }
  108454. }
  108455. #endif
  108456. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  108457. ** cannot appear on views. So we might as well translate every
  108458. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  108459. ** elsewhere.
  108460. */
  108461. if (tr_tm == TK_INSTEAD){
  108462. tr_tm = TK_BEFORE;
  108463. }
  108464. /* Build the Trigger object */
  108465. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  108466. if( pTrigger==0 ) goto trigger_cleanup;
  108467. pTrigger->zName = zName;
  108468. zName = 0;
  108469. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  108470. pTrigger->pSchema = db->aDb[iDb].pSchema;
  108471. pTrigger->pTabSchema = pTab->pSchema;
  108472. pTrigger->op = (u8)op;
  108473. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  108474. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  108475. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  108476. assert( pParse->pNewTrigger==0 );
  108477. pParse->pNewTrigger = pTrigger;
  108478. trigger_cleanup:
  108479. sqlite3DbFree(db, zName);
  108480. sqlite3SrcListDelete(db, pTableName);
  108481. sqlite3IdListDelete(db, pColumns);
  108482. sqlite3ExprDelete(db, pWhen);
  108483. if( !pParse->pNewTrigger ){
  108484. sqlite3DeleteTrigger(db, pTrigger);
  108485. }else{
  108486. assert( pParse->pNewTrigger==pTrigger );
  108487. }
  108488. }
  108489. /*
  108490. ** This routine is called after all of the trigger actions have been parsed
  108491. ** in order to complete the process of building the trigger.
  108492. */
  108493. SQLITE_PRIVATE void sqlite3FinishTrigger(
  108494. Parse *pParse, /* Parser context */
  108495. TriggerStep *pStepList, /* The triggered program */
  108496. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  108497. ){
  108498. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  108499. char *zName; /* Name of trigger */
  108500. sqlite3 *db = pParse->db; /* The database */
  108501. DbFixer sFix; /* Fixer object */
  108502. int iDb; /* Database containing the trigger */
  108503. Token nameToken; /* Trigger name for error reporting */
  108504. pParse->pNewTrigger = 0;
  108505. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  108506. zName = pTrig->zName;
  108507. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  108508. pTrig->step_list = pStepList;
  108509. while( pStepList ){
  108510. pStepList->pTrig = pTrig;
  108511. pStepList = pStepList->pNext;
  108512. }
  108513. nameToken.z = pTrig->zName;
  108514. nameToken.n = sqlite3Strlen30(nameToken.z);
  108515. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  108516. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  108517. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  108518. ){
  108519. goto triggerfinish_cleanup;
  108520. }
  108521. /* if we are not initializing,
  108522. ** build the sqlite_master entry
  108523. */
  108524. if( !db->init.busy ){
  108525. Vdbe *v;
  108526. char *z;
  108527. /* Make an entry in the sqlite_master table */
  108528. v = sqlite3GetVdbe(pParse);
  108529. if( v==0 ) goto triggerfinish_cleanup;
  108530. sqlite3BeginWriteOperation(pParse, 0, iDb);
  108531. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  108532. sqlite3NestedParse(pParse,
  108533. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  108534. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  108535. pTrig->table, z);
  108536. sqlite3DbFree(db, z);
  108537. sqlite3ChangeCookie(pParse, iDb);
  108538. sqlite3VdbeAddParseSchemaOp(v, iDb,
  108539. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  108540. }
  108541. if( db->init.busy ){
  108542. Trigger *pLink = pTrig;
  108543. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  108544. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  108545. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  108546. if( pTrig ){
  108547. db->mallocFailed = 1;
  108548. }else if( pLink->pSchema==pLink->pTabSchema ){
  108549. Table *pTab;
  108550. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  108551. assert( pTab!=0 );
  108552. pLink->pNext = pTab->pTrigger;
  108553. pTab->pTrigger = pLink;
  108554. }
  108555. }
  108556. triggerfinish_cleanup:
  108557. sqlite3DeleteTrigger(db, pTrig);
  108558. assert( !pParse->pNewTrigger );
  108559. sqlite3DeleteTriggerStep(db, pStepList);
  108560. }
  108561. /*
  108562. ** Turn a SELECT statement (that the pSelect parameter points to) into
  108563. ** a trigger step. Return a pointer to a TriggerStep structure.
  108564. **
  108565. ** The parser calls this routine when it finds a SELECT statement in
  108566. ** body of a TRIGGER.
  108567. */
  108568. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  108569. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  108570. if( pTriggerStep==0 ) {
  108571. sqlite3SelectDelete(db, pSelect);
  108572. return 0;
  108573. }
  108574. pTriggerStep->op = TK_SELECT;
  108575. pTriggerStep->pSelect = pSelect;
  108576. pTriggerStep->orconf = OE_Default;
  108577. return pTriggerStep;
  108578. }
  108579. /*
  108580. ** Allocate space to hold a new trigger step. The allocated space
  108581. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  108582. **
  108583. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  108584. */
  108585. static TriggerStep *triggerStepAllocate(
  108586. sqlite3 *db, /* Database connection */
  108587. u8 op, /* Trigger opcode */
  108588. Token *pName /* The target name */
  108589. ){
  108590. TriggerStep *pTriggerStep;
  108591. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  108592. if( pTriggerStep ){
  108593. char *z = (char*)&pTriggerStep[1];
  108594. memcpy(z, pName->z, pName->n);
  108595. sqlite3Dequote(z);
  108596. pTriggerStep->zTarget = z;
  108597. pTriggerStep->op = op;
  108598. }
  108599. return pTriggerStep;
  108600. }
  108601. /*
  108602. ** Build a trigger step out of an INSERT statement. Return a pointer
  108603. ** to the new trigger step.
  108604. **
  108605. ** The parser calls this routine when it sees an INSERT inside the
  108606. ** body of a trigger.
  108607. */
  108608. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  108609. sqlite3 *db, /* The database connection */
  108610. Token *pTableName, /* Name of the table into which we insert */
  108611. IdList *pColumn, /* List of columns in pTableName to insert into */
  108612. Select *pSelect, /* A SELECT statement that supplies values */
  108613. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  108614. ){
  108615. TriggerStep *pTriggerStep;
  108616. assert(pSelect != 0 || db->mallocFailed);
  108617. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  108618. if( pTriggerStep ){
  108619. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  108620. pTriggerStep->pIdList = pColumn;
  108621. pTriggerStep->orconf = orconf;
  108622. }else{
  108623. sqlite3IdListDelete(db, pColumn);
  108624. }
  108625. sqlite3SelectDelete(db, pSelect);
  108626. return pTriggerStep;
  108627. }
  108628. /*
  108629. ** Construct a trigger step that implements an UPDATE statement and return
  108630. ** a pointer to that trigger step. The parser calls this routine when it
  108631. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  108632. */
  108633. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  108634. sqlite3 *db, /* The database connection */
  108635. Token *pTableName, /* Name of the table to be updated */
  108636. ExprList *pEList, /* The SET clause: list of column and new values */
  108637. Expr *pWhere, /* The WHERE clause */
  108638. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  108639. ){
  108640. TriggerStep *pTriggerStep;
  108641. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  108642. if( pTriggerStep ){
  108643. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  108644. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  108645. pTriggerStep->orconf = orconf;
  108646. }
  108647. sqlite3ExprListDelete(db, pEList);
  108648. sqlite3ExprDelete(db, pWhere);
  108649. return pTriggerStep;
  108650. }
  108651. /*
  108652. ** Construct a trigger step that implements a DELETE statement and return
  108653. ** a pointer to that trigger step. The parser calls this routine when it
  108654. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  108655. */
  108656. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  108657. sqlite3 *db, /* Database connection */
  108658. Token *pTableName, /* The table from which rows are deleted */
  108659. Expr *pWhere /* The WHERE clause */
  108660. ){
  108661. TriggerStep *pTriggerStep;
  108662. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  108663. if( pTriggerStep ){
  108664. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  108665. pTriggerStep->orconf = OE_Default;
  108666. }
  108667. sqlite3ExprDelete(db, pWhere);
  108668. return pTriggerStep;
  108669. }
  108670. /*
  108671. ** Recursively delete a Trigger structure
  108672. */
  108673. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  108674. if( pTrigger==0 ) return;
  108675. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  108676. sqlite3DbFree(db, pTrigger->zName);
  108677. sqlite3DbFree(db, pTrigger->table);
  108678. sqlite3ExprDelete(db, pTrigger->pWhen);
  108679. sqlite3IdListDelete(db, pTrigger->pColumns);
  108680. sqlite3DbFree(db, pTrigger);
  108681. }
  108682. /*
  108683. ** This function is called to drop a trigger from the database schema.
  108684. **
  108685. ** This may be called directly from the parser and therefore identifies
  108686. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  108687. ** same job as this routine except it takes a pointer to the trigger
  108688. ** instead of the trigger name.
  108689. **/
  108690. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  108691. Trigger *pTrigger = 0;
  108692. int i;
  108693. const char *zDb;
  108694. const char *zName;
  108695. sqlite3 *db = pParse->db;
  108696. if( db->mallocFailed ) goto drop_trigger_cleanup;
  108697. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  108698. goto drop_trigger_cleanup;
  108699. }
  108700. assert( pName->nSrc==1 );
  108701. zDb = pName->a[0].zDatabase;
  108702. zName = pName->a[0].zName;
  108703. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  108704. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  108705. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  108706. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  108707. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  108708. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  108709. if( pTrigger ) break;
  108710. }
  108711. if( !pTrigger ){
  108712. if( !noErr ){
  108713. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  108714. }else{
  108715. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  108716. }
  108717. pParse->checkSchema = 1;
  108718. goto drop_trigger_cleanup;
  108719. }
  108720. sqlite3DropTriggerPtr(pParse, pTrigger);
  108721. drop_trigger_cleanup:
  108722. sqlite3SrcListDelete(db, pName);
  108723. }
  108724. /*
  108725. ** Return a pointer to the Table structure for the table that a trigger
  108726. ** is set on.
  108727. */
  108728. static Table *tableOfTrigger(Trigger *pTrigger){
  108729. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  108730. }
  108731. /*
  108732. ** Drop a trigger given a pointer to that trigger.
  108733. */
  108734. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  108735. Table *pTable;
  108736. Vdbe *v;
  108737. sqlite3 *db = pParse->db;
  108738. int iDb;
  108739. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  108740. assert( iDb>=0 && iDb<db->nDb );
  108741. pTable = tableOfTrigger(pTrigger);
  108742. assert( pTable );
  108743. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  108744. #ifndef SQLITE_OMIT_AUTHORIZATION
  108745. {
  108746. int code = SQLITE_DROP_TRIGGER;
  108747. const char *zDb = db->aDb[iDb].zName;
  108748. const char *zTab = SCHEMA_TABLE(iDb);
  108749. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  108750. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  108751. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  108752. return;
  108753. }
  108754. }
  108755. #endif
  108756. /* Generate code to destroy the database record of the trigger.
  108757. */
  108758. assert( pTable!=0 );
  108759. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  108760. sqlite3NestedParse(pParse,
  108761. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  108762. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrigger->zName
  108763. );
  108764. sqlite3ChangeCookie(pParse, iDb);
  108765. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  108766. }
  108767. }
  108768. /*
  108769. ** Remove a trigger from the hash tables of the sqlite* pointer.
  108770. */
  108771. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  108772. Trigger *pTrigger;
  108773. Hash *pHash;
  108774. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  108775. pHash = &(db->aDb[iDb].pSchema->trigHash);
  108776. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  108777. if( ALWAYS(pTrigger) ){
  108778. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  108779. Table *pTab = tableOfTrigger(pTrigger);
  108780. Trigger **pp;
  108781. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  108782. *pp = (*pp)->pNext;
  108783. }
  108784. sqlite3DeleteTrigger(db, pTrigger);
  108785. db->flags |= SQLITE_InternChanges;
  108786. }
  108787. }
  108788. /*
  108789. ** pEList is the SET clause of an UPDATE statement. Each entry
  108790. ** in pEList is of the format <id>=<expr>. If any of the entries
  108791. ** in pEList have an <id> which matches an identifier in pIdList,
  108792. ** then return TRUE. If pIdList==NULL, then it is considered a
  108793. ** wildcard that matches anything. Likewise if pEList==NULL then
  108794. ** it matches anything so always return true. Return false only
  108795. ** if there is no match.
  108796. */
  108797. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  108798. int e;
  108799. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  108800. for(e=0; e<pEList->nExpr; e++){
  108801. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  108802. }
  108803. return 0;
  108804. }
  108805. /*
  108806. ** Return a list of all triggers on table pTab if there exists at least
  108807. ** one trigger that must be fired when an operation of type 'op' is
  108808. ** performed on the table, and, if that operation is an UPDATE, if at
  108809. ** least one of the columns in pChanges is being modified.
  108810. */
  108811. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  108812. Parse *pParse, /* Parse context */
  108813. Table *pTab, /* The table the contains the triggers */
  108814. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  108815. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  108816. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  108817. ){
  108818. int mask = 0;
  108819. Trigger *pList = 0;
  108820. Trigger *p;
  108821. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  108822. pList = sqlite3TriggerList(pParse, pTab);
  108823. }
  108824. assert( pList==0 || IsVirtual(pTab)==0 );
  108825. for(p=pList; p; p=p->pNext){
  108826. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  108827. mask |= p->tr_tm;
  108828. }
  108829. }
  108830. if( pMask ){
  108831. *pMask = mask;
  108832. }
  108833. return (mask ? pList : 0);
  108834. }
  108835. /*
  108836. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  108837. ** to that SrcList.
  108838. **
  108839. ** This routine adds a specific database name, if needed, to the target when
  108840. ** forming the SrcList. This prevents a trigger in one database from
  108841. ** referring to a target in another database. An exception is when the
  108842. ** trigger is in TEMP in which case it can refer to any other database it
  108843. ** wants.
  108844. */
  108845. static SrcList *targetSrcList(
  108846. Parse *pParse, /* The parsing context */
  108847. TriggerStep *pStep /* The trigger containing the target token */
  108848. ){
  108849. sqlite3 *db = pParse->db;
  108850. int iDb; /* Index of the database to use */
  108851. SrcList *pSrc; /* SrcList to be returned */
  108852. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  108853. if( pSrc ){
  108854. assert( pSrc->nSrc>0 );
  108855. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  108856. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  108857. if( iDb==0 || iDb>=2 ){
  108858. assert( iDb<db->nDb );
  108859. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  108860. }
  108861. }
  108862. return pSrc;
  108863. }
  108864. /*
  108865. ** Generate VDBE code for the statements inside the body of a single
  108866. ** trigger.
  108867. */
  108868. static int codeTriggerProgram(
  108869. Parse *pParse, /* The parser context */
  108870. TriggerStep *pStepList, /* List of statements inside the trigger body */
  108871. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  108872. ){
  108873. TriggerStep *pStep;
  108874. Vdbe *v = pParse->pVdbe;
  108875. sqlite3 *db = pParse->db;
  108876. assert( pParse->pTriggerTab && pParse->pToplevel );
  108877. assert( pStepList );
  108878. assert( v!=0 );
  108879. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  108880. /* Figure out the ON CONFLICT policy that will be used for this step
  108881. ** of the trigger program. If the statement that caused this trigger
  108882. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  108883. ** the ON CONFLICT policy that was specified as part of the trigger
  108884. ** step statement. Example:
  108885. **
  108886. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  108887. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  108888. ** END;
  108889. **
  108890. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  108891. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  108892. */
  108893. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  108894. assert( pParse->okConstFactor==0 );
  108895. switch( pStep->op ){
  108896. case TK_UPDATE: {
  108897. sqlite3Update(pParse,
  108898. targetSrcList(pParse, pStep),
  108899. sqlite3ExprListDup(db, pStep->pExprList, 0),
  108900. sqlite3ExprDup(db, pStep->pWhere, 0),
  108901. pParse->eOrconf
  108902. );
  108903. break;
  108904. }
  108905. case TK_INSERT: {
  108906. sqlite3Insert(pParse,
  108907. targetSrcList(pParse, pStep),
  108908. sqlite3SelectDup(db, pStep->pSelect, 0),
  108909. sqlite3IdListDup(db, pStep->pIdList),
  108910. pParse->eOrconf
  108911. );
  108912. break;
  108913. }
  108914. case TK_DELETE: {
  108915. sqlite3DeleteFrom(pParse,
  108916. targetSrcList(pParse, pStep),
  108917. sqlite3ExprDup(db, pStep->pWhere, 0)
  108918. );
  108919. break;
  108920. }
  108921. default: assert( pStep->op==TK_SELECT ); {
  108922. SelectDest sDest;
  108923. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  108924. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  108925. sqlite3Select(pParse, pSelect, &sDest);
  108926. sqlite3SelectDelete(db, pSelect);
  108927. break;
  108928. }
  108929. }
  108930. if( pStep->op!=TK_SELECT ){
  108931. sqlite3VdbeAddOp0(v, OP_ResetCount);
  108932. }
  108933. }
  108934. return 0;
  108935. }
  108936. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  108937. /*
  108938. ** This function is used to add VdbeComment() annotations to a VDBE
  108939. ** program. It is not used in production code, only for debugging.
  108940. */
  108941. static const char *onErrorText(int onError){
  108942. switch( onError ){
  108943. case OE_Abort: return "abort";
  108944. case OE_Rollback: return "rollback";
  108945. case OE_Fail: return "fail";
  108946. case OE_Replace: return "replace";
  108947. case OE_Ignore: return "ignore";
  108948. case OE_Default: return "default";
  108949. }
  108950. return "n/a";
  108951. }
  108952. #endif
  108953. /*
  108954. ** Parse context structure pFrom has just been used to create a sub-vdbe
  108955. ** (trigger program). If an error has occurred, transfer error information
  108956. ** from pFrom to pTo.
  108957. */
  108958. static void transferParseError(Parse *pTo, Parse *pFrom){
  108959. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  108960. assert( pTo->zErrMsg==0 || pTo->nErr );
  108961. if( pTo->nErr==0 ){
  108962. pTo->zErrMsg = pFrom->zErrMsg;
  108963. pTo->nErr = pFrom->nErr;
  108964. pTo->rc = pFrom->rc;
  108965. }else{
  108966. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  108967. }
  108968. }
  108969. /*
  108970. ** Create and populate a new TriggerPrg object with a sub-program
  108971. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  108972. */
  108973. static TriggerPrg *codeRowTrigger(
  108974. Parse *pParse, /* Current parse context */
  108975. Trigger *pTrigger, /* Trigger to code */
  108976. Table *pTab, /* The table pTrigger is attached to */
  108977. int orconf /* ON CONFLICT policy to code trigger program with */
  108978. ){
  108979. Parse *pTop = sqlite3ParseToplevel(pParse);
  108980. sqlite3 *db = pParse->db; /* Database handle */
  108981. TriggerPrg *pPrg; /* Value to return */
  108982. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  108983. Vdbe *v; /* Temporary VM */
  108984. NameContext sNC; /* Name context for sub-vdbe */
  108985. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  108986. Parse *pSubParse; /* Parse context for sub-vdbe */
  108987. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  108988. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  108989. assert( pTop->pVdbe );
  108990. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  108991. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  108992. ** list of the top-level Parse object sooner rather than later. */
  108993. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  108994. if( !pPrg ) return 0;
  108995. pPrg->pNext = pTop->pTriggerPrg;
  108996. pTop->pTriggerPrg = pPrg;
  108997. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  108998. if( !pProgram ) return 0;
  108999. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  109000. pPrg->pTrigger = pTrigger;
  109001. pPrg->orconf = orconf;
  109002. pPrg->aColmask[0] = 0xffffffff;
  109003. pPrg->aColmask[1] = 0xffffffff;
  109004. /* Allocate and populate a new Parse context to use for coding the
  109005. ** trigger sub-program. */
  109006. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  109007. if( !pSubParse ) return 0;
  109008. memset(&sNC, 0, sizeof(sNC));
  109009. sNC.pParse = pSubParse;
  109010. pSubParse->db = db;
  109011. pSubParse->pTriggerTab = pTab;
  109012. pSubParse->pToplevel = pTop;
  109013. pSubParse->zAuthContext = pTrigger->zName;
  109014. pSubParse->eTriggerOp = pTrigger->op;
  109015. pSubParse->nQueryLoop = pParse->nQueryLoop;
  109016. v = sqlite3GetVdbe(pSubParse);
  109017. if( v ){
  109018. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  109019. pTrigger->zName, onErrorText(orconf),
  109020. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  109021. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  109022. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  109023. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  109024. pTab->zName
  109025. ));
  109026. #ifndef SQLITE_OMIT_TRACE
  109027. sqlite3VdbeChangeP4(v, -1,
  109028. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  109029. );
  109030. #endif
  109031. /* If one was specified, code the WHEN clause. If it evaluates to false
  109032. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  109033. ** OP_Halt inserted at the end of the program. */
  109034. if( pTrigger->pWhen ){
  109035. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  109036. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  109037. && db->mallocFailed==0
  109038. ){
  109039. iEndTrigger = sqlite3VdbeMakeLabel(v);
  109040. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  109041. }
  109042. sqlite3ExprDelete(db, pWhen);
  109043. }
  109044. /* Code the trigger program into the sub-vdbe. */
  109045. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  109046. /* Insert an OP_Halt at the end of the sub-program. */
  109047. if( iEndTrigger ){
  109048. sqlite3VdbeResolveLabel(v, iEndTrigger);
  109049. }
  109050. sqlite3VdbeAddOp0(v, OP_Halt);
  109051. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  109052. transferParseError(pParse, pSubParse);
  109053. if( db->mallocFailed==0 ){
  109054. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  109055. }
  109056. pProgram->nMem = pSubParse->nMem;
  109057. pProgram->nCsr = pSubParse->nTab;
  109058. pProgram->nOnce = pSubParse->nOnce;
  109059. pProgram->token = (void *)pTrigger;
  109060. pPrg->aColmask[0] = pSubParse->oldmask;
  109061. pPrg->aColmask[1] = pSubParse->newmask;
  109062. sqlite3VdbeDelete(v);
  109063. }
  109064. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  109065. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  109066. sqlite3ParserReset(pSubParse);
  109067. sqlite3StackFree(db, pSubParse);
  109068. return pPrg;
  109069. }
  109070. /*
  109071. ** Return a pointer to a TriggerPrg object containing the sub-program for
  109072. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  109073. ** TriggerPrg object exists, a new object is allocated and populated before
  109074. ** being returned.
  109075. */
  109076. static TriggerPrg *getRowTrigger(
  109077. Parse *pParse, /* Current parse context */
  109078. Trigger *pTrigger, /* Trigger to code */
  109079. Table *pTab, /* The table trigger pTrigger is attached to */
  109080. int orconf /* ON CONFLICT algorithm. */
  109081. ){
  109082. Parse *pRoot = sqlite3ParseToplevel(pParse);
  109083. TriggerPrg *pPrg;
  109084. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  109085. /* It may be that this trigger has already been coded (or is in the
  109086. ** process of being coded). If this is the case, then an entry with
  109087. ** a matching TriggerPrg.pTrigger field will be present somewhere
  109088. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  109089. for(pPrg=pRoot->pTriggerPrg;
  109090. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  109091. pPrg=pPrg->pNext
  109092. );
  109093. /* If an existing TriggerPrg could not be located, create a new one. */
  109094. if( !pPrg ){
  109095. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  109096. }
  109097. return pPrg;
  109098. }
  109099. /*
  109100. ** Generate code for the trigger program associated with trigger p on
  109101. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  109102. ** function are the same as those described in the header function for
  109103. ** sqlite3CodeRowTrigger()
  109104. */
  109105. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  109106. Parse *pParse, /* Parse context */
  109107. Trigger *p, /* Trigger to code */
  109108. Table *pTab, /* The table to code triggers from */
  109109. int reg, /* Reg array containing OLD.* and NEW.* values */
  109110. int orconf, /* ON CONFLICT policy */
  109111. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  109112. ){
  109113. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  109114. TriggerPrg *pPrg;
  109115. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  109116. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  109117. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  109118. ** is a pointer to the sub-vdbe containing the trigger program. */
  109119. if( pPrg ){
  109120. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  109121. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  109122. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  109123. VdbeComment(
  109124. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  109125. /* Set the P5 operand of the OP_Program instruction to non-zero if
  109126. ** recursive invocation of this trigger program is disallowed. Recursive
  109127. ** invocation is disallowed if (a) the sub-program is really a trigger,
  109128. ** not a foreign key action, and (b) the flag to enable recursive triggers
  109129. ** is clear. */
  109130. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  109131. }
  109132. }
  109133. /*
  109134. ** This is called to code the required FOR EACH ROW triggers for an operation
  109135. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  109136. ** is given by the op parameter. The tr_tm parameter determines whether the
  109137. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  109138. ** parameter pChanges is passed the list of columns being modified.
  109139. **
  109140. ** If there are no triggers that fire at the specified time for the specified
  109141. ** operation on pTab, this function is a no-op.
  109142. **
  109143. ** The reg argument is the address of the first in an array of registers
  109144. ** that contain the values substituted for the new.* and old.* references
  109145. ** in the trigger program. If N is the number of columns in table pTab
  109146. ** (a copy of pTab->nCol), then registers are populated as follows:
  109147. **
  109148. ** Register Contains
  109149. ** ------------------------------------------------------
  109150. ** reg+0 OLD.rowid
  109151. ** reg+1 OLD.* value of left-most column of pTab
  109152. ** ... ...
  109153. ** reg+N OLD.* value of right-most column of pTab
  109154. ** reg+N+1 NEW.rowid
  109155. ** reg+N+2 OLD.* value of left-most column of pTab
  109156. ** ... ...
  109157. ** reg+N+N+1 NEW.* value of right-most column of pTab
  109158. **
  109159. ** For ON DELETE triggers, the registers containing the NEW.* values will
  109160. ** never be accessed by the trigger program, so they are not allocated or
  109161. ** populated by the caller (there is no data to populate them with anyway).
  109162. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  109163. ** are never accessed, and so are not allocated by the caller. So, for an
  109164. ** ON INSERT trigger, the value passed to this function as parameter reg
  109165. ** is not a readable register, although registers (reg+N) through
  109166. ** (reg+N+N+1) are.
  109167. **
  109168. ** Parameter orconf is the default conflict resolution algorithm for the
  109169. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  109170. ** is the instruction that control should jump to if a trigger program
  109171. ** raises an IGNORE exception.
  109172. */
  109173. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  109174. Parse *pParse, /* Parse context */
  109175. Trigger *pTrigger, /* List of triggers on table pTab */
  109176. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  109177. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  109178. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  109179. Table *pTab, /* The table to code triggers from */
  109180. int reg, /* The first in an array of registers (see above) */
  109181. int orconf, /* ON CONFLICT policy */
  109182. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  109183. ){
  109184. Trigger *p; /* Used to iterate through pTrigger list */
  109185. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  109186. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  109187. assert( (op==TK_UPDATE)==(pChanges!=0) );
  109188. for(p=pTrigger; p; p=p->pNext){
  109189. /* Sanity checking: The schema for the trigger and for the table are
  109190. ** always defined. The trigger must be in the same schema as the table
  109191. ** or else it must be a TEMP trigger. */
  109192. assert( p->pSchema!=0 );
  109193. assert( p->pTabSchema!=0 );
  109194. assert( p->pSchema==p->pTabSchema
  109195. || p->pSchema==pParse->db->aDb[1].pSchema );
  109196. /* Determine whether we should code this trigger */
  109197. if( p->op==op
  109198. && p->tr_tm==tr_tm
  109199. && checkColumnOverlap(p->pColumns, pChanges)
  109200. ){
  109201. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  109202. }
  109203. }
  109204. }
  109205. /*
  109206. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  109207. ** This function returns a 32-bit bitmask indicating which columns of the
  109208. ** old.* or new.* tables actually are used by triggers. This information
  109209. ** may be used by the caller, for example, to avoid having to load the entire
  109210. ** old.* record into memory when executing an UPDATE or DELETE command.
  109211. **
  109212. ** Bit 0 of the returned mask is set if the left-most column of the
  109213. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  109214. ** the second leftmost column value is required, and so on. If there
  109215. ** are more than 32 columns in the table, and at least one of the columns
  109216. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  109217. **
  109218. ** It is not possible to determine if the old.rowid or new.rowid column is
  109219. ** accessed by triggers. The caller must always assume that it is.
  109220. **
  109221. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  109222. ** applies to the old.* table. If 1, the new.* table.
  109223. **
  109224. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  109225. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  109226. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  109227. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  109228. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  109229. */
  109230. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  109231. Parse *pParse, /* Parse context */
  109232. Trigger *pTrigger, /* List of triggers on table pTab */
  109233. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  109234. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  109235. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  109236. Table *pTab, /* The table to code triggers from */
  109237. int orconf /* Default ON CONFLICT policy for trigger steps */
  109238. ){
  109239. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  109240. u32 mask = 0;
  109241. Trigger *p;
  109242. assert( isNew==1 || isNew==0 );
  109243. for(p=pTrigger; p; p=p->pNext){
  109244. if( p->op==op && (tr_tm&p->tr_tm)
  109245. && checkColumnOverlap(p->pColumns,pChanges)
  109246. ){
  109247. TriggerPrg *pPrg;
  109248. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  109249. if( pPrg ){
  109250. mask |= pPrg->aColmask[isNew];
  109251. }
  109252. }
  109253. }
  109254. return mask;
  109255. }
  109256. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  109257. /************** End of trigger.c *********************************************/
  109258. /************** Begin file update.c ******************************************/
  109259. /*
  109260. ** 2001 September 15
  109261. **
  109262. ** The author disclaims copyright to this source code. In place of
  109263. ** a legal notice, here is a blessing:
  109264. **
  109265. ** May you do good and not evil.
  109266. ** May you find forgiveness for yourself and forgive others.
  109267. ** May you share freely, never taking more than you give.
  109268. **
  109269. *************************************************************************
  109270. ** This file contains C code routines that are called by the parser
  109271. ** to handle UPDATE statements.
  109272. */
  109273. /* #include "sqliteInt.h" */
  109274. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109275. /* Forward declaration */
  109276. static void updateVirtualTable(
  109277. Parse *pParse, /* The parsing context */
  109278. SrcList *pSrc, /* The virtual table to be modified */
  109279. Table *pTab, /* The virtual table */
  109280. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  109281. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  109282. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  109283. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  109284. int onError /* ON CONFLICT strategy */
  109285. );
  109286. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  109287. /*
  109288. ** The most recently coded instruction was an OP_Column to retrieve the
  109289. ** i-th column of table pTab. This routine sets the P4 parameter of the
  109290. ** OP_Column to the default value, if any.
  109291. **
  109292. ** The default value of a column is specified by a DEFAULT clause in the
  109293. ** column definition. This was either supplied by the user when the table
  109294. ** was created, or added later to the table definition by an ALTER TABLE
  109295. ** command. If the latter, then the row-records in the table btree on disk
  109296. ** may not contain a value for the column and the default value, taken
  109297. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  109298. ** If the former, then all row-records are guaranteed to include a value
  109299. ** for the column and the P4 value is not required.
  109300. **
  109301. ** Column definitions created by an ALTER TABLE command may only have
  109302. ** literal default values specified: a number, null or a string. (If a more
  109303. ** complicated default expression value was provided, it is evaluated
  109304. ** when the ALTER TABLE is executed and one of the literal values written
  109305. ** into the sqlite_master table.)
  109306. **
  109307. ** Therefore, the P4 parameter is only required if the default value for
  109308. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  109309. ** function is capable of transforming these types of expressions into
  109310. ** sqlite3_value objects.
  109311. **
  109312. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  109313. ** on register iReg. This is used when an equivalent integer value is
  109314. ** stored in place of an 8-byte floating point value in order to save
  109315. ** space.
  109316. */
  109317. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  109318. assert( pTab!=0 );
  109319. if( !pTab->pSelect ){
  109320. sqlite3_value *pValue = 0;
  109321. u8 enc = ENC(sqlite3VdbeDb(v));
  109322. Column *pCol = &pTab->aCol[i];
  109323. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  109324. assert( i<pTab->nCol );
  109325. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  109326. pCol->affinity, &pValue);
  109327. if( pValue ){
  109328. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  109329. }
  109330. #ifndef SQLITE_OMIT_FLOATING_POINT
  109331. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  109332. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  109333. }
  109334. #endif
  109335. }
  109336. }
  109337. /*
  109338. ** Process an UPDATE statement.
  109339. **
  109340. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  109341. ** \_______/ \________/ \______/ \________________/
  109342. * onError pTabList pChanges pWhere
  109343. */
  109344. SQLITE_PRIVATE void sqlite3Update(
  109345. Parse *pParse, /* The parser context */
  109346. SrcList *pTabList, /* The table in which we should change things */
  109347. ExprList *pChanges, /* Things to be changed */
  109348. Expr *pWhere, /* The WHERE clause. May be null */
  109349. int onError /* How to handle constraint errors */
  109350. ){
  109351. int i, j; /* Loop counters */
  109352. Table *pTab; /* The table to be updated */
  109353. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  109354. WhereInfo *pWInfo; /* Information about the WHERE clause */
  109355. Vdbe *v; /* The virtual database engine */
  109356. Index *pIdx; /* For looping over indices */
  109357. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  109358. int nIdx; /* Number of indices that need updating */
  109359. int iBaseCur; /* Base cursor number */
  109360. int iDataCur; /* Cursor for the canonical data btree */
  109361. int iIdxCur; /* Cursor for the first index */
  109362. sqlite3 *db; /* The database structure */
  109363. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  109364. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  109365. ** an expression for the i-th column of the table.
  109366. ** aXRef[i]==-1 if the i-th column is not changed. */
  109367. u8 *aToOpen; /* 1 for tables and indices to be opened */
  109368. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  109369. u8 chngRowid; /* Rowid changed in a normal table */
  109370. u8 chngKey; /* Either chngPk or chngRowid */
  109371. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  109372. AuthContext sContext; /* The authorization context */
  109373. NameContext sNC; /* The name-context to resolve expressions in */
  109374. int iDb; /* Database containing the table being updated */
  109375. int okOnePass; /* True for one-pass algorithm without the FIFO */
  109376. int hasFK; /* True if foreign key processing is required */
  109377. int labelBreak; /* Jump here to break out of UPDATE loop */
  109378. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  109379. #ifndef SQLITE_OMIT_TRIGGER
  109380. int isView; /* True when updating a view (INSTEAD OF trigger) */
  109381. Trigger *pTrigger; /* List of triggers on pTab, if required */
  109382. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  109383. #endif
  109384. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  109385. int iEph = 0; /* Ephemeral table holding all primary key values */
  109386. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  109387. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  109388. /* Register Allocations */
  109389. int regRowCount = 0; /* A count of rows changed */
  109390. int regOldRowid = 0; /* The old rowid */
  109391. int regNewRowid = 0; /* The new rowid */
  109392. int regNew = 0; /* Content of the NEW.* table in triggers */
  109393. int regOld = 0; /* Content of OLD.* table in triggers */
  109394. int regRowSet = 0; /* Rowset of rows to be updated */
  109395. int regKey = 0; /* composite PRIMARY KEY value */
  109396. memset(&sContext, 0, sizeof(sContext));
  109397. db = pParse->db;
  109398. if( pParse->nErr || db->mallocFailed ){
  109399. goto update_cleanup;
  109400. }
  109401. assert( pTabList->nSrc==1 );
  109402. /* Locate the table which we want to update.
  109403. */
  109404. pTab = sqlite3SrcListLookup(pParse, pTabList);
  109405. if( pTab==0 ) goto update_cleanup;
  109406. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  109407. /* Figure out if we have any triggers and if the table being
  109408. ** updated is a view.
  109409. */
  109410. #ifndef SQLITE_OMIT_TRIGGER
  109411. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  109412. isView = pTab->pSelect!=0;
  109413. assert( pTrigger || tmask==0 );
  109414. #else
  109415. # define pTrigger 0
  109416. # define isView 0
  109417. # define tmask 0
  109418. #endif
  109419. #ifdef SQLITE_OMIT_VIEW
  109420. # undef isView
  109421. # define isView 0
  109422. #endif
  109423. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  109424. goto update_cleanup;
  109425. }
  109426. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  109427. goto update_cleanup;
  109428. }
  109429. /* Allocate a cursors for the main database table and for all indices.
  109430. ** The index cursors might not be used, but if they are used they
  109431. ** need to occur right after the database cursor. So go ahead and
  109432. ** allocate enough space, just in case.
  109433. */
  109434. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  109435. iIdxCur = iDataCur+1;
  109436. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  109437. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  109438. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  109439. iDataCur = pParse->nTab;
  109440. pTabList->a[0].iCursor = iDataCur;
  109441. }
  109442. pParse->nTab++;
  109443. }
  109444. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  109445. ** Initialize aXRef[] and aToOpen[] to their default values.
  109446. */
  109447. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  109448. if( aXRef==0 ) goto update_cleanup;
  109449. aRegIdx = aXRef+pTab->nCol;
  109450. aToOpen = (u8*)(aRegIdx+nIdx);
  109451. memset(aToOpen, 1, nIdx+1);
  109452. aToOpen[nIdx+1] = 0;
  109453. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  109454. /* Initialize the name-context */
  109455. memset(&sNC, 0, sizeof(sNC));
  109456. sNC.pParse = pParse;
  109457. sNC.pSrcList = pTabList;
  109458. /* Resolve the column names in all the expressions of the
  109459. ** of the UPDATE statement. Also find the column index
  109460. ** for each column to be updated in the pChanges array. For each
  109461. ** column to be updated, make sure we have authorization to change
  109462. ** that column.
  109463. */
  109464. chngRowid = chngPk = 0;
  109465. for(i=0; i<pChanges->nExpr; i++){
  109466. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  109467. goto update_cleanup;
  109468. }
  109469. for(j=0; j<pTab->nCol; j++){
  109470. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  109471. if( j==pTab->iPKey ){
  109472. chngRowid = 1;
  109473. pRowidExpr = pChanges->a[i].pExpr;
  109474. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  109475. chngPk = 1;
  109476. }
  109477. aXRef[j] = i;
  109478. break;
  109479. }
  109480. }
  109481. if( j>=pTab->nCol ){
  109482. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  109483. j = -1;
  109484. chngRowid = 1;
  109485. pRowidExpr = pChanges->a[i].pExpr;
  109486. }else{
  109487. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  109488. pParse->checkSchema = 1;
  109489. goto update_cleanup;
  109490. }
  109491. }
  109492. #ifndef SQLITE_OMIT_AUTHORIZATION
  109493. {
  109494. int rc;
  109495. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  109496. j<0 ? "ROWID" : pTab->aCol[j].zName,
  109497. db->aDb[iDb].zName);
  109498. if( rc==SQLITE_DENY ){
  109499. goto update_cleanup;
  109500. }else if( rc==SQLITE_IGNORE ){
  109501. aXRef[j] = -1;
  109502. }
  109503. }
  109504. #endif
  109505. }
  109506. assert( (chngRowid & chngPk)==0 );
  109507. assert( chngRowid==0 || chngRowid==1 );
  109508. assert( chngPk==0 || chngPk==1 );
  109509. chngKey = chngRowid + chngPk;
  109510. /* The SET expressions are not actually used inside the WHERE loop.
  109511. ** So reset the colUsed mask. Unless this is a virtual table. In that
  109512. ** case, set all bits of the colUsed mask (to ensure that the virtual
  109513. ** table implementation makes all columns available).
  109514. */
  109515. pTabList->a[0].colUsed = IsVirtual(pTab) ? (Bitmask)-1 : 0;
  109516. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  109517. /* There is one entry in the aRegIdx[] array for each index on the table
  109518. ** being updated. Fill in aRegIdx[] with a register number that will hold
  109519. ** the key for accessing each index.
  109520. **
  109521. ** FIXME: Be smarter about omitting indexes that use expressions.
  109522. */
  109523. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  109524. int reg;
  109525. if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
  109526. reg = ++pParse->nMem;
  109527. }else{
  109528. reg = 0;
  109529. for(i=0; i<pIdx->nKeyCol; i++){
  109530. i16 iIdxCol = pIdx->aiColumn[i];
  109531. if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
  109532. reg = ++pParse->nMem;
  109533. break;
  109534. }
  109535. }
  109536. }
  109537. if( reg==0 ) aToOpen[j+1] = 0;
  109538. aRegIdx[j] = reg;
  109539. }
  109540. /* Begin generating code. */
  109541. v = sqlite3GetVdbe(pParse);
  109542. if( v==0 ) goto update_cleanup;
  109543. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  109544. sqlite3BeginWriteOperation(pParse, 1, iDb);
  109545. /* Allocate required registers. */
  109546. if( !IsVirtual(pTab) ){
  109547. regRowSet = ++pParse->nMem;
  109548. regOldRowid = regNewRowid = ++pParse->nMem;
  109549. if( chngPk || pTrigger || hasFK ){
  109550. regOld = pParse->nMem + 1;
  109551. pParse->nMem += pTab->nCol;
  109552. }
  109553. if( chngKey || pTrigger || hasFK ){
  109554. regNewRowid = ++pParse->nMem;
  109555. }
  109556. regNew = pParse->nMem + 1;
  109557. pParse->nMem += pTab->nCol;
  109558. }
  109559. /* Start the view context. */
  109560. if( isView ){
  109561. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  109562. }
  109563. /* If we are trying to update a view, realize that view into
  109564. ** an ephemeral table.
  109565. */
  109566. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  109567. if( isView ){
  109568. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  109569. }
  109570. #endif
  109571. /* Resolve the column names in all the expressions in the
  109572. ** WHERE clause.
  109573. */
  109574. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  109575. goto update_cleanup;
  109576. }
  109577. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109578. /* Virtual tables must be handled separately */
  109579. if( IsVirtual(pTab) ){
  109580. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  109581. pWhere, onError);
  109582. goto update_cleanup;
  109583. }
  109584. #endif
  109585. /* Begin the database scan
  109586. */
  109587. if( HasRowid(pTab) ){
  109588. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  109589. pWInfo = sqlite3WhereBegin(
  109590. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
  109591. );
  109592. if( pWInfo==0 ) goto update_cleanup;
  109593. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  109594. /* Remember the rowid of every item to be updated.
  109595. */
  109596. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  109597. if( !okOnePass ){
  109598. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  109599. }
  109600. /* End the database scan loop.
  109601. */
  109602. sqlite3WhereEnd(pWInfo);
  109603. }else{
  109604. int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
  109605. i16 nPk; /* Number of components of the PRIMARY KEY */
  109606. int addrOpen; /* Address of the OpenEphemeral instruction */
  109607. assert( pPk!=0 );
  109608. nPk = pPk->nKeyCol;
  109609. iPk = pParse->nMem+1;
  109610. pParse->nMem += nPk;
  109611. regKey = ++pParse->nMem;
  109612. iEph = pParse->nTab++;
  109613. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  109614. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  109615. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  109616. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  109617. WHERE_ONEPASS_DESIRED, iIdxCur);
  109618. if( pWInfo==0 ) goto update_cleanup;
  109619. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  109620. for(i=0; i<nPk; i++){
  109621. assert( pPk->aiColumn[i]>=0 );
  109622. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
  109623. iPk+i);
  109624. }
  109625. if( okOnePass ){
  109626. sqlite3VdbeChangeToNoop(v, addrOpen);
  109627. nKey = nPk;
  109628. regKey = iPk;
  109629. }else{
  109630. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  109631. sqlite3IndexAffinityStr(db, pPk), nPk);
  109632. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
  109633. }
  109634. sqlite3WhereEnd(pWInfo);
  109635. }
  109636. /* Initialize the count of updated rows
  109637. */
  109638. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  109639. regRowCount = ++pParse->nMem;
  109640. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  109641. }
  109642. labelBreak = sqlite3VdbeMakeLabel(v);
  109643. if( !isView ){
  109644. /*
  109645. ** Open every index that needs updating. Note that if any
  109646. ** index could potentially invoke a REPLACE conflict resolution
  109647. ** action, then we need to open all indices because we might need
  109648. ** to be deleting some records.
  109649. */
  109650. if( onError==OE_Replace ){
  109651. memset(aToOpen, 1, nIdx+1);
  109652. }else{
  109653. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  109654. if( pIdx->onError==OE_Replace ){
  109655. memset(aToOpen, 1, nIdx+1);
  109656. break;
  109657. }
  109658. }
  109659. }
  109660. if( okOnePass ){
  109661. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  109662. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  109663. }
  109664. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
  109665. 0, 0);
  109666. }
  109667. /* Top of the update loop */
  109668. if( okOnePass ){
  109669. if( aToOpen[iDataCur-iBaseCur] && !isView ){
  109670. assert( pPk );
  109671. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  109672. VdbeCoverageNeverTaken(v);
  109673. }
  109674. labelContinue = labelBreak;
  109675. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  109676. VdbeCoverageIf(v, pPk==0);
  109677. VdbeCoverageIf(v, pPk!=0);
  109678. }else if( pPk ){
  109679. labelContinue = sqlite3VdbeMakeLabel(v);
  109680. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  109681. addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
  109682. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  109683. VdbeCoverage(v);
  109684. }else{
  109685. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  109686. regOldRowid);
  109687. VdbeCoverage(v);
  109688. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  109689. VdbeCoverage(v);
  109690. }
  109691. /* If the record number will change, set register regNewRowid to
  109692. ** contain the new value. If the record number is not being modified,
  109693. ** then regNewRowid is the same register as regOldRowid, which is
  109694. ** already populated. */
  109695. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  109696. if( chngRowid ){
  109697. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  109698. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  109699. }
  109700. /* Compute the old pre-UPDATE content of the row being changed, if that
  109701. ** information is needed */
  109702. if( chngPk || hasFK || pTrigger ){
  109703. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  109704. oldmask |= sqlite3TriggerColmask(pParse,
  109705. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  109706. );
  109707. for(i=0; i<pTab->nCol; i++){
  109708. if( oldmask==0xffffffff
  109709. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  109710. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  109711. ){
  109712. testcase( oldmask!=0xffffffff && i==31 );
  109713. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  109714. }else{
  109715. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  109716. }
  109717. }
  109718. if( chngRowid==0 && pPk==0 ){
  109719. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  109720. }
  109721. }
  109722. /* Populate the array of registers beginning at regNew with the new
  109723. ** row data. This array is used to check constants, create the new
  109724. ** table and index records, and as the values for any new.* references
  109725. ** made by triggers.
  109726. **
  109727. ** If there are one or more BEFORE triggers, then do not populate the
  109728. ** registers associated with columns that are (a) not modified by
  109729. ** this UPDATE statement and (b) not accessed by new.* references. The
  109730. ** values for registers not modified by the UPDATE must be reloaded from
  109731. ** the database after the BEFORE triggers are fired anyway (as the trigger
  109732. ** may have modified them). So not loading those that are not going to
  109733. ** be used eliminates some redundant opcodes.
  109734. */
  109735. newmask = sqlite3TriggerColmask(
  109736. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  109737. );
  109738. for(i=0; i<pTab->nCol; i++){
  109739. if( i==pTab->iPKey ){
  109740. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  109741. }else{
  109742. j = aXRef[i];
  109743. if( j>=0 ){
  109744. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  109745. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  109746. /* This branch loads the value of a column that will not be changed
  109747. ** into a register. This is done if there are no BEFORE triggers, or
  109748. ** if there are one or more BEFORE triggers that use this value via
  109749. ** a new.* reference in a trigger program.
  109750. */
  109751. testcase( i==31 );
  109752. testcase( i==32 );
  109753. sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
  109754. }else{
  109755. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  109756. }
  109757. }
  109758. }
  109759. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  109760. ** verified. One could argue that this is wrong.
  109761. */
  109762. if( tmask&TRIGGER_BEFORE ){
  109763. sqlite3TableAffinity(v, pTab, regNew);
  109764. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  109765. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  109766. /* The row-trigger may have deleted the row being updated. In this
  109767. ** case, jump to the next row. No updates or AFTER triggers are
  109768. ** required. This behavior - what happens when the row being updated
  109769. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  109770. ** documentation.
  109771. */
  109772. if( pPk ){
  109773. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  109774. VdbeCoverage(v);
  109775. }else{
  109776. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  109777. VdbeCoverage(v);
  109778. }
  109779. /* If it did not delete it, the row-trigger may still have modified
  109780. ** some of the columns of the row being updated. Load the values for
  109781. ** all columns not modified by the update statement into their
  109782. ** registers in case this has happened.
  109783. */
  109784. for(i=0; i<pTab->nCol; i++){
  109785. if( aXRef[i]<0 && i!=pTab->iPKey ){
  109786. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  109787. }
  109788. }
  109789. }
  109790. if( !isView ){
  109791. int addr1 = 0; /* Address of jump instruction */
  109792. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  109793. /* Do constraint checks. */
  109794. assert( regOldRowid>0 );
  109795. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  109796. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
  109797. /* Do FK constraint checks. */
  109798. if( hasFK ){
  109799. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  109800. }
  109801. /* Delete the index entries associated with the current record. */
  109802. if( bReplace || chngKey ){
  109803. if( pPk ){
  109804. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  109805. }else{
  109806. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  109807. }
  109808. VdbeCoverageNeverTaken(v);
  109809. }
  109810. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  109811. /* If changing the record number, delete the old record. */
  109812. if( hasFK || chngKey || pPk!=0 ){
  109813. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  109814. }
  109815. if( bReplace || chngKey ){
  109816. sqlite3VdbeJumpHere(v, addr1);
  109817. }
  109818. if( hasFK ){
  109819. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  109820. }
  109821. /* Insert the new index entries and the new record. */
  109822. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  109823. regNewRowid, aRegIdx, 1, 0, 0);
  109824. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  109825. ** handle rows (possibly in other tables) that refer via a foreign key
  109826. ** to the row just updated. */
  109827. if( hasFK ){
  109828. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  109829. }
  109830. }
  109831. /* Increment the row counter
  109832. */
  109833. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  109834. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  109835. }
  109836. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  109837. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  109838. /* Repeat the above with the next record to be updated, until
  109839. ** all record selected by the WHERE clause have been updated.
  109840. */
  109841. if( okOnePass ){
  109842. /* Nothing to do at end-of-loop for a single-pass */
  109843. }else if( pPk ){
  109844. sqlite3VdbeResolveLabel(v, labelContinue);
  109845. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  109846. }else{
  109847. sqlite3VdbeGoto(v, labelContinue);
  109848. }
  109849. sqlite3VdbeResolveLabel(v, labelBreak);
  109850. /* Close all tables */
  109851. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  109852. assert( aRegIdx );
  109853. if( aToOpen[i+1] ){
  109854. sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
  109855. }
  109856. }
  109857. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
  109858. /* Update the sqlite_sequence table by storing the content of the
  109859. ** maximum rowid counter values recorded while inserting into
  109860. ** autoincrement tables.
  109861. */
  109862. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  109863. sqlite3AutoincrementEnd(pParse);
  109864. }
  109865. /*
  109866. ** Return the number of rows that were changed. If this routine is
  109867. ** generating code because of a call to sqlite3NestedParse(), do not
  109868. ** invoke the callback function.
  109869. */
  109870. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  109871. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  109872. sqlite3VdbeSetNumCols(v, 1);
  109873. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  109874. }
  109875. update_cleanup:
  109876. sqlite3AuthContextPop(&sContext);
  109877. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  109878. sqlite3SrcListDelete(db, pTabList);
  109879. sqlite3ExprListDelete(db, pChanges);
  109880. sqlite3ExprDelete(db, pWhere);
  109881. return;
  109882. }
  109883. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  109884. ** they may interfere with compilation of other functions in this file
  109885. ** (or in another file, if this file becomes part of the amalgamation). */
  109886. #ifdef isView
  109887. #undef isView
  109888. #endif
  109889. #ifdef pTrigger
  109890. #undef pTrigger
  109891. #endif
  109892. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109893. /*
  109894. ** Generate code for an UPDATE of a virtual table.
  109895. **
  109896. ** There are two possible strategies - the default and the special
  109897. ** "onepass" strategy. Onepass is only used if the virtual table
  109898. ** implementation indicates that pWhere may match at most one row.
  109899. **
  109900. ** The default strategy is to create an ephemeral table that contains
  109901. ** for each row to be changed:
  109902. **
  109903. ** (A) The original rowid of that row.
  109904. ** (B) The revised rowid for the row.
  109905. ** (C) The content of every column in the row.
  109906. **
  109907. ** Then loop through the contents of this ephemeral table executing a
  109908. ** VUpdate for each row. When finished, drop the ephemeral table.
  109909. **
  109910. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  109911. ** stores the same values (A, B and C above) in a register array and
  109912. ** makes a single invocation of VUpdate.
  109913. */
  109914. static void updateVirtualTable(
  109915. Parse *pParse, /* The parsing context */
  109916. SrcList *pSrc, /* The virtual table to be modified */
  109917. Table *pTab, /* The virtual table */
  109918. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  109919. Expr *pRowid, /* Expression used to recompute the rowid */
  109920. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  109921. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  109922. int onError /* ON CONFLICT strategy */
  109923. ){
  109924. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  109925. int ephemTab; /* Table holding the result of the SELECT */
  109926. int i; /* Loop counter */
  109927. sqlite3 *db = pParse->db; /* Database connection */
  109928. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  109929. WhereInfo *pWInfo;
  109930. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  109931. int regArg; /* First register in VUpdate arg array */
  109932. int regRec; /* Register in which to assemble record */
  109933. int regRowid; /* Register for ephem table rowid */
  109934. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  109935. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  109936. int bOnePass; /* True to use onepass strategy */
  109937. int addr; /* Address of OP_OpenEphemeral */
  109938. /* Allocate nArg registers to martial the arguments to VUpdate. Then
  109939. ** create and open the ephemeral table in which the records created from
  109940. ** these arguments will be temporarily stored. */
  109941. assert( v );
  109942. ephemTab = pParse->nTab++;
  109943. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  109944. regArg = pParse->nMem + 1;
  109945. pParse->nMem += nArg;
  109946. regRec = ++pParse->nMem;
  109947. regRowid = ++pParse->nMem;
  109948. /* Start scanning the virtual table */
  109949. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  109950. if( pWInfo==0 ) return;
  109951. /* Populate the argument registers. */
  109952. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  109953. if( pRowid ){
  109954. sqlite3ExprCode(pParse, pRowid, regArg+1);
  109955. }else{
  109956. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  109957. }
  109958. for(i=0; i<pTab->nCol; i++){
  109959. if( aXRef[i]>=0 ){
  109960. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  109961. }else{
  109962. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  109963. }
  109964. }
  109965. bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  109966. if( bOnePass ){
  109967. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  109968. ** above. Also, if this is a top-level parse (not a trigger), clear the
  109969. ** multi-write flag so that the VM does not open a statement journal */
  109970. sqlite3VdbeChangeToNoop(v, addr);
  109971. if( sqlite3IsToplevel(pParse) ){
  109972. pParse->isMultiWrite = 0;
  109973. }
  109974. }else{
  109975. /* Create a record from the argument register contents and insert it into
  109976. ** the ephemeral table. */
  109977. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  109978. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  109979. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  109980. }
  109981. if( bOnePass==0 ){
  109982. /* End the virtual table scan */
  109983. sqlite3WhereEnd(pWInfo);
  109984. /* Begin scannning through the ephemeral table. */
  109985. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  109986. /* Extract arguments from the current row of the ephemeral table and
  109987. ** invoke the VUpdate method. */
  109988. for(i=0; i<nArg; i++){
  109989. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  109990. }
  109991. }
  109992. sqlite3VtabMakeWritable(pParse, pTab);
  109993. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  109994. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  109995. sqlite3MayAbort(pParse);
  109996. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  109997. ** jump to here if the scan visited zero rows. */
  109998. if( bOnePass==0 ){
  109999. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  110000. sqlite3VdbeJumpHere(v, addr);
  110001. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  110002. }else{
  110003. sqlite3WhereEnd(pWInfo);
  110004. }
  110005. }
  110006. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  110007. /************** End of update.c **********************************************/
  110008. /************** Begin file vacuum.c ******************************************/
  110009. /*
  110010. ** 2003 April 6
  110011. **
  110012. ** The author disclaims copyright to this source code. In place of
  110013. ** a legal notice, here is a blessing:
  110014. **
  110015. ** May you do good and not evil.
  110016. ** May you find forgiveness for yourself and forgive others.
  110017. ** May you share freely, never taking more than you give.
  110018. **
  110019. *************************************************************************
  110020. ** This file contains code used to implement the VACUUM command.
  110021. **
  110022. ** Most of the code in this file may be omitted by defining the
  110023. ** SQLITE_OMIT_VACUUM macro.
  110024. */
  110025. /* #include "sqliteInt.h" */
  110026. /* #include "vdbeInt.h" */
  110027. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  110028. /*
  110029. ** Finalize a prepared statement. If there was an error, store the
  110030. ** text of the error message in *pzErrMsg. Return the result code.
  110031. */
  110032. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  110033. int rc;
  110034. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  110035. if( rc ){
  110036. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  110037. }
  110038. return rc;
  110039. }
  110040. /*
  110041. ** Execute zSql on database db. Return an error code.
  110042. */
  110043. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  110044. sqlite3_stmt *pStmt;
  110045. VVA_ONLY( int rc; )
  110046. if( !zSql ){
  110047. return SQLITE_NOMEM;
  110048. }
  110049. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  110050. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  110051. return sqlite3_errcode(db);
  110052. }
  110053. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  110054. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  110055. return vacuumFinalize(db, pStmt, pzErrMsg);
  110056. }
  110057. /*
  110058. ** Execute zSql on database db. The statement returns exactly
  110059. ** one column. Execute this as SQL on the same database.
  110060. */
  110061. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  110062. sqlite3_stmt *pStmt;
  110063. int rc;
  110064. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  110065. if( rc!=SQLITE_OK ) return rc;
  110066. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  110067. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  110068. if( rc!=SQLITE_OK ){
  110069. vacuumFinalize(db, pStmt, pzErrMsg);
  110070. return rc;
  110071. }
  110072. }
  110073. return vacuumFinalize(db, pStmt, pzErrMsg);
  110074. }
  110075. /*
  110076. ** The VACUUM command is used to clean up the database,
  110077. ** collapse free space, etc. It is modelled after the VACUUM command
  110078. ** in PostgreSQL. The VACUUM command works as follows:
  110079. **
  110080. ** (1) Create a new transient database file
  110081. ** (2) Copy all content from the database being vacuumed into
  110082. ** the new transient database file
  110083. ** (3) Copy content from the transient database back into the
  110084. ** original database.
  110085. **
  110086. ** The transient database requires temporary disk space approximately
  110087. ** equal to the size of the original database. The copy operation of
  110088. ** step (3) requires additional temporary disk space approximately equal
  110089. ** to the size of the original database for the rollback journal.
  110090. ** Hence, temporary disk space that is approximately 2x the size of the
  110091. ** original database is required. Every page of the database is written
  110092. ** approximately 3 times: Once for step (2) and twice for step (3).
  110093. ** Two writes per page are required in step (3) because the original
  110094. ** database content must be written into the rollback journal prior to
  110095. ** overwriting the database with the vacuumed content.
  110096. **
  110097. ** Only 1x temporary space and only 1x writes would be required if
  110098. ** the copy of step (3) were replaced by deleting the original database
  110099. ** and renaming the transient database as the original. But that will
  110100. ** not work if other processes are attached to the original database.
  110101. ** And a power loss in between deleting the original and renaming the
  110102. ** transient would cause the database file to appear to be deleted
  110103. ** following reboot.
  110104. */
  110105. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  110106. Vdbe *v = sqlite3GetVdbe(pParse);
  110107. if( v ){
  110108. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  110109. sqlite3VdbeUsesBtree(v, 0);
  110110. }
  110111. return;
  110112. }
  110113. /*
  110114. ** This routine implements the OP_Vacuum opcode of the VDBE.
  110115. */
  110116. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  110117. int rc = SQLITE_OK; /* Return code from service routines */
  110118. Btree *pMain; /* The database being vacuumed */
  110119. Btree *pTemp; /* The temporary database we vacuum into */
  110120. char *zSql = 0; /* SQL statements */
  110121. int saved_flags; /* Saved value of the db->flags */
  110122. int saved_nChange; /* Saved value of db->nChange */
  110123. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  110124. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  110125. Db *pDb = 0; /* Database to detach at end of vacuum */
  110126. int isMemDb; /* True if vacuuming a :memory: database */
  110127. int nRes; /* Bytes of reserved space at the end of each page */
  110128. int nDb; /* Number of attached databases */
  110129. if( !db->autoCommit ){
  110130. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  110131. return SQLITE_ERROR;
  110132. }
  110133. if( db->nVdbeActive>1 ){
  110134. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  110135. return SQLITE_ERROR;
  110136. }
  110137. /* Save the current value of the database flags so that it can be
  110138. ** restored before returning. Then set the writable-schema flag, and
  110139. ** disable CHECK and foreign key constraints. */
  110140. saved_flags = db->flags;
  110141. saved_nChange = db->nChange;
  110142. saved_nTotalChange = db->nTotalChange;
  110143. saved_xTrace = db->xTrace;
  110144. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  110145. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  110146. db->xTrace = 0;
  110147. pMain = db->aDb[0].pBt;
  110148. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  110149. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  110150. ** can be set to 'off' for this file, as it is not recovered if a crash
  110151. ** occurs anyway. The integrity of the database is maintained by a
  110152. ** (possibly synchronous) transaction opened on the main database before
  110153. ** sqlite3BtreeCopyFile() is called.
  110154. **
  110155. ** An optimisation would be to use a non-journaled pager.
  110156. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  110157. ** that actually made the VACUUM run slower. Very little journalling
  110158. ** actually occurs when doing a vacuum since the vacuum_db is initially
  110159. ** empty. Only the journal header is written. Apparently it takes more
  110160. ** time to parse and run the PRAGMA to turn journalling off than it does
  110161. ** to write the journal header file.
  110162. */
  110163. nDb = db->nDb;
  110164. if( sqlite3TempInMemory(db) ){
  110165. zSql = "ATTACH ':memory:' AS vacuum_db;";
  110166. }else{
  110167. zSql = "ATTACH '' AS vacuum_db;";
  110168. }
  110169. rc = execSql(db, pzErrMsg, zSql);
  110170. if( db->nDb>nDb ){
  110171. pDb = &db->aDb[db->nDb-1];
  110172. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  110173. }
  110174. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110175. pTemp = db->aDb[db->nDb-1].pBt;
  110176. /* The call to execSql() to attach the temp database has left the file
  110177. ** locked (as there was more than one active statement when the transaction
  110178. ** to read the schema was concluded. Unlock it here so that this doesn't
  110179. ** cause problems for the call to BtreeSetPageSize() below. */
  110180. sqlite3BtreeCommit(pTemp);
  110181. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  110182. /* A VACUUM cannot change the pagesize of an encrypted database. */
  110183. #ifdef SQLITE_HAS_CODEC
  110184. if( db->nextPagesize ){
  110185. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  110186. int nKey;
  110187. char *zKey;
  110188. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  110189. if( nKey ) db->nextPagesize = 0;
  110190. }
  110191. #endif
  110192. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  110193. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110194. /* Begin a transaction and take an exclusive lock on the main database
  110195. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  110196. ** to ensure that we do not try to change the page-size on a WAL database.
  110197. */
  110198. rc = execSql(db, pzErrMsg, "BEGIN;");
  110199. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110200. rc = sqlite3BtreeBeginTrans(pMain, 2);
  110201. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110202. /* Do not attempt to change the page size for a WAL database */
  110203. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  110204. ==PAGER_JOURNALMODE_WAL ){
  110205. db->nextPagesize = 0;
  110206. }
  110207. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  110208. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  110209. || NEVER(db->mallocFailed)
  110210. ){
  110211. rc = SQLITE_NOMEM;
  110212. goto end_of_vacuum;
  110213. }
  110214. #ifndef SQLITE_OMIT_AUTOVACUUM
  110215. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  110216. sqlite3BtreeGetAutoVacuum(pMain));
  110217. #endif
  110218. /* Query the schema of the main database. Create a mirror schema
  110219. ** in the temporary database.
  110220. */
  110221. rc = execExecSql(db, pzErrMsg,
  110222. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  110223. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  110224. " AND coalesce(rootpage,1)>0"
  110225. );
  110226. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110227. rc = execExecSql(db, pzErrMsg,
  110228. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  110229. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  110230. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110231. rc = execExecSql(db, pzErrMsg,
  110232. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  110233. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  110234. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110235. /* Loop through the tables in the main database. For each, do
  110236. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  110237. ** the contents to the temporary database.
  110238. */
  110239. assert( (db->flags & SQLITE_Vacuum)==0 );
  110240. db->flags |= SQLITE_Vacuum;
  110241. rc = execExecSql(db, pzErrMsg,
  110242. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  110243. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  110244. "FROM main.sqlite_master "
  110245. "WHERE type = 'table' AND name!='sqlite_sequence' "
  110246. " AND coalesce(rootpage,1)>0"
  110247. );
  110248. assert( (db->flags & SQLITE_Vacuum)!=0 );
  110249. db->flags &= ~SQLITE_Vacuum;
  110250. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110251. /* Copy over the sequence table
  110252. */
  110253. rc = execExecSql(db, pzErrMsg,
  110254. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  110255. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  110256. );
  110257. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110258. rc = execExecSql(db, pzErrMsg,
  110259. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  110260. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  110261. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  110262. );
  110263. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110264. /* Copy the triggers, views, and virtual tables from the main database
  110265. ** over to the temporary database. None of these objects has any
  110266. ** associated storage, so all we have to do is copy their entries
  110267. ** from the SQLITE_MASTER table.
  110268. */
  110269. rc = execSql(db, pzErrMsg,
  110270. "INSERT INTO vacuum_db.sqlite_master "
  110271. " SELECT type, name, tbl_name, rootpage, sql"
  110272. " FROM main.sqlite_master"
  110273. " WHERE type='view' OR type='trigger'"
  110274. " OR (type='table' AND rootpage=0)"
  110275. );
  110276. if( rc ) goto end_of_vacuum;
  110277. /* At this point, there is a write transaction open on both the
  110278. ** vacuum database and the main database. Assuming no error occurs,
  110279. ** both transactions are closed by this block - the main database
  110280. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  110281. ** call to sqlite3BtreeCommit().
  110282. */
  110283. {
  110284. u32 meta;
  110285. int i;
  110286. /* This array determines which meta meta values are preserved in the
  110287. ** vacuum. Even entries are the meta value number and odd entries
  110288. ** are an increment to apply to the meta value after the vacuum.
  110289. ** The increment is used to increase the schema cookie so that other
  110290. ** connections to the same database will know to reread the schema.
  110291. */
  110292. static const unsigned char aCopy[] = {
  110293. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  110294. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  110295. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  110296. BTREE_USER_VERSION, 0, /* Preserve the user version */
  110297. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  110298. };
  110299. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  110300. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  110301. /* Copy Btree meta values */
  110302. for(i=0; i<ArraySize(aCopy); i+=2){
  110303. /* GetMeta() and UpdateMeta() cannot fail in this context because
  110304. ** we already have page 1 loaded into cache and marked dirty. */
  110305. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  110306. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  110307. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  110308. }
  110309. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  110310. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110311. rc = sqlite3BtreeCommit(pTemp);
  110312. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  110313. #ifndef SQLITE_OMIT_AUTOVACUUM
  110314. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  110315. #endif
  110316. }
  110317. assert( rc==SQLITE_OK );
  110318. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  110319. end_of_vacuum:
  110320. /* Restore the original value of db->flags */
  110321. db->flags = saved_flags;
  110322. db->nChange = saved_nChange;
  110323. db->nTotalChange = saved_nTotalChange;
  110324. db->xTrace = saved_xTrace;
  110325. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  110326. /* Currently there is an SQL level transaction open on the vacuum
  110327. ** database. No locks are held on any other files (since the main file
  110328. ** was committed at the btree level). So it safe to end the transaction
  110329. ** by manually setting the autoCommit flag to true and detaching the
  110330. ** vacuum database. The vacuum_db journal file is deleted when the pager
  110331. ** is closed by the DETACH.
  110332. */
  110333. db->autoCommit = 1;
  110334. if( pDb ){
  110335. sqlite3BtreeClose(pDb->pBt);
  110336. pDb->pBt = 0;
  110337. pDb->pSchema = 0;
  110338. }
  110339. /* This both clears the schemas and reduces the size of the db->aDb[]
  110340. ** array. */
  110341. sqlite3ResetAllSchemasOfConnection(db);
  110342. return rc;
  110343. }
  110344. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  110345. /************** End of vacuum.c **********************************************/
  110346. /************** Begin file vtab.c ********************************************/
  110347. /*
  110348. ** 2006 June 10
  110349. **
  110350. ** The author disclaims copyright to this source code. In place of
  110351. ** a legal notice, here is a blessing:
  110352. **
  110353. ** May you do good and not evil.
  110354. ** May you find forgiveness for yourself and forgive others.
  110355. ** May you share freely, never taking more than you give.
  110356. **
  110357. *************************************************************************
  110358. ** This file contains code used to help implement virtual tables.
  110359. */
  110360. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110361. /* #include "sqliteInt.h" */
  110362. /*
  110363. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  110364. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  110365. ** this struct allocated on the stack. It is used by the implementation of
  110366. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  110367. ** are invoked only from within xCreate and xConnect methods.
  110368. */
  110369. struct VtabCtx {
  110370. VTable *pVTable; /* The virtual table being constructed */
  110371. Table *pTab; /* The Table object to which the virtual table belongs */
  110372. VtabCtx *pPrior; /* Parent context (if any) */
  110373. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  110374. };
  110375. /*
  110376. ** The actual function that does the work of creating a new module.
  110377. ** This function implements the sqlite3_create_module() and
  110378. ** sqlite3_create_module_v2() interfaces.
  110379. */
  110380. static int createModule(
  110381. sqlite3 *db, /* Database in which module is registered */
  110382. const char *zName, /* Name assigned to this module */
  110383. const sqlite3_module *pModule, /* The definition of the module */
  110384. void *pAux, /* Context pointer for xCreate/xConnect */
  110385. void (*xDestroy)(void *) /* Module destructor function */
  110386. ){
  110387. int rc = SQLITE_OK;
  110388. int nName;
  110389. sqlite3_mutex_enter(db->mutex);
  110390. nName = sqlite3Strlen30(zName);
  110391. if( sqlite3HashFind(&db->aModule, zName) ){
  110392. rc = SQLITE_MISUSE_BKPT;
  110393. }else{
  110394. Module *pMod;
  110395. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  110396. if( pMod ){
  110397. Module *pDel;
  110398. char *zCopy = (char *)(&pMod[1]);
  110399. memcpy(zCopy, zName, nName+1);
  110400. pMod->zName = zCopy;
  110401. pMod->pModule = pModule;
  110402. pMod->pAux = pAux;
  110403. pMod->xDestroy = xDestroy;
  110404. pMod->pEpoTab = 0;
  110405. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  110406. assert( pDel==0 || pDel==pMod );
  110407. if( pDel ){
  110408. db->mallocFailed = 1;
  110409. sqlite3DbFree(db, pDel);
  110410. }
  110411. }
  110412. }
  110413. rc = sqlite3ApiExit(db, rc);
  110414. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  110415. sqlite3_mutex_leave(db->mutex);
  110416. return rc;
  110417. }
  110418. /*
  110419. ** External API function used to create a new virtual-table module.
  110420. */
  110421. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  110422. sqlite3 *db, /* Database in which module is registered */
  110423. const char *zName, /* Name assigned to this module */
  110424. const sqlite3_module *pModule, /* The definition of the module */
  110425. void *pAux /* Context pointer for xCreate/xConnect */
  110426. ){
  110427. #ifdef SQLITE_ENABLE_API_ARMOR
  110428. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  110429. #endif
  110430. return createModule(db, zName, pModule, pAux, 0);
  110431. }
  110432. /*
  110433. ** External API function used to create a new virtual-table module.
  110434. */
  110435. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  110436. sqlite3 *db, /* Database in which module is registered */
  110437. const char *zName, /* Name assigned to this module */
  110438. const sqlite3_module *pModule, /* The definition of the module */
  110439. void *pAux, /* Context pointer for xCreate/xConnect */
  110440. void (*xDestroy)(void *) /* Module destructor function */
  110441. ){
  110442. #ifdef SQLITE_ENABLE_API_ARMOR
  110443. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  110444. #endif
  110445. return createModule(db, zName, pModule, pAux, xDestroy);
  110446. }
  110447. /*
  110448. ** Lock the virtual table so that it cannot be disconnected.
  110449. ** Locks nest. Every lock should have a corresponding unlock.
  110450. ** If an unlock is omitted, resources leaks will occur.
  110451. **
  110452. ** If a disconnect is attempted while a virtual table is locked,
  110453. ** the disconnect is deferred until all locks have been removed.
  110454. */
  110455. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  110456. pVTab->nRef++;
  110457. }
  110458. /*
  110459. ** pTab is a pointer to a Table structure representing a virtual-table.
  110460. ** Return a pointer to the VTable object used by connection db to access
  110461. ** this virtual-table, if one has been created, or NULL otherwise.
  110462. */
  110463. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  110464. VTable *pVtab;
  110465. assert( IsVirtual(pTab) );
  110466. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  110467. return pVtab;
  110468. }
  110469. /*
  110470. ** Decrement the ref-count on a virtual table object. When the ref-count
  110471. ** reaches zero, call the xDisconnect() method to delete the object.
  110472. */
  110473. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  110474. sqlite3 *db = pVTab->db;
  110475. assert( db );
  110476. assert( pVTab->nRef>0 );
  110477. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  110478. pVTab->nRef--;
  110479. if( pVTab->nRef==0 ){
  110480. sqlite3_vtab *p = pVTab->pVtab;
  110481. if( p ){
  110482. p->pModule->xDisconnect(p);
  110483. }
  110484. sqlite3DbFree(db, pVTab);
  110485. }
  110486. }
  110487. /*
  110488. ** Table p is a virtual table. This function moves all elements in the
  110489. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  110490. ** database connections to be disconnected at the next opportunity.
  110491. ** Except, if argument db is not NULL, then the entry associated with
  110492. ** connection db is left in the p->pVTable list.
  110493. */
  110494. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  110495. VTable *pRet = 0;
  110496. VTable *pVTable = p->pVTable;
  110497. p->pVTable = 0;
  110498. /* Assert that the mutex (if any) associated with the BtShared database
  110499. ** that contains table p is held by the caller. See header comments
  110500. ** above function sqlite3VtabUnlockList() for an explanation of why
  110501. ** this makes it safe to access the sqlite3.pDisconnect list of any
  110502. ** database connection that may have an entry in the p->pVTable list.
  110503. */
  110504. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  110505. while( pVTable ){
  110506. sqlite3 *db2 = pVTable->db;
  110507. VTable *pNext = pVTable->pNext;
  110508. assert( db2 );
  110509. if( db2==db ){
  110510. pRet = pVTable;
  110511. p->pVTable = pRet;
  110512. pRet->pNext = 0;
  110513. }else{
  110514. pVTable->pNext = db2->pDisconnect;
  110515. db2->pDisconnect = pVTable;
  110516. }
  110517. pVTable = pNext;
  110518. }
  110519. assert( !db || pRet );
  110520. return pRet;
  110521. }
  110522. /*
  110523. ** Table *p is a virtual table. This function removes the VTable object
  110524. ** for table *p associated with database connection db from the linked
  110525. ** list in p->pVTab. It also decrements the VTable ref count. This is
  110526. ** used when closing database connection db to free all of its VTable
  110527. ** objects without disturbing the rest of the Schema object (which may
  110528. ** be being used by other shared-cache connections).
  110529. */
  110530. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  110531. VTable **ppVTab;
  110532. assert( IsVirtual(p) );
  110533. assert( sqlite3BtreeHoldsAllMutexes(db) );
  110534. assert( sqlite3_mutex_held(db->mutex) );
  110535. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  110536. if( (*ppVTab)->db==db ){
  110537. VTable *pVTab = *ppVTab;
  110538. *ppVTab = pVTab->pNext;
  110539. sqlite3VtabUnlock(pVTab);
  110540. break;
  110541. }
  110542. }
  110543. }
  110544. /*
  110545. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  110546. **
  110547. ** This function may only be called when the mutexes associated with all
  110548. ** shared b-tree databases opened using connection db are held by the
  110549. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  110550. ** sqlite3.pDisconnect list is accessed only as follows:
  110551. **
  110552. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  110553. ** associated with the database handle itself must be held.
  110554. **
  110555. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  110556. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  110557. ** associated with the database the virtual table is stored in is held
  110558. ** or, if the virtual table is stored in a non-sharable database, then
  110559. ** the database handle mutex is held.
  110560. **
  110561. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  110562. ** by multiple threads. It is thread-safe.
  110563. */
  110564. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  110565. VTable *p = db->pDisconnect;
  110566. db->pDisconnect = 0;
  110567. assert( sqlite3BtreeHoldsAllMutexes(db) );
  110568. assert( sqlite3_mutex_held(db->mutex) );
  110569. if( p ){
  110570. sqlite3ExpirePreparedStatements(db);
  110571. do {
  110572. VTable *pNext = p->pNext;
  110573. sqlite3VtabUnlock(p);
  110574. p = pNext;
  110575. }while( p );
  110576. }
  110577. }
  110578. /*
  110579. ** Clear any and all virtual-table information from the Table record.
  110580. ** This routine is called, for example, just before deleting the Table
  110581. ** record.
  110582. **
  110583. ** Since it is a virtual-table, the Table structure contains a pointer
  110584. ** to the head of a linked list of VTable structures. Each VTable
  110585. ** structure is associated with a single sqlite3* user of the schema.
  110586. ** The reference count of the VTable structure associated with database
  110587. ** connection db is decremented immediately (which may lead to the
  110588. ** structure being xDisconnected and free). Any other VTable structures
  110589. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  110590. ** database connection.
  110591. */
  110592. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  110593. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  110594. if( p->azModuleArg ){
  110595. int i;
  110596. for(i=0; i<p->nModuleArg; i++){
  110597. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  110598. }
  110599. sqlite3DbFree(db, p->azModuleArg);
  110600. }
  110601. }
  110602. /*
  110603. ** Add a new module argument to pTable->azModuleArg[].
  110604. ** The string is not copied - the pointer is stored. The
  110605. ** string will be freed automatically when the table is
  110606. ** deleted.
  110607. */
  110608. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  110609. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  110610. char **azModuleArg;
  110611. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  110612. if( azModuleArg==0 ){
  110613. sqlite3DbFree(db, zArg);
  110614. }else{
  110615. int i = pTable->nModuleArg++;
  110616. azModuleArg[i] = zArg;
  110617. azModuleArg[i+1] = 0;
  110618. pTable->azModuleArg = azModuleArg;
  110619. }
  110620. }
  110621. /*
  110622. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  110623. ** statement. The module name has been parsed, but the optional list
  110624. ** of parameters that follow the module name are still pending.
  110625. */
  110626. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  110627. Parse *pParse, /* Parsing context */
  110628. Token *pName1, /* Name of new table, or database name */
  110629. Token *pName2, /* Name of new table or NULL */
  110630. Token *pModuleName, /* Name of the module for the virtual table */
  110631. int ifNotExists /* No error if the table already exists */
  110632. ){
  110633. int iDb; /* The database the table is being created in */
  110634. Table *pTable; /* The new virtual table */
  110635. sqlite3 *db; /* Database connection */
  110636. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  110637. pTable = pParse->pNewTable;
  110638. if( pTable==0 ) return;
  110639. assert( 0==pTable->pIndex );
  110640. db = pParse->db;
  110641. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  110642. assert( iDb>=0 );
  110643. pTable->tabFlags |= TF_Virtual;
  110644. pTable->nModuleArg = 0;
  110645. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  110646. addModuleArgument(db, pTable, 0);
  110647. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  110648. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  110649. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  110650. );
  110651. pParse->sNameToken.n = (int)(
  110652. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  110653. );
  110654. #ifndef SQLITE_OMIT_AUTHORIZATION
  110655. /* Creating a virtual table invokes the authorization callback twice.
  110656. ** The first invocation, to obtain permission to INSERT a row into the
  110657. ** sqlite_master table, has already been made by sqlite3StartTable().
  110658. ** The second call, to obtain permission to create the table, is made now.
  110659. */
  110660. if( pTable->azModuleArg ){
  110661. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  110662. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  110663. }
  110664. #endif
  110665. }
  110666. /*
  110667. ** This routine takes the module argument that has been accumulating
  110668. ** in pParse->zArg[] and appends it to the list of arguments on the
  110669. ** virtual table currently under construction in pParse->pTable.
  110670. */
  110671. static void addArgumentToVtab(Parse *pParse){
  110672. if( pParse->sArg.z && pParse->pNewTable ){
  110673. const char *z = (const char*)pParse->sArg.z;
  110674. int n = pParse->sArg.n;
  110675. sqlite3 *db = pParse->db;
  110676. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  110677. }
  110678. }
  110679. /*
  110680. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  110681. ** has been completely parsed.
  110682. */
  110683. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  110684. Table *pTab = pParse->pNewTable; /* The table being constructed */
  110685. sqlite3 *db = pParse->db; /* The database connection */
  110686. if( pTab==0 ) return;
  110687. addArgumentToVtab(pParse);
  110688. pParse->sArg.z = 0;
  110689. if( pTab->nModuleArg<1 ) return;
  110690. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  110691. ** first time (in other words if the virtual table is actually being
  110692. ** created now instead of just being read out of sqlite_master) then
  110693. ** do additional initialization work and store the statement text
  110694. ** in the sqlite_master table.
  110695. */
  110696. if( !db->init.busy ){
  110697. char *zStmt;
  110698. char *zWhere;
  110699. int iDb;
  110700. int iReg;
  110701. Vdbe *v;
  110702. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  110703. if( pEnd ){
  110704. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  110705. }
  110706. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  110707. /* A slot for the record has already been allocated in the
  110708. ** SQLITE_MASTER table. We just need to update that slot with all
  110709. ** the information we've collected.
  110710. **
  110711. ** The VM register number pParse->regRowid holds the rowid of an
  110712. ** entry in the sqlite_master table tht was created for this vtab
  110713. ** by sqlite3StartTable().
  110714. */
  110715. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  110716. sqlite3NestedParse(pParse,
  110717. "UPDATE %Q.%s "
  110718. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  110719. "WHERE rowid=#%d",
  110720. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  110721. pTab->zName,
  110722. pTab->zName,
  110723. zStmt,
  110724. pParse->regRowid
  110725. );
  110726. sqlite3DbFree(db, zStmt);
  110727. v = sqlite3GetVdbe(pParse);
  110728. sqlite3ChangeCookie(pParse, iDb);
  110729. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  110730. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  110731. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  110732. iReg = ++pParse->nMem;
  110733. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  110734. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  110735. }
  110736. /* If we are rereading the sqlite_master table create the in-memory
  110737. ** record of the table. The xConnect() method is not called until
  110738. ** the first time the virtual table is used in an SQL statement. This
  110739. ** allows a schema that contains virtual tables to be loaded before
  110740. ** the required virtual table implementations are registered. */
  110741. else {
  110742. Table *pOld;
  110743. Schema *pSchema = pTab->pSchema;
  110744. const char *zName = pTab->zName;
  110745. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  110746. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  110747. if( pOld ){
  110748. db->mallocFailed = 1;
  110749. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  110750. return;
  110751. }
  110752. pParse->pNewTable = 0;
  110753. }
  110754. }
  110755. /*
  110756. ** The parser calls this routine when it sees the first token
  110757. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  110758. */
  110759. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  110760. addArgumentToVtab(pParse);
  110761. pParse->sArg.z = 0;
  110762. pParse->sArg.n = 0;
  110763. }
  110764. /*
  110765. ** The parser calls this routine for each token after the first token
  110766. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  110767. */
  110768. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  110769. Token *pArg = &pParse->sArg;
  110770. if( pArg->z==0 ){
  110771. pArg->z = p->z;
  110772. pArg->n = p->n;
  110773. }else{
  110774. assert(pArg->z <= p->z);
  110775. pArg->n = (int)(&p->z[p->n] - pArg->z);
  110776. }
  110777. }
  110778. /*
  110779. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  110780. ** pointer to the function to invoke is passed as the fourth parameter
  110781. ** to this procedure.
  110782. */
  110783. static int vtabCallConstructor(
  110784. sqlite3 *db,
  110785. Table *pTab,
  110786. Module *pMod,
  110787. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  110788. char **pzErr
  110789. ){
  110790. VtabCtx sCtx;
  110791. VTable *pVTable;
  110792. int rc;
  110793. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  110794. int nArg = pTab->nModuleArg;
  110795. char *zErr = 0;
  110796. char *zModuleName;
  110797. int iDb;
  110798. VtabCtx *pCtx;
  110799. /* Check that the virtual-table is not already being initialized */
  110800. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  110801. if( pCtx->pTab==pTab ){
  110802. *pzErr = sqlite3MPrintf(db,
  110803. "vtable constructor called recursively: %s", pTab->zName
  110804. );
  110805. return SQLITE_LOCKED;
  110806. }
  110807. }
  110808. zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  110809. if( !zModuleName ){
  110810. return SQLITE_NOMEM;
  110811. }
  110812. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  110813. if( !pVTable ){
  110814. sqlite3DbFree(db, zModuleName);
  110815. return SQLITE_NOMEM;
  110816. }
  110817. pVTable->db = db;
  110818. pVTable->pMod = pMod;
  110819. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  110820. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  110821. /* Invoke the virtual table constructor */
  110822. assert( &db->pVtabCtx );
  110823. assert( xConstruct );
  110824. sCtx.pTab = pTab;
  110825. sCtx.pVTable = pVTable;
  110826. sCtx.pPrior = db->pVtabCtx;
  110827. sCtx.bDeclared = 0;
  110828. db->pVtabCtx = &sCtx;
  110829. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  110830. db->pVtabCtx = sCtx.pPrior;
  110831. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  110832. assert( sCtx.pTab==pTab );
  110833. if( SQLITE_OK!=rc ){
  110834. if( zErr==0 ){
  110835. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  110836. }else {
  110837. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  110838. sqlite3_free(zErr);
  110839. }
  110840. sqlite3DbFree(db, pVTable);
  110841. }else if( ALWAYS(pVTable->pVtab) ){
  110842. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  110843. ** the sqlite3_vtab object if successful. */
  110844. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  110845. pVTable->pVtab->pModule = pMod->pModule;
  110846. pVTable->nRef = 1;
  110847. if( sCtx.bDeclared==0 ){
  110848. const char *zFormat = "vtable constructor did not declare schema: %s";
  110849. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  110850. sqlite3VtabUnlock(pVTable);
  110851. rc = SQLITE_ERROR;
  110852. }else{
  110853. int iCol;
  110854. u8 oooHidden = 0;
  110855. /* If everything went according to plan, link the new VTable structure
  110856. ** into the linked list headed by pTab->pVTable. Then loop through the
  110857. ** columns of the table to see if any of them contain the token "hidden".
  110858. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  110859. ** the type string. */
  110860. pVTable->pNext = pTab->pVTable;
  110861. pTab->pVTable = pVTable;
  110862. for(iCol=0; iCol<pTab->nCol; iCol++){
  110863. char *zType = pTab->aCol[iCol].zType;
  110864. int nType;
  110865. int i = 0;
  110866. if( !zType ){
  110867. pTab->tabFlags |= oooHidden;
  110868. continue;
  110869. }
  110870. nType = sqlite3Strlen30(zType);
  110871. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  110872. for(i=0; i<nType; i++){
  110873. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  110874. && (zType[i+7]=='\0' || zType[i+7]==' ')
  110875. ){
  110876. i++;
  110877. break;
  110878. }
  110879. }
  110880. }
  110881. if( i<nType ){
  110882. int j;
  110883. int nDel = 6 + (zType[i+6] ? 1 : 0);
  110884. for(j=i; (j+nDel)<=nType; j++){
  110885. zType[j] = zType[j+nDel];
  110886. }
  110887. if( zType[i]=='\0' && i>0 ){
  110888. assert(zType[i-1]==' ');
  110889. zType[i-1] = '\0';
  110890. }
  110891. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  110892. oooHidden = TF_OOOHidden;
  110893. }else{
  110894. pTab->tabFlags |= oooHidden;
  110895. }
  110896. }
  110897. }
  110898. }
  110899. sqlite3DbFree(db, zModuleName);
  110900. return rc;
  110901. }
  110902. /*
  110903. ** This function is invoked by the parser to call the xConnect() method
  110904. ** of the virtual table pTab. If an error occurs, an error code is returned
  110905. ** and an error left in pParse.
  110906. **
  110907. ** This call is a no-op if table pTab is not a virtual table.
  110908. */
  110909. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  110910. sqlite3 *db = pParse->db;
  110911. const char *zMod;
  110912. Module *pMod;
  110913. int rc;
  110914. assert( pTab );
  110915. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  110916. return SQLITE_OK;
  110917. }
  110918. /* Locate the required virtual table module */
  110919. zMod = pTab->azModuleArg[0];
  110920. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  110921. if( !pMod ){
  110922. const char *zModule = pTab->azModuleArg[0];
  110923. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  110924. rc = SQLITE_ERROR;
  110925. }else{
  110926. char *zErr = 0;
  110927. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  110928. if( rc!=SQLITE_OK ){
  110929. sqlite3ErrorMsg(pParse, "%s", zErr);
  110930. }
  110931. sqlite3DbFree(db, zErr);
  110932. }
  110933. return rc;
  110934. }
  110935. /*
  110936. ** Grow the db->aVTrans[] array so that there is room for at least one
  110937. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  110938. */
  110939. static int growVTrans(sqlite3 *db){
  110940. const int ARRAY_INCR = 5;
  110941. /* Grow the sqlite3.aVTrans array if required */
  110942. if( (db->nVTrans%ARRAY_INCR)==0 ){
  110943. VTable **aVTrans;
  110944. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  110945. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  110946. if( !aVTrans ){
  110947. return SQLITE_NOMEM;
  110948. }
  110949. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  110950. db->aVTrans = aVTrans;
  110951. }
  110952. return SQLITE_OK;
  110953. }
  110954. /*
  110955. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  110956. ** have already been reserved using growVTrans().
  110957. */
  110958. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  110959. /* Add pVtab to the end of sqlite3.aVTrans */
  110960. db->aVTrans[db->nVTrans++] = pVTab;
  110961. sqlite3VtabLock(pVTab);
  110962. }
  110963. /*
  110964. ** This function is invoked by the vdbe to call the xCreate method
  110965. ** of the virtual table named zTab in database iDb.
  110966. **
  110967. ** If an error occurs, *pzErr is set to point an an English language
  110968. ** description of the error and an SQLITE_XXX error code is returned.
  110969. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  110970. */
  110971. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  110972. int rc = SQLITE_OK;
  110973. Table *pTab;
  110974. Module *pMod;
  110975. const char *zMod;
  110976. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  110977. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  110978. /* Locate the required virtual table module */
  110979. zMod = pTab->azModuleArg[0];
  110980. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  110981. /* If the module has been registered and includes a Create method,
  110982. ** invoke it now. If the module has not been registered, return an
  110983. ** error. Otherwise, do nothing.
  110984. */
  110985. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  110986. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  110987. rc = SQLITE_ERROR;
  110988. }else{
  110989. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  110990. }
  110991. /* Justification of ALWAYS(): The xConstructor method is required to
  110992. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  110993. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  110994. rc = growVTrans(db);
  110995. if( rc==SQLITE_OK ){
  110996. addToVTrans(db, sqlite3GetVTable(db, pTab));
  110997. }
  110998. }
  110999. return rc;
  111000. }
  111001. /*
  111002. ** This function is used to set the schema of a virtual table. It is only
  111003. ** valid to call this function from within the xCreate() or xConnect() of a
  111004. ** virtual table module.
  111005. */
  111006. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  111007. VtabCtx *pCtx;
  111008. Parse *pParse;
  111009. int rc = SQLITE_OK;
  111010. Table *pTab;
  111011. char *zErr = 0;
  111012. #ifdef SQLITE_ENABLE_API_ARMOR
  111013. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  111014. return SQLITE_MISUSE_BKPT;
  111015. }
  111016. #endif
  111017. sqlite3_mutex_enter(db->mutex);
  111018. pCtx = db->pVtabCtx;
  111019. if( !pCtx || pCtx->bDeclared ){
  111020. sqlite3Error(db, SQLITE_MISUSE);
  111021. sqlite3_mutex_leave(db->mutex);
  111022. return SQLITE_MISUSE_BKPT;
  111023. }
  111024. pTab = pCtx->pTab;
  111025. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  111026. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  111027. if( pParse==0 ){
  111028. rc = SQLITE_NOMEM;
  111029. }else{
  111030. pParse->declareVtab = 1;
  111031. pParse->db = db;
  111032. pParse->nQueryLoop = 1;
  111033. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  111034. && pParse->pNewTable
  111035. && !db->mallocFailed
  111036. && !pParse->pNewTable->pSelect
  111037. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  111038. ){
  111039. if( !pTab->aCol ){
  111040. pTab->aCol = pParse->pNewTable->aCol;
  111041. pTab->nCol = pParse->pNewTable->nCol;
  111042. pParse->pNewTable->nCol = 0;
  111043. pParse->pNewTable->aCol = 0;
  111044. }
  111045. pCtx->bDeclared = 1;
  111046. }else{
  111047. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  111048. sqlite3DbFree(db, zErr);
  111049. rc = SQLITE_ERROR;
  111050. }
  111051. pParse->declareVtab = 0;
  111052. if( pParse->pVdbe ){
  111053. sqlite3VdbeFinalize(pParse->pVdbe);
  111054. }
  111055. sqlite3DeleteTable(db, pParse->pNewTable);
  111056. sqlite3ParserReset(pParse);
  111057. sqlite3StackFree(db, pParse);
  111058. }
  111059. assert( (rc&0xff)==rc );
  111060. rc = sqlite3ApiExit(db, rc);
  111061. sqlite3_mutex_leave(db->mutex);
  111062. return rc;
  111063. }
  111064. /*
  111065. ** This function is invoked by the vdbe to call the xDestroy method
  111066. ** of the virtual table named zTab in database iDb. This occurs
  111067. ** when a DROP TABLE is mentioned.
  111068. **
  111069. ** This call is a no-op if zTab is not a virtual table.
  111070. */
  111071. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  111072. int rc = SQLITE_OK;
  111073. Table *pTab;
  111074. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  111075. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  111076. VTable *p;
  111077. int (*xDestroy)(sqlite3_vtab *);
  111078. for(p=pTab->pVTable; p; p=p->pNext){
  111079. assert( p->pVtab );
  111080. if( p->pVtab->nRef>0 ){
  111081. return SQLITE_LOCKED;
  111082. }
  111083. }
  111084. p = vtabDisconnectAll(db, pTab);
  111085. xDestroy = p->pMod->pModule->xDestroy;
  111086. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  111087. rc = xDestroy(p->pVtab);
  111088. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  111089. if( rc==SQLITE_OK ){
  111090. assert( pTab->pVTable==p && p->pNext==0 );
  111091. p->pVtab = 0;
  111092. pTab->pVTable = 0;
  111093. sqlite3VtabUnlock(p);
  111094. }
  111095. }
  111096. return rc;
  111097. }
  111098. /*
  111099. ** This function invokes either the xRollback or xCommit method
  111100. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  111101. ** called is identified by the second argument, "offset", which is
  111102. ** the offset of the method to call in the sqlite3_module structure.
  111103. **
  111104. ** The array is cleared after invoking the callbacks.
  111105. */
  111106. static void callFinaliser(sqlite3 *db, int offset){
  111107. int i;
  111108. if( db->aVTrans ){
  111109. VTable **aVTrans = db->aVTrans;
  111110. db->aVTrans = 0;
  111111. for(i=0; i<db->nVTrans; i++){
  111112. VTable *pVTab = aVTrans[i];
  111113. sqlite3_vtab *p = pVTab->pVtab;
  111114. if( p ){
  111115. int (*x)(sqlite3_vtab *);
  111116. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  111117. if( x ) x(p);
  111118. }
  111119. pVTab->iSavepoint = 0;
  111120. sqlite3VtabUnlock(pVTab);
  111121. }
  111122. sqlite3DbFree(db, aVTrans);
  111123. db->nVTrans = 0;
  111124. }
  111125. }
  111126. /*
  111127. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  111128. ** array. Return the error code for the first error that occurs, or
  111129. ** SQLITE_OK if all xSync operations are successful.
  111130. **
  111131. ** If an error message is available, leave it in p->zErrMsg.
  111132. */
  111133. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  111134. int i;
  111135. int rc = SQLITE_OK;
  111136. VTable **aVTrans = db->aVTrans;
  111137. db->aVTrans = 0;
  111138. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  111139. int (*x)(sqlite3_vtab *);
  111140. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  111141. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  111142. rc = x(pVtab);
  111143. sqlite3VtabImportErrmsg(p, pVtab);
  111144. }
  111145. }
  111146. db->aVTrans = aVTrans;
  111147. return rc;
  111148. }
  111149. /*
  111150. ** Invoke the xRollback method of all virtual tables in the
  111151. ** sqlite3.aVTrans array. Then clear the array itself.
  111152. */
  111153. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  111154. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  111155. return SQLITE_OK;
  111156. }
  111157. /*
  111158. ** Invoke the xCommit method of all virtual tables in the
  111159. ** sqlite3.aVTrans array. Then clear the array itself.
  111160. */
  111161. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  111162. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  111163. return SQLITE_OK;
  111164. }
  111165. /*
  111166. ** If the virtual table pVtab supports the transaction interface
  111167. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  111168. ** not currently open, invoke the xBegin method now.
  111169. **
  111170. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  111171. ** in the sqlite3.aVTrans array.
  111172. */
  111173. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  111174. int rc = SQLITE_OK;
  111175. const sqlite3_module *pModule;
  111176. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  111177. ** than zero, then this function is being called from within a
  111178. ** virtual module xSync() callback. It is illegal to write to
  111179. ** virtual module tables in this case, so return SQLITE_LOCKED.
  111180. */
  111181. if( sqlite3VtabInSync(db) ){
  111182. return SQLITE_LOCKED;
  111183. }
  111184. if( !pVTab ){
  111185. return SQLITE_OK;
  111186. }
  111187. pModule = pVTab->pVtab->pModule;
  111188. if( pModule->xBegin ){
  111189. int i;
  111190. /* If pVtab is already in the aVTrans array, return early */
  111191. for(i=0; i<db->nVTrans; i++){
  111192. if( db->aVTrans[i]==pVTab ){
  111193. return SQLITE_OK;
  111194. }
  111195. }
  111196. /* Invoke the xBegin method. If successful, add the vtab to the
  111197. ** sqlite3.aVTrans[] array. */
  111198. rc = growVTrans(db);
  111199. if( rc==SQLITE_OK ){
  111200. rc = pModule->xBegin(pVTab->pVtab);
  111201. if( rc==SQLITE_OK ){
  111202. int iSvpt = db->nStatement + db->nSavepoint;
  111203. addToVTrans(db, pVTab);
  111204. if( iSvpt ) rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, iSvpt-1);
  111205. }
  111206. }
  111207. }
  111208. return rc;
  111209. }
  111210. /*
  111211. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  111212. ** virtual tables that currently have an open transaction. Pass iSavepoint
  111213. ** as the second argument to the virtual table method invoked.
  111214. **
  111215. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  111216. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  111217. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  111218. ** an open transaction is invoked.
  111219. **
  111220. ** If any virtual table method returns an error code other than SQLITE_OK,
  111221. ** processing is abandoned and the error returned to the caller of this
  111222. ** function immediately. If all calls to virtual table methods are successful,
  111223. ** SQLITE_OK is returned.
  111224. */
  111225. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  111226. int rc = SQLITE_OK;
  111227. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  111228. assert( iSavepoint>=-1 );
  111229. if( db->aVTrans ){
  111230. int i;
  111231. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  111232. VTable *pVTab = db->aVTrans[i];
  111233. const sqlite3_module *pMod = pVTab->pMod->pModule;
  111234. if( pVTab->pVtab && pMod->iVersion>=2 ){
  111235. int (*xMethod)(sqlite3_vtab *, int);
  111236. switch( op ){
  111237. case SAVEPOINT_BEGIN:
  111238. xMethod = pMod->xSavepoint;
  111239. pVTab->iSavepoint = iSavepoint+1;
  111240. break;
  111241. case SAVEPOINT_ROLLBACK:
  111242. xMethod = pMod->xRollbackTo;
  111243. break;
  111244. default:
  111245. xMethod = pMod->xRelease;
  111246. break;
  111247. }
  111248. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  111249. rc = xMethod(pVTab->pVtab, iSavepoint);
  111250. }
  111251. }
  111252. }
  111253. }
  111254. return rc;
  111255. }
  111256. /*
  111257. ** The first parameter (pDef) is a function implementation. The
  111258. ** second parameter (pExpr) is the first argument to this function.
  111259. ** If pExpr is a column in a virtual table, then let the virtual
  111260. ** table implementation have an opportunity to overload the function.
  111261. **
  111262. ** This routine is used to allow virtual table implementations to
  111263. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  111264. **
  111265. ** Return either the pDef argument (indicating no change) or a
  111266. ** new FuncDef structure that is marked as ephemeral using the
  111267. ** SQLITE_FUNC_EPHEM flag.
  111268. */
  111269. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  111270. sqlite3 *db, /* Database connection for reporting malloc problems */
  111271. FuncDef *pDef, /* Function to possibly overload */
  111272. int nArg, /* Number of arguments to the function */
  111273. Expr *pExpr /* First argument to the function */
  111274. ){
  111275. Table *pTab;
  111276. sqlite3_vtab *pVtab;
  111277. sqlite3_module *pMod;
  111278. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  111279. void *pArg = 0;
  111280. FuncDef *pNew;
  111281. int rc = 0;
  111282. char *zLowerName;
  111283. unsigned char *z;
  111284. /* Check to see the left operand is a column in a virtual table */
  111285. if( NEVER(pExpr==0) ) return pDef;
  111286. if( pExpr->op!=TK_COLUMN ) return pDef;
  111287. pTab = pExpr->pTab;
  111288. if( NEVER(pTab==0) ) return pDef;
  111289. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  111290. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  111291. assert( pVtab!=0 );
  111292. assert( pVtab->pModule!=0 );
  111293. pMod = (sqlite3_module *)pVtab->pModule;
  111294. if( pMod->xFindFunction==0 ) return pDef;
  111295. /* Call the xFindFunction method on the virtual table implementation
  111296. ** to see if the implementation wants to overload this function
  111297. */
  111298. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  111299. if( zLowerName ){
  111300. for(z=(unsigned char*)zLowerName; *z; z++){
  111301. *z = sqlite3UpperToLower[*z];
  111302. }
  111303. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  111304. sqlite3DbFree(db, zLowerName);
  111305. }
  111306. if( rc==0 ){
  111307. return pDef;
  111308. }
  111309. /* Create a new ephemeral function definition for the overloaded
  111310. ** function */
  111311. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  111312. + sqlite3Strlen30(pDef->zName) + 1);
  111313. if( pNew==0 ){
  111314. return pDef;
  111315. }
  111316. *pNew = *pDef;
  111317. pNew->zName = (char *)&pNew[1];
  111318. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  111319. pNew->xFunc = xFunc;
  111320. pNew->pUserData = pArg;
  111321. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  111322. return pNew;
  111323. }
  111324. /*
  111325. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  111326. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  111327. ** array if it is missing. If pTab is already in the array, this routine
  111328. ** is a no-op.
  111329. */
  111330. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  111331. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  111332. int i, n;
  111333. Table **apVtabLock;
  111334. assert( IsVirtual(pTab) );
  111335. for(i=0; i<pToplevel->nVtabLock; i++){
  111336. if( pTab==pToplevel->apVtabLock[i] ) return;
  111337. }
  111338. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  111339. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  111340. if( apVtabLock ){
  111341. pToplevel->apVtabLock = apVtabLock;
  111342. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  111343. }else{
  111344. pToplevel->db->mallocFailed = 1;
  111345. }
  111346. }
  111347. /*
  111348. ** Check to see if virtual tale module pMod can be have an eponymous
  111349. ** virtual table instance. If it can, create one if one does not already
  111350. ** exist. Return non-zero if the eponymous virtual table instance exists
  111351. ** when this routine returns, and return zero if it does not exist.
  111352. **
  111353. ** An eponymous virtual table instance is one that is named after its
  111354. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  111355. ** statement in order to come into existance. Eponymous virtual table
  111356. ** instances always exist. They cannot be DROP-ed.
  111357. **
  111358. ** Any virtual table module for which xConnect and xCreate are the same
  111359. ** method can have an eponymous virtual table instance.
  111360. */
  111361. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  111362. const sqlite3_module *pModule = pMod->pModule;
  111363. Table *pTab;
  111364. char *zErr = 0;
  111365. int nName;
  111366. int rc;
  111367. sqlite3 *db = pParse->db;
  111368. if( pMod->pEpoTab ) return 1;
  111369. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  111370. nName = sqlite3Strlen30(pMod->zName) + 1;
  111371. pTab = sqlite3DbMallocZero(db, sizeof(Table) + nName);
  111372. if( pTab==0 ) return 0;
  111373. pMod->pEpoTab = pTab;
  111374. pTab->zName = (char*)&pTab[1];
  111375. memcpy(pTab->zName, pMod->zName, nName);
  111376. pTab->nRef = 1;
  111377. pTab->pSchema = db->aDb[0].pSchema;
  111378. pTab->tabFlags |= TF_Virtual;
  111379. pTab->nModuleArg = 0;
  111380. pTab->iPKey = -1;
  111381. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  111382. addModuleArgument(db, pTab, 0);
  111383. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  111384. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  111385. if( rc ){
  111386. sqlite3ErrorMsg(pParse, "%s", zErr);
  111387. sqlite3DbFree(db, zErr);
  111388. sqlite3VtabEponymousTableClear(db, pMod);
  111389. return 0;
  111390. }
  111391. return 1;
  111392. }
  111393. /*
  111394. ** Erase the eponymous virtual table instance associated with
  111395. ** virtual table module pMod, if it exists.
  111396. */
  111397. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  111398. Table *pTab = pMod->pEpoTab;
  111399. if( pTab!=0 ){
  111400. sqlite3DeleteColumnNames(db, pTab);
  111401. sqlite3VtabClear(db, pTab);
  111402. sqlite3DbFree(db, pTab);
  111403. pMod->pEpoTab = 0;
  111404. }
  111405. }
  111406. /*
  111407. ** Return the ON CONFLICT resolution mode in effect for the virtual
  111408. ** table update operation currently in progress.
  111409. **
  111410. ** The results of this routine are undefined unless it is called from
  111411. ** within an xUpdate method.
  111412. */
  111413. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
  111414. static const unsigned char aMap[] = {
  111415. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  111416. };
  111417. #ifdef SQLITE_ENABLE_API_ARMOR
  111418. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  111419. #endif
  111420. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  111421. assert( OE_Ignore==4 && OE_Replace==5 );
  111422. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  111423. return (int)aMap[db->vtabOnConflict-1];
  111424. }
  111425. /*
  111426. ** Call from within the xCreate() or xConnect() methods to provide
  111427. ** the SQLite core with additional information about the behavior
  111428. ** of the virtual table being implemented.
  111429. */
  111430. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
  111431. va_list ap;
  111432. int rc = SQLITE_OK;
  111433. #ifdef SQLITE_ENABLE_API_ARMOR
  111434. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  111435. #endif
  111436. sqlite3_mutex_enter(db->mutex);
  111437. va_start(ap, op);
  111438. switch( op ){
  111439. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  111440. VtabCtx *p = db->pVtabCtx;
  111441. if( !p ){
  111442. rc = SQLITE_MISUSE_BKPT;
  111443. }else{
  111444. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  111445. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  111446. }
  111447. break;
  111448. }
  111449. default:
  111450. rc = SQLITE_MISUSE_BKPT;
  111451. break;
  111452. }
  111453. va_end(ap);
  111454. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  111455. sqlite3_mutex_leave(db->mutex);
  111456. return rc;
  111457. }
  111458. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  111459. /************** End of vtab.c ************************************************/
  111460. /************** Begin file wherecode.c ***************************************/
  111461. /*
  111462. ** 2015-06-06
  111463. **
  111464. ** The author disclaims copyright to this source code. In place of
  111465. ** a legal notice, here is a blessing:
  111466. **
  111467. ** May you do good and not evil.
  111468. ** May you find forgiveness for yourself and forgive others.
  111469. ** May you share freely, never taking more than you give.
  111470. **
  111471. *************************************************************************
  111472. ** This module contains C code that generates VDBE code used to process
  111473. ** the WHERE clause of SQL statements.
  111474. **
  111475. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  111476. ** size of where.c and make it easier to edit. This file contains the routines
  111477. ** that actually generate the bulk of the WHERE loop code. The original where.c
  111478. ** file retains the code that does query planning and analysis.
  111479. */
  111480. /* #include "sqliteInt.h" */
  111481. /************** Include whereInt.h in the middle of wherecode.c **************/
  111482. /************** Begin file whereInt.h ****************************************/
  111483. /*
  111484. ** 2013-11-12
  111485. **
  111486. ** The author disclaims copyright to this source code. In place of
  111487. ** a legal notice, here is a blessing:
  111488. **
  111489. ** May you do good and not evil.
  111490. ** May you find forgiveness for yourself and forgive others.
  111491. ** May you share freely, never taking more than you give.
  111492. **
  111493. *************************************************************************
  111494. **
  111495. ** This file contains structure and macro definitions for the query
  111496. ** planner logic in "where.c". These definitions are broken out into
  111497. ** a separate source file for easier editing.
  111498. */
  111499. /*
  111500. ** Trace output macros
  111501. */
  111502. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  111503. /***/ int sqlite3WhereTrace;
  111504. #endif
  111505. #if defined(SQLITE_DEBUG) \
  111506. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  111507. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  111508. # define WHERETRACE_ENABLED 1
  111509. #else
  111510. # define WHERETRACE(K,X)
  111511. #endif
  111512. /* Forward references
  111513. */
  111514. typedef struct WhereClause WhereClause;
  111515. typedef struct WhereMaskSet WhereMaskSet;
  111516. typedef struct WhereOrInfo WhereOrInfo;
  111517. typedef struct WhereAndInfo WhereAndInfo;
  111518. typedef struct WhereLevel WhereLevel;
  111519. typedef struct WhereLoop WhereLoop;
  111520. typedef struct WherePath WherePath;
  111521. typedef struct WhereTerm WhereTerm;
  111522. typedef struct WhereLoopBuilder WhereLoopBuilder;
  111523. typedef struct WhereScan WhereScan;
  111524. typedef struct WhereOrCost WhereOrCost;
  111525. typedef struct WhereOrSet WhereOrSet;
  111526. /*
  111527. ** This object contains information needed to implement a single nested
  111528. ** loop in WHERE clause.
  111529. **
  111530. ** Contrast this object with WhereLoop. This object describes the
  111531. ** implementation of the loop. WhereLoop describes the algorithm.
  111532. ** This object contains a pointer to the WhereLoop algorithm as one of
  111533. ** its elements.
  111534. **
  111535. ** The WhereInfo object contains a single instance of this object for
  111536. ** each term in the FROM clause (which is to say, for each of the
  111537. ** nested loops as implemented). The order of WhereLevel objects determines
  111538. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  111539. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  111540. */
  111541. struct WhereLevel {
  111542. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  111543. int iTabCur; /* The VDBE cursor used to access the table */
  111544. int iIdxCur; /* The VDBE cursor used to access pIdx */
  111545. int addrBrk; /* Jump here to break out of the loop */
  111546. int addrNxt; /* Jump here to start the next IN combination */
  111547. int addrSkip; /* Jump here for next iteration of skip-scan */
  111548. int addrCont; /* Jump here to continue with the next loop cycle */
  111549. int addrFirst; /* First instruction of interior of the loop */
  111550. int addrBody; /* Beginning of the body of this loop */
  111551. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  111552. int iLikeRepCntr; /* LIKE range processing counter register */
  111553. int addrLikeRep; /* LIKE range processing address */
  111554. #endif
  111555. u8 iFrom; /* Which entry in the FROM clause */
  111556. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  111557. int p1, p2; /* Operands of the opcode used to ends the loop */
  111558. union { /* Information that depends on pWLoop->wsFlags */
  111559. struct {
  111560. int nIn; /* Number of entries in aInLoop[] */
  111561. struct InLoop {
  111562. int iCur; /* The VDBE cursor used by this IN operator */
  111563. int addrInTop; /* Top of the IN loop */
  111564. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  111565. } *aInLoop; /* Information about each nested IN operator */
  111566. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  111567. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  111568. } u;
  111569. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  111570. Bitmask notReady; /* FROM entries not usable at this level */
  111571. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  111572. int addrVisit; /* Address at which row is visited */
  111573. #endif
  111574. };
  111575. /*
  111576. ** Each instance of this object represents an algorithm for evaluating one
  111577. ** term of a join. Every term of the FROM clause will have at least
  111578. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  111579. ** prevent a query solution - which is an error) and many terms of the
  111580. ** FROM clause will have multiple WhereLoop objects, each describing a
  111581. ** potential way of implementing that FROM-clause term, together with
  111582. ** dependencies and cost estimates for using the chosen algorithm.
  111583. **
  111584. ** Query planning consists of building up a collection of these WhereLoop
  111585. ** objects, then computing a particular sequence of WhereLoop objects, with
  111586. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  111587. ** and that minimize the overall cost.
  111588. */
  111589. struct WhereLoop {
  111590. Bitmask prereq; /* Bitmask of other loops that must run first */
  111591. Bitmask maskSelf; /* Bitmask identifying table iTab */
  111592. #ifdef SQLITE_DEBUG
  111593. char cId; /* Symbolic ID of this loop for debugging use */
  111594. #endif
  111595. u8 iTab; /* Position in FROM clause of table for this loop */
  111596. u8 iSortIdx; /* Sorting index number. 0==None */
  111597. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  111598. LogEst rRun; /* Cost of running each loop */
  111599. LogEst nOut; /* Estimated number of output rows */
  111600. union {
  111601. struct { /* Information for internal btree tables */
  111602. u16 nEq; /* Number of equality constraints */
  111603. Index *pIndex; /* Index used, or NULL */
  111604. } btree;
  111605. struct { /* Information for virtual tables */
  111606. int idxNum; /* Index number */
  111607. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  111608. i8 isOrdered; /* True if satisfies ORDER BY */
  111609. u16 omitMask; /* Terms that may be omitted */
  111610. char *idxStr; /* Index identifier string */
  111611. } vtab;
  111612. } u;
  111613. u32 wsFlags; /* WHERE_* flags describing the plan */
  111614. u16 nLTerm; /* Number of entries in aLTerm[] */
  111615. u16 nSkip; /* Number of NULL aLTerm[] entries */
  111616. /**** whereLoopXfer() copies fields above ***********************/
  111617. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  111618. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  111619. WhereTerm **aLTerm; /* WhereTerms used */
  111620. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  111621. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  111622. };
  111623. /* This object holds the prerequisites and the cost of running a
  111624. ** subquery on one operand of an OR operator in the WHERE clause.
  111625. ** See WhereOrSet for additional information
  111626. */
  111627. struct WhereOrCost {
  111628. Bitmask prereq; /* Prerequisites */
  111629. LogEst rRun; /* Cost of running this subquery */
  111630. LogEst nOut; /* Number of outputs for this subquery */
  111631. };
  111632. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  111633. ** correspond to the subquery(s) of OR-clause processing. Only the
  111634. ** best N_OR_COST elements are retained.
  111635. */
  111636. #define N_OR_COST 3
  111637. struct WhereOrSet {
  111638. u16 n; /* Number of valid a[] entries */
  111639. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  111640. };
  111641. /*
  111642. ** Each instance of this object holds a sequence of WhereLoop objects
  111643. ** that implement some or all of a query plan.
  111644. **
  111645. ** Think of each WhereLoop object as a node in a graph with arcs
  111646. ** showing dependencies and costs for travelling between nodes. (That is
  111647. ** not a completely accurate description because WhereLoop costs are a
  111648. ** vector, not a scalar, and because dependencies are many-to-one, not
  111649. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  111650. ** Then a WherePath object is a path through the graph that visits some
  111651. ** or all of the WhereLoop objects once.
  111652. **
  111653. ** The "solver" works by creating the N best WherePath objects of length
  111654. ** 1. Then using those as a basis to compute the N best WherePath objects
  111655. ** of length 2. And so forth until the length of WherePaths equals the
  111656. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  111657. ** at the end is the chosen query plan.
  111658. */
  111659. struct WherePath {
  111660. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  111661. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  111662. LogEst nRow; /* Estimated number of rows generated by this path */
  111663. LogEst rCost; /* Total cost of this path */
  111664. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  111665. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  111666. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  111667. };
  111668. /*
  111669. ** The query generator uses an array of instances of this structure to
  111670. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  111671. ** clause subexpression is separated from the others by AND operators,
  111672. ** usually, or sometimes subexpressions separated by OR.
  111673. **
  111674. ** All WhereTerms are collected into a single WhereClause structure.
  111675. ** The following identity holds:
  111676. **
  111677. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  111678. **
  111679. ** When a term is of the form:
  111680. **
  111681. ** X <op> <expr>
  111682. **
  111683. ** where X is a column name and <op> is one of certain operators,
  111684. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  111685. ** cursor number and column number for X. WhereTerm.eOperator records
  111686. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  111687. ** use of a bitmask encoding for the operator allows us to search
  111688. ** quickly for terms that match any of several different operators.
  111689. **
  111690. ** A WhereTerm might also be two or more subterms connected by OR:
  111691. **
  111692. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  111693. **
  111694. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  111695. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  111696. ** is collected about the OR clause.
  111697. **
  111698. ** If a term in the WHERE clause does not match either of the two previous
  111699. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  111700. ** to the original subexpression content and wtFlags is set up appropriately
  111701. ** but no other fields in the WhereTerm object are meaningful.
  111702. **
  111703. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  111704. ** but they do so indirectly. A single WhereMaskSet structure translates
  111705. ** cursor number into bits and the translated bit is stored in the prereq
  111706. ** fields. The translation is used in order to maximize the number of
  111707. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  111708. ** spread out over the non-negative integers. For example, the cursor
  111709. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  111710. ** translates these sparse cursor numbers into consecutive integers
  111711. ** beginning with 0 in order to make the best possible use of the available
  111712. ** bits in the Bitmask. So, in the example above, the cursor numbers
  111713. ** would be mapped into integers 0 through 7.
  111714. **
  111715. ** The number of terms in a join is limited by the number of bits
  111716. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  111717. ** is only able to process joins with 64 or fewer tables.
  111718. */
  111719. struct WhereTerm {
  111720. Expr *pExpr; /* Pointer to the subexpression that is this term */
  111721. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  111722. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  111723. union {
  111724. int leftColumn; /* Column number of X in "X <op> <expr>" */
  111725. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  111726. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  111727. } u;
  111728. LogEst truthProb; /* Probability of truth for this expression */
  111729. u16 eOperator; /* A WO_xx value describing <op> */
  111730. u16 wtFlags; /* TERM_xxx bit flags. See below */
  111731. u8 nChild; /* Number of children that must disable us */
  111732. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  111733. WhereClause *pWC; /* The clause this term is part of */
  111734. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  111735. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  111736. };
  111737. /*
  111738. ** Allowed values of WhereTerm.wtFlags
  111739. */
  111740. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  111741. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  111742. #define TERM_CODED 0x04 /* This term is already coded */
  111743. #define TERM_COPIED 0x08 /* Has a child */
  111744. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  111745. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  111746. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  111747. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  111748. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  111749. #else
  111750. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  111751. #endif
  111752. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  111753. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  111754. #define TERM_LIKE 0x400 /* The original LIKE operator */
  111755. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  111756. /*
  111757. ** An instance of the WhereScan object is used as an iterator for locating
  111758. ** terms in the WHERE clause that are useful to the query planner.
  111759. */
  111760. struct WhereScan {
  111761. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  111762. WhereClause *pWC; /* WhereClause currently being scanned */
  111763. const char *zCollName; /* Required collating sequence, if not NULL */
  111764. Expr *pIdxExpr; /* Search for this index expression */
  111765. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  111766. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  111767. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  111768. u32 opMask; /* Acceptable operators */
  111769. int k; /* Resume scanning at this->pWC->a[this->k] */
  111770. int aiCur[11]; /* Cursors in the equivalence class */
  111771. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  111772. };
  111773. /*
  111774. ** An instance of the following structure holds all information about a
  111775. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  111776. **
  111777. ** Explanation of pOuter: For a WHERE clause of the form
  111778. **
  111779. ** a AND ((b AND c) OR (d AND e)) AND f
  111780. **
  111781. ** There are separate WhereClause objects for the whole clause and for
  111782. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  111783. ** subclauses points to the WhereClause object for the whole clause.
  111784. */
  111785. struct WhereClause {
  111786. WhereInfo *pWInfo; /* WHERE clause processing context */
  111787. WhereClause *pOuter; /* Outer conjunction */
  111788. u8 op; /* Split operator. TK_AND or TK_OR */
  111789. int nTerm; /* Number of terms */
  111790. int nSlot; /* Number of entries in a[] */
  111791. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  111792. #if defined(SQLITE_SMALL_STACK)
  111793. WhereTerm aStatic[1]; /* Initial static space for a[] */
  111794. #else
  111795. WhereTerm aStatic[8]; /* Initial static space for a[] */
  111796. #endif
  111797. };
  111798. /*
  111799. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  111800. ** a dynamically allocated instance of the following structure.
  111801. */
  111802. struct WhereOrInfo {
  111803. WhereClause wc; /* Decomposition into subterms */
  111804. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  111805. };
  111806. /*
  111807. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  111808. ** a dynamically allocated instance of the following structure.
  111809. */
  111810. struct WhereAndInfo {
  111811. WhereClause wc; /* The subexpression broken out */
  111812. };
  111813. /*
  111814. ** An instance of the following structure keeps track of a mapping
  111815. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  111816. **
  111817. ** The VDBE cursor numbers are small integers contained in
  111818. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  111819. ** clause, the cursor numbers might not begin with 0 and they might
  111820. ** contain gaps in the numbering sequence. But we want to make maximum
  111821. ** use of the bits in our bitmasks. This structure provides a mapping
  111822. ** from the sparse cursor numbers into consecutive integers beginning
  111823. ** with 0.
  111824. **
  111825. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  111826. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  111827. **
  111828. ** For example, if the WHERE clause expression used these VDBE
  111829. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  111830. ** would map those cursor numbers into bits 0 through 5.
  111831. **
  111832. ** Note that the mapping is not necessarily ordered. In the example
  111833. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  111834. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  111835. ** does not really matter. What is important is that sparse cursor
  111836. ** numbers all get mapped into bit numbers that begin with 0 and contain
  111837. ** no gaps.
  111838. */
  111839. struct WhereMaskSet {
  111840. int n; /* Number of assigned cursor values */
  111841. int ix[BMS]; /* Cursor assigned to each bit */
  111842. };
  111843. /*
  111844. ** Initialize a WhereMaskSet object
  111845. */
  111846. #define initMaskSet(P) (P)->n=0
  111847. /*
  111848. ** This object is a convenience wrapper holding all information needed
  111849. ** to construct WhereLoop objects for a particular query.
  111850. */
  111851. struct WhereLoopBuilder {
  111852. WhereInfo *pWInfo; /* Information about this WHERE */
  111853. WhereClause *pWC; /* WHERE clause terms */
  111854. ExprList *pOrderBy; /* ORDER BY clause */
  111855. WhereLoop *pNew; /* Template WhereLoop */
  111856. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  111857. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  111858. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  111859. int nRecValid; /* Number of valid fields currently in pRec */
  111860. #endif
  111861. };
  111862. /*
  111863. ** The WHERE clause processing routine has two halves. The
  111864. ** first part does the start of the WHERE loop and the second
  111865. ** half does the tail of the WHERE loop. An instance of
  111866. ** this structure is returned by the first half and passed
  111867. ** into the second half to give some continuity.
  111868. **
  111869. ** An instance of this object holds the complete state of the query
  111870. ** planner.
  111871. */
  111872. struct WhereInfo {
  111873. Parse *pParse; /* Parsing and code generating context */
  111874. SrcList *pTabList; /* List of tables in the join */
  111875. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  111876. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  111877. WhereLoop *pLoops; /* List of all WhereLoop objects */
  111878. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  111879. LogEst nRowOut; /* Estimated number of output rows */
  111880. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  111881. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  111882. u8 sorted; /* True if really sorted (not just grouped) */
  111883. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  111884. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  111885. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  111886. u8 nLevel; /* Number of nested loop */
  111887. int iTop; /* The very beginning of the WHERE loop */
  111888. int iContinue; /* Jump here to continue with next record */
  111889. int iBreak; /* Jump here to break out of the loop */
  111890. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  111891. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  111892. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  111893. WhereClause sWC; /* Decomposition of the WHERE clause */
  111894. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  111895. };
  111896. /*
  111897. ** Private interfaces - callable only by other where.c routines.
  111898. **
  111899. ** where.c:
  111900. */
  111901. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  111902. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  111903. WhereClause *pWC, /* The WHERE clause to be searched */
  111904. int iCur, /* Cursor number of LHS */
  111905. int iColumn, /* Column number of LHS */
  111906. Bitmask notReady, /* RHS must not overlap with this mask */
  111907. u32 op, /* Mask of WO_xx values describing operator */
  111908. Index *pIdx /* Must be compatible with this index, if not NULL */
  111909. );
  111910. /* wherecode.c: */
  111911. #ifndef SQLITE_OMIT_EXPLAIN
  111912. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  111913. Parse *pParse, /* Parse context */
  111914. SrcList *pTabList, /* Table list this loop refers to */
  111915. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  111916. int iLevel, /* Value for "level" column of output */
  111917. int iFrom, /* Value for "from" column of output */
  111918. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  111919. );
  111920. #else
  111921. # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
  111922. #endif /* SQLITE_OMIT_EXPLAIN */
  111923. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  111924. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  111925. Vdbe *v, /* Vdbe to add scanstatus entry to */
  111926. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  111927. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  111928. int addrExplain /* Address of OP_Explain (or 0) */
  111929. );
  111930. #else
  111931. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  111932. #endif
  111933. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  111934. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  111935. int iLevel, /* Which level of pWInfo->a[] should be coded */
  111936. Bitmask notReady /* Which tables are currently available */
  111937. );
  111938. /* whereexpr.c: */
  111939. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  111940. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  111941. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  111942. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  111943. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  111944. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  111945. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  111946. /*
  111947. ** Bitmasks for the operators on WhereTerm objects. These are all
  111948. ** operators that are of interest to the query planner. An
  111949. ** OR-ed combination of these values can be used when searching for
  111950. ** particular WhereTerms within a WhereClause.
  111951. */
  111952. #define WO_IN 0x0001
  111953. #define WO_EQ 0x0002
  111954. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  111955. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  111956. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  111957. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  111958. #define WO_MATCH 0x0040
  111959. #define WO_IS 0x0080
  111960. #define WO_ISNULL 0x0100
  111961. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  111962. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  111963. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  111964. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  111965. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  111966. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  111967. /*
  111968. ** These are definitions of bits in the WhereLoop.wsFlags field.
  111969. ** The particular combination of bits in each WhereLoop help to
  111970. ** determine the algorithm that WhereLoop represents.
  111971. */
  111972. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  111973. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  111974. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  111975. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  111976. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  111977. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  111978. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  111979. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  111980. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  111981. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  111982. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  111983. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  111984. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  111985. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  111986. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  111987. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  111988. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  111989. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  111990. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  111991. /************** End of whereInt.h ********************************************/
  111992. /************** Continuing where we left off in wherecode.c ******************/
  111993. #ifndef SQLITE_OMIT_EXPLAIN
  111994. /*
  111995. ** This routine is a helper for explainIndexRange() below
  111996. **
  111997. ** pStr holds the text of an expression that we are building up one term
  111998. ** at a time. This routine adds a new term to the end of the expression.
  111999. ** Terms are separated by AND so add the "AND" text for second and subsequent
  112000. ** terms only.
  112001. */
  112002. static void explainAppendTerm(
  112003. StrAccum *pStr, /* The text expression being built */
  112004. int iTerm, /* Index of this term. First is zero */
  112005. const char *zColumn, /* Name of the column */
  112006. const char *zOp /* Name of the operator */
  112007. ){
  112008. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  112009. sqlite3StrAccumAppendAll(pStr, zColumn);
  112010. sqlite3StrAccumAppend(pStr, zOp, 1);
  112011. sqlite3StrAccumAppend(pStr, "?", 1);
  112012. }
  112013. /*
  112014. ** Return the name of the i-th column of the pIdx index.
  112015. */
  112016. static const char *explainIndexColumnName(Index *pIdx, int i){
  112017. i = pIdx->aiColumn[i];
  112018. if( i==XN_EXPR ) return "<expr>";
  112019. if( i==XN_ROWID ) return "rowid";
  112020. return pIdx->pTable->aCol[i].zName;
  112021. }
  112022. /*
  112023. ** Argument pLevel describes a strategy for scanning table pTab. This
  112024. ** function appends text to pStr that describes the subset of table
  112025. ** rows scanned by the strategy in the form of an SQL expression.
  112026. **
  112027. ** For example, if the query:
  112028. **
  112029. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  112030. **
  112031. ** is run and there is an index on (a, b), then this function returns a
  112032. ** string similar to:
  112033. **
  112034. ** "a=? AND b>?"
  112035. */
  112036. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  112037. Index *pIndex = pLoop->u.btree.pIndex;
  112038. u16 nEq = pLoop->u.btree.nEq;
  112039. u16 nSkip = pLoop->nSkip;
  112040. int i, j;
  112041. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  112042. sqlite3StrAccumAppend(pStr, " (", 2);
  112043. for(i=0; i<nEq; i++){
  112044. const char *z = explainIndexColumnName(pIndex, i);
  112045. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  112046. sqlite3XPrintf(pStr, 0, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  112047. }
  112048. j = i;
  112049. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  112050. const char *z = explainIndexColumnName(pIndex, i);
  112051. explainAppendTerm(pStr, i++, z, ">");
  112052. }
  112053. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  112054. const char *z = explainIndexColumnName(pIndex, j);
  112055. explainAppendTerm(pStr, i, z, "<");
  112056. }
  112057. sqlite3StrAccumAppend(pStr, ")", 1);
  112058. }
  112059. /*
  112060. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  112061. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  112062. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  112063. ** is added to the output to describe the table scan strategy in pLevel.
  112064. **
  112065. ** If an OP_Explain opcode is added to the VM, its address is returned.
  112066. ** Otherwise, if no OP_Explain is coded, zero is returned.
  112067. */
  112068. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  112069. Parse *pParse, /* Parse context */
  112070. SrcList *pTabList, /* Table list this loop refers to */
  112071. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  112072. int iLevel, /* Value for "level" column of output */
  112073. int iFrom, /* Value for "from" column of output */
  112074. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  112075. ){
  112076. int ret = 0;
  112077. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  112078. if( pParse->explain==2 )
  112079. #endif
  112080. {
  112081. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  112082. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  112083. sqlite3 *db = pParse->db; /* Database handle */
  112084. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  112085. int isSearch; /* True for a SEARCH. False for SCAN. */
  112086. WhereLoop *pLoop; /* The controlling WhereLoop object */
  112087. u32 flags; /* Flags that describe this loop */
  112088. char *zMsg; /* Text to add to EQP output */
  112089. StrAccum str; /* EQP output string */
  112090. char zBuf[100]; /* Initial space for EQP output string */
  112091. pLoop = pLevel->pWLoop;
  112092. flags = pLoop->wsFlags;
  112093. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
  112094. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  112095. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  112096. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  112097. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  112098. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  112099. if( pItem->pSelect ){
  112100. sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
  112101. }else{
  112102. sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
  112103. }
  112104. if( pItem->zAlias ){
  112105. sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
  112106. }
  112107. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  112108. const char *zFmt = 0;
  112109. Index *pIdx;
  112110. assert( pLoop->u.btree.pIndex!=0 );
  112111. pIdx = pLoop->u.btree.pIndex;
  112112. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  112113. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  112114. if( isSearch ){
  112115. zFmt = "PRIMARY KEY";
  112116. }
  112117. }else if( flags & WHERE_PARTIALIDX ){
  112118. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  112119. }else if( flags & WHERE_AUTO_INDEX ){
  112120. zFmt = "AUTOMATIC COVERING INDEX";
  112121. }else if( flags & WHERE_IDX_ONLY ){
  112122. zFmt = "COVERING INDEX %s";
  112123. }else{
  112124. zFmt = "INDEX %s";
  112125. }
  112126. if( zFmt ){
  112127. sqlite3StrAccumAppend(&str, " USING ", 7);
  112128. sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
  112129. explainIndexRange(&str, pLoop);
  112130. }
  112131. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  112132. const char *zRangeOp;
  112133. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  112134. zRangeOp = "=";
  112135. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  112136. zRangeOp = ">? AND rowid<";
  112137. }else if( flags&WHERE_BTM_LIMIT ){
  112138. zRangeOp = ">";
  112139. }else{
  112140. assert( flags&WHERE_TOP_LIMIT);
  112141. zRangeOp = "<";
  112142. }
  112143. sqlite3XPrintf(&str, 0, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  112144. }
  112145. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112146. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  112147. sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
  112148. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  112149. }
  112150. #endif
  112151. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  112152. if( pLoop->nOut>=10 ){
  112153. sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  112154. }else{
  112155. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  112156. }
  112157. #endif
  112158. zMsg = sqlite3StrAccumFinish(&str);
  112159. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  112160. }
  112161. return ret;
  112162. }
  112163. #endif /* SQLITE_OMIT_EXPLAIN */
  112164. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  112165. /*
  112166. ** Configure the VM passed as the first argument with an
  112167. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  112168. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  112169. ** clause that the scan reads data from.
  112170. **
  112171. ** If argument addrExplain is not 0, it must be the address of an
  112172. ** OP_Explain instruction that describes the same loop.
  112173. */
  112174. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  112175. Vdbe *v, /* Vdbe to add scanstatus entry to */
  112176. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  112177. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  112178. int addrExplain /* Address of OP_Explain (or 0) */
  112179. ){
  112180. const char *zObj = 0;
  112181. WhereLoop *pLoop = pLvl->pWLoop;
  112182. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  112183. zObj = pLoop->u.btree.pIndex->zName;
  112184. }else{
  112185. zObj = pSrclist->a[pLvl->iFrom].zName;
  112186. }
  112187. sqlite3VdbeScanStatus(
  112188. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  112189. );
  112190. }
  112191. #endif
  112192. /*
  112193. ** Disable a term in the WHERE clause. Except, do not disable the term
  112194. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  112195. ** or USING clause of that join.
  112196. **
  112197. ** Consider the term t2.z='ok' in the following queries:
  112198. **
  112199. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  112200. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  112201. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  112202. **
  112203. ** The t2.z='ok' is disabled in the in (2) because it originates
  112204. ** in the ON clause. The term is disabled in (3) because it is not part
  112205. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  112206. **
  112207. ** Disabling a term causes that term to not be tested in the inner loop
  112208. ** of the join. Disabling is an optimization. When terms are satisfied
  112209. ** by indices, we disable them to prevent redundant tests in the inner
  112210. ** loop. We would get the correct results if nothing were ever disabled,
  112211. ** but joins might run a little slower. The trick is to disable as much
  112212. ** as we can without disabling too much. If we disabled in (1), we'd get
  112213. ** the wrong answer. See ticket #813.
  112214. **
  112215. ** If all the children of a term are disabled, then that term is also
  112216. ** automatically disabled. In this way, terms get disabled if derived
  112217. ** virtual terms are tested first. For example:
  112218. **
  112219. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  112220. ** \___________/ \______/ \_____/
  112221. ** parent child1 child2
  112222. **
  112223. ** Only the parent term was in the original WHERE clause. The child1
  112224. ** and child2 terms were added by the LIKE optimization. If both of
  112225. ** the virtual child terms are valid, then testing of the parent can be
  112226. ** skipped.
  112227. **
  112228. ** Usually the parent term is marked as TERM_CODED. But if the parent
  112229. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  112230. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  112231. ** a conditional such that is only evaluated on the second pass of a
  112232. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  112233. */
  112234. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  112235. int nLoop = 0;
  112236. while( pTerm
  112237. && (pTerm->wtFlags & TERM_CODED)==0
  112238. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  112239. && (pLevel->notReady & pTerm->prereqAll)==0
  112240. ){
  112241. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  112242. pTerm->wtFlags |= TERM_LIKECOND;
  112243. }else{
  112244. pTerm->wtFlags |= TERM_CODED;
  112245. }
  112246. if( pTerm->iParent<0 ) break;
  112247. pTerm = &pTerm->pWC->a[pTerm->iParent];
  112248. pTerm->nChild--;
  112249. if( pTerm->nChild!=0 ) break;
  112250. nLoop++;
  112251. }
  112252. }
  112253. /*
  112254. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  112255. ** to the n registers starting at base.
  112256. **
  112257. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  112258. ** beginning and end of zAff are ignored. If all entries in zAff are
  112259. ** SQLITE_AFF_BLOB, then no code gets generated.
  112260. **
  112261. ** This routine makes its own copy of zAff so that the caller is free
  112262. ** to modify zAff after this routine returns.
  112263. */
  112264. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  112265. Vdbe *v = pParse->pVdbe;
  112266. if( zAff==0 ){
  112267. assert( pParse->db->mallocFailed );
  112268. return;
  112269. }
  112270. assert( v!=0 );
  112271. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  112272. ** and end of the affinity string.
  112273. */
  112274. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  112275. n--;
  112276. base++;
  112277. zAff++;
  112278. }
  112279. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  112280. n--;
  112281. }
  112282. /* Code the OP_Affinity opcode if there is anything left to do. */
  112283. if( n>0 ){
  112284. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  112285. sqlite3VdbeChangeP4(v, -1, zAff, n);
  112286. sqlite3ExprCacheAffinityChange(pParse, base, n);
  112287. }
  112288. }
  112289. /*
  112290. ** Generate code for a single equality term of the WHERE clause. An equality
  112291. ** term can be either X=expr or X IN (...). pTerm is the term to be
  112292. ** coded.
  112293. **
  112294. ** The current value for the constraint is left in register iReg.
  112295. **
  112296. ** For a constraint of the form X=expr, the expression is evaluated and its
  112297. ** result is left on the stack. For constraints of the form X IN (...)
  112298. ** this routine sets up a loop that will iterate over all values of X.
  112299. */
  112300. static int codeEqualityTerm(
  112301. Parse *pParse, /* The parsing context */
  112302. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  112303. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  112304. int iEq, /* Index of the equality term within this level */
  112305. int bRev, /* True for reverse-order IN operations */
  112306. int iTarget /* Attempt to leave results in this register */
  112307. ){
  112308. Expr *pX = pTerm->pExpr;
  112309. Vdbe *v = pParse->pVdbe;
  112310. int iReg; /* Register holding results */
  112311. assert( iTarget>0 );
  112312. if( pX->op==TK_EQ || pX->op==TK_IS ){
  112313. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  112314. }else if( pX->op==TK_ISNULL ){
  112315. iReg = iTarget;
  112316. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  112317. #ifndef SQLITE_OMIT_SUBQUERY
  112318. }else{
  112319. int eType;
  112320. int iTab;
  112321. struct InLoop *pIn;
  112322. WhereLoop *pLoop = pLevel->pWLoop;
  112323. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  112324. && pLoop->u.btree.pIndex!=0
  112325. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  112326. ){
  112327. testcase( iEq==0 );
  112328. testcase( bRev );
  112329. bRev = !bRev;
  112330. }
  112331. assert( pX->op==TK_IN );
  112332. iReg = iTarget;
  112333. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
  112334. if( eType==IN_INDEX_INDEX_DESC ){
  112335. testcase( bRev );
  112336. bRev = !bRev;
  112337. }
  112338. iTab = pX->iTable;
  112339. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  112340. VdbeCoverageIf(v, bRev);
  112341. VdbeCoverageIf(v, !bRev);
  112342. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  112343. pLoop->wsFlags |= WHERE_IN_ABLE;
  112344. if( pLevel->u.in.nIn==0 ){
  112345. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  112346. }
  112347. pLevel->u.in.nIn++;
  112348. pLevel->u.in.aInLoop =
  112349. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  112350. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  112351. pIn = pLevel->u.in.aInLoop;
  112352. if( pIn ){
  112353. pIn += pLevel->u.in.nIn - 1;
  112354. pIn->iCur = iTab;
  112355. if( eType==IN_INDEX_ROWID ){
  112356. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  112357. }else{
  112358. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  112359. }
  112360. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  112361. sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
  112362. }else{
  112363. pLevel->u.in.nIn = 0;
  112364. }
  112365. #endif
  112366. }
  112367. disableTerm(pLevel, pTerm);
  112368. return iReg;
  112369. }
  112370. /*
  112371. ** Generate code that will evaluate all == and IN constraints for an
  112372. ** index scan.
  112373. **
  112374. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  112375. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  112376. ** The index has as many as three equality constraints, but in this
  112377. ** example, the third "c" value is an inequality. So only two
  112378. ** constraints are coded. This routine will generate code to evaluate
  112379. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  112380. ** in consecutive registers and the index of the first register is returned.
  112381. **
  112382. ** In the example above nEq==2. But this subroutine works for any value
  112383. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  112384. ** The only thing it does is allocate the pLevel->iMem memory cell and
  112385. ** compute the affinity string.
  112386. **
  112387. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  112388. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  112389. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  112390. ** occurs after the nEq quality constraints.
  112391. **
  112392. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  112393. ** the index of the first memory cell in that range. The code that
  112394. ** calls this routine will use that memory range to store keys for
  112395. ** start and termination conditions of the loop.
  112396. ** key value of the loop. If one or more IN operators appear, then
  112397. ** this routine allocates an additional nEq memory cells for internal
  112398. ** use.
  112399. **
  112400. ** Before returning, *pzAff is set to point to a buffer containing a
  112401. ** copy of the column affinity string of the index allocated using
  112402. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  112403. ** with equality constraints that use BLOB or NONE affinity are set to
  112404. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  112405. **
  112406. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  112407. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  112408. **
  112409. ** In the example above, the index on t1(a) has TEXT affinity. But since
  112410. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  112411. ** no conversion should be attempted before using a t2.b value as part of
  112412. ** a key to search the index. Hence the first byte in the returned affinity
  112413. ** string in this example would be set to SQLITE_AFF_BLOB.
  112414. */
  112415. static int codeAllEqualityTerms(
  112416. Parse *pParse, /* Parsing context */
  112417. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  112418. int bRev, /* Reverse the order of IN operators */
  112419. int nExtraReg, /* Number of extra registers to allocate */
  112420. char **pzAff /* OUT: Set to point to affinity string */
  112421. ){
  112422. u16 nEq; /* The number of == or IN constraints to code */
  112423. u16 nSkip; /* Number of left-most columns to skip */
  112424. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  112425. Index *pIdx; /* The index being used for this loop */
  112426. WhereTerm *pTerm; /* A single constraint term */
  112427. WhereLoop *pLoop; /* The WhereLoop object */
  112428. int j; /* Loop counter */
  112429. int regBase; /* Base register */
  112430. int nReg; /* Number of registers to allocate */
  112431. char *zAff; /* Affinity string to return */
  112432. /* This module is only called on query plans that use an index. */
  112433. pLoop = pLevel->pWLoop;
  112434. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  112435. nEq = pLoop->u.btree.nEq;
  112436. nSkip = pLoop->nSkip;
  112437. pIdx = pLoop->u.btree.pIndex;
  112438. assert( pIdx!=0 );
  112439. /* Figure out how many memory cells we will need then allocate them.
  112440. */
  112441. regBase = pParse->nMem + 1;
  112442. nReg = pLoop->u.btree.nEq + nExtraReg;
  112443. pParse->nMem += nReg;
  112444. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  112445. if( !zAff ){
  112446. pParse->db->mallocFailed = 1;
  112447. }
  112448. if( nSkip ){
  112449. int iIdxCur = pLevel->iIdxCur;
  112450. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  112451. VdbeCoverageIf(v, bRev==0);
  112452. VdbeCoverageIf(v, bRev!=0);
  112453. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  112454. j = sqlite3VdbeAddOp0(v, OP_Goto);
  112455. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  112456. iIdxCur, 0, regBase, nSkip);
  112457. VdbeCoverageIf(v, bRev==0);
  112458. VdbeCoverageIf(v, bRev!=0);
  112459. sqlite3VdbeJumpHere(v, j);
  112460. for(j=0; j<nSkip; j++){
  112461. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  112462. testcase( pIdx->aiColumn[j]==XN_EXPR );
  112463. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  112464. }
  112465. }
  112466. /* Evaluate the equality constraints
  112467. */
  112468. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  112469. for(j=nSkip; j<nEq; j++){
  112470. int r1;
  112471. pTerm = pLoop->aLTerm[j];
  112472. assert( pTerm!=0 );
  112473. /* The following testcase is true for indices with redundant columns.
  112474. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  112475. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  112476. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  112477. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  112478. if( r1!=regBase+j ){
  112479. if( nReg==1 ){
  112480. sqlite3ReleaseTempReg(pParse, regBase);
  112481. regBase = r1;
  112482. }else{
  112483. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  112484. }
  112485. }
  112486. testcase( pTerm->eOperator & WO_ISNULL );
  112487. testcase( pTerm->eOperator & WO_IN );
  112488. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  112489. Expr *pRight = pTerm->pExpr->pRight;
  112490. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  112491. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  112492. VdbeCoverage(v);
  112493. }
  112494. if( zAff ){
  112495. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  112496. zAff[j] = SQLITE_AFF_BLOB;
  112497. }
  112498. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  112499. zAff[j] = SQLITE_AFF_BLOB;
  112500. }
  112501. }
  112502. }
  112503. }
  112504. *pzAff = zAff;
  112505. return regBase;
  112506. }
  112507. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  112508. /*
  112509. ** If the most recently coded instruction is a constant range contraint
  112510. ** that originated from the LIKE optimization, then change the P3 to be
  112511. ** pLoop->iLikeRepCntr and set P5.
  112512. **
  112513. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  112514. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  112515. ** scan loop run twice, once for strings and a second time for BLOBs.
  112516. ** The OP_String opcodes on the second pass convert the upper and lower
  112517. ** bound string contants to blobs. This routine makes the necessary changes
  112518. ** to the OP_String opcodes for that to happen.
  112519. **
  112520. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  112521. ** only the one pass through the string space is required, so this routine
  112522. ** becomes a no-op.
  112523. */
  112524. static void whereLikeOptimizationStringFixup(
  112525. Vdbe *v, /* prepared statement under construction */
  112526. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  112527. WhereTerm *pTerm /* The upper or lower bound just coded */
  112528. ){
  112529. if( pTerm->wtFlags & TERM_LIKEOPT ){
  112530. VdbeOp *pOp;
  112531. assert( pLevel->iLikeRepCntr>0 );
  112532. pOp = sqlite3VdbeGetOp(v, -1);
  112533. assert( pOp!=0 );
  112534. assert( pOp->opcode==OP_String8
  112535. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  112536. pOp->p3 = pLevel->iLikeRepCntr;
  112537. pOp->p5 = 1;
  112538. }
  112539. }
  112540. #else
  112541. # define whereLikeOptimizationStringFixup(A,B,C)
  112542. #endif
  112543. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  112544. /*
  112545. ** Information is passed from codeCursorHint() down to individual nodes of
  112546. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  112547. ** structure.
  112548. */
  112549. struct CCurHint {
  112550. int iTabCur; /* Cursor for the main table */
  112551. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  112552. Index *pIdx; /* The index used to access the table */
  112553. };
  112554. /*
  112555. ** This function is called for every node of an expression that is a candidate
  112556. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  112557. ** the table CCurHint.iTabCur, verify that the same column can be
  112558. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  112559. */
  112560. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  112561. struct CCurHint *pHint = pWalker->u.pCCurHint;
  112562. assert( pHint->pIdx!=0 );
  112563. if( pExpr->op==TK_COLUMN
  112564. && pExpr->iTable==pHint->iTabCur
  112565. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  112566. ){
  112567. pWalker->eCode = 1;
  112568. }
  112569. return WRC_Continue;
  112570. }
  112571. /*
  112572. ** This function is called on every node of an expression tree used as an
  112573. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  112574. ** that accesses any table other than the one identified by
  112575. ** CCurHint.iTabCur, then do the following:
  112576. **
  112577. ** 1) allocate a register and code an OP_Column instruction to read
  112578. ** the specified column into the new register, and
  112579. **
  112580. ** 2) transform the expression node to a TK_REGISTER node that reads
  112581. ** from the newly populated register.
  112582. **
  112583. ** Also, if the node is a TK_COLUMN that does access the table idenified
  112584. ** by pCCurHint.iTabCur, and an index is being used (which we will
  112585. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  112586. ** an access of the index rather than the original table.
  112587. */
  112588. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  112589. int rc = WRC_Continue;
  112590. struct CCurHint *pHint = pWalker->u.pCCurHint;
  112591. if( pExpr->op==TK_COLUMN ){
  112592. if( pExpr->iTable!=pHint->iTabCur ){
  112593. Vdbe *v = pWalker->pParse->pVdbe;
  112594. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  112595. sqlite3ExprCodeGetColumnOfTable(
  112596. v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
  112597. );
  112598. pExpr->op = TK_REGISTER;
  112599. pExpr->iTable = reg;
  112600. }else if( pHint->pIdx!=0 ){
  112601. pExpr->iTable = pHint->iIdxCur;
  112602. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  112603. assert( pExpr->iColumn>=0 );
  112604. }
  112605. }else if( pExpr->op==TK_AGG_FUNCTION ){
  112606. /* An aggregate function in the WHERE clause of a query means this must
  112607. ** be a correlated sub-query, and expression pExpr is an aggregate from
  112608. ** the parent context. Do not walk the function arguments in this case.
  112609. **
  112610. ** todo: It should be possible to replace this node with a TK_REGISTER
  112611. ** expression, as the result of the expression must be stored in a
  112612. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  112613. rc = WRC_Prune;
  112614. }
  112615. return rc;
  112616. }
  112617. /*
  112618. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  112619. */
  112620. static void codeCursorHint(
  112621. WhereInfo *pWInfo, /* The where clause */
  112622. WhereLevel *pLevel, /* Which loop to provide hints for */
  112623. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  112624. ){
  112625. Parse *pParse = pWInfo->pParse;
  112626. sqlite3 *db = pParse->db;
  112627. Vdbe *v = pParse->pVdbe;
  112628. Expr *pExpr = 0;
  112629. WhereLoop *pLoop = pLevel->pWLoop;
  112630. int iCur;
  112631. WhereClause *pWC;
  112632. WhereTerm *pTerm;
  112633. int i, j;
  112634. struct CCurHint sHint;
  112635. Walker sWalker;
  112636. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  112637. iCur = pLevel->iTabCur;
  112638. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  112639. sHint.iTabCur = iCur;
  112640. sHint.iIdxCur = pLevel->iIdxCur;
  112641. sHint.pIdx = pLoop->u.btree.pIndex;
  112642. memset(&sWalker, 0, sizeof(sWalker));
  112643. sWalker.pParse = pParse;
  112644. sWalker.u.pCCurHint = &sHint;
  112645. pWC = &pWInfo->sWC;
  112646. for(i=0; i<pWC->nTerm; i++){
  112647. pTerm = &pWC->a[i];
  112648. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  112649. if( pTerm->prereqAll & pLevel->notReady ) continue;
  112650. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  112651. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  112652. ** the cursor. These terms are not needed as hints for a pure range
  112653. ** scan (that has no == terms) so omit them. */
  112654. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  112655. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  112656. if( j<pLoop->nLTerm ) continue;
  112657. }
  112658. /* No subqueries or non-deterministic functions allowed */
  112659. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  112660. /* For an index scan, make sure referenced columns are actually in
  112661. ** the index. */
  112662. if( sHint.pIdx!=0 ){
  112663. sWalker.eCode = 0;
  112664. sWalker.xExprCallback = codeCursorHintCheckExpr;
  112665. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  112666. if( sWalker.eCode ) continue;
  112667. }
  112668. /* If we survive all prior tests, that means this term is worth hinting */
  112669. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  112670. }
  112671. if( pExpr!=0 ){
  112672. sWalker.xExprCallback = codeCursorHintFixExpr;
  112673. sqlite3WalkExpr(&sWalker, pExpr);
  112674. sqlite3VdbeAddOp4(v, OP_CursorHint,
  112675. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  112676. (const char*)pExpr, P4_EXPR);
  112677. }
  112678. }
  112679. #else
  112680. # define codeCursorHint(A,B,C) /* No-op */
  112681. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  112682. /*
  112683. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  112684. ** implementation described by pWInfo.
  112685. */
  112686. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  112687. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  112688. int iLevel, /* Which level of pWInfo->a[] should be coded */
  112689. Bitmask notReady /* Which tables are currently available */
  112690. ){
  112691. int j, k; /* Loop counters */
  112692. int iCur; /* The VDBE cursor for the table */
  112693. int addrNxt; /* Where to jump to continue with the next IN case */
  112694. int omitTable; /* True if we use the index only */
  112695. int bRev; /* True if we need to scan in reverse order */
  112696. WhereLevel *pLevel; /* The where level to be coded */
  112697. WhereLoop *pLoop; /* The WhereLoop object being coded */
  112698. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  112699. WhereTerm *pTerm; /* A WHERE clause term */
  112700. Parse *pParse; /* Parsing context */
  112701. sqlite3 *db; /* Database connection */
  112702. Vdbe *v; /* The prepared stmt under constructions */
  112703. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  112704. int addrBrk; /* Jump here to break out of the loop */
  112705. int addrCont; /* Jump here to continue with next cycle */
  112706. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  112707. int iReleaseReg = 0; /* Temp register to free before returning */
  112708. pParse = pWInfo->pParse;
  112709. v = pParse->pVdbe;
  112710. pWC = &pWInfo->sWC;
  112711. db = pParse->db;
  112712. pLevel = &pWInfo->a[iLevel];
  112713. pLoop = pLevel->pWLoop;
  112714. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  112715. iCur = pTabItem->iCursor;
  112716. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  112717. bRev = (pWInfo->revMask>>iLevel)&1;
  112718. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  112719. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  112720. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  112721. /* Create labels for the "break" and "continue" instructions
  112722. ** for the current loop. Jump to addrBrk to break out of a loop.
  112723. ** Jump to cont to go immediately to the next iteration of the
  112724. ** loop.
  112725. **
  112726. ** When there is an IN operator, we also have a "addrNxt" label that
  112727. ** means to continue with the next IN value combination. When
  112728. ** there are no IN operators in the constraints, the "addrNxt" label
  112729. ** is the same as "addrBrk".
  112730. */
  112731. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  112732. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  112733. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  112734. ** initialize a memory cell that records if this table matches any
  112735. ** row of the left table of the join.
  112736. */
  112737. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  112738. pLevel->iLeftJoin = ++pParse->nMem;
  112739. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  112740. VdbeComment((v, "init LEFT JOIN no-match flag"));
  112741. }
  112742. /* Special case of a FROM clause subquery implemented as a co-routine */
  112743. if( pTabItem->fg.viaCoroutine ){
  112744. int regYield = pTabItem->regReturn;
  112745. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  112746. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  112747. VdbeCoverage(v);
  112748. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  112749. pLevel->op = OP_Goto;
  112750. }else
  112751. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112752. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  112753. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  112754. ** to access the data.
  112755. */
  112756. int iReg; /* P3 Value for OP_VFilter */
  112757. int addrNotFound;
  112758. int nConstraint = pLoop->nLTerm;
  112759. sqlite3ExprCachePush(pParse);
  112760. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  112761. addrNotFound = pLevel->addrBrk;
  112762. for(j=0; j<nConstraint; j++){
  112763. int iTarget = iReg+j+2;
  112764. pTerm = pLoop->aLTerm[j];
  112765. if( pTerm==0 ) continue;
  112766. if( pTerm->eOperator & WO_IN ){
  112767. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  112768. addrNotFound = pLevel->addrNxt;
  112769. }else{
  112770. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  112771. }
  112772. }
  112773. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  112774. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  112775. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  112776. pLoop->u.vtab.idxStr,
  112777. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  112778. VdbeCoverage(v);
  112779. pLoop->u.vtab.needFree = 0;
  112780. for(j=0; j<nConstraint && j<16; j++){
  112781. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  112782. disableTerm(pLevel, pLoop->aLTerm[j]);
  112783. }
  112784. }
  112785. pLevel->p1 = iCur;
  112786. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  112787. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  112788. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  112789. sqlite3ExprCachePop(pParse);
  112790. }else
  112791. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  112792. if( (pLoop->wsFlags & WHERE_IPK)!=0
  112793. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  112794. ){
  112795. /* Case 2: We can directly reference a single row using an
  112796. ** equality comparison against the ROWID field. Or
  112797. ** we reference multiple rows using a "rowid IN (...)"
  112798. ** construct.
  112799. */
  112800. assert( pLoop->u.btree.nEq==1 );
  112801. pTerm = pLoop->aLTerm[0];
  112802. assert( pTerm!=0 );
  112803. assert( pTerm->pExpr!=0 );
  112804. assert( omitTable==0 );
  112805. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  112806. iReleaseReg = ++pParse->nMem;
  112807. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  112808. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  112809. addrNxt = pLevel->addrNxt;
  112810. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
  112811. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  112812. VdbeCoverage(v);
  112813. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  112814. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  112815. VdbeComment((v, "pk"));
  112816. pLevel->op = OP_Noop;
  112817. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  112818. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  112819. ){
  112820. /* Case 3: We have an inequality comparison against the ROWID field.
  112821. */
  112822. int testOp = OP_Noop;
  112823. int start;
  112824. int memEndValue = 0;
  112825. WhereTerm *pStart, *pEnd;
  112826. assert( omitTable==0 );
  112827. j = 0;
  112828. pStart = pEnd = 0;
  112829. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  112830. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  112831. assert( pStart!=0 || pEnd!=0 );
  112832. if( bRev ){
  112833. pTerm = pStart;
  112834. pStart = pEnd;
  112835. pEnd = pTerm;
  112836. }
  112837. codeCursorHint(pWInfo, pLevel, pEnd);
  112838. if( pStart ){
  112839. Expr *pX; /* The expression that defines the start bound */
  112840. int r1, rTemp; /* Registers for holding the start boundary */
  112841. /* The following constant maps TK_xx codes into corresponding
  112842. ** seek opcodes. It depends on a particular ordering of TK_xx
  112843. */
  112844. const u8 aMoveOp[] = {
  112845. /* TK_GT */ OP_SeekGT,
  112846. /* TK_LE */ OP_SeekLE,
  112847. /* TK_LT */ OP_SeekLT,
  112848. /* TK_GE */ OP_SeekGE
  112849. };
  112850. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  112851. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  112852. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  112853. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  112854. testcase( pStart->wtFlags & TERM_VIRTUAL );
  112855. pX = pStart->pExpr;
  112856. assert( pX!=0 );
  112857. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  112858. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  112859. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  112860. VdbeComment((v, "pk"));
  112861. VdbeCoverageIf(v, pX->op==TK_GT);
  112862. VdbeCoverageIf(v, pX->op==TK_LE);
  112863. VdbeCoverageIf(v, pX->op==TK_LT);
  112864. VdbeCoverageIf(v, pX->op==TK_GE);
  112865. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  112866. sqlite3ReleaseTempReg(pParse, rTemp);
  112867. disableTerm(pLevel, pStart);
  112868. }else{
  112869. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  112870. VdbeCoverageIf(v, bRev==0);
  112871. VdbeCoverageIf(v, bRev!=0);
  112872. }
  112873. if( pEnd ){
  112874. Expr *pX;
  112875. pX = pEnd->pExpr;
  112876. assert( pX!=0 );
  112877. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  112878. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  112879. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  112880. memEndValue = ++pParse->nMem;
  112881. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  112882. if( pX->op==TK_LT || pX->op==TK_GT ){
  112883. testOp = bRev ? OP_Le : OP_Ge;
  112884. }else{
  112885. testOp = bRev ? OP_Lt : OP_Gt;
  112886. }
  112887. disableTerm(pLevel, pEnd);
  112888. }
  112889. start = sqlite3VdbeCurrentAddr(v);
  112890. pLevel->op = bRev ? OP_Prev : OP_Next;
  112891. pLevel->p1 = iCur;
  112892. pLevel->p2 = start;
  112893. assert( pLevel->p5==0 );
  112894. if( testOp!=OP_Noop ){
  112895. iRowidReg = ++pParse->nMem;
  112896. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  112897. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  112898. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  112899. VdbeCoverageIf(v, testOp==OP_Le);
  112900. VdbeCoverageIf(v, testOp==OP_Lt);
  112901. VdbeCoverageIf(v, testOp==OP_Ge);
  112902. VdbeCoverageIf(v, testOp==OP_Gt);
  112903. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  112904. }
  112905. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  112906. /* Case 4: A scan using an index.
  112907. **
  112908. ** The WHERE clause may contain zero or more equality
  112909. ** terms ("==" or "IN" operators) that refer to the N
  112910. ** left-most columns of the index. It may also contain
  112911. ** inequality constraints (>, <, >= or <=) on the indexed
  112912. ** column that immediately follows the N equalities. Only
  112913. ** the right-most column can be an inequality - the rest must
  112914. ** use the "==" and "IN" operators. For example, if the
  112915. ** index is on (x,y,z), then the following clauses are all
  112916. ** optimized:
  112917. **
  112918. ** x=5
  112919. ** x=5 AND y=10
  112920. ** x=5 AND y<10
  112921. ** x=5 AND y>5 AND y<10
  112922. ** x=5 AND y=5 AND z<=10
  112923. **
  112924. ** The z<10 term of the following cannot be used, only
  112925. ** the x=5 term:
  112926. **
  112927. ** x=5 AND z<10
  112928. **
  112929. ** N may be zero if there are inequality constraints.
  112930. ** If there are no inequality constraints, then N is at
  112931. ** least one.
  112932. **
  112933. ** This case is also used when there are no WHERE clause
  112934. ** constraints but an index is selected anyway, in order
  112935. ** to force the output order to conform to an ORDER BY.
  112936. */
  112937. static const u8 aStartOp[] = {
  112938. 0,
  112939. 0,
  112940. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  112941. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  112942. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  112943. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  112944. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  112945. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  112946. };
  112947. static const u8 aEndOp[] = {
  112948. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  112949. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  112950. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  112951. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  112952. };
  112953. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  112954. int regBase; /* Base register holding constraint values */
  112955. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  112956. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  112957. int startEq; /* True if range start uses ==, >= or <= */
  112958. int endEq; /* True if range end uses ==, >= or <= */
  112959. int start_constraints; /* Start of range is constrained */
  112960. int nConstraint; /* Number of constraint terms */
  112961. Index *pIdx; /* The index we will be using */
  112962. int iIdxCur; /* The VDBE cursor for the index */
  112963. int nExtraReg = 0; /* Number of extra registers needed */
  112964. int op; /* Instruction opcode */
  112965. char *zStartAff; /* Affinity for start of range constraint */
  112966. char cEndAff = 0; /* Affinity for end of range constraint */
  112967. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  112968. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  112969. pIdx = pLoop->u.btree.pIndex;
  112970. iIdxCur = pLevel->iIdxCur;
  112971. assert( nEq>=pLoop->nSkip );
  112972. /* If this loop satisfies a sort order (pOrderBy) request that
  112973. ** was passed to this function to implement a "SELECT min(x) ..."
  112974. ** query, then the caller will only allow the loop to run for
  112975. ** a single iteration. This means that the first row returned
  112976. ** should not have a NULL value stored in 'x'. If column 'x' is
  112977. ** the first one after the nEq equality constraints in the index,
  112978. ** this requires some special handling.
  112979. */
  112980. assert( pWInfo->pOrderBy==0
  112981. || pWInfo->pOrderBy->nExpr==1
  112982. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  112983. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  112984. && pWInfo->nOBSat>0
  112985. && (pIdx->nKeyCol>nEq)
  112986. ){
  112987. assert( pLoop->nSkip==0 );
  112988. bSeekPastNull = 1;
  112989. nExtraReg = 1;
  112990. }
  112991. /* Find any inequality constraint terms for the start and end
  112992. ** of the range.
  112993. */
  112994. j = nEq;
  112995. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  112996. pRangeStart = pLoop->aLTerm[j++];
  112997. nExtraReg = 1;
  112998. /* Like optimization range constraints always occur in pairs */
  112999. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  113000. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  113001. }
  113002. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  113003. pRangeEnd = pLoop->aLTerm[j++];
  113004. nExtraReg = 1;
  113005. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  113006. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  113007. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  113008. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  113009. pLevel->iLikeRepCntr = ++pParse->nMem;
  113010. testcase( bRev );
  113011. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  113012. sqlite3VdbeAddOp2(v, OP_Integer,
  113013. bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
  113014. pLevel->iLikeRepCntr);
  113015. VdbeComment((v, "LIKE loop counter"));
  113016. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  113017. }
  113018. #endif
  113019. if( pRangeStart==0
  113020. && (j = pIdx->aiColumn[nEq])>=0
  113021. && pIdx->pTable->aCol[j].notNull==0
  113022. ){
  113023. bSeekPastNull = 1;
  113024. }
  113025. }
  113026. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  113027. /* If we are doing a reverse order scan on an ascending index, or
  113028. ** a forward order scan on a descending index, interchange the
  113029. ** start and end terms (pRangeStart and pRangeEnd).
  113030. */
  113031. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  113032. || (bRev && pIdx->nKeyCol==nEq)
  113033. ){
  113034. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  113035. SWAP(u8, bSeekPastNull, bStopAtNull);
  113036. }
  113037. /* Generate code to evaluate all constraint terms using == or IN
  113038. ** and store the values of those terms in an array of registers
  113039. ** starting at regBase.
  113040. */
  113041. codeCursorHint(pWInfo, pLevel, pRangeEnd);
  113042. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  113043. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  113044. if( zStartAff ) cEndAff = zStartAff[nEq];
  113045. addrNxt = pLevel->addrNxt;
  113046. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  113047. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  113048. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  113049. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  113050. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  113051. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  113052. start_constraints = pRangeStart || nEq>0;
  113053. /* Seek the index cursor to the start of the range. */
  113054. nConstraint = nEq;
  113055. if( pRangeStart ){
  113056. Expr *pRight = pRangeStart->pExpr->pRight;
  113057. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  113058. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  113059. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  113060. && sqlite3ExprCanBeNull(pRight)
  113061. ){
  113062. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  113063. VdbeCoverage(v);
  113064. }
  113065. if( zStartAff ){
  113066. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
  113067. /* Since the comparison is to be performed with no conversions
  113068. ** applied to the operands, set the affinity to apply to pRight to
  113069. ** SQLITE_AFF_BLOB. */
  113070. zStartAff[nEq] = SQLITE_AFF_BLOB;
  113071. }
  113072. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  113073. zStartAff[nEq] = SQLITE_AFF_BLOB;
  113074. }
  113075. }
  113076. nConstraint++;
  113077. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  113078. }else if( bSeekPastNull ){
  113079. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  113080. nConstraint++;
  113081. startEq = 0;
  113082. start_constraints = 1;
  113083. }
  113084. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  113085. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  113086. assert( op!=0 );
  113087. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  113088. VdbeCoverage(v);
  113089. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  113090. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  113091. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  113092. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  113093. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  113094. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  113095. /* Load the value for the inequality constraint at the end of the
  113096. ** range (if any).
  113097. */
  113098. nConstraint = nEq;
  113099. if( pRangeEnd ){
  113100. Expr *pRight = pRangeEnd->pExpr->pRight;
  113101. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  113102. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  113103. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  113104. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  113105. && sqlite3ExprCanBeNull(pRight)
  113106. ){
  113107. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  113108. VdbeCoverage(v);
  113109. }
  113110. if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
  113111. && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
  113112. ){
  113113. codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
  113114. }
  113115. nConstraint++;
  113116. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  113117. }else if( bStopAtNull ){
  113118. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  113119. endEq = 0;
  113120. nConstraint++;
  113121. }
  113122. sqlite3DbFree(db, zStartAff);
  113123. /* Top of the loop body */
  113124. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  113125. /* Check if the index cursor is past the end of the range. */
  113126. if( nConstraint ){
  113127. op = aEndOp[bRev*2 + endEq];
  113128. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  113129. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  113130. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  113131. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  113132. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  113133. }
  113134. /* Seek the table cursor, if required */
  113135. disableTerm(pLevel, pRangeStart);
  113136. disableTerm(pLevel, pRangeEnd);
  113137. if( omitTable ){
  113138. /* pIdx is a covering index. No need to access the main table. */
  113139. }else if( HasRowid(pIdx->pTable) ){
  113140. iRowidReg = ++pParse->nMem;
  113141. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  113142. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  113143. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  113144. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  113145. VdbeCoverage(v);
  113146. }else{
  113147. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  113148. }
  113149. }else if( iCur!=iIdxCur ){
  113150. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  113151. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  113152. for(j=0; j<pPk->nKeyCol; j++){
  113153. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  113154. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  113155. }
  113156. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  113157. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  113158. }
  113159. /* Record the instruction used to terminate the loop. Disable
  113160. ** WHERE clause terms made redundant by the index range scan.
  113161. */
  113162. if( pLoop->wsFlags & WHERE_ONEROW ){
  113163. pLevel->op = OP_Noop;
  113164. }else if( bRev ){
  113165. pLevel->op = OP_Prev;
  113166. }else{
  113167. pLevel->op = OP_Next;
  113168. }
  113169. pLevel->p1 = iIdxCur;
  113170. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  113171. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  113172. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  113173. }else{
  113174. assert( pLevel->p5==0 );
  113175. }
  113176. }else
  113177. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  113178. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  113179. /* Case 5: Two or more separately indexed terms connected by OR
  113180. **
  113181. ** Example:
  113182. **
  113183. ** CREATE TABLE t1(a,b,c,d);
  113184. ** CREATE INDEX i1 ON t1(a);
  113185. ** CREATE INDEX i2 ON t1(b);
  113186. ** CREATE INDEX i3 ON t1(c);
  113187. **
  113188. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  113189. **
  113190. ** In the example, there are three indexed terms connected by OR.
  113191. ** The top of the loop looks like this:
  113192. **
  113193. ** Null 1 # Zero the rowset in reg 1
  113194. **
  113195. ** Then, for each indexed term, the following. The arguments to
  113196. ** RowSetTest are such that the rowid of the current row is inserted
  113197. ** into the RowSet. If it is already present, control skips the
  113198. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  113199. **
  113200. ** sqlite3WhereBegin(<term>)
  113201. ** RowSetTest # Insert rowid into rowset
  113202. ** Gosub 2 A
  113203. ** sqlite3WhereEnd()
  113204. **
  113205. ** Following the above, code to terminate the loop. Label A, the target
  113206. ** of the Gosub above, jumps to the instruction right after the Goto.
  113207. **
  113208. ** Null 1 # Zero the rowset in reg 1
  113209. ** Goto B # The loop is finished.
  113210. **
  113211. ** A: <loop body> # Return data, whatever.
  113212. **
  113213. ** Return 2 # Jump back to the Gosub
  113214. **
  113215. ** B: <after the loop>
  113216. **
  113217. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  113218. ** use an ephemeral index instead of a RowSet to record the primary
  113219. ** keys of the rows we have already seen.
  113220. **
  113221. */
  113222. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  113223. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  113224. Index *pCov = 0; /* Potential covering index (or NULL) */
  113225. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  113226. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  113227. int regRowset = 0; /* Register for RowSet object */
  113228. int regRowid = 0; /* Register holding rowid */
  113229. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  113230. int iRetInit; /* Address of regReturn init */
  113231. int untestedTerms = 0; /* Some terms not completely tested */
  113232. int ii; /* Loop counter */
  113233. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  113234. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  113235. Table *pTab = pTabItem->pTab;
  113236. pTerm = pLoop->aLTerm[0];
  113237. assert( pTerm!=0 );
  113238. assert( pTerm->eOperator & WO_OR );
  113239. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  113240. pOrWc = &pTerm->u.pOrInfo->wc;
  113241. pLevel->op = OP_Return;
  113242. pLevel->p1 = regReturn;
  113243. /* Set up a new SrcList in pOrTab containing the table being scanned
  113244. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  113245. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  113246. */
  113247. if( pWInfo->nLevel>1 ){
  113248. int nNotReady; /* The number of notReady tables */
  113249. struct SrcList_item *origSrc; /* Original list of tables */
  113250. nNotReady = pWInfo->nLevel - iLevel - 1;
  113251. pOrTab = sqlite3StackAllocRaw(db,
  113252. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  113253. if( pOrTab==0 ) return notReady;
  113254. pOrTab->nAlloc = (u8)(nNotReady + 1);
  113255. pOrTab->nSrc = pOrTab->nAlloc;
  113256. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  113257. origSrc = pWInfo->pTabList->a;
  113258. for(k=1; k<=nNotReady; k++){
  113259. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  113260. }
  113261. }else{
  113262. pOrTab = pWInfo->pTabList;
  113263. }
  113264. /* Initialize the rowset register to contain NULL. An SQL NULL is
  113265. ** equivalent to an empty rowset. Or, create an ephemeral index
  113266. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  113267. **
  113268. ** Also initialize regReturn to contain the address of the instruction
  113269. ** immediately following the OP_Return at the bottom of the loop. This
  113270. ** is required in a few obscure LEFT JOIN cases where control jumps
  113271. ** over the top of the loop into the body of it. In this case the
  113272. ** correct response for the end-of-loop code (the OP_Return) is to
  113273. ** fall through to the next instruction, just as an OP_Next does if
  113274. ** called on an uninitialized cursor.
  113275. */
  113276. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  113277. if( HasRowid(pTab) ){
  113278. regRowset = ++pParse->nMem;
  113279. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  113280. }else{
  113281. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  113282. regRowset = pParse->nTab++;
  113283. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  113284. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  113285. }
  113286. regRowid = ++pParse->nMem;
  113287. }
  113288. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  113289. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  113290. ** Then for every term xN, evaluate as the subexpression: xN AND z
  113291. ** That way, terms in y that are factored into the disjunction will
  113292. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  113293. **
  113294. ** Actually, each subexpression is converted to "xN AND w" where w is
  113295. ** the "interesting" terms of z - terms that did not originate in the
  113296. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  113297. ** indices.
  113298. **
  113299. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  113300. ** is not contained in the ON clause of a LEFT JOIN.
  113301. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  113302. */
  113303. if( pWC->nTerm>1 ){
  113304. int iTerm;
  113305. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  113306. Expr *pExpr = pWC->a[iTerm].pExpr;
  113307. if( &pWC->a[iTerm] == pTerm ) continue;
  113308. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  113309. if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
  113310. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  113311. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  113312. pExpr = sqlite3ExprDup(db, pExpr, 0);
  113313. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  113314. }
  113315. if( pAndExpr ){
  113316. pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
  113317. }
  113318. }
  113319. /* Run a separate WHERE clause for each term of the OR clause. After
  113320. ** eliminating duplicates from other WHERE clauses, the action for each
  113321. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  113322. */
  113323. wctrlFlags = WHERE_OMIT_OPEN_CLOSE
  113324. | WHERE_FORCE_TABLE
  113325. | WHERE_ONETABLE_ONLY
  113326. | WHERE_NO_AUTOINDEX;
  113327. for(ii=0; ii<pOrWc->nTerm; ii++){
  113328. WhereTerm *pOrTerm = &pOrWc->a[ii];
  113329. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  113330. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  113331. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  113332. int jmp1 = 0; /* Address of jump operation */
  113333. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  113334. pAndExpr->pLeft = pOrExpr;
  113335. pOrExpr = pAndExpr;
  113336. }
  113337. /* Loop through table entries that match term pOrTerm. */
  113338. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  113339. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  113340. wctrlFlags, iCovCur);
  113341. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  113342. if( pSubWInfo ){
  113343. WhereLoop *pSubLoop;
  113344. int addrExplain = sqlite3WhereExplainOneScan(
  113345. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  113346. );
  113347. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  113348. /* This is the sub-WHERE clause body. First skip over
  113349. ** duplicate rows from prior sub-WHERE clauses, and record the
  113350. ** rowid (or PRIMARY KEY) for the current row so that the same
  113351. ** row will be skipped in subsequent sub-WHERE clauses.
  113352. */
  113353. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  113354. int r;
  113355. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  113356. if( HasRowid(pTab) ){
  113357. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  113358. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  113359. r,iSet);
  113360. VdbeCoverage(v);
  113361. }else{
  113362. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  113363. int nPk = pPk->nKeyCol;
  113364. int iPk;
  113365. /* Read the PK into an array of temp registers. */
  113366. r = sqlite3GetTempRange(pParse, nPk);
  113367. for(iPk=0; iPk<nPk; iPk++){
  113368. int iCol = pPk->aiColumn[iPk];
  113369. sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
  113370. }
  113371. /* Check if the temp table already contains this key. If so,
  113372. ** the row has already been included in the result set and
  113373. ** can be ignored (by jumping past the Gosub below). Otherwise,
  113374. ** insert the key into the temp table and proceed with processing
  113375. ** the row.
  113376. **
  113377. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  113378. ** is zero, assume that the key cannot already be present in
  113379. ** the temp table. And if iSet is -1, assume that there is no
  113380. ** need to insert the key into the temp table, as it will never
  113381. ** be tested for. */
  113382. if( iSet ){
  113383. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  113384. VdbeCoverage(v);
  113385. }
  113386. if( iSet>=0 ){
  113387. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  113388. sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
  113389. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  113390. }
  113391. /* Release the array of temp registers */
  113392. sqlite3ReleaseTempRange(pParse, r, nPk);
  113393. }
  113394. }
  113395. /* Invoke the main loop body as a subroutine */
  113396. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  113397. /* Jump here (skipping the main loop body subroutine) if the
  113398. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  113399. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  113400. /* The pSubWInfo->untestedTerms flag means that this OR term
  113401. ** contained one or more AND term from a notReady table. The
  113402. ** terms from the notReady table could not be tested and will
  113403. ** need to be tested later.
  113404. */
  113405. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  113406. /* If all of the OR-connected terms are optimized using the same
  113407. ** index, and the index is opened using the same cursor number
  113408. ** by each call to sqlite3WhereBegin() made by this loop, it may
  113409. ** be possible to use that index as a covering index.
  113410. **
  113411. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  113412. ** uses an index, and this is either the first OR-connected term
  113413. ** processed or the index is the same as that used by all previous
  113414. ** terms, set pCov to the candidate covering index. Otherwise, set
  113415. ** pCov to NULL to indicate that no candidate covering index will
  113416. ** be available.
  113417. */
  113418. pSubLoop = pSubWInfo->a[0].pWLoop;
  113419. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  113420. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  113421. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  113422. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  113423. ){
  113424. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  113425. pCov = pSubLoop->u.btree.pIndex;
  113426. wctrlFlags |= WHERE_REOPEN_IDX;
  113427. }else{
  113428. pCov = 0;
  113429. }
  113430. /* Finish the loop through table entries that match term pOrTerm. */
  113431. sqlite3WhereEnd(pSubWInfo);
  113432. }
  113433. }
  113434. }
  113435. pLevel->u.pCovidx = pCov;
  113436. if( pCov ) pLevel->iIdxCur = iCovCur;
  113437. if( pAndExpr ){
  113438. pAndExpr->pLeft = 0;
  113439. sqlite3ExprDelete(db, pAndExpr);
  113440. }
  113441. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  113442. sqlite3VdbeGoto(v, pLevel->addrBrk);
  113443. sqlite3VdbeResolveLabel(v, iLoopBody);
  113444. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  113445. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  113446. }else
  113447. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  113448. {
  113449. /* Case 6: There is no usable index. We must do a complete
  113450. ** scan of the entire table.
  113451. */
  113452. static const u8 aStep[] = { OP_Next, OP_Prev };
  113453. static const u8 aStart[] = { OP_Rewind, OP_Last };
  113454. assert( bRev==0 || bRev==1 );
  113455. if( pTabItem->fg.isRecursive ){
  113456. /* Tables marked isRecursive have only a single row that is stored in
  113457. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  113458. pLevel->op = OP_Noop;
  113459. }else{
  113460. codeCursorHint(pWInfo, pLevel, 0);
  113461. pLevel->op = aStep[bRev];
  113462. pLevel->p1 = iCur;
  113463. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  113464. VdbeCoverageIf(v, bRev==0);
  113465. VdbeCoverageIf(v, bRev!=0);
  113466. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  113467. }
  113468. }
  113469. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  113470. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  113471. #endif
  113472. /* Insert code to test every subexpression that can be completely
  113473. ** computed using the current set of tables.
  113474. */
  113475. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  113476. Expr *pE;
  113477. int skipLikeAddr = 0;
  113478. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  113479. testcase( pTerm->wtFlags & TERM_CODED );
  113480. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  113481. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  113482. testcase( pWInfo->untestedTerms==0
  113483. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  113484. pWInfo->untestedTerms = 1;
  113485. continue;
  113486. }
  113487. pE = pTerm->pExpr;
  113488. assert( pE!=0 );
  113489. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  113490. continue;
  113491. }
  113492. if( pTerm->wtFlags & TERM_LIKECOND ){
  113493. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  113494. continue;
  113495. #else
  113496. assert( pLevel->iLikeRepCntr>0 );
  113497. skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
  113498. VdbeCoverage(v);
  113499. #endif
  113500. }
  113501. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  113502. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  113503. pTerm->wtFlags |= TERM_CODED;
  113504. }
  113505. /* Insert code to test for implied constraints based on transitivity
  113506. ** of the "==" operator.
  113507. **
  113508. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  113509. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  113510. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  113511. ** the implied "t1.a=123" constraint.
  113512. */
  113513. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  113514. Expr *pE, *pEAlt;
  113515. WhereTerm *pAlt;
  113516. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  113517. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  113518. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  113519. if( pTerm->leftCursor!=iCur ) continue;
  113520. if( pLevel->iLeftJoin ) continue;
  113521. pE = pTerm->pExpr;
  113522. assert( !ExprHasProperty(pE, EP_FromJoin) );
  113523. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  113524. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  113525. WO_EQ|WO_IN|WO_IS, 0);
  113526. if( pAlt==0 ) continue;
  113527. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  113528. testcase( pAlt->eOperator & WO_EQ );
  113529. testcase( pAlt->eOperator & WO_IS );
  113530. testcase( pAlt->eOperator & WO_IN );
  113531. VdbeModuleComment((v, "begin transitive constraint"));
  113532. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  113533. if( pEAlt ){
  113534. *pEAlt = *pAlt->pExpr;
  113535. pEAlt->pLeft = pE->pLeft;
  113536. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  113537. sqlite3StackFree(db, pEAlt);
  113538. }
  113539. }
  113540. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  113541. ** at least one row of the right table has matched the left table.
  113542. */
  113543. if( pLevel->iLeftJoin ){
  113544. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  113545. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  113546. VdbeComment((v, "record LEFT JOIN hit"));
  113547. sqlite3ExprCacheClear(pParse);
  113548. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  113549. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  113550. testcase( pTerm->wtFlags & TERM_CODED );
  113551. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  113552. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  113553. assert( pWInfo->untestedTerms );
  113554. continue;
  113555. }
  113556. assert( pTerm->pExpr );
  113557. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  113558. pTerm->wtFlags |= TERM_CODED;
  113559. }
  113560. }
  113561. return pLevel->notReady;
  113562. }
  113563. /************** End of wherecode.c *******************************************/
  113564. /************** Begin file whereexpr.c ***************************************/
  113565. /*
  113566. ** 2015-06-08
  113567. **
  113568. ** The author disclaims copyright to this source code. In place of
  113569. ** a legal notice, here is a blessing:
  113570. **
  113571. ** May you do good and not evil.
  113572. ** May you find forgiveness for yourself and forgive others.
  113573. ** May you share freely, never taking more than you give.
  113574. **
  113575. *************************************************************************
  113576. ** This module contains C code that generates VDBE code used to process
  113577. ** the WHERE clause of SQL statements.
  113578. **
  113579. ** This file was originally part of where.c but was split out to improve
  113580. ** readability and editabiliity. This file contains utility routines for
  113581. ** analyzing Expr objects in the WHERE clause.
  113582. */
  113583. /* #include "sqliteInt.h" */
  113584. /* #include "whereInt.h" */
  113585. /* Forward declarations */
  113586. static void exprAnalyze(SrcList*, WhereClause*, int);
  113587. /*
  113588. ** Deallocate all memory associated with a WhereOrInfo object.
  113589. */
  113590. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  113591. sqlite3WhereClauseClear(&p->wc);
  113592. sqlite3DbFree(db, p);
  113593. }
  113594. /*
  113595. ** Deallocate all memory associated with a WhereAndInfo object.
  113596. */
  113597. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  113598. sqlite3WhereClauseClear(&p->wc);
  113599. sqlite3DbFree(db, p);
  113600. }
  113601. /*
  113602. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  113603. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  113604. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  113605. ** 0 is returned if the new WhereTerm could not be added due to a memory
  113606. ** allocation error. The memory allocation failure will be recorded in
  113607. ** the db->mallocFailed flag so that higher-level functions can detect it.
  113608. **
  113609. ** This routine will increase the size of the pWC->a[] array as necessary.
  113610. **
  113611. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  113612. ** for freeing the expression p is assumed by the WhereClause object pWC.
  113613. ** This is true even if this routine fails to allocate a new WhereTerm.
  113614. **
  113615. ** WARNING: This routine might reallocate the space used to store
  113616. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  113617. ** calling this routine. Such pointers may be reinitialized by referencing
  113618. ** the pWC->a[] array.
  113619. */
  113620. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  113621. WhereTerm *pTerm;
  113622. int idx;
  113623. testcase( wtFlags & TERM_VIRTUAL );
  113624. if( pWC->nTerm>=pWC->nSlot ){
  113625. WhereTerm *pOld = pWC->a;
  113626. sqlite3 *db = pWC->pWInfo->pParse->db;
  113627. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  113628. if( pWC->a==0 ){
  113629. if( wtFlags & TERM_DYNAMIC ){
  113630. sqlite3ExprDelete(db, p);
  113631. }
  113632. pWC->a = pOld;
  113633. return 0;
  113634. }
  113635. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  113636. if( pOld!=pWC->aStatic ){
  113637. sqlite3DbFree(db, pOld);
  113638. }
  113639. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  113640. memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
  113641. }
  113642. pTerm = &pWC->a[idx = pWC->nTerm++];
  113643. if( p && ExprHasProperty(p, EP_Unlikely) ){
  113644. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  113645. }else{
  113646. pTerm->truthProb = 1;
  113647. }
  113648. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  113649. pTerm->wtFlags = wtFlags;
  113650. pTerm->pWC = pWC;
  113651. pTerm->iParent = -1;
  113652. return idx;
  113653. }
  113654. /*
  113655. ** Return TRUE if the given operator is one of the operators that is
  113656. ** allowed for an indexable WHERE clause term. The allowed operators are
  113657. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  113658. */
  113659. static int allowedOp(int op){
  113660. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  113661. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  113662. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  113663. assert( TK_GE==TK_EQ+4 );
  113664. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  113665. }
  113666. /*
  113667. ** Commute a comparison operator. Expressions of the form "X op Y"
  113668. ** are converted into "Y op X".
  113669. **
  113670. ** If left/right precedence rules come into play when determining the
  113671. ** collating sequence, then COLLATE operators are adjusted to ensure
  113672. ** that the collating sequence does not change. For example:
  113673. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  113674. ** the left hand side of a comparison overrides any collation sequence
  113675. ** attached to the right. For the same reason the EP_Collate flag
  113676. ** is not commuted.
  113677. */
  113678. static void exprCommute(Parse *pParse, Expr *pExpr){
  113679. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  113680. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  113681. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  113682. if( expRight==expLeft ){
  113683. /* Either X and Y both have COLLATE operator or neither do */
  113684. if( expRight ){
  113685. /* Both X and Y have COLLATE operators. Make sure X is always
  113686. ** used by clearing the EP_Collate flag from Y. */
  113687. pExpr->pRight->flags &= ~EP_Collate;
  113688. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  113689. /* Neither X nor Y have COLLATE operators, but X has a non-default
  113690. ** collating sequence. So add the EP_Collate marker on X to cause
  113691. ** it to be searched first. */
  113692. pExpr->pLeft->flags |= EP_Collate;
  113693. }
  113694. }
  113695. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  113696. if( pExpr->op>=TK_GT ){
  113697. assert( TK_LT==TK_GT+2 );
  113698. assert( TK_GE==TK_LE+2 );
  113699. assert( TK_GT>TK_EQ );
  113700. assert( TK_GT<TK_LE );
  113701. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  113702. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  113703. }
  113704. }
  113705. /*
  113706. ** Translate from TK_xx operator to WO_xx bitmask.
  113707. */
  113708. static u16 operatorMask(int op){
  113709. u16 c;
  113710. assert( allowedOp(op) );
  113711. if( op==TK_IN ){
  113712. c = WO_IN;
  113713. }else if( op==TK_ISNULL ){
  113714. c = WO_ISNULL;
  113715. }else if( op==TK_IS ){
  113716. c = WO_IS;
  113717. }else{
  113718. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  113719. c = (u16)(WO_EQ<<(op-TK_EQ));
  113720. }
  113721. assert( op!=TK_ISNULL || c==WO_ISNULL );
  113722. assert( op!=TK_IN || c==WO_IN );
  113723. assert( op!=TK_EQ || c==WO_EQ );
  113724. assert( op!=TK_LT || c==WO_LT );
  113725. assert( op!=TK_LE || c==WO_LE );
  113726. assert( op!=TK_GT || c==WO_GT );
  113727. assert( op!=TK_GE || c==WO_GE );
  113728. assert( op!=TK_IS || c==WO_IS );
  113729. return c;
  113730. }
  113731. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  113732. /*
  113733. ** Check to see if the given expression is a LIKE or GLOB operator that
  113734. ** can be optimized using inequality constraints. Return TRUE if it is
  113735. ** so and false if not.
  113736. **
  113737. ** In order for the operator to be optimizible, the RHS must be a string
  113738. ** literal that does not begin with a wildcard. The LHS must be a column
  113739. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  113740. ** that virtual tables cannot participate in the LIKE optimization.) The
  113741. ** collating sequence for the column on the LHS must be appropriate for
  113742. ** the operator.
  113743. */
  113744. static int isLikeOrGlob(
  113745. Parse *pParse, /* Parsing and code generating context */
  113746. Expr *pExpr, /* Test this expression */
  113747. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  113748. int *pisComplete, /* True if the only wildcard is % in the last character */
  113749. int *pnoCase /* True if uppercase is equivalent to lowercase */
  113750. ){
  113751. const char *z = 0; /* String on RHS of LIKE operator */
  113752. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  113753. ExprList *pList; /* List of operands to the LIKE operator */
  113754. int c; /* One character in z[] */
  113755. int cnt; /* Number of non-wildcard prefix characters */
  113756. char wc[3]; /* Wildcard characters */
  113757. sqlite3 *db = pParse->db; /* Database connection */
  113758. sqlite3_value *pVal = 0;
  113759. int op; /* Opcode of pRight */
  113760. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  113761. return 0;
  113762. }
  113763. #ifdef SQLITE_EBCDIC
  113764. if( *pnoCase ) return 0;
  113765. #endif
  113766. pList = pExpr->x.pList;
  113767. pLeft = pList->a[1].pExpr;
  113768. if( pLeft->op!=TK_COLUMN
  113769. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  113770. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  113771. ){
  113772. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  113773. ** be the name of an indexed column with TEXT affinity. */
  113774. return 0;
  113775. }
  113776. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  113777. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  113778. op = pRight->op;
  113779. if( op==TK_VARIABLE ){
  113780. Vdbe *pReprepare = pParse->pReprepare;
  113781. int iCol = pRight->iColumn;
  113782. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  113783. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  113784. z = (char *)sqlite3_value_text(pVal);
  113785. }
  113786. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  113787. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  113788. }else if( op==TK_STRING ){
  113789. z = pRight->u.zToken;
  113790. }
  113791. if( z ){
  113792. cnt = 0;
  113793. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  113794. cnt++;
  113795. }
  113796. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  113797. Expr *pPrefix;
  113798. *pisComplete = c==wc[0] && z[cnt+1]==0;
  113799. pPrefix = sqlite3Expr(db, TK_STRING, z);
  113800. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  113801. *ppPrefix = pPrefix;
  113802. if( op==TK_VARIABLE ){
  113803. Vdbe *v = pParse->pVdbe;
  113804. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  113805. if( *pisComplete && pRight->u.zToken[1] ){
  113806. /* If the rhs of the LIKE expression is a variable, and the current
  113807. ** value of the variable means there is no need to invoke the LIKE
  113808. ** function, then no OP_Variable will be added to the program.
  113809. ** This causes problems for the sqlite3_bind_parameter_name()
  113810. ** API. To work around them, add a dummy OP_Variable here.
  113811. */
  113812. int r1 = sqlite3GetTempReg(pParse);
  113813. sqlite3ExprCodeTarget(pParse, pRight, r1);
  113814. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  113815. sqlite3ReleaseTempReg(pParse, r1);
  113816. }
  113817. }
  113818. }else{
  113819. z = 0;
  113820. }
  113821. }
  113822. sqlite3ValueFree(pVal);
  113823. return (z!=0);
  113824. }
  113825. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  113826. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113827. /*
  113828. ** Check to see if the given expression is of the form
  113829. **
  113830. ** column OP expr
  113831. **
  113832. ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
  113833. ** column of a virtual table.
  113834. **
  113835. ** If it is then return TRUE. If not, return FALSE.
  113836. */
  113837. static int isMatchOfColumn(
  113838. Expr *pExpr, /* Test this expression */
  113839. unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
  113840. ){
  113841. struct Op2 {
  113842. const char *zOp;
  113843. unsigned char eOp2;
  113844. } aOp[] = {
  113845. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  113846. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  113847. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  113848. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  113849. };
  113850. ExprList *pList;
  113851. Expr *pCol; /* Column reference */
  113852. int i;
  113853. if( pExpr->op!=TK_FUNCTION ){
  113854. return 0;
  113855. }
  113856. pList = pExpr->x.pList;
  113857. if( pList==0 || pList->nExpr!=2 ){
  113858. return 0;
  113859. }
  113860. pCol = pList->a[1].pExpr;
  113861. if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
  113862. return 0;
  113863. }
  113864. for(i=0; i<ArraySize(aOp); i++){
  113865. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  113866. *peOp2 = aOp[i].eOp2;
  113867. return 1;
  113868. }
  113869. }
  113870. return 0;
  113871. }
  113872. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  113873. /*
  113874. ** If the pBase expression originated in the ON or USING clause of
  113875. ** a join, then transfer the appropriate markings over to derived.
  113876. */
  113877. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  113878. if( pDerived ){
  113879. pDerived->flags |= pBase->flags & EP_FromJoin;
  113880. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  113881. }
  113882. }
  113883. /*
  113884. ** Mark term iChild as being a child of term iParent
  113885. */
  113886. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  113887. pWC->a[iChild].iParent = iParent;
  113888. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  113889. pWC->a[iParent].nChild++;
  113890. }
  113891. /*
  113892. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  113893. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  113894. ** the number of available subterms, return NULL.
  113895. */
  113896. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  113897. if( pTerm->eOperator!=WO_AND ){
  113898. return N==0 ? pTerm : 0;
  113899. }
  113900. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  113901. return &pTerm->u.pAndInfo->wc.a[N];
  113902. }
  113903. return 0;
  113904. }
  113905. /*
  113906. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  113907. ** two subterms are in disjunction - they are OR-ed together.
  113908. **
  113909. ** If these two terms are both of the form: "A op B" with the same
  113910. ** A and B values but different operators and if the operators are
  113911. ** compatible (if one is = and the other is <, for example) then
  113912. ** add a new virtual AND term to pWC that is the combination of the
  113913. ** two.
  113914. **
  113915. ** Some examples:
  113916. **
  113917. ** x<y OR x=y --> x<=y
  113918. ** x=y OR x=y --> x=y
  113919. ** x<=y OR x<y --> x<=y
  113920. **
  113921. ** The following is NOT generated:
  113922. **
  113923. ** x<y OR x>y --> x!=y
  113924. */
  113925. static void whereCombineDisjuncts(
  113926. SrcList *pSrc, /* the FROM clause */
  113927. WhereClause *pWC, /* The complete WHERE clause */
  113928. WhereTerm *pOne, /* First disjunct */
  113929. WhereTerm *pTwo /* Second disjunct */
  113930. ){
  113931. u16 eOp = pOne->eOperator | pTwo->eOperator;
  113932. sqlite3 *db; /* Database connection (for malloc) */
  113933. Expr *pNew; /* New virtual expression */
  113934. int op; /* Operator for the combined expression */
  113935. int idxNew; /* Index in pWC of the next virtual term */
  113936. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  113937. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  113938. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  113939. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  113940. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  113941. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  113942. if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  113943. if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
  113944. /* If we reach this point, it means the two subterms can be combined */
  113945. if( (eOp & (eOp-1))!=0 ){
  113946. if( eOp & (WO_LT|WO_LE) ){
  113947. eOp = WO_LE;
  113948. }else{
  113949. assert( eOp & (WO_GT|WO_GE) );
  113950. eOp = WO_GE;
  113951. }
  113952. }
  113953. db = pWC->pWInfo->pParse->db;
  113954. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  113955. if( pNew==0 ) return;
  113956. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  113957. pNew->op = op;
  113958. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  113959. exprAnalyze(pSrc, pWC, idxNew);
  113960. }
  113961. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  113962. /*
  113963. ** Analyze a term that consists of two or more OR-connected
  113964. ** subterms. So in:
  113965. **
  113966. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  113967. ** ^^^^^^^^^^^^^^^^^^^^
  113968. **
  113969. ** This routine analyzes terms such as the middle term in the above example.
  113970. ** A WhereOrTerm object is computed and attached to the term under
  113971. ** analysis, regardless of the outcome of the analysis. Hence:
  113972. **
  113973. ** WhereTerm.wtFlags |= TERM_ORINFO
  113974. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  113975. **
  113976. ** The term being analyzed must have two or more of OR-connected subterms.
  113977. ** A single subterm might be a set of AND-connected sub-subterms.
  113978. ** Examples of terms under analysis:
  113979. **
  113980. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  113981. ** (B) x=expr1 OR expr2=x OR x=expr3
  113982. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  113983. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  113984. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  113985. ** (F) x>A OR (x=A AND y>=B)
  113986. **
  113987. ** CASE 1:
  113988. **
  113989. ** If all subterms are of the form T.C=expr for some single column of C and
  113990. ** a single table T (as shown in example B above) then create a new virtual
  113991. ** term that is an equivalent IN expression. In other words, if the term
  113992. ** being analyzed is:
  113993. **
  113994. ** x = expr1 OR expr2 = x OR x = expr3
  113995. **
  113996. ** then create a new virtual term like this:
  113997. **
  113998. ** x IN (expr1,expr2,expr3)
  113999. **
  114000. ** CASE 2:
  114001. **
  114002. ** If there are exactly two disjuncts and one side has x>A and the other side
  114003. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  114004. ** WHERE clause of the form "x>=A". Example:
  114005. **
  114006. ** x>A OR (x=A AND y>B) adds: x>=A
  114007. **
  114008. ** The added conjunct can sometimes be helpful in query planning.
  114009. **
  114010. ** CASE 3:
  114011. **
  114012. ** If all subterms are indexable by a single table T, then set
  114013. **
  114014. ** WhereTerm.eOperator = WO_OR
  114015. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  114016. **
  114017. ** A subterm is "indexable" if it is of the form
  114018. ** "T.C <op> <expr>" where C is any column of table T and
  114019. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  114020. ** A subterm is also indexable if it is an AND of two or more
  114021. ** subsubterms at least one of which is indexable. Indexable AND
  114022. ** subterms have their eOperator set to WO_AND and they have
  114023. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  114024. **
  114025. ** From another point of view, "indexable" means that the subterm could
  114026. ** potentially be used with an index if an appropriate index exists.
  114027. ** This analysis does not consider whether or not the index exists; that
  114028. ** is decided elsewhere. This analysis only looks at whether subterms
  114029. ** appropriate for indexing exist.
  114030. **
  114031. ** All examples A through E above satisfy case 3. But if a term
  114032. ** also satisfies case 1 (such as B) we know that the optimizer will
  114033. ** always prefer case 1, so in that case we pretend that case 3 is not
  114034. ** satisfied.
  114035. **
  114036. ** It might be the case that multiple tables are indexable. For example,
  114037. ** (E) above is indexable on tables P, Q, and R.
  114038. **
  114039. ** Terms that satisfy case 3 are candidates for lookup by using
  114040. ** separate indices to find rowids for each subterm and composing
  114041. ** the union of all rowids using a RowSet object. This is similar
  114042. ** to "bitmap indices" in other database engines.
  114043. **
  114044. ** OTHERWISE:
  114045. **
  114046. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  114047. ** zero. This term is not useful for search.
  114048. */
  114049. static void exprAnalyzeOrTerm(
  114050. SrcList *pSrc, /* the FROM clause */
  114051. WhereClause *pWC, /* the complete WHERE clause */
  114052. int idxTerm /* Index of the OR-term to be analyzed */
  114053. ){
  114054. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  114055. Parse *pParse = pWInfo->pParse; /* Parser context */
  114056. sqlite3 *db = pParse->db; /* Database connection */
  114057. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  114058. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  114059. int i; /* Loop counters */
  114060. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  114061. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  114062. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  114063. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  114064. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  114065. /*
  114066. ** Break the OR clause into its separate subterms. The subterms are
  114067. ** stored in a WhereClause structure containing within the WhereOrInfo
  114068. ** object that is attached to the original OR clause term.
  114069. */
  114070. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  114071. assert( pExpr->op==TK_OR );
  114072. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  114073. if( pOrInfo==0 ) return;
  114074. pTerm->wtFlags |= TERM_ORINFO;
  114075. pOrWc = &pOrInfo->wc;
  114076. sqlite3WhereClauseInit(pOrWc, pWInfo);
  114077. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  114078. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  114079. if( db->mallocFailed ) return;
  114080. assert( pOrWc->nTerm>=2 );
  114081. /*
  114082. ** Compute the set of tables that might satisfy cases 1 or 3.
  114083. */
  114084. indexable = ~(Bitmask)0;
  114085. chngToIN = ~(Bitmask)0;
  114086. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  114087. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  114088. WhereAndInfo *pAndInfo;
  114089. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  114090. chngToIN = 0;
  114091. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  114092. if( pAndInfo ){
  114093. WhereClause *pAndWC;
  114094. WhereTerm *pAndTerm;
  114095. int j;
  114096. Bitmask b = 0;
  114097. pOrTerm->u.pAndInfo = pAndInfo;
  114098. pOrTerm->wtFlags |= TERM_ANDINFO;
  114099. pOrTerm->eOperator = WO_AND;
  114100. pAndWC = &pAndInfo->wc;
  114101. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  114102. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  114103. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  114104. pAndWC->pOuter = pWC;
  114105. testcase( db->mallocFailed );
  114106. if( !db->mallocFailed ){
  114107. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  114108. assert( pAndTerm->pExpr );
  114109. if( allowedOp(pAndTerm->pExpr->op) ){
  114110. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  114111. }
  114112. }
  114113. }
  114114. indexable &= b;
  114115. }
  114116. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  114117. /* Skip this term for now. We revisit it when we process the
  114118. ** corresponding TERM_VIRTUAL term */
  114119. }else{
  114120. Bitmask b;
  114121. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  114122. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  114123. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  114124. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  114125. }
  114126. indexable &= b;
  114127. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  114128. chngToIN = 0;
  114129. }else{
  114130. chngToIN &= b;
  114131. }
  114132. }
  114133. }
  114134. /*
  114135. ** Record the set of tables that satisfy case 3. The set might be
  114136. ** empty.
  114137. */
  114138. pOrInfo->indexable = indexable;
  114139. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  114140. /* For a two-way OR, attempt to implementation case 2.
  114141. */
  114142. if( indexable && pOrWc->nTerm==2 ){
  114143. int iOne = 0;
  114144. WhereTerm *pOne;
  114145. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  114146. int iTwo = 0;
  114147. WhereTerm *pTwo;
  114148. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  114149. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  114150. }
  114151. }
  114152. }
  114153. /*
  114154. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  114155. ** we have to do some additional checking to see if case 1 really
  114156. ** is satisfied.
  114157. **
  114158. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  114159. ** that there is no possibility of transforming the OR clause into an
  114160. ** IN operator because one or more terms in the OR clause contain
  114161. ** something other than == on a column in the single table. The 1-bit
  114162. ** case means that every term of the OR clause is of the form
  114163. ** "table.column=expr" for some single table. The one bit that is set
  114164. ** will correspond to the common table. We still need to check to make
  114165. ** sure the same column is used on all terms. The 2-bit case is when
  114166. ** the all terms are of the form "table1.column=table2.column". It
  114167. ** might be possible to form an IN operator with either table1.column
  114168. ** or table2.column as the LHS if either is common to every term of
  114169. ** the OR clause.
  114170. **
  114171. ** Note that terms of the form "table.column1=table.column2" (the
  114172. ** same table on both sizes of the ==) cannot be optimized.
  114173. */
  114174. if( chngToIN ){
  114175. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  114176. int iColumn = -1; /* Column index on lhs of IN operator */
  114177. int iCursor = -1; /* Table cursor common to all terms */
  114178. int j = 0; /* Loop counter */
  114179. /* Search for a table and column that appears on one side or the
  114180. ** other of the == operator in every subterm. That table and column
  114181. ** will be recorded in iCursor and iColumn. There might not be any
  114182. ** such table and column. Set okToChngToIN if an appropriate table
  114183. ** and column is found but leave okToChngToIN false if not found.
  114184. */
  114185. for(j=0; j<2 && !okToChngToIN; j++){
  114186. pOrTerm = pOrWc->a;
  114187. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  114188. assert( pOrTerm->eOperator & WO_EQ );
  114189. pOrTerm->wtFlags &= ~TERM_OR_OK;
  114190. if( pOrTerm->leftCursor==iCursor ){
  114191. /* This is the 2-bit case and we are on the second iteration and
  114192. ** current term is from the first iteration. So skip this term. */
  114193. assert( j==1 );
  114194. continue;
  114195. }
  114196. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  114197. pOrTerm->leftCursor))==0 ){
  114198. /* This term must be of the form t1.a==t2.b where t2 is in the
  114199. ** chngToIN set but t1 is not. This term will be either preceded
  114200. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  114201. ** and use its inversion. */
  114202. testcase( pOrTerm->wtFlags & TERM_COPIED );
  114203. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  114204. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  114205. continue;
  114206. }
  114207. iColumn = pOrTerm->u.leftColumn;
  114208. iCursor = pOrTerm->leftCursor;
  114209. break;
  114210. }
  114211. if( i<0 ){
  114212. /* No candidate table+column was found. This can only occur
  114213. ** on the second iteration */
  114214. assert( j==1 );
  114215. assert( IsPowerOfTwo(chngToIN) );
  114216. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  114217. break;
  114218. }
  114219. testcase( j==1 );
  114220. /* We have found a candidate table and column. Check to see if that
  114221. ** table and column is common to every term in the OR clause */
  114222. okToChngToIN = 1;
  114223. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  114224. assert( pOrTerm->eOperator & WO_EQ );
  114225. if( pOrTerm->leftCursor!=iCursor ){
  114226. pOrTerm->wtFlags &= ~TERM_OR_OK;
  114227. }else if( pOrTerm->u.leftColumn!=iColumn ){
  114228. okToChngToIN = 0;
  114229. }else{
  114230. int affLeft, affRight;
  114231. /* If the right-hand side is also a column, then the affinities
  114232. ** of both right and left sides must be such that no type
  114233. ** conversions are required on the right. (Ticket #2249)
  114234. */
  114235. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  114236. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  114237. if( affRight!=0 && affRight!=affLeft ){
  114238. okToChngToIN = 0;
  114239. }else{
  114240. pOrTerm->wtFlags |= TERM_OR_OK;
  114241. }
  114242. }
  114243. }
  114244. }
  114245. /* At this point, okToChngToIN is true if original pTerm satisfies
  114246. ** case 1. In that case, construct a new virtual term that is
  114247. ** pTerm converted into an IN operator.
  114248. */
  114249. if( okToChngToIN ){
  114250. Expr *pDup; /* A transient duplicate expression */
  114251. ExprList *pList = 0; /* The RHS of the IN operator */
  114252. Expr *pLeft = 0; /* The LHS of the IN operator */
  114253. Expr *pNew; /* The complete IN operator */
  114254. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  114255. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  114256. assert( pOrTerm->eOperator & WO_EQ );
  114257. assert( pOrTerm->leftCursor==iCursor );
  114258. assert( pOrTerm->u.leftColumn==iColumn );
  114259. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  114260. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  114261. pLeft = pOrTerm->pExpr->pLeft;
  114262. }
  114263. assert( pLeft!=0 );
  114264. pDup = sqlite3ExprDup(db, pLeft, 0);
  114265. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  114266. if( pNew ){
  114267. int idxNew;
  114268. transferJoinMarkings(pNew, pExpr);
  114269. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  114270. pNew->x.pList = pList;
  114271. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  114272. testcase( idxNew==0 );
  114273. exprAnalyze(pSrc, pWC, idxNew);
  114274. pTerm = &pWC->a[idxTerm];
  114275. markTermAsChild(pWC, idxNew, idxTerm);
  114276. }else{
  114277. sqlite3ExprListDelete(db, pList);
  114278. }
  114279. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  114280. }
  114281. }
  114282. }
  114283. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  114284. /*
  114285. ** We already know that pExpr is a binary operator where both operands are
  114286. ** column references. This routine checks to see if pExpr is an equivalence
  114287. ** relation:
  114288. ** 1. The SQLITE_Transitive optimization must be enabled
  114289. ** 2. Must be either an == or an IS operator
  114290. ** 3. Not originating in the ON clause of an OUTER JOIN
  114291. ** 4. The affinities of A and B must be compatible
  114292. ** 5a. Both operands use the same collating sequence OR
  114293. ** 5b. The overall collating sequence is BINARY
  114294. ** If this routine returns TRUE, that means that the RHS can be substituted
  114295. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  114296. ** This is an optimization. No harm comes from returning 0. But if 1 is
  114297. ** returned when it should not be, then incorrect answers might result.
  114298. */
  114299. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  114300. char aff1, aff2;
  114301. CollSeq *pColl;
  114302. const char *zColl1, *zColl2;
  114303. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  114304. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  114305. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  114306. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  114307. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  114308. if( aff1!=aff2
  114309. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  114310. ){
  114311. return 0;
  114312. }
  114313. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  114314. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  114315. pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  114316. /* Since pLeft and pRight are both a column references, their collating
  114317. ** sequence should always be defined. */
  114318. zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
  114319. pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  114320. zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
  114321. return sqlite3StrICmp(zColl1, zColl2)==0;
  114322. }
  114323. /*
  114324. ** Recursively walk the expressions of a SELECT statement and generate
  114325. ** a bitmask indicating which tables are used in that expression
  114326. ** tree.
  114327. */
  114328. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  114329. Bitmask mask = 0;
  114330. while( pS ){
  114331. SrcList *pSrc = pS->pSrc;
  114332. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  114333. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  114334. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  114335. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  114336. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  114337. if( ALWAYS(pSrc!=0) ){
  114338. int i;
  114339. for(i=0; i<pSrc->nSrc; i++){
  114340. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  114341. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  114342. }
  114343. }
  114344. pS = pS->pPrior;
  114345. }
  114346. return mask;
  114347. }
  114348. /*
  114349. ** Expression pExpr is one operand of a comparison operator that might
  114350. ** be useful for indexing. This routine checks to see if pExpr appears
  114351. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  114352. ** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor
  114353. ** number of the table that is indexed and *piColumn to the column number
  114354. ** of the column that is indexed, or -2 if an expression is being indexed.
  114355. **
  114356. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  114357. ** true even if that particular column is not indexed, because the column
  114358. ** might be added to an automatic index later.
  114359. */
  114360. static int exprMightBeIndexed(
  114361. SrcList *pFrom, /* The FROM clause */
  114362. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  114363. Expr *pExpr, /* An operand of a comparison operator */
  114364. int *piCur, /* Write the referenced table cursor number here */
  114365. int *piColumn /* Write the referenced table column number here */
  114366. ){
  114367. Index *pIdx;
  114368. int i;
  114369. int iCur;
  114370. if( pExpr->op==TK_COLUMN ){
  114371. *piCur = pExpr->iTable;
  114372. *piColumn = pExpr->iColumn;
  114373. return 1;
  114374. }
  114375. if( mPrereq==0 ) return 0; /* No table references */
  114376. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  114377. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  114378. iCur = pFrom->a[i].iCursor;
  114379. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  114380. if( pIdx->aColExpr==0 ) continue;
  114381. for(i=0; i<pIdx->nKeyCol; i++){
  114382. if( pIdx->aiColumn[i]!=(-2) ) continue;
  114383. if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  114384. *piCur = iCur;
  114385. *piColumn = -2;
  114386. return 1;
  114387. }
  114388. }
  114389. }
  114390. return 0;
  114391. }
  114392. /*
  114393. ** The input to this routine is an WhereTerm structure with only the
  114394. ** "pExpr" field filled in. The job of this routine is to analyze the
  114395. ** subexpression and populate all the other fields of the WhereTerm
  114396. ** structure.
  114397. **
  114398. ** If the expression is of the form "<expr> <op> X" it gets commuted
  114399. ** to the standard form of "X <op> <expr>".
  114400. **
  114401. ** If the expression is of the form "X <op> Y" where both X and Y are
  114402. ** columns, then the original expression is unchanged and a new virtual
  114403. ** term of the form "Y <op> X" is added to the WHERE clause and
  114404. ** analyzed separately. The original term is marked with TERM_COPIED
  114405. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  114406. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  114407. ** is a commuted copy of a prior term.) The original term has nChild=1
  114408. ** and the copy has idxParent set to the index of the original term.
  114409. */
  114410. static void exprAnalyze(
  114411. SrcList *pSrc, /* the FROM clause */
  114412. WhereClause *pWC, /* the WHERE clause */
  114413. int idxTerm /* Index of the term to be analyzed */
  114414. ){
  114415. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  114416. WhereTerm *pTerm; /* The term to be analyzed */
  114417. WhereMaskSet *pMaskSet; /* Set of table index masks */
  114418. Expr *pExpr; /* The expression to be analyzed */
  114419. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  114420. Bitmask prereqAll; /* Prerequesites of pExpr */
  114421. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  114422. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  114423. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  114424. int noCase = 0; /* uppercase equivalent to lowercase */
  114425. int op; /* Top-level operator. pExpr->op */
  114426. Parse *pParse = pWInfo->pParse; /* Parsing context */
  114427. sqlite3 *db = pParse->db; /* Database connection */
  114428. unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
  114429. if( db->mallocFailed ){
  114430. return;
  114431. }
  114432. pTerm = &pWC->a[idxTerm];
  114433. pMaskSet = &pWInfo->sMaskSet;
  114434. pExpr = pTerm->pExpr;
  114435. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  114436. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  114437. op = pExpr->op;
  114438. if( op==TK_IN ){
  114439. assert( pExpr->pRight==0 );
  114440. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  114441. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  114442. }else{
  114443. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  114444. }
  114445. }else if( op==TK_ISNULL ){
  114446. pTerm->prereqRight = 0;
  114447. }else{
  114448. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  114449. }
  114450. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  114451. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  114452. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  114453. prereqAll |= x;
  114454. extraRight = x-1; /* ON clause terms may not be used with an index
  114455. ** on left table of a LEFT JOIN. Ticket #3015 */
  114456. }
  114457. pTerm->prereqAll = prereqAll;
  114458. pTerm->leftCursor = -1;
  114459. pTerm->iParent = -1;
  114460. pTerm->eOperator = 0;
  114461. if( allowedOp(op) ){
  114462. int iCur, iColumn;
  114463. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  114464. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  114465. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  114466. if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
  114467. pTerm->leftCursor = iCur;
  114468. pTerm->u.leftColumn = iColumn;
  114469. pTerm->eOperator = operatorMask(op) & opMask;
  114470. }
  114471. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  114472. if( pRight
  114473. && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
  114474. ){
  114475. WhereTerm *pNew;
  114476. Expr *pDup;
  114477. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  114478. if( pTerm->leftCursor>=0 ){
  114479. int idxNew;
  114480. pDup = sqlite3ExprDup(db, pExpr, 0);
  114481. if( db->mallocFailed ){
  114482. sqlite3ExprDelete(db, pDup);
  114483. return;
  114484. }
  114485. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  114486. if( idxNew==0 ) return;
  114487. pNew = &pWC->a[idxNew];
  114488. markTermAsChild(pWC, idxNew, idxTerm);
  114489. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  114490. pTerm = &pWC->a[idxTerm];
  114491. pTerm->wtFlags |= TERM_COPIED;
  114492. if( termIsEquivalence(pParse, pDup) ){
  114493. pTerm->eOperator |= WO_EQUIV;
  114494. eExtraOp = WO_EQUIV;
  114495. }
  114496. }else{
  114497. pDup = pExpr;
  114498. pNew = pTerm;
  114499. }
  114500. exprCommute(pParse, pDup);
  114501. pNew->leftCursor = iCur;
  114502. pNew->u.leftColumn = iColumn;
  114503. testcase( (prereqLeft | extraRight) != prereqLeft );
  114504. pNew->prereqRight = prereqLeft | extraRight;
  114505. pNew->prereqAll = prereqAll;
  114506. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  114507. }
  114508. }
  114509. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  114510. /* If a term is the BETWEEN operator, create two new virtual terms
  114511. ** that define the range that the BETWEEN implements. For example:
  114512. **
  114513. ** a BETWEEN b AND c
  114514. **
  114515. ** is converted into:
  114516. **
  114517. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  114518. **
  114519. ** The two new terms are added onto the end of the WhereClause object.
  114520. ** The new terms are "dynamic" and are children of the original BETWEEN
  114521. ** term. That means that if the BETWEEN term is coded, the children are
  114522. ** skipped. Or, if the children are satisfied by an index, the original
  114523. ** BETWEEN term is skipped.
  114524. */
  114525. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  114526. ExprList *pList = pExpr->x.pList;
  114527. int i;
  114528. static const u8 ops[] = {TK_GE, TK_LE};
  114529. assert( pList!=0 );
  114530. assert( pList->nExpr==2 );
  114531. for(i=0; i<2; i++){
  114532. Expr *pNewExpr;
  114533. int idxNew;
  114534. pNewExpr = sqlite3PExpr(pParse, ops[i],
  114535. sqlite3ExprDup(db, pExpr->pLeft, 0),
  114536. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  114537. transferJoinMarkings(pNewExpr, pExpr);
  114538. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  114539. testcase( idxNew==0 );
  114540. exprAnalyze(pSrc, pWC, idxNew);
  114541. pTerm = &pWC->a[idxTerm];
  114542. markTermAsChild(pWC, idxNew, idxTerm);
  114543. }
  114544. }
  114545. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  114546. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  114547. /* Analyze a term that is composed of two or more subterms connected by
  114548. ** an OR operator.
  114549. */
  114550. else if( pExpr->op==TK_OR ){
  114551. assert( pWC->op==TK_AND );
  114552. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  114553. pTerm = &pWC->a[idxTerm];
  114554. }
  114555. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  114556. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  114557. /* Add constraints to reduce the search space on a LIKE or GLOB
  114558. ** operator.
  114559. **
  114560. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  114561. **
  114562. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  114563. **
  114564. ** The last character of the prefix "abc" is incremented to form the
  114565. ** termination condition "abd". If case is not significant (the default
  114566. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  114567. ** bound is made all lowercase so that the bounds also work when comparing
  114568. ** BLOBs.
  114569. */
  114570. if( pWC->op==TK_AND
  114571. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  114572. ){
  114573. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  114574. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  114575. Expr *pNewExpr1;
  114576. Expr *pNewExpr2;
  114577. int idxNew1;
  114578. int idxNew2;
  114579. const char *zCollSeqName; /* Name of collating sequence */
  114580. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  114581. pLeft = pExpr->x.pList->a[1].pExpr;
  114582. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  114583. /* Convert the lower bound to upper-case and the upper bound to
  114584. ** lower-case (upper-case is less than lower-case in ASCII) so that
  114585. ** the range constraints also work for BLOBs
  114586. */
  114587. if( noCase && !pParse->db->mallocFailed ){
  114588. int i;
  114589. char c;
  114590. pTerm->wtFlags |= TERM_LIKE;
  114591. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  114592. pStr1->u.zToken[i] = sqlite3Toupper(c);
  114593. pStr2->u.zToken[i] = sqlite3Tolower(c);
  114594. }
  114595. }
  114596. if( !db->mallocFailed ){
  114597. u8 c, *pC; /* Last character before the first wildcard */
  114598. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  114599. c = *pC;
  114600. if( noCase ){
  114601. /* The point is to increment the last character before the first
  114602. ** wildcard. But if we increment '@', that will push it into the
  114603. ** alphabetic range where case conversions will mess up the
  114604. ** inequality. To avoid this, make sure to also run the full
  114605. ** LIKE on all candidate expressions by clearing the isComplete flag
  114606. */
  114607. if( c=='A'-1 ) isComplete = 0;
  114608. c = sqlite3UpperToLower[c];
  114609. }
  114610. *pC = c + 1;
  114611. }
  114612. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  114613. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  114614. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  114615. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  114616. pStr1, 0);
  114617. transferJoinMarkings(pNewExpr1, pExpr);
  114618. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  114619. testcase( idxNew1==0 );
  114620. exprAnalyze(pSrc, pWC, idxNew1);
  114621. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  114622. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  114623. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  114624. pStr2, 0);
  114625. transferJoinMarkings(pNewExpr2, pExpr);
  114626. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  114627. testcase( idxNew2==0 );
  114628. exprAnalyze(pSrc, pWC, idxNew2);
  114629. pTerm = &pWC->a[idxTerm];
  114630. if( isComplete ){
  114631. markTermAsChild(pWC, idxNew1, idxTerm);
  114632. markTermAsChild(pWC, idxNew2, idxTerm);
  114633. }
  114634. }
  114635. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  114636. #ifndef SQLITE_OMIT_VIRTUALTABLE
  114637. /* Add a WO_MATCH auxiliary term to the constraint set if the
  114638. ** current expression is of the form: column MATCH expr.
  114639. ** This information is used by the xBestIndex methods of
  114640. ** virtual tables. The native query optimizer does not attempt
  114641. ** to do anything with MATCH functions.
  114642. */
  114643. if( isMatchOfColumn(pExpr, &eOp2) ){
  114644. int idxNew;
  114645. Expr *pRight, *pLeft;
  114646. WhereTerm *pNewTerm;
  114647. Bitmask prereqColumn, prereqExpr;
  114648. pRight = pExpr->x.pList->a[0].pExpr;
  114649. pLeft = pExpr->x.pList->a[1].pExpr;
  114650. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  114651. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  114652. if( (prereqExpr & prereqColumn)==0 ){
  114653. Expr *pNewExpr;
  114654. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  114655. 0, sqlite3ExprDup(db, pRight, 0), 0);
  114656. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  114657. testcase( idxNew==0 );
  114658. pNewTerm = &pWC->a[idxNew];
  114659. pNewTerm->prereqRight = prereqExpr;
  114660. pNewTerm->leftCursor = pLeft->iTable;
  114661. pNewTerm->u.leftColumn = pLeft->iColumn;
  114662. pNewTerm->eOperator = WO_MATCH;
  114663. pNewTerm->eMatchOp = eOp2;
  114664. markTermAsChild(pWC, idxNew, idxTerm);
  114665. pTerm = &pWC->a[idxTerm];
  114666. pTerm->wtFlags |= TERM_COPIED;
  114667. pNewTerm->prereqAll = pTerm->prereqAll;
  114668. }
  114669. }
  114670. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  114671. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  114672. /* When sqlite_stat3 histogram data is available an operator of the
  114673. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  114674. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  114675. ** virtual term of that form.
  114676. **
  114677. ** Note that the virtual term must be tagged with TERM_VNULL.
  114678. */
  114679. if( pExpr->op==TK_NOTNULL
  114680. && pExpr->pLeft->op==TK_COLUMN
  114681. && pExpr->pLeft->iColumn>=0
  114682. && OptimizationEnabled(db, SQLITE_Stat34)
  114683. ){
  114684. Expr *pNewExpr;
  114685. Expr *pLeft = pExpr->pLeft;
  114686. int idxNew;
  114687. WhereTerm *pNewTerm;
  114688. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  114689. sqlite3ExprDup(db, pLeft, 0),
  114690. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  114691. idxNew = whereClauseInsert(pWC, pNewExpr,
  114692. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  114693. if( idxNew ){
  114694. pNewTerm = &pWC->a[idxNew];
  114695. pNewTerm->prereqRight = 0;
  114696. pNewTerm->leftCursor = pLeft->iTable;
  114697. pNewTerm->u.leftColumn = pLeft->iColumn;
  114698. pNewTerm->eOperator = WO_GT;
  114699. markTermAsChild(pWC, idxNew, idxTerm);
  114700. pTerm = &pWC->a[idxTerm];
  114701. pTerm->wtFlags |= TERM_COPIED;
  114702. pNewTerm->prereqAll = pTerm->prereqAll;
  114703. }
  114704. }
  114705. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  114706. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  114707. ** an index for tables to the left of the join.
  114708. */
  114709. pTerm->prereqRight |= extraRight;
  114710. }
  114711. /***************************************************************************
  114712. ** Routines with file scope above. Interface to the rest of the where.c
  114713. ** subsystem follows.
  114714. ***************************************************************************/
  114715. /*
  114716. ** This routine identifies subexpressions in the WHERE clause where
  114717. ** each subexpression is separated by the AND operator or some other
  114718. ** operator specified in the op parameter. The WhereClause structure
  114719. ** is filled with pointers to subexpressions. For example:
  114720. **
  114721. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  114722. ** \________/ \_______________/ \________________/
  114723. ** slot[0] slot[1] slot[2]
  114724. **
  114725. ** The original WHERE clause in pExpr is unaltered. All this routine
  114726. ** does is make slot[] entries point to substructure within pExpr.
  114727. **
  114728. ** In the previous sentence and in the diagram, "slot[]" refers to
  114729. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  114730. ** all terms of the WHERE clause.
  114731. */
  114732. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  114733. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  114734. pWC->op = op;
  114735. if( pE2==0 ) return;
  114736. if( pE2->op!=op ){
  114737. whereClauseInsert(pWC, pExpr, 0);
  114738. }else{
  114739. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  114740. sqlite3WhereSplit(pWC, pE2->pRight, op);
  114741. }
  114742. }
  114743. /*
  114744. ** Initialize a preallocated WhereClause structure.
  114745. */
  114746. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  114747. WhereClause *pWC, /* The WhereClause to be initialized */
  114748. WhereInfo *pWInfo /* The WHERE processing context */
  114749. ){
  114750. pWC->pWInfo = pWInfo;
  114751. pWC->pOuter = 0;
  114752. pWC->nTerm = 0;
  114753. pWC->nSlot = ArraySize(pWC->aStatic);
  114754. pWC->a = pWC->aStatic;
  114755. }
  114756. /*
  114757. ** Deallocate a WhereClause structure. The WhereClause structure
  114758. ** itself is not freed. This routine is the inverse of
  114759. ** sqlite3WhereClauseInit().
  114760. */
  114761. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  114762. int i;
  114763. WhereTerm *a;
  114764. sqlite3 *db = pWC->pWInfo->pParse->db;
  114765. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  114766. if( a->wtFlags & TERM_DYNAMIC ){
  114767. sqlite3ExprDelete(db, a->pExpr);
  114768. }
  114769. if( a->wtFlags & TERM_ORINFO ){
  114770. whereOrInfoDelete(db, a->u.pOrInfo);
  114771. }else if( a->wtFlags & TERM_ANDINFO ){
  114772. whereAndInfoDelete(db, a->u.pAndInfo);
  114773. }
  114774. }
  114775. if( pWC->a!=pWC->aStatic ){
  114776. sqlite3DbFree(db, pWC->a);
  114777. }
  114778. }
  114779. /*
  114780. ** These routines walk (recursively) an expression tree and generate
  114781. ** a bitmask indicating which tables are used in that expression
  114782. ** tree.
  114783. */
  114784. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  114785. Bitmask mask = 0;
  114786. if( p==0 ) return 0;
  114787. if( p->op==TK_COLUMN ){
  114788. mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
  114789. return mask;
  114790. }
  114791. mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
  114792. mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  114793. if( ExprHasProperty(p, EP_xIsSelect) ){
  114794. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  114795. }else{
  114796. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  114797. }
  114798. return mask;
  114799. }
  114800. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  114801. int i;
  114802. Bitmask mask = 0;
  114803. if( pList ){
  114804. for(i=0; i<pList->nExpr; i++){
  114805. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  114806. }
  114807. }
  114808. return mask;
  114809. }
  114810. /*
  114811. ** Call exprAnalyze on all terms in a WHERE clause.
  114812. **
  114813. ** Note that exprAnalyze() might add new virtual terms onto the
  114814. ** end of the WHERE clause. We do not want to analyze these new
  114815. ** virtual terms, so start analyzing at the end and work forward
  114816. ** so that the added virtual terms are never processed.
  114817. */
  114818. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  114819. SrcList *pTabList, /* the FROM clause */
  114820. WhereClause *pWC /* the WHERE clause to be analyzed */
  114821. ){
  114822. int i;
  114823. for(i=pWC->nTerm-1; i>=0; i--){
  114824. exprAnalyze(pTabList, pWC, i);
  114825. }
  114826. }
  114827. /*
  114828. ** For table-valued-functions, transform the function arguments into
  114829. ** new WHERE clause terms.
  114830. **
  114831. ** Each function argument translates into an equality constraint against
  114832. ** a HIDDEN column in the table.
  114833. */
  114834. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  114835. Parse *pParse, /* Parsing context */
  114836. struct SrcList_item *pItem, /* The FROM clause term to process */
  114837. WhereClause *pWC /* Xfer function arguments to here */
  114838. ){
  114839. Table *pTab;
  114840. int j, k;
  114841. ExprList *pArgs;
  114842. Expr *pColRef;
  114843. Expr *pTerm;
  114844. if( pItem->fg.isTabFunc==0 ) return;
  114845. pTab = pItem->pTab;
  114846. assert( pTab!=0 );
  114847. pArgs = pItem->u1.pFuncArg;
  114848. if( pArgs==0 ) return;
  114849. for(j=k=0; j<pArgs->nExpr; j++){
  114850. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  114851. if( k>=pTab->nCol ){
  114852. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  114853. pTab->zName, j);
  114854. return;
  114855. }
  114856. pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
  114857. if( pColRef==0 ) return;
  114858. pColRef->iTable = pItem->iCursor;
  114859. pColRef->iColumn = k++;
  114860. pColRef->pTab = pTab;
  114861. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
  114862. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
  114863. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  114864. }
  114865. }
  114866. /************** End of whereexpr.c *******************************************/
  114867. /************** Begin file where.c *******************************************/
  114868. /*
  114869. ** 2001 September 15
  114870. **
  114871. ** The author disclaims copyright to this source code. In place of
  114872. ** a legal notice, here is a blessing:
  114873. **
  114874. ** May you do good and not evil.
  114875. ** May you find forgiveness for yourself and forgive others.
  114876. ** May you share freely, never taking more than you give.
  114877. **
  114878. *************************************************************************
  114879. ** This module contains C code that generates VDBE code used to process
  114880. ** the WHERE clause of SQL statements. This module is responsible for
  114881. ** generating the code that loops through a table looking for applicable
  114882. ** rows. Indices are selected and used to speed the search when doing
  114883. ** so is applicable. Because this module is responsible for selecting
  114884. ** indices, you might also think of this module as the "query optimizer".
  114885. */
  114886. /* #include "sqliteInt.h" */
  114887. /* #include "whereInt.h" */
  114888. /* Forward declaration of methods */
  114889. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  114890. /* Test variable that can be set to enable WHERE tracing */
  114891. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  114892. /***/ int sqlite3WhereTrace = 0;
  114893. #endif
  114894. /*
  114895. ** Return the estimated number of output rows from a WHERE clause
  114896. */
  114897. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  114898. return sqlite3LogEstToInt(pWInfo->nRowOut);
  114899. }
  114900. /*
  114901. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  114902. ** WHERE clause returns outputs for DISTINCT processing.
  114903. */
  114904. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  114905. return pWInfo->eDistinct;
  114906. }
  114907. /*
  114908. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  114909. ** Return FALSE if the output needs to be sorted.
  114910. */
  114911. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  114912. return pWInfo->nOBSat;
  114913. }
  114914. /*
  114915. ** Return the VDBE address or label to jump to in order to continue
  114916. ** immediately with the next row of a WHERE clause.
  114917. */
  114918. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  114919. assert( pWInfo->iContinue!=0 );
  114920. return pWInfo->iContinue;
  114921. }
  114922. /*
  114923. ** Return the VDBE address or label to jump to in order to break
  114924. ** out of a WHERE loop.
  114925. */
  114926. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  114927. return pWInfo->iBreak;
  114928. }
  114929. /*
  114930. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  114931. ** operate directly on the rowis returned by a WHERE clause. Return
  114932. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  114933. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  114934. ** optimization can be used on multiple
  114935. **
  114936. ** If the ONEPASS optimization is used (if this routine returns true)
  114937. ** then also write the indices of open cursors used by ONEPASS
  114938. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  114939. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  114940. ** Either value may be -1, indicating that cursor is not used.
  114941. ** Any cursors returned will have been opened for writing.
  114942. **
  114943. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  114944. ** unable to use the ONEPASS optimization.
  114945. */
  114946. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  114947. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  114948. #ifdef WHERETRACE_ENABLED
  114949. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  114950. sqlite3DebugPrintf("%s cursors: %d %d\n",
  114951. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  114952. aiCur[0], aiCur[1]);
  114953. }
  114954. #endif
  114955. return pWInfo->eOnePass;
  114956. }
  114957. /*
  114958. ** Move the content of pSrc into pDest
  114959. */
  114960. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  114961. pDest->n = pSrc->n;
  114962. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  114963. }
  114964. /*
  114965. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  114966. **
  114967. ** The new entry might overwrite an existing entry, or it might be
  114968. ** appended, or it might be discarded. Do whatever is the right thing
  114969. ** so that pSet keeps the N_OR_COST best entries seen so far.
  114970. */
  114971. static int whereOrInsert(
  114972. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  114973. Bitmask prereq, /* Prerequisites of the new entry */
  114974. LogEst rRun, /* Run-cost of the new entry */
  114975. LogEst nOut /* Number of outputs for the new entry */
  114976. ){
  114977. u16 i;
  114978. WhereOrCost *p;
  114979. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  114980. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  114981. goto whereOrInsert_done;
  114982. }
  114983. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  114984. return 0;
  114985. }
  114986. }
  114987. if( pSet->n<N_OR_COST ){
  114988. p = &pSet->a[pSet->n++];
  114989. p->nOut = nOut;
  114990. }else{
  114991. p = pSet->a;
  114992. for(i=1; i<pSet->n; i++){
  114993. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  114994. }
  114995. if( p->rRun<=rRun ) return 0;
  114996. }
  114997. whereOrInsert_done:
  114998. p->prereq = prereq;
  114999. p->rRun = rRun;
  115000. if( p->nOut>nOut ) p->nOut = nOut;
  115001. return 1;
  115002. }
  115003. /*
  115004. ** Return the bitmask for the given cursor number. Return 0 if
  115005. ** iCursor is not in the set.
  115006. */
  115007. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  115008. int i;
  115009. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  115010. for(i=0; i<pMaskSet->n; i++){
  115011. if( pMaskSet->ix[i]==iCursor ){
  115012. return MASKBIT(i);
  115013. }
  115014. }
  115015. return 0;
  115016. }
  115017. /*
  115018. ** Create a new mask for cursor iCursor.
  115019. **
  115020. ** There is one cursor per table in the FROM clause. The number of
  115021. ** tables in the FROM clause is limited by a test early in the
  115022. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  115023. ** array will never overflow.
  115024. */
  115025. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  115026. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  115027. pMaskSet->ix[pMaskSet->n++] = iCursor;
  115028. }
  115029. /*
  115030. ** Advance to the next WhereTerm that matches according to the criteria
  115031. ** established when the pScan object was initialized by whereScanInit().
  115032. ** Return NULL if there are no more matching WhereTerms.
  115033. */
  115034. static WhereTerm *whereScanNext(WhereScan *pScan){
  115035. int iCur; /* The cursor on the LHS of the term */
  115036. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  115037. Expr *pX; /* An expression being tested */
  115038. WhereClause *pWC; /* Shorthand for pScan->pWC */
  115039. WhereTerm *pTerm; /* The term being tested */
  115040. int k = pScan->k; /* Where to start scanning */
  115041. while( pScan->iEquiv<=pScan->nEquiv ){
  115042. iCur = pScan->aiCur[pScan->iEquiv-1];
  115043. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  115044. if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
  115045. while( (pWC = pScan->pWC)!=0 ){
  115046. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  115047. if( pTerm->leftCursor==iCur
  115048. && pTerm->u.leftColumn==iColumn
  115049. && (iColumn!=XN_EXPR
  115050. || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
  115051. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  115052. ){
  115053. if( (pTerm->eOperator & WO_EQUIV)!=0
  115054. && pScan->nEquiv<ArraySize(pScan->aiCur)
  115055. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  115056. ){
  115057. int j;
  115058. for(j=0; j<pScan->nEquiv; j++){
  115059. if( pScan->aiCur[j]==pX->iTable
  115060. && pScan->aiColumn[j]==pX->iColumn ){
  115061. break;
  115062. }
  115063. }
  115064. if( j==pScan->nEquiv ){
  115065. pScan->aiCur[j] = pX->iTable;
  115066. pScan->aiColumn[j] = pX->iColumn;
  115067. pScan->nEquiv++;
  115068. }
  115069. }
  115070. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  115071. /* Verify the affinity and collating sequence match */
  115072. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  115073. CollSeq *pColl;
  115074. Parse *pParse = pWC->pWInfo->pParse;
  115075. pX = pTerm->pExpr;
  115076. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  115077. continue;
  115078. }
  115079. assert(pX->pLeft);
  115080. pColl = sqlite3BinaryCompareCollSeq(pParse,
  115081. pX->pLeft, pX->pRight);
  115082. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  115083. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  115084. continue;
  115085. }
  115086. }
  115087. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  115088. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  115089. && pX->iTable==pScan->aiCur[0]
  115090. && pX->iColumn==pScan->aiColumn[0]
  115091. ){
  115092. testcase( pTerm->eOperator & WO_IS );
  115093. continue;
  115094. }
  115095. pScan->k = k+1;
  115096. return pTerm;
  115097. }
  115098. }
  115099. }
  115100. pScan->pWC = pScan->pWC->pOuter;
  115101. k = 0;
  115102. }
  115103. pScan->pWC = pScan->pOrigWC;
  115104. k = 0;
  115105. pScan->iEquiv++;
  115106. }
  115107. return 0;
  115108. }
  115109. /*
  115110. ** Initialize a WHERE clause scanner object. Return a pointer to the
  115111. ** first match. Return NULL if there are no matches.
  115112. **
  115113. ** The scanner will be searching the WHERE clause pWC. It will look
  115114. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  115115. ** iCur. The <op> must be one of the operators described by opMask.
  115116. **
  115117. ** If the search is for X and the WHERE clause contains terms of the
  115118. ** form X=Y then this routine might also return terms of the form
  115119. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  115120. ** but is enough to handle most commonly occurring SQL statements.
  115121. **
  115122. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  115123. ** index pIdx.
  115124. */
  115125. static WhereTerm *whereScanInit(
  115126. WhereScan *pScan, /* The WhereScan object being initialized */
  115127. WhereClause *pWC, /* The WHERE clause to be scanned */
  115128. int iCur, /* Cursor to scan for */
  115129. int iColumn, /* Column to scan for */
  115130. u32 opMask, /* Operator(s) to scan for */
  115131. Index *pIdx /* Must be compatible with this index */
  115132. ){
  115133. int j = 0;
  115134. /* memset(pScan, 0, sizeof(*pScan)); */
  115135. pScan->pOrigWC = pWC;
  115136. pScan->pWC = pWC;
  115137. pScan->pIdxExpr = 0;
  115138. if( pIdx ){
  115139. j = iColumn;
  115140. iColumn = pIdx->aiColumn[j];
  115141. if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  115142. }
  115143. if( pIdx && iColumn>=0 ){
  115144. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  115145. pScan->zCollName = pIdx->azColl[j];
  115146. }else{
  115147. pScan->idxaff = 0;
  115148. pScan->zCollName = 0;
  115149. }
  115150. pScan->opMask = opMask;
  115151. pScan->k = 0;
  115152. pScan->aiCur[0] = iCur;
  115153. pScan->aiColumn[0] = iColumn;
  115154. pScan->nEquiv = 1;
  115155. pScan->iEquiv = 1;
  115156. return whereScanNext(pScan);
  115157. }
  115158. /*
  115159. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  115160. ** where X is a reference to the iColumn of table iCur and <op> is one of
  115161. ** the WO_xx operator codes specified by the op parameter.
  115162. ** Return a pointer to the term. Return 0 if not found.
  115163. **
  115164. ** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
  115165. ** rather than the iColumn-th column of table iCur.
  115166. **
  115167. ** The term returned might by Y=<expr> if there is another constraint in
  115168. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  115169. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  115170. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  115171. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  115172. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  115173. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  115174. **
  115175. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  115176. ** then try for the one with no dependencies on <expr> - in other words where
  115177. ** <expr> is a constant expression of some kind. Only return entries of
  115178. ** the form "X <op> Y" where Y is a column in another table if no terms of
  115179. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  115180. ** exist, try to return a term that does not use WO_EQUIV.
  115181. */
  115182. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  115183. WhereClause *pWC, /* The WHERE clause to be searched */
  115184. int iCur, /* Cursor number of LHS */
  115185. int iColumn, /* Column number of LHS */
  115186. Bitmask notReady, /* RHS must not overlap with this mask */
  115187. u32 op, /* Mask of WO_xx values describing operator */
  115188. Index *pIdx /* Must be compatible with this index, if not NULL */
  115189. ){
  115190. WhereTerm *pResult = 0;
  115191. WhereTerm *p;
  115192. WhereScan scan;
  115193. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  115194. op &= WO_EQ|WO_IS;
  115195. while( p ){
  115196. if( (p->prereqRight & notReady)==0 ){
  115197. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  115198. testcase( p->eOperator & WO_IS );
  115199. return p;
  115200. }
  115201. if( pResult==0 ) pResult = p;
  115202. }
  115203. p = whereScanNext(&scan);
  115204. }
  115205. return pResult;
  115206. }
  115207. /*
  115208. ** This function searches pList for an entry that matches the iCol-th column
  115209. ** of index pIdx.
  115210. **
  115211. ** If such an expression is found, its index in pList->a[] is returned. If
  115212. ** no expression is found, -1 is returned.
  115213. */
  115214. static int findIndexCol(
  115215. Parse *pParse, /* Parse context */
  115216. ExprList *pList, /* Expression list to search */
  115217. int iBase, /* Cursor for table associated with pIdx */
  115218. Index *pIdx, /* Index to match column of */
  115219. int iCol /* Column of index to match */
  115220. ){
  115221. int i;
  115222. const char *zColl = pIdx->azColl[iCol];
  115223. for(i=0; i<pList->nExpr; i++){
  115224. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  115225. if( p->op==TK_COLUMN
  115226. && p->iColumn==pIdx->aiColumn[iCol]
  115227. && p->iTable==iBase
  115228. ){
  115229. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  115230. if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  115231. return i;
  115232. }
  115233. }
  115234. }
  115235. return -1;
  115236. }
  115237. /*
  115238. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  115239. */
  115240. static int indexColumnNotNull(Index *pIdx, int iCol){
  115241. int j;
  115242. assert( pIdx!=0 );
  115243. assert( iCol>=0 && iCol<pIdx->nColumn );
  115244. j = pIdx->aiColumn[iCol];
  115245. if( j>=0 ){
  115246. return pIdx->pTable->aCol[j].notNull;
  115247. }else if( j==(-1) ){
  115248. return 1;
  115249. }else{
  115250. assert( j==(-2) );
  115251. return 0; /* Assume an indexed expression can always yield a NULL */
  115252. }
  115253. }
  115254. /*
  115255. ** Return true if the DISTINCT expression-list passed as the third argument
  115256. ** is redundant.
  115257. **
  115258. ** A DISTINCT list is redundant if any subset of the columns in the
  115259. ** DISTINCT list are collectively unique and individually non-null.
  115260. */
  115261. static int isDistinctRedundant(
  115262. Parse *pParse, /* Parsing context */
  115263. SrcList *pTabList, /* The FROM clause */
  115264. WhereClause *pWC, /* The WHERE clause */
  115265. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  115266. ){
  115267. Table *pTab;
  115268. Index *pIdx;
  115269. int i;
  115270. int iBase;
  115271. /* If there is more than one table or sub-select in the FROM clause of
  115272. ** this query, then it will not be possible to show that the DISTINCT
  115273. ** clause is redundant. */
  115274. if( pTabList->nSrc!=1 ) return 0;
  115275. iBase = pTabList->a[0].iCursor;
  115276. pTab = pTabList->a[0].pTab;
  115277. /* If any of the expressions is an IPK column on table iBase, then return
  115278. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  115279. ** current SELECT is a correlated sub-query.
  115280. */
  115281. for(i=0; i<pDistinct->nExpr; i++){
  115282. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  115283. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  115284. }
  115285. /* Loop through all indices on the table, checking each to see if it makes
  115286. ** the DISTINCT qualifier redundant. It does so if:
  115287. **
  115288. ** 1. The index is itself UNIQUE, and
  115289. **
  115290. ** 2. All of the columns in the index are either part of the pDistinct
  115291. ** list, or else the WHERE clause contains a term of the form "col=X",
  115292. ** where X is a constant value. The collation sequences of the
  115293. ** comparison and select-list expressions must match those of the index.
  115294. **
  115295. ** 3. All of those index columns for which the WHERE clause does not
  115296. ** contain a "col=X" term are subject to a NOT NULL constraint.
  115297. */
  115298. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  115299. if( !IsUniqueIndex(pIdx) ) continue;
  115300. for(i=0; i<pIdx->nKeyCol; i++){
  115301. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  115302. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  115303. if( indexColumnNotNull(pIdx, i)==0 ) break;
  115304. }
  115305. }
  115306. if( i==pIdx->nKeyCol ){
  115307. /* This index implies that the DISTINCT qualifier is redundant. */
  115308. return 1;
  115309. }
  115310. }
  115311. return 0;
  115312. }
  115313. /*
  115314. ** Estimate the logarithm of the input value to base 2.
  115315. */
  115316. static LogEst estLog(LogEst N){
  115317. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  115318. }
  115319. /*
  115320. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  115321. **
  115322. ** This routine runs over generated VDBE code and translates OP_Column
  115323. ** opcodes into OP_Copy when the table is being accessed via co-routine
  115324. ** instead of via table lookup.
  115325. **
  115326. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  115327. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  115328. ** then each OP_Rowid is transformed into an instruction to increment the
  115329. ** value stored in its output register.
  115330. */
  115331. static void translateColumnToCopy(
  115332. Vdbe *v, /* The VDBE containing code to translate */
  115333. int iStart, /* Translate from this opcode to the end */
  115334. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  115335. int iRegister, /* The first column is in this register */
  115336. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  115337. ){
  115338. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  115339. int iEnd = sqlite3VdbeCurrentAddr(v);
  115340. for(; iStart<iEnd; iStart++, pOp++){
  115341. if( pOp->p1!=iTabCur ) continue;
  115342. if( pOp->opcode==OP_Column ){
  115343. pOp->opcode = OP_Copy;
  115344. pOp->p1 = pOp->p2 + iRegister;
  115345. pOp->p2 = pOp->p3;
  115346. pOp->p3 = 0;
  115347. }else if( pOp->opcode==OP_Rowid ){
  115348. if( bIncrRowid ){
  115349. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  115350. pOp->opcode = OP_AddImm;
  115351. pOp->p1 = pOp->p2;
  115352. pOp->p2 = 1;
  115353. }else{
  115354. pOp->opcode = OP_Null;
  115355. pOp->p1 = 0;
  115356. pOp->p3 = 0;
  115357. }
  115358. }
  115359. }
  115360. }
  115361. /*
  115362. ** Two routines for printing the content of an sqlite3_index_info
  115363. ** structure. Used for testing and debugging only. If neither
  115364. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  115365. ** are no-ops.
  115366. */
  115367. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  115368. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  115369. int i;
  115370. if( !sqlite3WhereTrace ) return;
  115371. for(i=0; i<p->nConstraint; i++){
  115372. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  115373. i,
  115374. p->aConstraint[i].iColumn,
  115375. p->aConstraint[i].iTermOffset,
  115376. p->aConstraint[i].op,
  115377. p->aConstraint[i].usable);
  115378. }
  115379. for(i=0; i<p->nOrderBy; i++){
  115380. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  115381. i,
  115382. p->aOrderBy[i].iColumn,
  115383. p->aOrderBy[i].desc);
  115384. }
  115385. }
  115386. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  115387. int i;
  115388. if( !sqlite3WhereTrace ) return;
  115389. for(i=0; i<p->nConstraint; i++){
  115390. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  115391. i,
  115392. p->aConstraintUsage[i].argvIndex,
  115393. p->aConstraintUsage[i].omit);
  115394. }
  115395. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  115396. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  115397. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  115398. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  115399. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  115400. }
  115401. #else
  115402. #define TRACE_IDX_INPUTS(A)
  115403. #define TRACE_IDX_OUTPUTS(A)
  115404. #endif
  115405. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  115406. /*
  115407. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  115408. ** could be used with an index to access pSrc, assuming an appropriate
  115409. ** index existed.
  115410. */
  115411. static int termCanDriveIndex(
  115412. WhereTerm *pTerm, /* WHERE clause term to check */
  115413. struct SrcList_item *pSrc, /* Table we are trying to access */
  115414. Bitmask notReady /* Tables in outer loops of the join */
  115415. ){
  115416. char aff;
  115417. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  115418. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  115419. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  115420. if( pTerm->u.leftColumn<0 ) return 0;
  115421. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  115422. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  115423. testcase( pTerm->pExpr->op==TK_IS );
  115424. return 1;
  115425. }
  115426. #endif
  115427. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  115428. /*
  115429. ** Generate code to construct the Index object for an automatic index
  115430. ** and to set up the WhereLevel object pLevel so that the code generator
  115431. ** makes use of the automatic index.
  115432. */
  115433. static void constructAutomaticIndex(
  115434. Parse *pParse, /* The parsing context */
  115435. WhereClause *pWC, /* The WHERE clause */
  115436. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  115437. Bitmask notReady, /* Mask of cursors that are not available */
  115438. WhereLevel *pLevel /* Write new index here */
  115439. ){
  115440. int nKeyCol; /* Number of columns in the constructed index */
  115441. WhereTerm *pTerm; /* A single term of the WHERE clause */
  115442. WhereTerm *pWCEnd; /* End of pWC->a[] */
  115443. Index *pIdx; /* Object describing the transient index */
  115444. Vdbe *v; /* Prepared statement under construction */
  115445. int addrInit; /* Address of the initialization bypass jump */
  115446. Table *pTable; /* The table being indexed */
  115447. int addrTop; /* Top of the index fill loop */
  115448. int regRecord; /* Register holding an index record */
  115449. int n; /* Column counter */
  115450. int i; /* Loop counter */
  115451. int mxBitCol; /* Maximum column in pSrc->colUsed */
  115452. CollSeq *pColl; /* Collating sequence to on a column */
  115453. WhereLoop *pLoop; /* The Loop object */
  115454. char *zNotUsed; /* Extra space on the end of pIdx */
  115455. Bitmask idxCols; /* Bitmap of columns used for indexing */
  115456. Bitmask extraCols; /* Bitmap of additional columns */
  115457. u8 sentWarning = 0; /* True if a warnning has been issued */
  115458. Expr *pPartial = 0; /* Partial Index Expression */
  115459. int iContinue = 0; /* Jump here to skip excluded rows */
  115460. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  115461. int addrCounter = 0; /* Address where integer counter is initialized */
  115462. int regBase; /* Array of registers where record is assembled */
  115463. /* Generate code to skip over the creation and initialization of the
  115464. ** transient index on 2nd and subsequent iterations of the loop. */
  115465. v = pParse->pVdbe;
  115466. assert( v!=0 );
  115467. addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  115468. /* Count the number of columns that will be added to the index
  115469. ** and used to match WHERE clause constraints */
  115470. nKeyCol = 0;
  115471. pTable = pSrc->pTab;
  115472. pWCEnd = &pWC->a[pWC->nTerm];
  115473. pLoop = pLevel->pWLoop;
  115474. idxCols = 0;
  115475. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  115476. Expr *pExpr = pTerm->pExpr;
  115477. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  115478. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  115479. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  115480. if( pLoop->prereq==0
  115481. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  115482. && !ExprHasProperty(pExpr, EP_FromJoin)
  115483. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  115484. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  115485. sqlite3ExprDup(pParse->db, pExpr, 0));
  115486. }
  115487. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  115488. int iCol = pTerm->u.leftColumn;
  115489. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  115490. testcase( iCol==BMS );
  115491. testcase( iCol==BMS-1 );
  115492. if( !sentWarning ){
  115493. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  115494. "automatic index on %s(%s)", pTable->zName,
  115495. pTable->aCol[iCol].zName);
  115496. sentWarning = 1;
  115497. }
  115498. if( (idxCols & cMask)==0 ){
  115499. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  115500. goto end_auto_index_create;
  115501. }
  115502. pLoop->aLTerm[nKeyCol++] = pTerm;
  115503. idxCols |= cMask;
  115504. }
  115505. }
  115506. }
  115507. assert( nKeyCol>0 );
  115508. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  115509. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  115510. | WHERE_AUTO_INDEX;
  115511. /* Count the number of additional columns needed to create a
  115512. ** covering index. A "covering index" is an index that contains all
  115513. ** columns that are needed by the query. With a covering index, the
  115514. ** original table never needs to be accessed. Automatic indices must
  115515. ** be a covering index because the index will not be updated if the
  115516. ** original table changes and the index and table cannot both be used
  115517. ** if they go out of sync.
  115518. */
  115519. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  115520. mxBitCol = MIN(BMS-1,pTable->nCol);
  115521. testcase( pTable->nCol==BMS-1 );
  115522. testcase( pTable->nCol==BMS-2 );
  115523. for(i=0; i<mxBitCol; i++){
  115524. if( extraCols & MASKBIT(i) ) nKeyCol++;
  115525. }
  115526. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  115527. nKeyCol += pTable->nCol - BMS + 1;
  115528. }
  115529. /* Construct the Index object to describe this index */
  115530. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  115531. if( pIdx==0 ) goto end_auto_index_create;
  115532. pLoop->u.btree.pIndex = pIdx;
  115533. pIdx->zName = "auto-index";
  115534. pIdx->pTable = pTable;
  115535. n = 0;
  115536. idxCols = 0;
  115537. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  115538. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  115539. int iCol = pTerm->u.leftColumn;
  115540. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  115541. testcase( iCol==BMS-1 );
  115542. testcase( iCol==BMS );
  115543. if( (idxCols & cMask)==0 ){
  115544. Expr *pX = pTerm->pExpr;
  115545. idxCols |= cMask;
  115546. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  115547. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  115548. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  115549. n++;
  115550. }
  115551. }
  115552. }
  115553. assert( (u32)n==pLoop->u.btree.nEq );
  115554. /* Add additional columns needed to make the automatic index into
  115555. ** a covering index */
  115556. for(i=0; i<mxBitCol; i++){
  115557. if( extraCols & MASKBIT(i) ){
  115558. pIdx->aiColumn[n] = i;
  115559. pIdx->azColl[n] = sqlite3StrBINARY;
  115560. n++;
  115561. }
  115562. }
  115563. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  115564. for(i=BMS-1; i<pTable->nCol; i++){
  115565. pIdx->aiColumn[n] = i;
  115566. pIdx->azColl[n] = sqlite3StrBINARY;
  115567. n++;
  115568. }
  115569. }
  115570. assert( n==nKeyCol );
  115571. pIdx->aiColumn[n] = XN_ROWID;
  115572. pIdx->azColl[n] = sqlite3StrBINARY;
  115573. /* Create the automatic index */
  115574. assert( pLevel->iIdxCur>=0 );
  115575. pLevel->iIdxCur = pParse->nTab++;
  115576. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  115577. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  115578. VdbeComment((v, "for %s", pTable->zName));
  115579. /* Fill the automatic index with content */
  115580. sqlite3ExprCachePush(pParse);
  115581. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  115582. if( pTabItem->fg.viaCoroutine ){
  115583. int regYield = pTabItem->regReturn;
  115584. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  115585. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  115586. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  115587. VdbeCoverage(v);
  115588. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  115589. }else{
  115590. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  115591. }
  115592. if( pPartial ){
  115593. iContinue = sqlite3VdbeMakeLabel(v);
  115594. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  115595. pLoop->wsFlags |= WHERE_PARTIALIDX;
  115596. }
  115597. regRecord = sqlite3GetTempReg(pParse);
  115598. regBase = sqlite3GenerateIndexKey(
  115599. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  115600. );
  115601. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  115602. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  115603. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  115604. if( pTabItem->fg.viaCoroutine ){
  115605. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  115606. translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
  115607. sqlite3VdbeGoto(v, addrTop);
  115608. pTabItem->fg.viaCoroutine = 0;
  115609. }else{
  115610. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  115611. }
  115612. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  115613. sqlite3VdbeJumpHere(v, addrTop);
  115614. sqlite3ReleaseTempReg(pParse, regRecord);
  115615. sqlite3ExprCachePop(pParse);
  115616. /* Jump here when skipping the initialization */
  115617. sqlite3VdbeJumpHere(v, addrInit);
  115618. end_auto_index_create:
  115619. sqlite3ExprDelete(pParse->db, pPartial);
  115620. }
  115621. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  115622. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115623. /*
  115624. ** Allocate and populate an sqlite3_index_info structure. It is the
  115625. ** responsibility of the caller to eventually release the structure
  115626. ** by passing the pointer returned by this function to sqlite3_free().
  115627. */
  115628. static sqlite3_index_info *allocateIndexInfo(
  115629. Parse *pParse,
  115630. WhereClause *pWC,
  115631. Bitmask mUnusable, /* Ignore terms with these prereqs */
  115632. struct SrcList_item *pSrc,
  115633. ExprList *pOrderBy
  115634. ){
  115635. int i, j;
  115636. int nTerm;
  115637. struct sqlite3_index_constraint *pIdxCons;
  115638. struct sqlite3_index_orderby *pIdxOrderBy;
  115639. struct sqlite3_index_constraint_usage *pUsage;
  115640. WhereTerm *pTerm;
  115641. int nOrderBy;
  115642. sqlite3_index_info *pIdxInfo;
  115643. /* Count the number of possible WHERE clause constraints referring
  115644. ** to this virtual table */
  115645. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  115646. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  115647. if( pTerm->prereqRight & mUnusable ) continue;
  115648. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  115649. testcase( pTerm->eOperator & WO_IN );
  115650. testcase( pTerm->eOperator & WO_ISNULL );
  115651. testcase( pTerm->eOperator & WO_IS );
  115652. testcase( pTerm->eOperator & WO_ALL );
  115653. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  115654. if( pTerm->wtFlags & TERM_VNULL ) continue;
  115655. assert( pTerm->u.leftColumn>=(-1) );
  115656. nTerm++;
  115657. }
  115658. /* If the ORDER BY clause contains only columns in the current
  115659. ** virtual table then allocate space for the aOrderBy part of
  115660. ** the sqlite3_index_info structure.
  115661. */
  115662. nOrderBy = 0;
  115663. if( pOrderBy ){
  115664. int n = pOrderBy->nExpr;
  115665. for(i=0; i<n; i++){
  115666. Expr *pExpr = pOrderBy->a[i].pExpr;
  115667. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  115668. }
  115669. if( i==n){
  115670. nOrderBy = n;
  115671. }
  115672. }
  115673. /* Allocate the sqlite3_index_info structure
  115674. */
  115675. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  115676. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  115677. + sizeof(*pIdxOrderBy)*nOrderBy );
  115678. if( pIdxInfo==0 ){
  115679. sqlite3ErrorMsg(pParse, "out of memory");
  115680. return 0;
  115681. }
  115682. /* Initialize the structure. The sqlite3_index_info structure contains
  115683. ** many fields that are declared "const" to prevent xBestIndex from
  115684. ** changing them. We have to do some funky casting in order to
  115685. ** initialize those fields.
  115686. */
  115687. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  115688. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  115689. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  115690. *(int*)&pIdxInfo->nConstraint = nTerm;
  115691. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  115692. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  115693. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  115694. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  115695. pUsage;
  115696. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  115697. u8 op;
  115698. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  115699. if( pTerm->prereqRight & mUnusable ) continue;
  115700. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  115701. testcase( pTerm->eOperator & WO_IN );
  115702. testcase( pTerm->eOperator & WO_IS );
  115703. testcase( pTerm->eOperator & WO_ISNULL );
  115704. testcase( pTerm->eOperator & WO_ALL );
  115705. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  115706. if( pTerm->wtFlags & TERM_VNULL ) continue;
  115707. assert( pTerm->u.leftColumn>=(-1) );
  115708. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  115709. pIdxCons[j].iTermOffset = i;
  115710. op = (u8)pTerm->eOperator & WO_ALL;
  115711. if( op==WO_IN ) op = WO_EQ;
  115712. if( op==WO_MATCH ){
  115713. op = pTerm->eMatchOp;
  115714. }
  115715. pIdxCons[j].op = op;
  115716. /* The direct assignment in the previous line is possible only because
  115717. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  115718. ** following asserts verify this fact. */
  115719. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  115720. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  115721. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  115722. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  115723. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  115724. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  115725. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  115726. j++;
  115727. }
  115728. for(i=0; i<nOrderBy; i++){
  115729. Expr *pExpr = pOrderBy->a[i].pExpr;
  115730. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  115731. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  115732. }
  115733. return pIdxInfo;
  115734. }
  115735. /*
  115736. ** The table object reference passed as the second argument to this function
  115737. ** must represent a virtual table. This function invokes the xBestIndex()
  115738. ** method of the virtual table with the sqlite3_index_info object that
  115739. ** comes in as the 3rd argument to this function.
  115740. **
  115741. ** If an error occurs, pParse is populated with an error message and a
  115742. ** non-zero value is returned. Otherwise, 0 is returned and the output
  115743. ** part of the sqlite3_index_info structure is left populated.
  115744. **
  115745. ** Whether or not an error is returned, it is the responsibility of the
  115746. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  115747. ** that this is required.
  115748. */
  115749. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  115750. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  115751. int i;
  115752. int rc;
  115753. TRACE_IDX_INPUTS(p);
  115754. rc = pVtab->pModule->xBestIndex(pVtab, p);
  115755. TRACE_IDX_OUTPUTS(p);
  115756. if( rc!=SQLITE_OK ){
  115757. if( rc==SQLITE_NOMEM ){
  115758. pParse->db->mallocFailed = 1;
  115759. }else if( !pVtab->zErrMsg ){
  115760. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  115761. }else{
  115762. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  115763. }
  115764. }
  115765. sqlite3_free(pVtab->zErrMsg);
  115766. pVtab->zErrMsg = 0;
  115767. for(i=0; i<p->nConstraint; i++){
  115768. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  115769. sqlite3ErrorMsg(pParse,
  115770. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  115771. }
  115772. }
  115773. return pParse->nErr;
  115774. }
  115775. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  115776. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115777. /*
  115778. ** Estimate the location of a particular key among all keys in an
  115779. ** index. Store the results in aStat as follows:
  115780. **
  115781. ** aStat[0] Est. number of rows less than pRec
  115782. ** aStat[1] Est. number of rows equal to pRec
  115783. **
  115784. ** Return the index of the sample that is the smallest sample that
  115785. ** is greater than or equal to pRec. Note that this index is not an index
  115786. ** into the aSample[] array - it is an index into a virtual set of samples
  115787. ** based on the contents of aSample[] and the number of fields in record
  115788. ** pRec.
  115789. */
  115790. static int whereKeyStats(
  115791. Parse *pParse, /* Database connection */
  115792. Index *pIdx, /* Index to consider domain of */
  115793. UnpackedRecord *pRec, /* Vector of values to consider */
  115794. int roundUp, /* Round up if true. Round down if false */
  115795. tRowcnt *aStat /* OUT: stats written here */
  115796. ){
  115797. IndexSample *aSample = pIdx->aSample;
  115798. int iCol; /* Index of required stats in anEq[] etc. */
  115799. int i; /* Index of first sample >= pRec */
  115800. int iSample; /* Smallest sample larger than or equal to pRec */
  115801. int iMin = 0; /* Smallest sample not yet tested */
  115802. int iTest; /* Next sample to test */
  115803. int res; /* Result of comparison operation */
  115804. int nField; /* Number of fields in pRec */
  115805. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  115806. #ifndef SQLITE_DEBUG
  115807. UNUSED_PARAMETER( pParse );
  115808. #endif
  115809. assert( pRec!=0 );
  115810. assert( pIdx->nSample>0 );
  115811. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  115812. /* Do a binary search to find the first sample greater than or equal
  115813. ** to pRec. If pRec contains a single field, the set of samples to search
  115814. ** is simply the aSample[] array. If the samples in aSample[] contain more
  115815. ** than one fields, all fields following the first are ignored.
  115816. **
  115817. ** If pRec contains N fields, where N is more than one, then as well as the
  115818. ** samples in aSample[] (truncated to N fields), the search also has to
  115819. ** consider prefixes of those samples. For example, if the set of samples
  115820. ** in aSample is:
  115821. **
  115822. ** aSample[0] = (a, 5)
  115823. ** aSample[1] = (a, 10)
  115824. ** aSample[2] = (b, 5)
  115825. ** aSample[3] = (c, 100)
  115826. ** aSample[4] = (c, 105)
  115827. **
  115828. ** Then the search space should ideally be the samples above and the
  115829. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  115830. ** the code actually searches this set:
  115831. **
  115832. ** 0: (a)
  115833. ** 1: (a, 5)
  115834. ** 2: (a, 10)
  115835. ** 3: (a, 10)
  115836. ** 4: (b)
  115837. ** 5: (b, 5)
  115838. ** 6: (c)
  115839. ** 7: (c, 100)
  115840. ** 8: (c, 105)
  115841. ** 9: (c, 105)
  115842. **
  115843. ** For each sample in the aSample[] array, N samples are present in the
  115844. ** effective sample array. In the above, samples 0 and 1 are based on
  115845. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  115846. **
  115847. ** Often, sample i of each block of N effective samples has (i+1) fields.
  115848. ** Except, each sample may be extended to ensure that it is greater than or
  115849. ** equal to the previous sample in the array. For example, in the above,
  115850. ** sample 2 is the first sample of a block of N samples, so at first it
  115851. ** appears that it should be 1 field in size. However, that would make it
  115852. ** smaller than sample 1, so the binary search would not work. As a result,
  115853. ** it is extended to two fields. The duplicates that this creates do not
  115854. ** cause any problems.
  115855. */
  115856. nField = pRec->nField;
  115857. iCol = 0;
  115858. iSample = pIdx->nSample * nField;
  115859. do{
  115860. int iSamp; /* Index in aSample[] of test sample */
  115861. int n; /* Number of fields in test sample */
  115862. iTest = (iMin+iSample)/2;
  115863. iSamp = iTest / nField;
  115864. if( iSamp>0 ){
  115865. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  115866. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  115867. ** fields that is greater than the previous effective sample. */
  115868. for(n=(iTest % nField) + 1; n<nField; n++){
  115869. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  115870. }
  115871. }else{
  115872. n = iTest + 1;
  115873. }
  115874. pRec->nField = n;
  115875. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  115876. if( res<0 ){
  115877. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  115878. iMin = iTest+1;
  115879. }else if( res==0 && n<nField ){
  115880. iLower = aSample[iSamp].anLt[n-1];
  115881. iMin = iTest+1;
  115882. res = -1;
  115883. }else{
  115884. iSample = iTest;
  115885. iCol = n-1;
  115886. }
  115887. }while( res && iMin<iSample );
  115888. i = iSample / nField;
  115889. #ifdef SQLITE_DEBUG
  115890. /* The following assert statements check that the binary search code
  115891. ** above found the right answer. This block serves no purpose other
  115892. ** than to invoke the asserts. */
  115893. if( pParse->db->mallocFailed==0 ){
  115894. if( res==0 ){
  115895. /* If (res==0) is true, then pRec must be equal to sample i. */
  115896. assert( i<pIdx->nSample );
  115897. assert( iCol==nField-1 );
  115898. pRec->nField = nField;
  115899. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  115900. || pParse->db->mallocFailed
  115901. );
  115902. }else{
  115903. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  115904. ** all samples in the aSample[] array, pRec must be smaller than the
  115905. ** (iCol+1) field prefix of sample i. */
  115906. assert( i<=pIdx->nSample && i>=0 );
  115907. pRec->nField = iCol+1;
  115908. assert( i==pIdx->nSample
  115909. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  115910. || pParse->db->mallocFailed );
  115911. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  115912. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  115913. ** be greater than or equal to the (iCol) field prefix of sample i.
  115914. ** If (i>0), then pRec must also be greater than sample (i-1). */
  115915. if( iCol>0 ){
  115916. pRec->nField = iCol;
  115917. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  115918. || pParse->db->mallocFailed );
  115919. }
  115920. if( i>0 ){
  115921. pRec->nField = nField;
  115922. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  115923. || pParse->db->mallocFailed );
  115924. }
  115925. }
  115926. }
  115927. #endif /* ifdef SQLITE_DEBUG */
  115928. if( res==0 ){
  115929. /* Record pRec is equal to sample i */
  115930. assert( iCol==nField-1 );
  115931. aStat[0] = aSample[i].anLt[iCol];
  115932. aStat[1] = aSample[i].anEq[iCol];
  115933. }else{
  115934. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  115935. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  115936. ** is larger than all samples in the array. */
  115937. tRowcnt iUpper, iGap;
  115938. if( i>=pIdx->nSample ){
  115939. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  115940. }else{
  115941. iUpper = aSample[i].anLt[iCol];
  115942. }
  115943. if( iLower>=iUpper ){
  115944. iGap = 0;
  115945. }else{
  115946. iGap = iUpper - iLower;
  115947. }
  115948. if( roundUp ){
  115949. iGap = (iGap*2)/3;
  115950. }else{
  115951. iGap = iGap/3;
  115952. }
  115953. aStat[0] = iLower + iGap;
  115954. aStat[1] = pIdx->aAvgEq[iCol];
  115955. }
  115956. /* Restore the pRec->nField value before returning. */
  115957. pRec->nField = nField;
  115958. return i;
  115959. }
  115960. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  115961. /*
  115962. ** If it is not NULL, pTerm is a term that provides an upper or lower
  115963. ** bound on a range scan. Without considering pTerm, it is estimated
  115964. ** that the scan will visit nNew rows. This function returns the number
  115965. ** estimated to be visited after taking pTerm into account.
  115966. **
  115967. ** If the user explicitly specified a likelihood() value for this term,
  115968. ** then the return value is the likelihood multiplied by the number of
  115969. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  115970. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  115971. */
  115972. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  115973. LogEst nRet = nNew;
  115974. if( pTerm ){
  115975. if( pTerm->truthProb<=0 ){
  115976. nRet += pTerm->truthProb;
  115977. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  115978. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  115979. }
  115980. }
  115981. return nRet;
  115982. }
  115983. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115984. /*
  115985. ** Return the affinity for a single column of an index.
  115986. */
  115987. static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  115988. assert( iCol>=0 && iCol<pIdx->nColumn );
  115989. if( !pIdx->zColAff ){
  115990. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  115991. }
  115992. return pIdx->zColAff[iCol];
  115993. }
  115994. #endif
  115995. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115996. /*
  115997. ** This function is called to estimate the number of rows visited by a
  115998. ** range-scan on a skip-scan index. For example:
  115999. **
  116000. ** CREATE INDEX i1 ON t1(a, b, c);
  116001. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  116002. **
  116003. ** Value pLoop->nOut is currently set to the estimated number of rows
  116004. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  116005. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  116006. ** on the stat4 data for the index. this scan will be peformed multiple
  116007. ** times (once for each (a,b) combination that matches a=?) is dealt with
  116008. ** by the caller.
  116009. **
  116010. ** It does this by scanning through all stat4 samples, comparing values
  116011. ** extracted from pLower and pUpper with the corresponding column in each
  116012. ** sample. If L and U are the number of samples found to be less than or
  116013. ** equal to the values extracted from pLower and pUpper respectively, and
  116014. ** N is the total number of samples, the pLoop->nOut value is adjusted
  116015. ** as follows:
  116016. **
  116017. ** nOut = nOut * ( min(U - L, 1) / N )
  116018. **
  116019. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  116020. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  116021. ** U is set to N.
  116022. **
  116023. ** Normally, this function sets *pbDone to 1 before returning. However,
  116024. ** if no value can be extracted from either pLower or pUpper (and so the
  116025. ** estimate of the number of rows delivered remains unchanged), *pbDone
  116026. ** is left as is.
  116027. **
  116028. ** If an error occurs, an SQLite error code is returned. Otherwise,
  116029. ** SQLITE_OK.
  116030. */
  116031. static int whereRangeSkipScanEst(
  116032. Parse *pParse, /* Parsing & code generating context */
  116033. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  116034. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  116035. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  116036. int *pbDone /* Set to true if at least one expr. value extracted */
  116037. ){
  116038. Index *p = pLoop->u.btree.pIndex;
  116039. int nEq = pLoop->u.btree.nEq;
  116040. sqlite3 *db = pParse->db;
  116041. int nLower = -1;
  116042. int nUpper = p->nSample+1;
  116043. int rc = SQLITE_OK;
  116044. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  116045. CollSeq *pColl;
  116046. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  116047. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  116048. sqlite3_value *pVal = 0; /* Value extracted from record */
  116049. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  116050. if( pLower ){
  116051. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  116052. nLower = 0;
  116053. }
  116054. if( pUpper && rc==SQLITE_OK ){
  116055. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  116056. nUpper = p2 ? 0 : p->nSample;
  116057. }
  116058. if( p1 || p2 ){
  116059. int i;
  116060. int nDiff;
  116061. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  116062. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  116063. if( rc==SQLITE_OK && p1 ){
  116064. int res = sqlite3MemCompare(p1, pVal, pColl);
  116065. if( res>=0 ) nLower++;
  116066. }
  116067. if( rc==SQLITE_OK && p2 ){
  116068. int res = sqlite3MemCompare(p2, pVal, pColl);
  116069. if( res>=0 ) nUpper++;
  116070. }
  116071. }
  116072. nDiff = (nUpper - nLower);
  116073. if( nDiff<=0 ) nDiff = 1;
  116074. /* If there is both an upper and lower bound specified, and the
  116075. ** comparisons indicate that they are close together, use the fallback
  116076. ** method (assume that the scan visits 1/64 of the rows) for estimating
  116077. ** the number of rows visited. Otherwise, estimate the number of rows
  116078. ** using the method described in the header comment for this function. */
  116079. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  116080. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  116081. pLoop->nOut -= nAdjust;
  116082. *pbDone = 1;
  116083. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  116084. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  116085. }
  116086. }else{
  116087. assert( *pbDone==0 );
  116088. }
  116089. sqlite3ValueFree(p1);
  116090. sqlite3ValueFree(p2);
  116091. sqlite3ValueFree(pVal);
  116092. return rc;
  116093. }
  116094. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  116095. /*
  116096. ** This function is used to estimate the number of rows that will be visited
  116097. ** by scanning an index for a range of values. The range may have an upper
  116098. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  116099. ** and lower bounds are represented by pLower and pUpper respectively. For
  116100. ** example, assuming that index p is on t1(a):
  116101. **
  116102. ** ... FROM t1 WHERE a > ? AND a < ? ...
  116103. ** |_____| |_____|
  116104. ** | |
  116105. ** pLower pUpper
  116106. **
  116107. ** If either of the upper or lower bound is not present, then NULL is passed in
  116108. ** place of the corresponding WhereTerm.
  116109. **
  116110. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  116111. ** column subject to the range constraint. Or, equivalently, the number of
  116112. ** equality constraints optimized by the proposed index scan. For example,
  116113. ** assuming index p is on t1(a, b), and the SQL query is:
  116114. **
  116115. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  116116. **
  116117. ** then nEq is set to 1 (as the range restricted column, b, is the second
  116118. ** left-most column of the index). Or, if the query is:
  116119. **
  116120. ** ... FROM t1 WHERE a > ? AND a < ? ...
  116121. **
  116122. ** then nEq is set to 0.
  116123. **
  116124. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  116125. ** number of rows that the index scan is expected to visit without
  116126. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  116127. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  116128. ** to account for the range constraints pLower and pUpper.
  116129. **
  116130. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  116131. ** used, a single range inequality reduces the search space by a factor of 4.
  116132. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  116133. ** rows visited by a factor of 64.
  116134. */
  116135. static int whereRangeScanEst(
  116136. Parse *pParse, /* Parsing & code generating context */
  116137. WhereLoopBuilder *pBuilder,
  116138. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  116139. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  116140. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  116141. ){
  116142. int rc = SQLITE_OK;
  116143. int nOut = pLoop->nOut;
  116144. LogEst nNew;
  116145. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  116146. Index *p = pLoop->u.btree.pIndex;
  116147. int nEq = pLoop->u.btree.nEq;
  116148. if( p->nSample>0 && nEq<p->nSampleCol ){
  116149. if( nEq==pBuilder->nRecValid ){
  116150. UnpackedRecord *pRec = pBuilder->pRec;
  116151. tRowcnt a[2];
  116152. u8 aff;
  116153. /* Variable iLower will be set to the estimate of the number of rows in
  116154. ** the index that are less than the lower bound of the range query. The
  116155. ** lower bound being the concatenation of $P and $L, where $P is the
  116156. ** key-prefix formed by the nEq values matched against the nEq left-most
  116157. ** columns of the index, and $L is the value in pLower.
  116158. **
  116159. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  116160. ** is not a simple variable or literal value), the lower bound of the
  116161. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  116162. ** if $L is available, whereKeyStats() is called for both ($P) and
  116163. ** ($P:$L) and the larger of the two returned values is used.
  116164. **
  116165. ** Similarly, iUpper is to be set to the estimate of the number of rows
  116166. ** less than the upper bound of the range query. Where the upper bound
  116167. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  116168. ** of iUpper are requested of whereKeyStats() and the smaller used.
  116169. **
  116170. ** The number of rows between the two bounds is then just iUpper-iLower.
  116171. */
  116172. tRowcnt iLower; /* Rows less than the lower bound */
  116173. tRowcnt iUpper; /* Rows less than the upper bound */
  116174. int iLwrIdx = -2; /* aSample[] for the lower bound */
  116175. int iUprIdx = -1; /* aSample[] for the upper bound */
  116176. if( pRec ){
  116177. testcase( pRec->nField!=pBuilder->nRecValid );
  116178. pRec->nField = pBuilder->nRecValid;
  116179. }
  116180. aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
  116181. assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
  116182. /* Determine iLower and iUpper using ($P) only. */
  116183. if( nEq==0 ){
  116184. iLower = 0;
  116185. iUpper = p->nRowEst0;
  116186. }else{
  116187. /* Note: this call could be optimized away - since the same values must
  116188. ** have been requested when testing key $P in whereEqualScanEst(). */
  116189. whereKeyStats(pParse, p, pRec, 0, a);
  116190. iLower = a[0];
  116191. iUpper = a[0] + a[1];
  116192. }
  116193. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  116194. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  116195. assert( p->aSortOrder!=0 );
  116196. if( p->aSortOrder[nEq] ){
  116197. /* The roles of pLower and pUpper are swapped for a DESC index */
  116198. SWAP(WhereTerm*, pLower, pUpper);
  116199. }
  116200. /* If possible, improve on the iLower estimate using ($P:$L). */
  116201. if( pLower ){
  116202. int bOk; /* True if value is extracted from pExpr */
  116203. Expr *pExpr = pLower->pExpr->pRight;
  116204. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  116205. if( rc==SQLITE_OK && bOk ){
  116206. tRowcnt iNew;
  116207. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  116208. iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  116209. if( iNew>iLower ) iLower = iNew;
  116210. nOut--;
  116211. pLower = 0;
  116212. }
  116213. }
  116214. /* If possible, improve on the iUpper estimate using ($P:$U). */
  116215. if( pUpper ){
  116216. int bOk; /* True if value is extracted from pExpr */
  116217. Expr *pExpr = pUpper->pExpr->pRight;
  116218. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  116219. if( rc==SQLITE_OK && bOk ){
  116220. tRowcnt iNew;
  116221. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  116222. iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  116223. if( iNew<iUpper ) iUpper = iNew;
  116224. nOut--;
  116225. pUpper = 0;
  116226. }
  116227. }
  116228. pBuilder->pRec = pRec;
  116229. if( rc==SQLITE_OK ){
  116230. if( iUpper>iLower ){
  116231. nNew = sqlite3LogEst(iUpper - iLower);
  116232. /* TUNING: If both iUpper and iLower are derived from the same
  116233. ** sample, then assume they are 4x more selective. This brings
  116234. ** the estimated selectivity more in line with what it would be
  116235. ** if estimated without the use of STAT3/4 tables. */
  116236. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  116237. }else{
  116238. nNew = 10; assert( 10==sqlite3LogEst(2) );
  116239. }
  116240. if( nNew<nOut ){
  116241. nOut = nNew;
  116242. }
  116243. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  116244. (u32)iLower, (u32)iUpper, nOut));
  116245. }
  116246. }else{
  116247. int bDone = 0;
  116248. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  116249. if( bDone ) return rc;
  116250. }
  116251. }
  116252. #else
  116253. UNUSED_PARAMETER(pParse);
  116254. UNUSED_PARAMETER(pBuilder);
  116255. assert( pLower || pUpper );
  116256. #endif
  116257. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  116258. nNew = whereRangeAdjust(pLower, nOut);
  116259. nNew = whereRangeAdjust(pUpper, nNew);
  116260. /* TUNING: If there is both an upper and lower limit and neither limit
  116261. ** has an application-defined likelihood(), assume the range is
  116262. ** reduced by an additional 75%. This means that, by default, an open-ended
  116263. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  116264. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  116265. ** match 1/64 of the index. */
  116266. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  116267. nNew -= 20;
  116268. }
  116269. nOut -= (pLower!=0) + (pUpper!=0);
  116270. if( nNew<10 ) nNew = 10;
  116271. if( nNew<nOut ) nOut = nNew;
  116272. #if defined(WHERETRACE_ENABLED)
  116273. if( pLoop->nOut>nOut ){
  116274. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  116275. pLoop->nOut, nOut));
  116276. }
  116277. #endif
  116278. pLoop->nOut = (LogEst)nOut;
  116279. return rc;
  116280. }
  116281. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  116282. /*
  116283. ** Estimate the number of rows that will be returned based on
  116284. ** an equality constraint x=VALUE and where that VALUE occurs in
  116285. ** the histogram data. This only works when x is the left-most
  116286. ** column of an index and sqlite_stat3 histogram data is available
  116287. ** for that index. When pExpr==NULL that means the constraint is
  116288. ** "x IS NULL" instead of "x=VALUE".
  116289. **
  116290. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  116291. ** If unable to make an estimate, leave *pnRow unchanged and return
  116292. ** non-zero.
  116293. **
  116294. ** This routine can fail if it is unable to load a collating sequence
  116295. ** required for string comparison, or if unable to allocate memory
  116296. ** for a UTF conversion required for comparison. The error is stored
  116297. ** in the pParse structure.
  116298. */
  116299. static int whereEqualScanEst(
  116300. Parse *pParse, /* Parsing & code generating context */
  116301. WhereLoopBuilder *pBuilder,
  116302. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  116303. tRowcnt *pnRow /* Write the revised row estimate here */
  116304. ){
  116305. Index *p = pBuilder->pNew->u.btree.pIndex;
  116306. int nEq = pBuilder->pNew->u.btree.nEq;
  116307. UnpackedRecord *pRec = pBuilder->pRec;
  116308. u8 aff; /* Column affinity */
  116309. int rc; /* Subfunction return code */
  116310. tRowcnt a[2]; /* Statistics */
  116311. int bOk;
  116312. assert( nEq>=1 );
  116313. assert( nEq<=p->nColumn );
  116314. assert( p->aSample!=0 );
  116315. assert( p->nSample>0 );
  116316. assert( pBuilder->nRecValid<nEq );
  116317. /* If values are not available for all fields of the index to the left
  116318. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  116319. if( pBuilder->nRecValid<(nEq-1) ){
  116320. return SQLITE_NOTFOUND;
  116321. }
  116322. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  116323. ** below would return the same value. */
  116324. if( nEq>=p->nColumn ){
  116325. *pnRow = 1;
  116326. return SQLITE_OK;
  116327. }
  116328. aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
  116329. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  116330. pBuilder->pRec = pRec;
  116331. if( rc!=SQLITE_OK ) return rc;
  116332. if( bOk==0 ) return SQLITE_NOTFOUND;
  116333. pBuilder->nRecValid = nEq;
  116334. whereKeyStats(pParse, p, pRec, 0, a);
  116335. WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
  116336. *pnRow = a[1];
  116337. return rc;
  116338. }
  116339. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  116340. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  116341. /*
  116342. ** Estimate the number of rows that will be returned based on
  116343. ** an IN constraint where the right-hand side of the IN operator
  116344. ** is a list of values. Example:
  116345. **
  116346. ** WHERE x IN (1,2,3,4)
  116347. **
  116348. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  116349. ** If unable to make an estimate, leave *pnRow unchanged and return
  116350. ** non-zero.
  116351. **
  116352. ** This routine can fail if it is unable to load a collating sequence
  116353. ** required for string comparison, or if unable to allocate memory
  116354. ** for a UTF conversion required for comparison. The error is stored
  116355. ** in the pParse structure.
  116356. */
  116357. static int whereInScanEst(
  116358. Parse *pParse, /* Parsing & code generating context */
  116359. WhereLoopBuilder *pBuilder,
  116360. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  116361. tRowcnt *pnRow /* Write the revised row estimate here */
  116362. ){
  116363. Index *p = pBuilder->pNew->u.btree.pIndex;
  116364. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  116365. int nRecValid = pBuilder->nRecValid;
  116366. int rc = SQLITE_OK; /* Subfunction return code */
  116367. tRowcnt nEst; /* Number of rows for a single term */
  116368. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  116369. int i; /* Loop counter */
  116370. assert( p->aSample!=0 );
  116371. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  116372. nEst = nRow0;
  116373. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  116374. nRowEst += nEst;
  116375. pBuilder->nRecValid = nRecValid;
  116376. }
  116377. if( rc==SQLITE_OK ){
  116378. if( nRowEst > nRow0 ) nRowEst = nRow0;
  116379. *pnRow = nRowEst;
  116380. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  116381. }
  116382. assert( pBuilder->nRecValid==nRecValid );
  116383. return rc;
  116384. }
  116385. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  116386. #ifdef WHERETRACE_ENABLED
  116387. /*
  116388. ** Print the content of a WhereTerm object
  116389. */
  116390. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  116391. if( pTerm==0 ){
  116392. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  116393. }else{
  116394. char zType[4];
  116395. memcpy(zType, "...", 4);
  116396. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  116397. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  116398. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  116399. sqlite3DebugPrintf(
  116400. "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
  116401. iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
  116402. pTerm->eOperator, pTerm->wtFlags);
  116403. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  116404. }
  116405. }
  116406. #endif
  116407. #ifdef WHERETRACE_ENABLED
  116408. /*
  116409. ** Print a WhereLoop object for debugging purposes
  116410. */
  116411. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  116412. WhereInfo *pWInfo = pWC->pWInfo;
  116413. int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
  116414. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  116415. Table *pTab = pItem->pTab;
  116416. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  116417. p->iTab, nb, p->maskSelf, nb, p->prereq);
  116418. sqlite3DebugPrintf(" %12s",
  116419. pItem->zAlias ? pItem->zAlias : pTab->zName);
  116420. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  116421. const char *zName;
  116422. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  116423. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  116424. int i = sqlite3Strlen30(zName) - 1;
  116425. while( zName[i]!='_' ) i--;
  116426. zName += i;
  116427. }
  116428. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  116429. }else{
  116430. sqlite3DebugPrintf("%20s","");
  116431. }
  116432. }else{
  116433. char *z;
  116434. if( p->u.vtab.idxStr ){
  116435. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  116436. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  116437. }else{
  116438. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  116439. }
  116440. sqlite3DebugPrintf(" %-19s", z);
  116441. sqlite3_free(z);
  116442. }
  116443. if( p->wsFlags & WHERE_SKIPSCAN ){
  116444. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  116445. }else{
  116446. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  116447. }
  116448. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  116449. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  116450. int i;
  116451. for(i=0; i<p->nLTerm; i++){
  116452. whereTermPrint(p->aLTerm[i], i);
  116453. }
  116454. }
  116455. }
  116456. #endif
  116457. /*
  116458. ** Convert bulk memory into a valid WhereLoop that can be passed
  116459. ** to whereLoopClear harmlessly.
  116460. */
  116461. static void whereLoopInit(WhereLoop *p){
  116462. p->aLTerm = p->aLTermSpace;
  116463. p->nLTerm = 0;
  116464. p->nLSlot = ArraySize(p->aLTermSpace);
  116465. p->wsFlags = 0;
  116466. }
  116467. /*
  116468. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  116469. */
  116470. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  116471. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  116472. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  116473. sqlite3_free(p->u.vtab.idxStr);
  116474. p->u.vtab.needFree = 0;
  116475. p->u.vtab.idxStr = 0;
  116476. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  116477. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  116478. sqlite3DbFree(db, p->u.btree.pIndex);
  116479. p->u.btree.pIndex = 0;
  116480. }
  116481. }
  116482. }
  116483. /*
  116484. ** Deallocate internal memory used by a WhereLoop object
  116485. */
  116486. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  116487. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  116488. whereLoopClearUnion(db, p);
  116489. whereLoopInit(p);
  116490. }
  116491. /*
  116492. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  116493. */
  116494. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  116495. WhereTerm **paNew;
  116496. if( p->nLSlot>=n ) return SQLITE_OK;
  116497. n = (n+7)&~7;
  116498. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  116499. if( paNew==0 ) return SQLITE_NOMEM;
  116500. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  116501. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  116502. p->aLTerm = paNew;
  116503. p->nLSlot = n;
  116504. return SQLITE_OK;
  116505. }
  116506. /*
  116507. ** Transfer content from the second pLoop into the first.
  116508. */
  116509. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  116510. whereLoopClearUnion(db, pTo);
  116511. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  116512. memset(&pTo->u, 0, sizeof(pTo->u));
  116513. return SQLITE_NOMEM;
  116514. }
  116515. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  116516. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  116517. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  116518. pFrom->u.vtab.needFree = 0;
  116519. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  116520. pFrom->u.btree.pIndex = 0;
  116521. }
  116522. return SQLITE_OK;
  116523. }
  116524. /*
  116525. ** Delete a WhereLoop object
  116526. */
  116527. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  116528. whereLoopClear(db, p);
  116529. sqlite3DbFree(db, p);
  116530. }
  116531. /*
  116532. ** Free a WhereInfo structure
  116533. */
  116534. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  116535. if( ALWAYS(pWInfo) ){
  116536. int i;
  116537. for(i=0; i<pWInfo->nLevel; i++){
  116538. WhereLevel *pLevel = &pWInfo->a[i];
  116539. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  116540. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  116541. }
  116542. }
  116543. sqlite3WhereClauseClear(&pWInfo->sWC);
  116544. while( pWInfo->pLoops ){
  116545. WhereLoop *p = pWInfo->pLoops;
  116546. pWInfo->pLoops = p->pNextLoop;
  116547. whereLoopDelete(db, p);
  116548. }
  116549. sqlite3DbFree(db, pWInfo);
  116550. }
  116551. }
  116552. /*
  116553. ** Return TRUE if all of the following are true:
  116554. **
  116555. ** (1) X has the same or lower cost that Y
  116556. ** (2) X is a proper subset of Y
  116557. ** (3) X skips at least as many columns as Y
  116558. **
  116559. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  116560. ** than Y and that every WHERE clause term used by X is also used
  116561. ** by Y.
  116562. **
  116563. ** If X is a proper subset of Y then Y is a better choice and ought
  116564. ** to have a lower cost. This routine returns TRUE when that cost
  116565. ** relationship is inverted and needs to be adjusted. The third rule
  116566. ** was added because if X uses skip-scan less than Y it still might
  116567. ** deserve a lower cost even if it is a proper subset of Y.
  116568. */
  116569. static int whereLoopCheaperProperSubset(
  116570. const WhereLoop *pX, /* First WhereLoop to compare */
  116571. const WhereLoop *pY /* Compare against this WhereLoop */
  116572. ){
  116573. int i, j;
  116574. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  116575. return 0; /* X is not a subset of Y */
  116576. }
  116577. if( pY->nSkip > pX->nSkip ) return 0;
  116578. if( pX->rRun >= pY->rRun ){
  116579. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  116580. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  116581. }
  116582. for(i=pX->nLTerm-1; i>=0; i--){
  116583. if( pX->aLTerm[i]==0 ) continue;
  116584. for(j=pY->nLTerm-1; j>=0; j--){
  116585. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  116586. }
  116587. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  116588. }
  116589. return 1; /* All conditions meet */
  116590. }
  116591. /*
  116592. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  116593. ** that:
  116594. **
  116595. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  116596. ** subset of pTemplate
  116597. **
  116598. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  116599. ** is a proper subset.
  116600. **
  116601. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  116602. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  116603. ** also used by Y.
  116604. */
  116605. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  116606. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  116607. for(; p; p=p->pNextLoop){
  116608. if( p->iTab!=pTemplate->iTab ) continue;
  116609. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  116610. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  116611. /* Adjust pTemplate cost downward so that it is cheaper than its
  116612. ** subset p. */
  116613. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  116614. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  116615. pTemplate->rRun = p->rRun;
  116616. pTemplate->nOut = p->nOut - 1;
  116617. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  116618. /* Adjust pTemplate cost upward so that it is costlier than p since
  116619. ** pTemplate is a proper subset of p */
  116620. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  116621. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  116622. pTemplate->rRun = p->rRun;
  116623. pTemplate->nOut = p->nOut + 1;
  116624. }
  116625. }
  116626. }
  116627. /*
  116628. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  116629. ** supplanted by pTemplate.
  116630. **
  116631. ** Return NULL if the WhereLoop list contains an entry that can supplant
  116632. ** pTemplate, in other words if pTemplate does not belong on the list.
  116633. **
  116634. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  116635. ** link that points to pX.
  116636. **
  116637. ** If pTemplate cannot supplant any existing element of the list but needs
  116638. ** to be added to the list, then return a pointer to the tail of the list.
  116639. */
  116640. static WhereLoop **whereLoopFindLesser(
  116641. WhereLoop **ppPrev,
  116642. const WhereLoop *pTemplate
  116643. ){
  116644. WhereLoop *p;
  116645. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  116646. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  116647. /* If either the iTab or iSortIdx values for two WhereLoop are different
  116648. ** then those WhereLoops need to be considered separately. Neither is
  116649. ** a candidate to replace the other. */
  116650. continue;
  116651. }
  116652. /* In the current implementation, the rSetup value is either zero
  116653. ** or the cost of building an automatic index (NlogN) and the NlogN
  116654. ** is the same for compatible WhereLoops. */
  116655. assert( p->rSetup==0 || pTemplate->rSetup==0
  116656. || p->rSetup==pTemplate->rSetup );
  116657. /* whereLoopAddBtree() always generates and inserts the automatic index
  116658. ** case first. Hence compatible candidate WhereLoops never have a larger
  116659. ** rSetup. Call this SETUP-INVARIANT */
  116660. assert( p->rSetup>=pTemplate->rSetup );
  116661. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  116662. ** UNIQUE constraint) with one or more == constraints is better
  116663. ** than an automatic index. Unless it is a skip-scan. */
  116664. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  116665. && (pTemplate->nSkip)==0
  116666. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  116667. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  116668. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  116669. ){
  116670. break;
  116671. }
  116672. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  116673. ** discarded. WhereLoop p is better if:
  116674. ** (1) p has no more dependencies than pTemplate, and
  116675. ** (2) p has an equal or lower cost than pTemplate
  116676. */
  116677. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  116678. && p->rSetup<=pTemplate->rSetup /* (2a) */
  116679. && p->rRun<=pTemplate->rRun /* (2b) */
  116680. && p->nOut<=pTemplate->nOut /* (2c) */
  116681. ){
  116682. return 0; /* Discard pTemplate */
  116683. }
  116684. /* If pTemplate is always better than p, then cause p to be overwritten
  116685. ** with pTemplate. pTemplate is better than p if:
  116686. ** (1) pTemplate has no more dependences than p, and
  116687. ** (2) pTemplate has an equal or lower cost than p.
  116688. */
  116689. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  116690. && p->rRun>=pTemplate->rRun /* (2a) */
  116691. && p->nOut>=pTemplate->nOut /* (2b) */
  116692. ){
  116693. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  116694. break; /* Cause p to be overwritten by pTemplate */
  116695. }
  116696. }
  116697. return ppPrev;
  116698. }
  116699. /*
  116700. ** Insert or replace a WhereLoop entry using the template supplied.
  116701. **
  116702. ** An existing WhereLoop entry might be overwritten if the new template
  116703. ** is better and has fewer dependencies. Or the template will be ignored
  116704. ** and no insert will occur if an existing WhereLoop is faster and has
  116705. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  116706. ** added based on the template.
  116707. **
  116708. ** If pBuilder->pOrSet is not NULL then we care about only the
  116709. ** prerequisites and rRun and nOut costs of the N best loops. That
  116710. ** information is gathered in the pBuilder->pOrSet object. This special
  116711. ** processing mode is used only for OR clause processing.
  116712. **
  116713. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  116714. ** still might overwrite similar loops with the new template if the
  116715. ** new template is better. Loops may be overwritten if the following
  116716. ** conditions are met:
  116717. **
  116718. ** (1) They have the same iTab.
  116719. ** (2) They have the same iSortIdx.
  116720. ** (3) The template has same or fewer dependencies than the current loop
  116721. ** (4) The template has the same or lower cost than the current loop
  116722. */
  116723. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  116724. WhereLoop **ppPrev, *p;
  116725. WhereInfo *pWInfo = pBuilder->pWInfo;
  116726. sqlite3 *db = pWInfo->pParse->db;
  116727. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  116728. ** and prereqs.
  116729. */
  116730. if( pBuilder->pOrSet!=0 ){
  116731. if( pTemplate->nLTerm ){
  116732. #if WHERETRACE_ENABLED
  116733. u16 n = pBuilder->pOrSet->n;
  116734. int x =
  116735. #endif
  116736. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  116737. pTemplate->nOut);
  116738. #if WHERETRACE_ENABLED /* 0x8 */
  116739. if( sqlite3WhereTrace & 0x8 ){
  116740. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  116741. whereLoopPrint(pTemplate, pBuilder->pWC);
  116742. }
  116743. #endif
  116744. }
  116745. return SQLITE_OK;
  116746. }
  116747. /* Look for an existing WhereLoop to replace with pTemplate
  116748. */
  116749. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  116750. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  116751. if( ppPrev==0 ){
  116752. /* There already exists a WhereLoop on the list that is better
  116753. ** than pTemplate, so just ignore pTemplate */
  116754. #if WHERETRACE_ENABLED /* 0x8 */
  116755. if( sqlite3WhereTrace & 0x8 ){
  116756. sqlite3DebugPrintf(" skip: ");
  116757. whereLoopPrint(pTemplate, pBuilder->pWC);
  116758. }
  116759. #endif
  116760. return SQLITE_OK;
  116761. }else{
  116762. p = *ppPrev;
  116763. }
  116764. /* If we reach this point it means that either p[] should be overwritten
  116765. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  116766. ** WhereLoop and insert it.
  116767. */
  116768. #if WHERETRACE_ENABLED /* 0x8 */
  116769. if( sqlite3WhereTrace & 0x8 ){
  116770. if( p!=0 ){
  116771. sqlite3DebugPrintf("replace: ");
  116772. whereLoopPrint(p, pBuilder->pWC);
  116773. }
  116774. sqlite3DebugPrintf(" add: ");
  116775. whereLoopPrint(pTemplate, pBuilder->pWC);
  116776. }
  116777. #endif
  116778. if( p==0 ){
  116779. /* Allocate a new WhereLoop to add to the end of the list */
  116780. *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  116781. if( p==0 ) return SQLITE_NOMEM;
  116782. whereLoopInit(p);
  116783. p->pNextLoop = 0;
  116784. }else{
  116785. /* We will be overwriting WhereLoop p[]. But before we do, first
  116786. ** go through the rest of the list and delete any other entries besides
  116787. ** p[] that are also supplated by pTemplate */
  116788. WhereLoop **ppTail = &p->pNextLoop;
  116789. WhereLoop *pToDel;
  116790. while( *ppTail ){
  116791. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  116792. if( ppTail==0 ) break;
  116793. pToDel = *ppTail;
  116794. if( pToDel==0 ) break;
  116795. *ppTail = pToDel->pNextLoop;
  116796. #if WHERETRACE_ENABLED /* 0x8 */
  116797. if( sqlite3WhereTrace & 0x8 ){
  116798. sqlite3DebugPrintf(" delete: ");
  116799. whereLoopPrint(pToDel, pBuilder->pWC);
  116800. }
  116801. #endif
  116802. whereLoopDelete(db, pToDel);
  116803. }
  116804. }
  116805. whereLoopXfer(db, p, pTemplate);
  116806. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  116807. Index *pIndex = p->u.btree.pIndex;
  116808. if( pIndex && pIndex->tnum==0 ){
  116809. p->u.btree.pIndex = 0;
  116810. }
  116811. }
  116812. return SQLITE_OK;
  116813. }
  116814. /*
  116815. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  116816. ** WHERE clause that reference the loop but which are not used by an
  116817. ** index.
  116818. *
  116819. ** For every WHERE clause term that is not used by the index
  116820. ** and which has a truth probability assigned by one of the likelihood(),
  116821. ** likely(), or unlikely() SQL functions, reduce the estimated number
  116822. ** of output rows by the probability specified.
  116823. **
  116824. ** TUNING: For every WHERE clause term that is not used by the index
  116825. ** and which does not have an assigned truth probability, heuristics
  116826. ** described below are used to try to estimate the truth probability.
  116827. ** TODO --> Perhaps this is something that could be improved by better
  116828. ** table statistics.
  116829. **
  116830. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  116831. ** value corresponds to -1 in LogEst notation, so this means decrement
  116832. ** the WhereLoop.nOut field for every such WHERE clause term.
  116833. **
  116834. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  116835. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  116836. ** final output row estimate is no greater than 1/4 of the total number
  116837. ** of rows in the table. In other words, assume that x==EXPR will filter
  116838. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  116839. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  116840. ** on the "x" column and so in that case only cap the output row estimate
  116841. ** at 1/2 instead of 1/4.
  116842. */
  116843. static void whereLoopOutputAdjust(
  116844. WhereClause *pWC, /* The WHERE clause */
  116845. WhereLoop *pLoop, /* The loop to adjust downward */
  116846. LogEst nRow /* Number of rows in the entire table */
  116847. ){
  116848. WhereTerm *pTerm, *pX;
  116849. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  116850. int i, j, k;
  116851. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  116852. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  116853. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  116854. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  116855. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  116856. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  116857. for(j=pLoop->nLTerm-1; j>=0; j--){
  116858. pX = pLoop->aLTerm[j];
  116859. if( pX==0 ) continue;
  116860. if( pX==pTerm ) break;
  116861. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  116862. }
  116863. if( j<0 ){
  116864. if( pTerm->truthProb<=0 ){
  116865. /* If a truth probability is specified using the likelihood() hints,
  116866. ** then use the probability provided by the application. */
  116867. pLoop->nOut += pTerm->truthProb;
  116868. }else{
  116869. /* In the absence of explicit truth probabilities, use heuristics to
  116870. ** guess a reasonable truth probability. */
  116871. pLoop->nOut--;
  116872. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  116873. Expr *pRight = pTerm->pExpr->pRight;
  116874. testcase( pTerm->pExpr->op==TK_IS );
  116875. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  116876. k = 10;
  116877. }else{
  116878. k = 20;
  116879. }
  116880. if( iReduce<k ) iReduce = k;
  116881. }
  116882. }
  116883. }
  116884. }
  116885. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  116886. }
  116887. /*
  116888. ** Adjust the cost C by the costMult facter T. This only occurs if
  116889. ** compiled with -DSQLITE_ENABLE_COSTMULT
  116890. */
  116891. #ifdef SQLITE_ENABLE_COSTMULT
  116892. # define ApplyCostMultiplier(C,T) C += T
  116893. #else
  116894. # define ApplyCostMultiplier(C,T)
  116895. #endif
  116896. /*
  116897. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  116898. ** index pIndex. Try to match one more.
  116899. **
  116900. ** When this function is called, pBuilder->pNew->nOut contains the
  116901. ** number of rows expected to be visited by filtering using the nEq
  116902. ** terms only. If it is modified, this value is restored before this
  116903. ** function returns.
  116904. **
  116905. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  116906. ** INTEGER PRIMARY KEY.
  116907. */
  116908. static int whereLoopAddBtreeIndex(
  116909. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  116910. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  116911. Index *pProbe, /* An index on pSrc */
  116912. LogEst nInMul /* log(Number of iterations due to IN) */
  116913. ){
  116914. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  116915. Parse *pParse = pWInfo->pParse; /* Parsing context */
  116916. sqlite3 *db = pParse->db; /* Database connection malloc context */
  116917. WhereLoop *pNew; /* Template WhereLoop under construction */
  116918. WhereTerm *pTerm; /* A WhereTerm under consideration */
  116919. int opMask; /* Valid operators for constraints */
  116920. WhereScan scan; /* Iterator for WHERE terms */
  116921. Bitmask saved_prereq; /* Original value of pNew->prereq */
  116922. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  116923. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  116924. u16 saved_nSkip; /* Original value of pNew->nSkip */
  116925. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  116926. LogEst saved_nOut; /* Original value of pNew->nOut */
  116927. int rc = SQLITE_OK; /* Return code */
  116928. LogEst rSize; /* Number of rows in the table */
  116929. LogEst rLogSize; /* Logarithm of table size */
  116930. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  116931. pNew = pBuilder->pNew;
  116932. if( db->mallocFailed ) return SQLITE_NOMEM;
  116933. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  116934. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  116935. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  116936. opMask = WO_LT|WO_LE;
  116937. }else if( /*pProbe->tnum<=0 ||*/ (pSrc->fg.jointype & JT_LEFT)!=0 ){
  116938. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  116939. }else{
  116940. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  116941. }
  116942. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  116943. assert( pNew->u.btree.nEq<pProbe->nColumn );
  116944. saved_nEq = pNew->u.btree.nEq;
  116945. saved_nSkip = pNew->nSkip;
  116946. saved_nLTerm = pNew->nLTerm;
  116947. saved_wsFlags = pNew->wsFlags;
  116948. saved_prereq = pNew->prereq;
  116949. saved_nOut = pNew->nOut;
  116950. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  116951. opMask, pProbe);
  116952. pNew->rSetup = 0;
  116953. rSize = pProbe->aiRowLogEst[0];
  116954. rLogSize = estLog(rSize);
  116955. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  116956. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  116957. LogEst rCostIdx;
  116958. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  116959. int nIn = 0;
  116960. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  116961. int nRecValid = pBuilder->nRecValid;
  116962. #endif
  116963. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  116964. && indexColumnNotNull(pProbe, saved_nEq)
  116965. ){
  116966. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  116967. }
  116968. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  116969. /* Do not allow the upper bound of a LIKE optimization range constraint
  116970. ** to mix with a lower range bound from some other source */
  116971. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  116972. pNew->wsFlags = saved_wsFlags;
  116973. pNew->u.btree.nEq = saved_nEq;
  116974. pNew->nLTerm = saved_nLTerm;
  116975. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  116976. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  116977. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  116978. assert( nInMul==0
  116979. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  116980. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  116981. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  116982. );
  116983. if( eOp & WO_IN ){
  116984. Expr *pExpr = pTerm->pExpr;
  116985. pNew->wsFlags |= WHERE_COLUMN_IN;
  116986. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  116987. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  116988. nIn = 46; assert( 46==sqlite3LogEst(25) );
  116989. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  116990. /* "x IN (value, value, ...)" */
  116991. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  116992. }
  116993. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  116994. ** changes "x IN (?)" into "x=?". */
  116995. }else if( eOp & (WO_EQ|WO_IS) ){
  116996. int iCol = pProbe->aiColumn[saved_nEq];
  116997. pNew->wsFlags |= WHERE_COLUMN_EQ;
  116998. assert( saved_nEq==pNew->u.btree.nEq );
  116999. if( iCol==XN_ROWID
  117000. || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  117001. ){
  117002. if( iCol>=0 && pProbe->uniqNotNull==0 ){
  117003. pNew->wsFlags |= WHERE_UNQ_WANTED;
  117004. }else{
  117005. pNew->wsFlags |= WHERE_ONEROW;
  117006. }
  117007. }
  117008. }else if( eOp & WO_ISNULL ){
  117009. pNew->wsFlags |= WHERE_COLUMN_NULL;
  117010. }else if( eOp & (WO_GT|WO_GE) ){
  117011. testcase( eOp & WO_GT );
  117012. testcase( eOp & WO_GE );
  117013. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  117014. pBtm = pTerm;
  117015. pTop = 0;
  117016. if( pTerm->wtFlags & TERM_LIKEOPT ){
  117017. /* Range contraints that come from the LIKE optimization are
  117018. ** always used in pairs. */
  117019. pTop = &pTerm[1];
  117020. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  117021. assert( pTop->wtFlags & TERM_LIKEOPT );
  117022. assert( pTop->eOperator==WO_LT );
  117023. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  117024. pNew->aLTerm[pNew->nLTerm++] = pTop;
  117025. pNew->wsFlags |= WHERE_TOP_LIMIT;
  117026. }
  117027. }else{
  117028. assert( eOp & (WO_LT|WO_LE) );
  117029. testcase( eOp & WO_LT );
  117030. testcase( eOp & WO_LE );
  117031. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  117032. pTop = pTerm;
  117033. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  117034. pNew->aLTerm[pNew->nLTerm-2] : 0;
  117035. }
  117036. /* At this point pNew->nOut is set to the number of rows expected to
  117037. ** be visited by the index scan before considering term pTerm, or the
  117038. ** values of nIn and nInMul. In other words, assuming that all
  117039. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  117040. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  117041. assert( pNew->nOut==saved_nOut );
  117042. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  117043. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  117044. ** data, using some other estimate. */
  117045. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  117046. }else{
  117047. int nEq = ++pNew->u.btree.nEq;
  117048. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  117049. assert( pNew->nOut==saved_nOut );
  117050. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  117051. assert( (eOp & WO_IN) || nIn==0 );
  117052. testcase( eOp & WO_IN );
  117053. pNew->nOut += pTerm->truthProb;
  117054. pNew->nOut -= nIn;
  117055. }else{
  117056. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  117057. tRowcnt nOut = 0;
  117058. if( nInMul==0
  117059. && pProbe->nSample
  117060. && pNew->u.btree.nEq<=pProbe->nSampleCol
  117061. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  117062. ){
  117063. Expr *pExpr = pTerm->pExpr;
  117064. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  117065. testcase( eOp & WO_EQ );
  117066. testcase( eOp & WO_IS );
  117067. testcase( eOp & WO_ISNULL );
  117068. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  117069. }else{
  117070. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  117071. }
  117072. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  117073. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  117074. if( nOut ){
  117075. pNew->nOut = sqlite3LogEst(nOut);
  117076. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  117077. pNew->nOut -= nIn;
  117078. }
  117079. }
  117080. if( nOut==0 )
  117081. #endif
  117082. {
  117083. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  117084. if( eOp & WO_ISNULL ){
  117085. /* TUNING: If there is no likelihood() value, assume that a
  117086. ** "col IS NULL" expression matches twice as many rows
  117087. ** as (col=?). */
  117088. pNew->nOut += 10;
  117089. }
  117090. }
  117091. }
  117092. }
  117093. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  117094. ** it to pNew->rRun, which is currently set to the cost of the index
  117095. ** seek only. Then, if this is a non-covering index, add the cost of
  117096. ** visiting the rows in the main table. */
  117097. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  117098. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  117099. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  117100. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  117101. }
  117102. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  117103. nOutUnadjusted = pNew->nOut;
  117104. pNew->rRun += nInMul + nIn;
  117105. pNew->nOut += nInMul + nIn;
  117106. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  117107. rc = whereLoopInsert(pBuilder, pNew);
  117108. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  117109. pNew->nOut = saved_nOut;
  117110. }else{
  117111. pNew->nOut = nOutUnadjusted;
  117112. }
  117113. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  117114. && pNew->u.btree.nEq<pProbe->nColumn
  117115. ){
  117116. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  117117. }
  117118. pNew->nOut = saved_nOut;
  117119. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  117120. pBuilder->nRecValid = nRecValid;
  117121. #endif
  117122. }
  117123. pNew->prereq = saved_prereq;
  117124. pNew->u.btree.nEq = saved_nEq;
  117125. pNew->nSkip = saved_nSkip;
  117126. pNew->wsFlags = saved_wsFlags;
  117127. pNew->nOut = saved_nOut;
  117128. pNew->nLTerm = saved_nLTerm;
  117129. /* Consider using a skip-scan if there are no WHERE clause constraints
  117130. ** available for the left-most terms of the index, and if the average
  117131. ** number of repeats in the left-most terms is at least 18.
  117132. **
  117133. ** The magic number 18 is selected on the basis that scanning 17 rows
  117134. ** is almost always quicker than an index seek (even though if the index
  117135. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  117136. ** the code). And, even if it is not, it should not be too much slower.
  117137. ** On the other hand, the extra seeks could end up being significantly
  117138. ** more expensive. */
  117139. assert( 42==sqlite3LogEst(18) );
  117140. if( saved_nEq==saved_nSkip
  117141. && saved_nEq+1<pProbe->nKeyCol
  117142. && pProbe->noSkipScan==0
  117143. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  117144. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  117145. ){
  117146. LogEst nIter;
  117147. pNew->u.btree.nEq++;
  117148. pNew->nSkip++;
  117149. pNew->aLTerm[pNew->nLTerm++] = 0;
  117150. pNew->wsFlags |= WHERE_SKIPSCAN;
  117151. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  117152. pNew->nOut -= nIter;
  117153. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  117154. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  117155. nIter += 5;
  117156. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  117157. pNew->nOut = saved_nOut;
  117158. pNew->u.btree.nEq = saved_nEq;
  117159. pNew->nSkip = saved_nSkip;
  117160. pNew->wsFlags = saved_wsFlags;
  117161. }
  117162. return rc;
  117163. }
  117164. /*
  117165. ** Return True if it is possible that pIndex might be useful in
  117166. ** implementing the ORDER BY clause in pBuilder.
  117167. **
  117168. ** Return False if pBuilder does not contain an ORDER BY clause or
  117169. ** if there is no way for pIndex to be useful in implementing that
  117170. ** ORDER BY clause.
  117171. */
  117172. static int indexMightHelpWithOrderBy(
  117173. WhereLoopBuilder *pBuilder,
  117174. Index *pIndex,
  117175. int iCursor
  117176. ){
  117177. ExprList *pOB;
  117178. ExprList *aColExpr;
  117179. int ii, jj;
  117180. if( pIndex->bUnordered ) return 0;
  117181. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  117182. for(ii=0; ii<pOB->nExpr; ii++){
  117183. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  117184. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  117185. if( pExpr->iColumn<0 ) return 1;
  117186. for(jj=0; jj<pIndex->nKeyCol; jj++){
  117187. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  117188. }
  117189. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  117190. for(jj=0; jj<pIndex->nKeyCol; jj++){
  117191. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  117192. if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  117193. return 1;
  117194. }
  117195. }
  117196. }
  117197. }
  117198. return 0;
  117199. }
  117200. /*
  117201. ** Return a bitmask where 1s indicate that the corresponding column of
  117202. ** the table is used by an index. Only the first 63 columns are considered.
  117203. */
  117204. static Bitmask columnsInIndex(Index *pIdx){
  117205. Bitmask m = 0;
  117206. int j;
  117207. for(j=pIdx->nColumn-1; j>=0; j--){
  117208. int x = pIdx->aiColumn[j];
  117209. if( x>=0 ){
  117210. testcase( x==BMS-1 );
  117211. testcase( x==BMS-2 );
  117212. if( x<BMS-1 ) m |= MASKBIT(x);
  117213. }
  117214. }
  117215. return m;
  117216. }
  117217. /* Check to see if a partial index with pPartIndexWhere can be used
  117218. ** in the current query. Return true if it can be and false if not.
  117219. */
  117220. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  117221. int i;
  117222. WhereTerm *pTerm;
  117223. while( pWhere->op==TK_AND ){
  117224. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  117225. pWhere = pWhere->pRight;
  117226. }
  117227. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  117228. Expr *pExpr = pTerm->pExpr;
  117229. if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
  117230. && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  117231. ){
  117232. return 1;
  117233. }
  117234. }
  117235. return 0;
  117236. }
  117237. /*
  117238. ** Add all WhereLoop objects for a single table of the join where the table
  117239. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  117240. ** a b-tree table, not a virtual table.
  117241. **
  117242. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  117243. ** are calculated as follows:
  117244. **
  117245. ** For a full scan, assuming the table (or index) contains nRow rows:
  117246. **
  117247. ** cost = nRow * 3.0 // full-table scan
  117248. ** cost = nRow * K // scan of covering index
  117249. ** cost = nRow * (K+3.0) // scan of non-covering index
  117250. **
  117251. ** where K is a value between 1.1 and 3.0 set based on the relative
  117252. ** estimated average size of the index and table records.
  117253. **
  117254. ** For an index scan, where nVisit is the number of index rows visited
  117255. ** by the scan, and nSeek is the number of seek operations required on
  117256. ** the index b-tree:
  117257. **
  117258. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  117259. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  117260. **
  117261. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  117262. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  117263. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  117264. **
  117265. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  117266. ** of uncertainty. For this reason, scoring is designed to pick plans that
  117267. ** "do the least harm" if the estimates are inaccurate. For example, a
  117268. ** log(nRow) factor is omitted from a non-covering index scan in order to
  117269. ** bias the scoring in favor of using an index, since the worst-case
  117270. ** performance of using an index is far better than the worst-case performance
  117271. ** of a full table scan.
  117272. */
  117273. static int whereLoopAddBtree(
  117274. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  117275. Bitmask mExtra /* Extra prerequesites for using this table */
  117276. ){
  117277. WhereInfo *pWInfo; /* WHERE analysis context */
  117278. Index *pProbe; /* An index we are evaluating */
  117279. Index sPk; /* A fake index object for the primary key */
  117280. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  117281. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  117282. SrcList *pTabList; /* The FROM clause */
  117283. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  117284. WhereLoop *pNew; /* Template WhereLoop object */
  117285. int rc = SQLITE_OK; /* Return code */
  117286. int iSortIdx = 1; /* Index number */
  117287. int b; /* A boolean value */
  117288. LogEst rSize; /* number of rows in the table */
  117289. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  117290. WhereClause *pWC; /* The parsed WHERE clause */
  117291. Table *pTab; /* Table being queried */
  117292. pNew = pBuilder->pNew;
  117293. pWInfo = pBuilder->pWInfo;
  117294. pTabList = pWInfo->pTabList;
  117295. pSrc = pTabList->a + pNew->iTab;
  117296. pTab = pSrc->pTab;
  117297. pWC = pBuilder->pWC;
  117298. assert( !IsVirtual(pSrc->pTab) );
  117299. if( pSrc->pIBIndex ){
  117300. /* An INDEXED BY clause specifies a particular index to use */
  117301. pProbe = pSrc->pIBIndex;
  117302. }else if( !HasRowid(pTab) ){
  117303. pProbe = pTab->pIndex;
  117304. }else{
  117305. /* There is no INDEXED BY clause. Create a fake Index object in local
  117306. ** variable sPk to represent the rowid primary key index. Make this
  117307. ** fake index the first in a chain of Index objects with all of the real
  117308. ** indices to follow */
  117309. Index *pFirst; /* First of real indices on the table */
  117310. memset(&sPk, 0, sizeof(Index));
  117311. sPk.nKeyCol = 1;
  117312. sPk.nColumn = 1;
  117313. sPk.aiColumn = &aiColumnPk;
  117314. sPk.aiRowLogEst = aiRowEstPk;
  117315. sPk.onError = OE_Replace;
  117316. sPk.pTable = pTab;
  117317. sPk.szIdxRow = pTab->szTabRow;
  117318. aiRowEstPk[0] = pTab->nRowLogEst;
  117319. aiRowEstPk[1] = 0;
  117320. pFirst = pSrc->pTab->pIndex;
  117321. if( pSrc->fg.notIndexed==0 ){
  117322. /* The real indices of the table are only considered if the
  117323. ** NOT INDEXED qualifier is omitted from the FROM clause */
  117324. sPk.pNext = pFirst;
  117325. }
  117326. pProbe = &sPk;
  117327. }
  117328. rSize = pTab->nRowLogEst;
  117329. rLogSize = estLog(rSize);
  117330. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  117331. /* Automatic indexes */
  117332. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  117333. && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
  117334. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  117335. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  117336. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  117337. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  117338. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  117339. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  117340. ){
  117341. /* Generate auto-index WhereLoops */
  117342. WhereTerm *pTerm;
  117343. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  117344. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  117345. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  117346. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  117347. pNew->u.btree.nEq = 1;
  117348. pNew->nSkip = 0;
  117349. pNew->u.btree.pIndex = 0;
  117350. pNew->nLTerm = 1;
  117351. pNew->aLTerm[0] = pTerm;
  117352. /* TUNING: One-time cost for computing the automatic index is
  117353. ** estimated to be X*N*log2(N) where N is the number of rows in
  117354. ** the table being indexed and where X is 7 (LogEst=28) for normal
  117355. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  117356. ** of X is smaller for views and subqueries so that the query planner
  117357. ** will be more aggressive about generating automatic indexes for
  117358. ** those objects, since there is no opportunity to add schema
  117359. ** indexes on subqueries and views. */
  117360. pNew->rSetup = rLogSize + rSize + 4;
  117361. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  117362. pNew->rSetup += 24;
  117363. }
  117364. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  117365. /* TUNING: Each index lookup yields 20 rows in the table. This
  117366. ** is more than the usual guess of 10 rows, since we have no way
  117367. ** of knowing how selective the index will ultimately be. It would
  117368. ** not be unreasonable to make this value much larger. */
  117369. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  117370. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  117371. pNew->wsFlags = WHERE_AUTO_INDEX;
  117372. pNew->prereq = mExtra | pTerm->prereqRight;
  117373. rc = whereLoopInsert(pBuilder, pNew);
  117374. }
  117375. }
  117376. }
  117377. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  117378. /* Loop over all indices
  117379. */
  117380. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  117381. if( pProbe->pPartIdxWhere!=0
  117382. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  117383. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  117384. continue; /* Partial index inappropriate for this query */
  117385. }
  117386. rSize = pProbe->aiRowLogEst[0];
  117387. pNew->u.btree.nEq = 0;
  117388. pNew->nSkip = 0;
  117389. pNew->nLTerm = 0;
  117390. pNew->iSortIdx = 0;
  117391. pNew->rSetup = 0;
  117392. pNew->prereq = mExtra;
  117393. pNew->nOut = rSize;
  117394. pNew->u.btree.pIndex = pProbe;
  117395. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  117396. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  117397. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  117398. if( pProbe->tnum<=0 ){
  117399. /* Integer primary key index */
  117400. pNew->wsFlags = WHERE_IPK;
  117401. /* Full table scan */
  117402. pNew->iSortIdx = b ? iSortIdx : 0;
  117403. /* TUNING: Cost of full table scan is (N*3.0). */
  117404. pNew->rRun = rSize + 16;
  117405. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  117406. whereLoopOutputAdjust(pWC, pNew, rSize);
  117407. rc = whereLoopInsert(pBuilder, pNew);
  117408. pNew->nOut = rSize;
  117409. if( rc ) break;
  117410. }else{
  117411. Bitmask m;
  117412. if( pProbe->isCovering ){
  117413. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  117414. m = 0;
  117415. }else{
  117416. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  117417. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  117418. }
  117419. /* Full scan via index */
  117420. if( b
  117421. || !HasRowid(pTab)
  117422. || ( m==0
  117423. && pProbe->bUnordered==0
  117424. && (pProbe->szIdxRow<pTab->szTabRow)
  117425. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  117426. && sqlite3GlobalConfig.bUseCis
  117427. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  117428. )
  117429. ){
  117430. pNew->iSortIdx = b ? iSortIdx : 0;
  117431. /* The cost of visiting the index rows is N*K, where K is
  117432. ** between 1.1 and 3.0, depending on the relative sizes of the
  117433. ** index and table rows. If this is a non-covering index scan,
  117434. ** also add the cost of visiting table rows (N*3.0). */
  117435. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  117436. if( m!=0 ){
  117437. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
  117438. }
  117439. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  117440. whereLoopOutputAdjust(pWC, pNew, rSize);
  117441. rc = whereLoopInsert(pBuilder, pNew);
  117442. pNew->nOut = rSize;
  117443. if( rc ) break;
  117444. }
  117445. }
  117446. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  117447. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  117448. sqlite3Stat4ProbeFree(pBuilder->pRec);
  117449. pBuilder->nRecValid = 0;
  117450. pBuilder->pRec = 0;
  117451. #endif
  117452. /* If there was an INDEXED BY clause, then only that one index is
  117453. ** considered. */
  117454. if( pSrc->pIBIndex ) break;
  117455. }
  117456. return rc;
  117457. }
  117458. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117459. /*
  117460. ** Add all WhereLoop objects for a table of the join identified by
  117461. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  117462. **
  117463. ** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and
  117464. ** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause
  117465. ** entries that occur before the virtual table in the FROM clause and are
  117466. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  117467. ** mUnusable mask contains all FROM clause entries that occur after the
  117468. ** virtual table and are separated from it by at least one LEFT or
  117469. ** CROSS JOIN.
  117470. **
  117471. ** For example, if the query were:
  117472. **
  117473. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  117474. **
  117475. ** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6).
  117476. **
  117477. ** All the tables in mExtra must be scanned before the current virtual
  117478. ** table. So any terms for which all prerequisites are satisfied by
  117479. ** mExtra may be specified as "usable" in all calls to xBestIndex.
  117480. ** Conversely, all tables in mUnusable must be scanned after the current
  117481. ** virtual table, so any terms for which the prerequisites overlap with
  117482. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  117483. */
  117484. static int whereLoopAddVirtual(
  117485. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  117486. Bitmask mExtra, /* Tables that must be scanned before this one */
  117487. Bitmask mUnusable /* Tables that must be scanned after this one */
  117488. ){
  117489. WhereInfo *pWInfo; /* WHERE analysis context */
  117490. Parse *pParse; /* The parsing context */
  117491. WhereClause *pWC; /* The WHERE clause */
  117492. struct SrcList_item *pSrc; /* The FROM clause term to search */
  117493. Table *pTab;
  117494. sqlite3 *db;
  117495. sqlite3_index_info *pIdxInfo;
  117496. struct sqlite3_index_constraint *pIdxCons;
  117497. struct sqlite3_index_constraint_usage *pUsage;
  117498. WhereTerm *pTerm;
  117499. int i, j;
  117500. int iTerm, mxTerm;
  117501. int nConstraint;
  117502. int seenIn = 0; /* True if an IN operator is seen */
  117503. int seenVar = 0; /* True if a non-constant constraint is seen */
  117504. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  117505. WhereLoop *pNew;
  117506. int rc = SQLITE_OK;
  117507. assert( (mExtra & mUnusable)==0 );
  117508. pWInfo = pBuilder->pWInfo;
  117509. pParse = pWInfo->pParse;
  117510. db = pParse->db;
  117511. pWC = pBuilder->pWC;
  117512. pNew = pBuilder->pNew;
  117513. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  117514. pTab = pSrc->pTab;
  117515. assert( IsVirtual(pTab) );
  117516. pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy);
  117517. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  117518. pNew->prereq = 0;
  117519. pNew->rSetup = 0;
  117520. pNew->wsFlags = WHERE_VIRTUALTABLE;
  117521. pNew->nLTerm = 0;
  117522. pNew->u.vtab.needFree = 0;
  117523. pUsage = pIdxInfo->aConstraintUsage;
  117524. nConstraint = pIdxInfo->nConstraint;
  117525. if( whereLoopResize(db, pNew, nConstraint) ){
  117526. sqlite3DbFree(db, pIdxInfo);
  117527. return SQLITE_NOMEM;
  117528. }
  117529. for(iPhase=0; iPhase<=3; iPhase++){
  117530. if( !seenIn && (iPhase&1)!=0 ){
  117531. iPhase++;
  117532. if( iPhase>3 ) break;
  117533. }
  117534. if( !seenVar && iPhase>1 ) break;
  117535. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  117536. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  117537. j = pIdxCons->iTermOffset;
  117538. pTerm = &pWC->a[j];
  117539. switch( iPhase ){
  117540. case 0: /* Constants without IN operator */
  117541. pIdxCons->usable = 0;
  117542. if( (pTerm->eOperator & WO_IN)!=0 ){
  117543. seenIn = 1;
  117544. }
  117545. if( (pTerm->prereqRight & ~mExtra)!=0 ){
  117546. seenVar = 1;
  117547. }else if( (pTerm->eOperator & WO_IN)==0 ){
  117548. pIdxCons->usable = 1;
  117549. }
  117550. break;
  117551. case 1: /* Constants with IN operators */
  117552. assert( seenIn );
  117553. pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0;
  117554. break;
  117555. case 2: /* Variables without IN */
  117556. assert( seenVar );
  117557. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  117558. break;
  117559. default: /* Variables with IN */
  117560. assert( seenVar && seenIn );
  117561. pIdxCons->usable = 1;
  117562. break;
  117563. }
  117564. }
  117565. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  117566. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  117567. pIdxInfo->idxStr = 0;
  117568. pIdxInfo->idxNum = 0;
  117569. pIdxInfo->needToFreeIdxStr = 0;
  117570. pIdxInfo->orderByConsumed = 0;
  117571. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  117572. pIdxInfo->estimatedRows = 25;
  117573. pIdxInfo->idxFlags = 0;
  117574. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  117575. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  117576. if( rc ) goto whereLoopAddVtab_exit;
  117577. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  117578. pNew->prereq = mExtra;
  117579. mxTerm = -1;
  117580. assert( pNew->nLSlot>=nConstraint );
  117581. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  117582. pNew->u.vtab.omitMask = 0;
  117583. for(i=0; i<nConstraint; i++, pIdxCons++){
  117584. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  117585. j = pIdxCons->iTermOffset;
  117586. if( iTerm>=nConstraint
  117587. || j<0
  117588. || j>=pWC->nTerm
  117589. || pNew->aLTerm[iTerm]!=0
  117590. ){
  117591. rc = SQLITE_ERROR;
  117592. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  117593. goto whereLoopAddVtab_exit;
  117594. }
  117595. testcase( iTerm==nConstraint-1 );
  117596. testcase( j==0 );
  117597. testcase( j==pWC->nTerm-1 );
  117598. pTerm = &pWC->a[j];
  117599. pNew->prereq |= pTerm->prereqRight;
  117600. assert( iTerm<pNew->nLSlot );
  117601. pNew->aLTerm[iTerm] = pTerm;
  117602. if( iTerm>mxTerm ) mxTerm = iTerm;
  117603. testcase( iTerm==15 );
  117604. testcase( iTerm==16 );
  117605. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  117606. if( (pTerm->eOperator & WO_IN)!=0 ){
  117607. if( pUsage[i].omit==0 ){
  117608. /* Do not attempt to use an IN constraint if the virtual table
  117609. ** says that the equivalent EQ constraint cannot be safely omitted.
  117610. ** If we do attempt to use such a constraint, some rows might be
  117611. ** repeated in the output. */
  117612. break;
  117613. }
  117614. /* A virtual table that is constrained by an IN clause may not
  117615. ** consume the ORDER BY clause because (1) the order of IN terms
  117616. ** is not necessarily related to the order of output terms and
  117617. ** (2) Multiple outputs from a single IN value will not merge
  117618. ** together. */
  117619. pIdxInfo->orderByConsumed = 0;
  117620. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  117621. }
  117622. }
  117623. }
  117624. if( i>=nConstraint ){
  117625. pNew->nLTerm = mxTerm+1;
  117626. assert( pNew->nLTerm<=pNew->nLSlot );
  117627. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  117628. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  117629. pIdxInfo->needToFreeIdxStr = 0;
  117630. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  117631. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  117632. pIdxInfo->nOrderBy : 0);
  117633. pNew->rSetup = 0;
  117634. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  117635. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  117636. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  117637. ** that the scan will visit at most one row. Clear it otherwise. */
  117638. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  117639. pNew->wsFlags |= WHERE_ONEROW;
  117640. }else{
  117641. pNew->wsFlags &= ~WHERE_ONEROW;
  117642. }
  117643. whereLoopInsert(pBuilder, pNew);
  117644. if( pNew->u.vtab.needFree ){
  117645. sqlite3_free(pNew->u.vtab.idxStr);
  117646. pNew->u.vtab.needFree = 0;
  117647. }
  117648. }
  117649. }
  117650. whereLoopAddVtab_exit:
  117651. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  117652. sqlite3DbFree(db, pIdxInfo);
  117653. return rc;
  117654. }
  117655. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  117656. /*
  117657. ** Add WhereLoop entries to handle OR terms. This works for either
  117658. ** btrees or virtual tables.
  117659. */
  117660. static int whereLoopAddOr(
  117661. WhereLoopBuilder *pBuilder,
  117662. Bitmask mExtra,
  117663. Bitmask mUnusable
  117664. ){
  117665. WhereInfo *pWInfo = pBuilder->pWInfo;
  117666. WhereClause *pWC;
  117667. WhereLoop *pNew;
  117668. WhereTerm *pTerm, *pWCEnd;
  117669. int rc = SQLITE_OK;
  117670. int iCur;
  117671. WhereClause tempWC;
  117672. WhereLoopBuilder sSubBuild;
  117673. WhereOrSet sSum, sCur;
  117674. struct SrcList_item *pItem;
  117675. pWC = pBuilder->pWC;
  117676. pWCEnd = pWC->a + pWC->nTerm;
  117677. pNew = pBuilder->pNew;
  117678. memset(&sSum, 0, sizeof(sSum));
  117679. pItem = pWInfo->pTabList->a + pNew->iTab;
  117680. iCur = pItem->iCursor;
  117681. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  117682. if( (pTerm->eOperator & WO_OR)!=0
  117683. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  117684. ){
  117685. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  117686. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  117687. WhereTerm *pOrTerm;
  117688. int once = 1;
  117689. int i, j;
  117690. sSubBuild = *pBuilder;
  117691. sSubBuild.pOrderBy = 0;
  117692. sSubBuild.pOrSet = &sCur;
  117693. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  117694. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  117695. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  117696. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  117697. }else if( pOrTerm->leftCursor==iCur ){
  117698. tempWC.pWInfo = pWC->pWInfo;
  117699. tempWC.pOuter = pWC;
  117700. tempWC.op = TK_AND;
  117701. tempWC.nTerm = 1;
  117702. tempWC.a = pOrTerm;
  117703. sSubBuild.pWC = &tempWC;
  117704. }else{
  117705. continue;
  117706. }
  117707. sCur.n = 0;
  117708. #ifdef WHERETRACE_ENABLED
  117709. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  117710. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  117711. if( sqlite3WhereTrace & 0x400 ){
  117712. for(i=0; i<sSubBuild.pWC->nTerm; i++){
  117713. whereTermPrint(&sSubBuild.pWC->a[i], i);
  117714. }
  117715. }
  117716. #endif
  117717. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117718. if( IsVirtual(pItem->pTab) ){
  117719. rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable);
  117720. }else
  117721. #endif
  117722. {
  117723. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  117724. }
  117725. if( rc==SQLITE_OK ){
  117726. rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable);
  117727. }
  117728. assert( rc==SQLITE_OK || sCur.n==0 );
  117729. if( sCur.n==0 ){
  117730. sSum.n = 0;
  117731. break;
  117732. }else if( once ){
  117733. whereOrMove(&sSum, &sCur);
  117734. once = 0;
  117735. }else{
  117736. WhereOrSet sPrev;
  117737. whereOrMove(&sPrev, &sSum);
  117738. sSum.n = 0;
  117739. for(i=0; i<sPrev.n; i++){
  117740. for(j=0; j<sCur.n; j++){
  117741. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  117742. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  117743. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  117744. }
  117745. }
  117746. }
  117747. }
  117748. pNew->nLTerm = 1;
  117749. pNew->aLTerm[0] = pTerm;
  117750. pNew->wsFlags = WHERE_MULTI_OR;
  117751. pNew->rSetup = 0;
  117752. pNew->iSortIdx = 0;
  117753. memset(&pNew->u, 0, sizeof(pNew->u));
  117754. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  117755. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  117756. ** of all sub-scans required by the OR-scan. However, due to rounding
  117757. ** errors, it may be that the cost of the OR-scan is equal to its
  117758. ** most expensive sub-scan. Add the smallest possible penalty
  117759. ** (equivalent to multiplying the cost by 1.07) to ensure that
  117760. ** this does not happen. Otherwise, for WHERE clauses such as the
  117761. ** following where there is an index on "y":
  117762. **
  117763. ** WHERE likelihood(x=?, 0.99) OR y=?
  117764. **
  117765. ** the planner may elect to "OR" together a full-table scan and an
  117766. ** index lookup. And other similarly odd results. */
  117767. pNew->rRun = sSum.a[i].rRun + 1;
  117768. pNew->nOut = sSum.a[i].nOut;
  117769. pNew->prereq = sSum.a[i].prereq;
  117770. rc = whereLoopInsert(pBuilder, pNew);
  117771. }
  117772. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  117773. }
  117774. }
  117775. return rc;
  117776. }
  117777. /*
  117778. ** Add all WhereLoop objects for all tables
  117779. */
  117780. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  117781. WhereInfo *pWInfo = pBuilder->pWInfo;
  117782. Bitmask mExtra = 0;
  117783. Bitmask mPrior = 0;
  117784. int iTab;
  117785. SrcList *pTabList = pWInfo->pTabList;
  117786. struct SrcList_item *pItem;
  117787. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  117788. sqlite3 *db = pWInfo->pParse->db;
  117789. int rc = SQLITE_OK;
  117790. WhereLoop *pNew;
  117791. u8 priorJointype = 0;
  117792. /* Loop over the tables in the join, from left to right */
  117793. pNew = pBuilder->pNew;
  117794. whereLoopInit(pNew);
  117795. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  117796. Bitmask mUnusable = 0;
  117797. pNew->iTab = iTab;
  117798. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  117799. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  117800. /* This condition is true when pItem is the FROM clause term on the
  117801. ** right-hand-side of a LEFT or CROSS JOIN. */
  117802. mExtra = mPrior;
  117803. }
  117804. priorJointype = pItem->fg.jointype;
  117805. if( IsVirtual(pItem->pTab) ){
  117806. struct SrcList_item *p;
  117807. for(p=&pItem[1]; p<pEnd; p++){
  117808. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  117809. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  117810. }
  117811. }
  117812. rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable);
  117813. }else{
  117814. rc = whereLoopAddBtree(pBuilder, mExtra);
  117815. }
  117816. if( rc==SQLITE_OK ){
  117817. rc = whereLoopAddOr(pBuilder, mExtra, mUnusable);
  117818. }
  117819. mPrior |= pNew->maskSelf;
  117820. if( rc || db->mallocFailed ) break;
  117821. }
  117822. whereLoopClear(db, pNew);
  117823. return rc;
  117824. }
  117825. /*
  117826. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  117827. ** parameters) to see if it outputs rows in the requested ORDER BY
  117828. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  117829. **
  117830. ** N>0: N terms of the ORDER BY clause are satisfied
  117831. ** N==0: No terms of the ORDER BY clause are satisfied
  117832. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  117833. **
  117834. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  117835. ** strict. With GROUP BY and DISTINCT the only requirement is that
  117836. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  117837. ** and DISTINCT do not require rows to appear in any particular order as long
  117838. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  117839. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  117840. ** pOrderBy terms must be matched in strict left-to-right order.
  117841. */
  117842. static i8 wherePathSatisfiesOrderBy(
  117843. WhereInfo *pWInfo, /* The WHERE clause */
  117844. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  117845. WherePath *pPath, /* The WherePath to check */
  117846. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  117847. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  117848. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  117849. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  117850. ){
  117851. u8 revSet; /* True if rev is known */
  117852. u8 rev; /* Composite sort order */
  117853. u8 revIdx; /* Index sort order */
  117854. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  117855. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  117856. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  117857. u16 nKeyCol; /* Number of key columns in pIndex */
  117858. u16 nColumn; /* Total number of ordered columns in the index */
  117859. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  117860. int iLoop; /* Index of WhereLoop in pPath being processed */
  117861. int i, j; /* Loop counters */
  117862. int iCur; /* Cursor number for current WhereLoop */
  117863. int iColumn; /* A column number within table iCur */
  117864. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  117865. WhereTerm *pTerm; /* A single term of the WHERE clause */
  117866. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  117867. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  117868. Index *pIndex; /* The index associated with pLoop */
  117869. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  117870. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  117871. Bitmask obDone; /* Mask of all ORDER BY terms */
  117872. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  117873. Bitmask ready; /* Mask of inner loops */
  117874. /*
  117875. ** We say the WhereLoop is "one-row" if it generates no more than one
  117876. ** row of output. A WhereLoop is one-row if all of the following are true:
  117877. ** (a) All index columns match with WHERE_COLUMN_EQ.
  117878. ** (b) The index is unique
  117879. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  117880. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  117881. **
  117882. ** We say the WhereLoop is "order-distinct" if the set of columns from
  117883. ** that WhereLoop that are in the ORDER BY clause are different for every
  117884. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  117885. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  117886. ** is not order-distinct. To be order-distinct is not quite the same as being
  117887. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  117888. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  117889. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  117890. **
  117891. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  117892. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  117893. ** automatically order-distinct.
  117894. */
  117895. assert( pOrderBy!=0 );
  117896. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  117897. nOrderBy = pOrderBy->nExpr;
  117898. testcase( nOrderBy==BMS-1 );
  117899. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  117900. isOrderDistinct = 1;
  117901. obDone = MASKBIT(nOrderBy)-1;
  117902. orderDistinctMask = 0;
  117903. ready = 0;
  117904. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  117905. if( iLoop>0 ) ready |= pLoop->maskSelf;
  117906. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  117907. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  117908. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  117909. break;
  117910. }
  117911. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  117912. /* Mark off any ORDER BY term X that is a column in the table of
  117913. ** the current loop for which there is term in the WHERE
  117914. ** clause of the form X IS NULL or X=? that reference only outer
  117915. ** loops.
  117916. */
  117917. for(i=0; i<nOrderBy; i++){
  117918. if( MASKBIT(i) & obSat ) continue;
  117919. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  117920. if( pOBExpr->op!=TK_COLUMN ) continue;
  117921. if( pOBExpr->iTable!=iCur ) continue;
  117922. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  117923. ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
  117924. if( pTerm==0 ) continue;
  117925. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  117926. const char *z1, *z2;
  117927. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  117928. if( !pColl ) pColl = db->pDfltColl;
  117929. z1 = pColl->zName;
  117930. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  117931. if( !pColl ) pColl = db->pDfltColl;
  117932. z2 = pColl->zName;
  117933. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  117934. testcase( pTerm->pExpr->op==TK_IS );
  117935. }
  117936. obSat |= MASKBIT(i);
  117937. }
  117938. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  117939. if( pLoop->wsFlags & WHERE_IPK ){
  117940. pIndex = 0;
  117941. nKeyCol = 0;
  117942. nColumn = 1;
  117943. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  117944. return 0;
  117945. }else{
  117946. nKeyCol = pIndex->nKeyCol;
  117947. nColumn = pIndex->nColumn;
  117948. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  117949. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  117950. || !HasRowid(pIndex->pTable));
  117951. isOrderDistinct = IsUniqueIndex(pIndex);
  117952. }
  117953. /* Loop through all columns of the index and deal with the ones
  117954. ** that are not constrained by == or IN.
  117955. */
  117956. rev = revSet = 0;
  117957. distinctColumns = 0;
  117958. for(j=0; j<nColumn; j++){
  117959. u8 bOnce; /* True to run the ORDER BY search loop */
  117960. /* Skip over == and IS NULL terms */
  117961. if( j<pLoop->u.btree.nEq
  117962. && pLoop->nSkip==0
  117963. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
  117964. ){
  117965. if( i & WO_ISNULL ){
  117966. testcase( isOrderDistinct );
  117967. isOrderDistinct = 0;
  117968. }
  117969. continue;
  117970. }
  117971. /* Get the column number in the table (iColumn) and sort order
  117972. ** (revIdx) for the j-th column of the index.
  117973. */
  117974. if( pIndex ){
  117975. iColumn = pIndex->aiColumn[j];
  117976. revIdx = pIndex->aSortOrder[j];
  117977. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  117978. }else{
  117979. iColumn = XN_ROWID;
  117980. revIdx = 0;
  117981. }
  117982. /* An unconstrained column that might be NULL means that this
  117983. ** WhereLoop is not well-ordered
  117984. */
  117985. if( isOrderDistinct
  117986. && iColumn>=0
  117987. && j>=pLoop->u.btree.nEq
  117988. && pIndex->pTable->aCol[iColumn].notNull==0
  117989. ){
  117990. isOrderDistinct = 0;
  117991. }
  117992. /* Find the ORDER BY term that corresponds to the j-th column
  117993. ** of the index and mark that ORDER BY term off
  117994. */
  117995. bOnce = 1;
  117996. isMatch = 0;
  117997. for(i=0; bOnce && i<nOrderBy; i++){
  117998. if( MASKBIT(i) & obSat ) continue;
  117999. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  118000. testcase( wctrlFlags & WHERE_GROUPBY );
  118001. testcase( wctrlFlags & WHERE_DISTINCTBY );
  118002. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  118003. if( iColumn>=(-1) ){
  118004. if( pOBExpr->op!=TK_COLUMN ) continue;
  118005. if( pOBExpr->iTable!=iCur ) continue;
  118006. if( pOBExpr->iColumn!=iColumn ) continue;
  118007. }else{
  118008. if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
  118009. continue;
  118010. }
  118011. }
  118012. if( iColumn>=0 ){
  118013. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  118014. if( !pColl ) pColl = db->pDfltColl;
  118015. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  118016. }
  118017. isMatch = 1;
  118018. break;
  118019. }
  118020. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  118021. /* Make sure the sort order is compatible in an ORDER BY clause.
  118022. ** Sort order is irrelevant for a GROUP BY clause. */
  118023. if( revSet ){
  118024. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  118025. }else{
  118026. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  118027. if( rev ) *pRevMask |= MASKBIT(iLoop);
  118028. revSet = 1;
  118029. }
  118030. }
  118031. if( isMatch ){
  118032. if( iColumn<0 ){
  118033. testcase( distinctColumns==0 );
  118034. distinctColumns = 1;
  118035. }
  118036. obSat |= MASKBIT(i);
  118037. }else{
  118038. /* No match found */
  118039. if( j==0 || j<nKeyCol ){
  118040. testcase( isOrderDistinct!=0 );
  118041. isOrderDistinct = 0;
  118042. }
  118043. break;
  118044. }
  118045. } /* end Loop over all index columns */
  118046. if( distinctColumns ){
  118047. testcase( isOrderDistinct==0 );
  118048. isOrderDistinct = 1;
  118049. }
  118050. } /* end-if not one-row */
  118051. /* Mark off any other ORDER BY terms that reference pLoop */
  118052. if( isOrderDistinct ){
  118053. orderDistinctMask |= pLoop->maskSelf;
  118054. for(i=0; i<nOrderBy; i++){
  118055. Expr *p;
  118056. Bitmask mTerm;
  118057. if( MASKBIT(i) & obSat ) continue;
  118058. p = pOrderBy->a[i].pExpr;
  118059. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  118060. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  118061. if( (mTerm&~orderDistinctMask)==0 ){
  118062. obSat |= MASKBIT(i);
  118063. }
  118064. }
  118065. }
  118066. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  118067. if( obSat==obDone ) return (i8)nOrderBy;
  118068. if( !isOrderDistinct ){
  118069. for(i=nOrderBy-1; i>0; i--){
  118070. Bitmask m = MASKBIT(i) - 1;
  118071. if( (obSat&m)==m ) return i;
  118072. }
  118073. return 0;
  118074. }
  118075. return -1;
  118076. }
  118077. /*
  118078. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  118079. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  118080. ** BY clause - and so any order that groups rows as required satisfies the
  118081. ** request.
  118082. **
  118083. ** Normally, in this case it is not possible for the caller to determine
  118084. ** whether or not the rows are really being delivered in sorted order, or
  118085. ** just in some other order that provides the required grouping. However,
  118086. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  118087. ** this function may be called on the returned WhereInfo object. It returns
  118088. ** true if the rows really will be sorted in the specified order, or false
  118089. ** otherwise.
  118090. **
  118091. ** For example, assuming:
  118092. **
  118093. ** CREATE INDEX i1 ON t1(x, Y);
  118094. **
  118095. ** then
  118096. **
  118097. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  118098. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  118099. */
  118100. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  118101. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  118102. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  118103. return pWInfo->sorted;
  118104. }
  118105. #ifdef WHERETRACE_ENABLED
  118106. /* For debugging use only: */
  118107. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  118108. static char zName[65];
  118109. int i;
  118110. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  118111. if( pLast ) zName[i++] = pLast->cId;
  118112. zName[i] = 0;
  118113. return zName;
  118114. }
  118115. #endif
  118116. /*
  118117. ** Return the cost of sorting nRow rows, assuming that the keys have
  118118. ** nOrderby columns and that the first nSorted columns are already in
  118119. ** order.
  118120. */
  118121. static LogEst whereSortingCost(
  118122. WhereInfo *pWInfo,
  118123. LogEst nRow,
  118124. int nOrderBy,
  118125. int nSorted
  118126. ){
  118127. /* TUNING: Estimated cost of a full external sort, where N is
  118128. ** the number of rows to sort is:
  118129. **
  118130. ** cost = (3.0 * N * log(N)).
  118131. **
  118132. ** Or, if the order-by clause has X terms but only the last Y
  118133. ** terms are out of order, then block-sorting will reduce the
  118134. ** sorting cost to:
  118135. **
  118136. ** cost = (3.0 * N * log(N)) * (Y/X)
  118137. **
  118138. ** The (Y/X) term is implemented using stack variable rScale
  118139. ** below. */
  118140. LogEst rScale, rSortCost;
  118141. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  118142. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  118143. rSortCost = nRow + estLog(nRow) + rScale + 16;
  118144. /* TUNING: The cost of implementing DISTINCT using a B-TREE is
  118145. ** similar but with a larger constant of proportionality.
  118146. ** Multiply by an additional factor of 3.0. */
  118147. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  118148. rSortCost += 16;
  118149. }
  118150. return rSortCost;
  118151. }
  118152. /*
  118153. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  118154. ** attempts to find the lowest cost path that visits each WhereLoop
  118155. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  118156. **
  118157. ** Assume that the total number of output rows that will need to be sorted
  118158. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  118159. ** costs if nRowEst==0.
  118160. **
  118161. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  118162. ** error occurs.
  118163. */
  118164. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  118165. int mxChoice; /* Maximum number of simultaneous paths tracked */
  118166. int nLoop; /* Number of terms in the join */
  118167. Parse *pParse; /* Parsing context */
  118168. sqlite3 *db; /* The database connection */
  118169. int iLoop; /* Loop counter over the terms of the join */
  118170. int ii, jj; /* Loop counters */
  118171. int mxI = 0; /* Index of next entry to replace */
  118172. int nOrderBy; /* Number of ORDER BY clause terms */
  118173. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  118174. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  118175. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  118176. WherePath *aFrom; /* All nFrom paths at the previous level */
  118177. WherePath *aTo; /* The nTo best paths at the current level */
  118178. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  118179. WherePath *pTo; /* An element of aTo[] that we are working on */
  118180. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  118181. WhereLoop **pX; /* Used to divy up the pSpace memory */
  118182. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  118183. char *pSpace; /* Temporary memory used by this routine */
  118184. int nSpace; /* Bytes of space allocated at pSpace */
  118185. pParse = pWInfo->pParse;
  118186. db = pParse->db;
  118187. nLoop = pWInfo->nLevel;
  118188. /* TUNING: For simple queries, only the best path is tracked.
  118189. ** For 2-way joins, the 5 best paths are followed.
  118190. ** For joins of 3 or more tables, track the 10 best paths */
  118191. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  118192. assert( nLoop<=pWInfo->pTabList->nSrc );
  118193. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  118194. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  118195. ** case the purpose of this call is to estimate the number of rows returned
  118196. ** by the overall query. Once this estimate has been obtained, the caller
  118197. ** will invoke this function a second time, passing the estimate as the
  118198. ** nRowEst parameter. */
  118199. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  118200. nOrderBy = 0;
  118201. }else{
  118202. nOrderBy = pWInfo->pOrderBy->nExpr;
  118203. }
  118204. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  118205. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  118206. nSpace += sizeof(LogEst) * nOrderBy;
  118207. pSpace = sqlite3DbMallocRaw(db, nSpace);
  118208. if( pSpace==0 ) return SQLITE_NOMEM;
  118209. aTo = (WherePath*)pSpace;
  118210. aFrom = aTo+mxChoice;
  118211. memset(aFrom, 0, sizeof(aFrom[0]));
  118212. pX = (WhereLoop**)(aFrom+mxChoice);
  118213. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  118214. pFrom->aLoop = pX;
  118215. }
  118216. if( nOrderBy ){
  118217. /* If there is an ORDER BY clause and it is not being ignored, set up
  118218. ** space for the aSortCost[] array. Each element of the aSortCost array
  118219. ** is either zero - meaning it has not yet been initialized - or the
  118220. ** cost of sorting nRowEst rows of data where the first X terms of
  118221. ** the ORDER BY clause are already in order, where X is the array
  118222. ** index. */
  118223. aSortCost = (LogEst*)pX;
  118224. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  118225. }
  118226. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  118227. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  118228. /* Seed the search with a single WherePath containing zero WhereLoops.
  118229. **
  118230. ** TUNING: Do not let the number of iterations go above 28. If the cost
  118231. ** of computing an automatic index is not paid back within the first 28
  118232. ** rows, then do not use the automatic index. */
  118233. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  118234. nFrom = 1;
  118235. assert( aFrom[0].isOrdered==0 );
  118236. if( nOrderBy ){
  118237. /* If nLoop is zero, then there are no FROM terms in the query. Since
  118238. ** in this case the query may return a maximum of one row, the results
  118239. ** are already in the requested order. Set isOrdered to nOrderBy to
  118240. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  118241. ** -1, indicating that the result set may or may not be ordered,
  118242. ** depending on the loops added to the current plan. */
  118243. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  118244. }
  118245. /* Compute successively longer WherePaths using the previous generation
  118246. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  118247. ** best paths at each generation */
  118248. for(iLoop=0; iLoop<nLoop; iLoop++){
  118249. nTo = 0;
  118250. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  118251. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  118252. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  118253. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  118254. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  118255. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  118256. Bitmask maskNew; /* Mask of src visited by (..) */
  118257. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  118258. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  118259. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  118260. /* At this point, pWLoop is a candidate to be the next loop.
  118261. ** Compute its cost */
  118262. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  118263. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  118264. nOut = pFrom->nRow + pWLoop->nOut;
  118265. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  118266. if( isOrdered<0 ){
  118267. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  118268. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  118269. iLoop, pWLoop, &revMask);
  118270. }else{
  118271. revMask = pFrom->revLoop;
  118272. }
  118273. if( isOrdered>=0 && isOrdered<nOrderBy ){
  118274. if( aSortCost[isOrdered]==0 ){
  118275. aSortCost[isOrdered] = whereSortingCost(
  118276. pWInfo, nRowEst, nOrderBy, isOrdered
  118277. );
  118278. }
  118279. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  118280. WHERETRACE(0x002,
  118281. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  118282. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  118283. rUnsorted, rCost));
  118284. }else{
  118285. rCost = rUnsorted;
  118286. }
  118287. /* Check to see if pWLoop should be added to the set of
  118288. ** mxChoice best-so-far paths.
  118289. **
  118290. ** First look for an existing path among best-so-far paths
  118291. ** that covers the same set of loops and has the same isOrdered
  118292. ** setting as the current path candidate.
  118293. **
  118294. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  118295. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  118296. ** of legal values for isOrdered, -1..64.
  118297. */
  118298. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  118299. if( pTo->maskLoop==maskNew
  118300. && ((pTo->isOrdered^isOrdered)&0x80)==0
  118301. ){
  118302. testcase( jj==nTo-1 );
  118303. break;
  118304. }
  118305. }
  118306. if( jj>=nTo ){
  118307. /* None of the existing best-so-far paths match the candidate. */
  118308. if( nTo>=mxChoice
  118309. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  118310. ){
  118311. /* The current candidate is no better than any of the mxChoice
  118312. ** paths currently in the best-so-far buffer. So discard
  118313. ** this candidate as not viable. */
  118314. #ifdef WHERETRACE_ENABLED /* 0x4 */
  118315. if( sqlite3WhereTrace&0x4 ){
  118316. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  118317. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  118318. isOrdered>=0 ? isOrdered+'0' : '?');
  118319. }
  118320. #endif
  118321. continue;
  118322. }
  118323. /* If we reach this points it means that the new candidate path
  118324. ** needs to be added to the set of best-so-far paths. */
  118325. if( nTo<mxChoice ){
  118326. /* Increase the size of the aTo set by one */
  118327. jj = nTo++;
  118328. }else{
  118329. /* New path replaces the prior worst to keep count below mxChoice */
  118330. jj = mxI;
  118331. }
  118332. pTo = &aTo[jj];
  118333. #ifdef WHERETRACE_ENABLED /* 0x4 */
  118334. if( sqlite3WhereTrace&0x4 ){
  118335. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  118336. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  118337. isOrdered>=0 ? isOrdered+'0' : '?');
  118338. }
  118339. #endif
  118340. }else{
  118341. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  118342. ** same set of loops and has the sam isOrdered setting as the
  118343. ** candidate path. Check to see if the candidate should replace
  118344. ** pTo or if the candidate should be skipped */
  118345. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  118346. #ifdef WHERETRACE_ENABLED /* 0x4 */
  118347. if( sqlite3WhereTrace&0x4 ){
  118348. sqlite3DebugPrintf(
  118349. "Skip %s cost=%-3d,%3d order=%c",
  118350. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  118351. isOrdered>=0 ? isOrdered+'0' : '?');
  118352. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  118353. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  118354. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  118355. }
  118356. #endif
  118357. /* Discard the candidate path from further consideration */
  118358. testcase( pTo->rCost==rCost );
  118359. continue;
  118360. }
  118361. testcase( pTo->rCost==rCost+1 );
  118362. /* Control reaches here if the candidate path is better than the
  118363. ** pTo path. Replace pTo with the candidate. */
  118364. #ifdef WHERETRACE_ENABLED /* 0x4 */
  118365. if( sqlite3WhereTrace&0x4 ){
  118366. sqlite3DebugPrintf(
  118367. "Update %s cost=%-3d,%3d order=%c",
  118368. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  118369. isOrdered>=0 ? isOrdered+'0' : '?');
  118370. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  118371. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  118372. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  118373. }
  118374. #endif
  118375. }
  118376. /* pWLoop is a winner. Add it to the set of best so far */
  118377. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  118378. pTo->revLoop = revMask;
  118379. pTo->nRow = nOut;
  118380. pTo->rCost = rCost;
  118381. pTo->rUnsorted = rUnsorted;
  118382. pTo->isOrdered = isOrdered;
  118383. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  118384. pTo->aLoop[iLoop] = pWLoop;
  118385. if( nTo>=mxChoice ){
  118386. mxI = 0;
  118387. mxCost = aTo[0].rCost;
  118388. mxUnsorted = aTo[0].nRow;
  118389. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  118390. if( pTo->rCost>mxCost
  118391. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  118392. ){
  118393. mxCost = pTo->rCost;
  118394. mxUnsorted = pTo->rUnsorted;
  118395. mxI = jj;
  118396. }
  118397. }
  118398. }
  118399. }
  118400. }
  118401. #ifdef WHERETRACE_ENABLED /* >=2 */
  118402. if( sqlite3WhereTrace & 0x02 ){
  118403. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  118404. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  118405. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  118406. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  118407. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  118408. if( pTo->isOrdered>0 ){
  118409. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  118410. }else{
  118411. sqlite3DebugPrintf("\n");
  118412. }
  118413. }
  118414. }
  118415. #endif
  118416. /* Swap the roles of aFrom and aTo for the next generation */
  118417. pFrom = aTo;
  118418. aTo = aFrom;
  118419. aFrom = pFrom;
  118420. nFrom = nTo;
  118421. }
  118422. if( nFrom==0 ){
  118423. sqlite3ErrorMsg(pParse, "no query solution");
  118424. sqlite3DbFree(db, pSpace);
  118425. return SQLITE_ERROR;
  118426. }
  118427. /* Find the lowest cost path. pFrom will be left pointing to that path */
  118428. pFrom = aFrom;
  118429. for(ii=1; ii<nFrom; ii++){
  118430. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  118431. }
  118432. assert( pWInfo->nLevel==nLoop );
  118433. /* Load the lowest cost path into pWInfo */
  118434. for(iLoop=0; iLoop<nLoop; iLoop++){
  118435. WhereLevel *pLevel = pWInfo->a + iLoop;
  118436. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  118437. pLevel->iFrom = pWLoop->iTab;
  118438. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  118439. }
  118440. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  118441. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  118442. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  118443. && nRowEst
  118444. ){
  118445. Bitmask notUsed;
  118446. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  118447. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  118448. if( rc==pWInfo->pResultSet->nExpr ){
  118449. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  118450. }
  118451. }
  118452. if( pWInfo->pOrderBy ){
  118453. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  118454. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  118455. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  118456. }
  118457. }else{
  118458. pWInfo->nOBSat = pFrom->isOrdered;
  118459. if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
  118460. pWInfo->revMask = pFrom->revLoop;
  118461. }
  118462. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  118463. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  118464. ){
  118465. Bitmask revMask = 0;
  118466. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  118467. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  118468. );
  118469. assert( pWInfo->sorted==0 );
  118470. if( nOrder==pWInfo->pOrderBy->nExpr ){
  118471. pWInfo->sorted = 1;
  118472. pWInfo->revMask = revMask;
  118473. }
  118474. }
  118475. }
  118476. pWInfo->nRowOut = pFrom->nRow;
  118477. /* Free temporary memory and return success */
  118478. sqlite3DbFree(db, pSpace);
  118479. return SQLITE_OK;
  118480. }
  118481. /*
  118482. ** Most queries use only a single table (they are not joins) and have
  118483. ** simple == constraints against indexed fields. This routine attempts
  118484. ** to plan those simple cases using much less ceremony than the
  118485. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  118486. ** times for the common case.
  118487. **
  118488. ** Return non-zero on success, if this query can be handled by this
  118489. ** no-frills query planner. Return zero if this query needs the
  118490. ** general-purpose query planner.
  118491. */
  118492. static int whereShortCut(WhereLoopBuilder *pBuilder){
  118493. WhereInfo *pWInfo;
  118494. struct SrcList_item *pItem;
  118495. WhereClause *pWC;
  118496. WhereTerm *pTerm;
  118497. WhereLoop *pLoop;
  118498. int iCur;
  118499. int j;
  118500. Table *pTab;
  118501. Index *pIdx;
  118502. pWInfo = pBuilder->pWInfo;
  118503. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  118504. assert( pWInfo->pTabList->nSrc>=1 );
  118505. pItem = pWInfo->pTabList->a;
  118506. pTab = pItem->pTab;
  118507. if( IsVirtual(pTab) ) return 0;
  118508. if( pItem->fg.isIndexedBy ) return 0;
  118509. iCur = pItem->iCursor;
  118510. pWC = &pWInfo->sWC;
  118511. pLoop = pBuilder->pNew;
  118512. pLoop->wsFlags = 0;
  118513. pLoop->nSkip = 0;
  118514. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  118515. if( pTerm ){
  118516. testcase( pTerm->eOperator & WO_IS );
  118517. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  118518. pLoop->aLTerm[0] = pTerm;
  118519. pLoop->nLTerm = 1;
  118520. pLoop->u.btree.nEq = 1;
  118521. /* TUNING: Cost of a rowid lookup is 10 */
  118522. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  118523. }else{
  118524. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  118525. int opMask;
  118526. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  118527. if( !IsUniqueIndex(pIdx)
  118528. || pIdx->pPartIdxWhere!=0
  118529. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  118530. ) continue;
  118531. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  118532. for(j=0; j<pIdx->nKeyCol; j++){
  118533. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  118534. if( pTerm==0 ) break;
  118535. testcase( pTerm->eOperator & WO_IS );
  118536. pLoop->aLTerm[j] = pTerm;
  118537. }
  118538. if( j!=pIdx->nKeyCol ) continue;
  118539. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  118540. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  118541. pLoop->wsFlags |= WHERE_IDX_ONLY;
  118542. }
  118543. pLoop->nLTerm = j;
  118544. pLoop->u.btree.nEq = j;
  118545. pLoop->u.btree.pIndex = pIdx;
  118546. /* TUNING: Cost of a unique index lookup is 15 */
  118547. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  118548. break;
  118549. }
  118550. }
  118551. if( pLoop->wsFlags ){
  118552. pLoop->nOut = (LogEst)1;
  118553. pWInfo->a[0].pWLoop = pLoop;
  118554. pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  118555. pWInfo->a[0].iTabCur = iCur;
  118556. pWInfo->nRowOut = 1;
  118557. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  118558. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  118559. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  118560. }
  118561. #ifdef SQLITE_DEBUG
  118562. pLoop->cId = '0';
  118563. #endif
  118564. return 1;
  118565. }
  118566. return 0;
  118567. }
  118568. /*
  118569. ** Generate the beginning of the loop used for WHERE clause processing.
  118570. ** The return value is a pointer to an opaque structure that contains
  118571. ** information needed to terminate the loop. Later, the calling routine
  118572. ** should invoke sqlite3WhereEnd() with the return value of this function
  118573. ** in order to complete the WHERE clause processing.
  118574. **
  118575. ** If an error occurs, this routine returns NULL.
  118576. **
  118577. ** The basic idea is to do a nested loop, one loop for each table in
  118578. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  118579. ** same as a SELECT with only a single table in the FROM clause.) For
  118580. ** example, if the SQL is this:
  118581. **
  118582. ** SELECT * FROM t1, t2, t3 WHERE ...;
  118583. **
  118584. ** Then the code generated is conceptually like the following:
  118585. **
  118586. ** foreach row1 in t1 do \ Code generated
  118587. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  118588. ** foreach row3 in t3 do /
  118589. ** ...
  118590. ** end \ Code generated
  118591. ** end |-- by sqlite3WhereEnd()
  118592. ** end /
  118593. **
  118594. ** Note that the loops might not be nested in the order in which they
  118595. ** appear in the FROM clause if a different order is better able to make
  118596. ** use of indices. Note also that when the IN operator appears in
  118597. ** the WHERE clause, it might result in additional nested loops for
  118598. ** scanning through all values on the right-hand side of the IN.
  118599. **
  118600. ** There are Btree cursors associated with each table. t1 uses cursor
  118601. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  118602. ** And so forth. This routine generates code to open those VDBE cursors
  118603. ** and sqlite3WhereEnd() generates the code to close them.
  118604. **
  118605. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  118606. ** in pTabList pointing at their appropriate entries. The [...] code
  118607. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  118608. ** data from the various tables of the loop.
  118609. **
  118610. ** If the WHERE clause is empty, the foreach loops must each scan their
  118611. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  118612. ** the tables have indices and there are terms in the WHERE clause that
  118613. ** refer to those indices, a complete table scan can be avoided and the
  118614. ** code will run much faster. Most of the work of this routine is checking
  118615. ** to see if there are indices that can be used to speed up the loop.
  118616. **
  118617. ** Terms of the WHERE clause are also used to limit which rows actually
  118618. ** make it to the "..." in the middle of the loop. After each "foreach",
  118619. ** terms of the WHERE clause that use only terms in that loop and outer
  118620. ** loops are evaluated and if false a jump is made around all subsequent
  118621. ** inner loops (or around the "..." if the test occurs within the inner-
  118622. ** most loop)
  118623. **
  118624. ** OUTER JOINS
  118625. **
  118626. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  118627. **
  118628. ** foreach row1 in t1 do
  118629. ** flag = 0
  118630. ** foreach row2 in t2 do
  118631. ** start:
  118632. ** ...
  118633. ** flag = 1
  118634. ** end
  118635. ** if flag==0 then
  118636. ** move the row2 cursor to a null row
  118637. ** goto start
  118638. ** fi
  118639. ** end
  118640. **
  118641. ** ORDER BY CLAUSE PROCESSING
  118642. **
  118643. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  118644. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  118645. ** if there is one. If there is no ORDER BY clause or if this routine
  118646. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  118647. **
  118648. ** The iIdxCur parameter is the cursor number of an index. If
  118649. ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
  118650. ** to use for OR clause processing. The WHERE clause should use this
  118651. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  118652. ** the first cursor in an array of cursors for all indices. iIdxCur should
  118653. ** be used to compute the appropriate cursor depending on which index is
  118654. ** used.
  118655. */
  118656. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  118657. Parse *pParse, /* The parser context */
  118658. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  118659. Expr *pWhere, /* The WHERE clause */
  118660. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  118661. ExprList *pResultSet, /* Result set of the query */
  118662. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  118663. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  118664. ){
  118665. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  118666. int nTabList; /* Number of elements in pTabList */
  118667. WhereInfo *pWInfo; /* Will become the return value of this function */
  118668. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  118669. Bitmask notReady; /* Cursors that are not yet positioned */
  118670. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  118671. WhereMaskSet *pMaskSet; /* The expression mask set */
  118672. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  118673. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  118674. int ii; /* Loop counter */
  118675. sqlite3 *db; /* Database connection */
  118676. int rc; /* Return code */
  118677. u8 bFordelete = 0;
  118678. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  118679. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  118680. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  118681. ));
  118682. /* Variable initialization */
  118683. db = pParse->db;
  118684. memset(&sWLB, 0, sizeof(sWLB));
  118685. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  118686. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  118687. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  118688. sWLB.pOrderBy = pOrderBy;
  118689. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  118690. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  118691. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  118692. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  118693. }
  118694. /* The number of tables in the FROM clause is limited by the number of
  118695. ** bits in a Bitmask
  118696. */
  118697. testcase( pTabList->nSrc==BMS );
  118698. if( pTabList->nSrc>BMS ){
  118699. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  118700. return 0;
  118701. }
  118702. /* This function normally generates a nested loop for all tables in
  118703. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  118704. ** only generate code for the first table in pTabList and assume that
  118705. ** any cursors associated with subsequent tables are uninitialized.
  118706. */
  118707. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  118708. /* Allocate and initialize the WhereInfo structure that will become the
  118709. ** return value. A single allocation is used to store the WhereInfo
  118710. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  118711. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  118712. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  118713. ** some architectures. Hence the ROUND8() below.
  118714. */
  118715. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  118716. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  118717. if( db->mallocFailed ){
  118718. sqlite3DbFree(db, pWInfo);
  118719. pWInfo = 0;
  118720. goto whereBeginError;
  118721. }
  118722. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  118723. pWInfo->nLevel = nTabList;
  118724. pWInfo->pParse = pParse;
  118725. pWInfo->pTabList = pTabList;
  118726. pWInfo->pOrderBy = pOrderBy;
  118727. pWInfo->pResultSet = pResultSet;
  118728. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  118729. pWInfo->wctrlFlags = wctrlFlags;
  118730. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  118731. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  118732. pMaskSet = &pWInfo->sMaskSet;
  118733. sWLB.pWInfo = pWInfo;
  118734. sWLB.pWC = &pWInfo->sWC;
  118735. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  118736. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  118737. whereLoopInit(sWLB.pNew);
  118738. #ifdef SQLITE_DEBUG
  118739. sWLB.pNew->cId = '*';
  118740. #endif
  118741. /* Split the WHERE clause into separate subexpressions where each
  118742. ** subexpression is separated by an AND operator.
  118743. */
  118744. initMaskSet(pMaskSet);
  118745. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  118746. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  118747. /* Special case: a WHERE clause that is constant. Evaluate the
  118748. ** expression and either jump over all of the code or fall thru.
  118749. */
  118750. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  118751. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  118752. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  118753. SQLITE_JUMPIFNULL);
  118754. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  118755. }
  118756. }
  118757. /* Special case: No FROM clause
  118758. */
  118759. if( nTabList==0 ){
  118760. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  118761. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  118762. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  118763. }
  118764. }
  118765. /* Assign a bit from the bitmask to every term in the FROM clause.
  118766. **
  118767. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  118768. **
  118769. ** The rule of the previous sentence ensures thta if X is the bitmask for
  118770. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  118771. ** Knowing the bitmask for all tables to the left of a left join is
  118772. ** important. Ticket #3015.
  118773. **
  118774. ** Note that bitmasks are created for all pTabList->nSrc tables in
  118775. ** pTabList, not just the first nTabList tables. nTabList is normally
  118776. ** equal to pTabList->nSrc but might be shortened to 1 if the
  118777. ** WHERE_ONETABLE_ONLY flag is set.
  118778. */
  118779. for(ii=0; ii<pTabList->nSrc; ii++){
  118780. createMask(pMaskSet, pTabList->a[ii].iCursor);
  118781. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  118782. }
  118783. #ifdef SQLITE_DEBUG
  118784. for(ii=0; ii<pTabList->nSrc; ii++){
  118785. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  118786. assert( m==MASKBIT(ii) );
  118787. }
  118788. #endif
  118789. /* Analyze all of the subexpressions. */
  118790. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  118791. if( db->mallocFailed ) goto whereBeginError;
  118792. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  118793. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  118794. /* The DISTINCT marking is pointless. Ignore it. */
  118795. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  118796. }else if( pOrderBy==0 ){
  118797. /* Try to ORDER BY the result set to make distinct processing easier */
  118798. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  118799. pWInfo->pOrderBy = pResultSet;
  118800. }
  118801. }
  118802. /* Construct the WhereLoop objects */
  118803. WHERETRACE(0xffff,("*** Optimizer Start *** (wctrlFlags: 0x%x)\n",
  118804. wctrlFlags));
  118805. #if defined(WHERETRACE_ENABLED)
  118806. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  118807. int i;
  118808. for(i=0; i<sWLB.pWC->nTerm; i++){
  118809. whereTermPrint(&sWLB.pWC->a[i], i);
  118810. }
  118811. }
  118812. #endif
  118813. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  118814. rc = whereLoopAddAll(&sWLB);
  118815. if( rc ) goto whereBeginError;
  118816. #ifdef WHERETRACE_ENABLED
  118817. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  118818. WhereLoop *p;
  118819. int i;
  118820. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  118821. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  118822. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  118823. p->cId = zLabel[i%sizeof(zLabel)];
  118824. whereLoopPrint(p, sWLB.pWC);
  118825. }
  118826. }
  118827. #endif
  118828. wherePathSolver(pWInfo, 0);
  118829. if( db->mallocFailed ) goto whereBeginError;
  118830. if( pWInfo->pOrderBy ){
  118831. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  118832. if( db->mallocFailed ) goto whereBeginError;
  118833. }
  118834. }
  118835. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  118836. pWInfo->revMask = (Bitmask)(-1);
  118837. }
  118838. if( pParse->nErr || NEVER(db->mallocFailed) ){
  118839. goto whereBeginError;
  118840. }
  118841. #ifdef WHERETRACE_ENABLED
  118842. if( sqlite3WhereTrace ){
  118843. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  118844. if( pWInfo->nOBSat>0 ){
  118845. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  118846. }
  118847. switch( pWInfo->eDistinct ){
  118848. case WHERE_DISTINCT_UNIQUE: {
  118849. sqlite3DebugPrintf(" DISTINCT=unique");
  118850. break;
  118851. }
  118852. case WHERE_DISTINCT_ORDERED: {
  118853. sqlite3DebugPrintf(" DISTINCT=ordered");
  118854. break;
  118855. }
  118856. case WHERE_DISTINCT_UNORDERED: {
  118857. sqlite3DebugPrintf(" DISTINCT=unordered");
  118858. break;
  118859. }
  118860. }
  118861. sqlite3DebugPrintf("\n");
  118862. for(ii=0; ii<pWInfo->nLevel; ii++){
  118863. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  118864. }
  118865. }
  118866. #endif
  118867. /* Attempt to omit tables from the join that do not effect the result */
  118868. if( pWInfo->nLevel>=2
  118869. && pResultSet!=0
  118870. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  118871. ){
  118872. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  118873. if( sWLB.pOrderBy ){
  118874. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  118875. }
  118876. while( pWInfo->nLevel>=2 ){
  118877. WhereTerm *pTerm, *pEnd;
  118878. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  118879. if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
  118880. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  118881. && (pLoop->wsFlags & WHERE_ONEROW)==0
  118882. ){
  118883. break;
  118884. }
  118885. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  118886. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  118887. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  118888. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  118889. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  118890. ){
  118891. break;
  118892. }
  118893. }
  118894. if( pTerm<pEnd ) break;
  118895. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  118896. pWInfo->nLevel--;
  118897. nTabList--;
  118898. }
  118899. }
  118900. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  118901. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  118902. /* If the caller is an UPDATE or DELETE statement that is requesting
  118903. ** to use a one-pass algorithm, determine if this is appropriate.
  118904. ** The one-pass algorithm only works if the WHERE clause constrains
  118905. ** the statement to update or delete a single row.
  118906. */
  118907. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  118908. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  118909. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  118910. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  118911. if( bOnerow || ( (wctrlFlags & WHERE_ONEPASS_MULTIROW)
  118912. && 0==(wsFlags & WHERE_VIRTUALTABLE)
  118913. )){
  118914. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  118915. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  118916. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  118917. bFordelete = OPFLAG_FORDELETE;
  118918. }
  118919. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  118920. }
  118921. }
  118922. }
  118923. /* Open all tables in the pTabList and any indices selected for
  118924. ** searching those tables.
  118925. */
  118926. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  118927. Table *pTab; /* Table to open */
  118928. int iDb; /* Index of database containing table/index */
  118929. struct SrcList_item *pTabItem;
  118930. pTabItem = &pTabList->a[pLevel->iFrom];
  118931. pTab = pTabItem->pTab;
  118932. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  118933. pLoop = pLevel->pWLoop;
  118934. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  118935. /* Do nothing */
  118936. }else
  118937. #ifndef SQLITE_OMIT_VIRTUALTABLE
  118938. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  118939. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  118940. int iCur = pTabItem->iCursor;
  118941. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  118942. }else if( IsVirtual(pTab) ){
  118943. /* noop */
  118944. }else
  118945. #endif
  118946. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  118947. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  118948. int op = OP_OpenRead;
  118949. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  118950. op = OP_OpenWrite;
  118951. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  118952. };
  118953. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  118954. assert( pTabItem->iCursor==pLevel->iTabCur );
  118955. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  118956. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  118957. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  118958. Bitmask b = pTabItem->colUsed;
  118959. int n = 0;
  118960. for(; b; b=b>>1, n++){}
  118961. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  118962. SQLITE_INT_TO_PTR(n), P4_INT32);
  118963. assert( n<=pTab->nCol );
  118964. }
  118965. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  118966. if( pLoop->u.btree.pIndex!=0 ){
  118967. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  118968. }else
  118969. #endif
  118970. {
  118971. sqlite3VdbeChangeP5(v, bFordelete);
  118972. }
  118973. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  118974. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  118975. (const u8*)&pTabItem->colUsed, P4_INT64);
  118976. #endif
  118977. }else{
  118978. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  118979. }
  118980. if( pLoop->wsFlags & WHERE_INDEXED ){
  118981. Index *pIx = pLoop->u.btree.pIndex;
  118982. int iIndexCur;
  118983. int op = OP_OpenRead;
  118984. /* iIdxCur is always set if to a positive value if ONEPASS is possible */
  118985. assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  118986. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  118987. && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
  118988. ){
  118989. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  118990. ** WITHOUT ROWID table. No need for a separate index */
  118991. iIndexCur = pLevel->iTabCur;
  118992. op = 0;
  118993. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  118994. Index *pJ = pTabItem->pTab->pIndex;
  118995. iIndexCur = iIdxCur;
  118996. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  118997. while( ALWAYS(pJ) && pJ!=pIx ){
  118998. iIndexCur++;
  118999. pJ = pJ->pNext;
  119000. }
  119001. op = OP_OpenWrite;
  119002. pWInfo->aiCurOnePass[1] = iIndexCur;
  119003. }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
  119004. iIndexCur = iIdxCur;
  119005. if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
  119006. }else{
  119007. iIndexCur = pParse->nTab++;
  119008. }
  119009. pLevel->iIdxCur = iIndexCur;
  119010. assert( pIx->pSchema==pTab->pSchema );
  119011. assert( iIndexCur>=0 );
  119012. if( op ){
  119013. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  119014. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  119015. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  119016. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  119017. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  119018. ){
  119019. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  119020. }
  119021. VdbeComment((v, "%s", pIx->zName));
  119022. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  119023. {
  119024. u64 colUsed = 0;
  119025. int ii, jj;
  119026. for(ii=0; ii<pIx->nColumn; ii++){
  119027. jj = pIx->aiColumn[ii];
  119028. if( jj<0 ) continue;
  119029. if( jj>63 ) jj = 63;
  119030. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  119031. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  119032. }
  119033. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  119034. (u8*)&colUsed, P4_INT64);
  119035. }
  119036. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  119037. }
  119038. }
  119039. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  119040. }
  119041. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  119042. if( db->mallocFailed ) goto whereBeginError;
  119043. /* Generate the code to do the search. Each iteration of the for
  119044. ** loop below generates code for a single nested loop of the VM
  119045. ** program.
  119046. */
  119047. notReady = ~(Bitmask)0;
  119048. for(ii=0; ii<nTabList; ii++){
  119049. int addrExplain;
  119050. int wsFlags;
  119051. pLevel = &pWInfo->a[ii];
  119052. wsFlags = pLevel->pWLoop->wsFlags;
  119053. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  119054. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  119055. constructAutomaticIndex(pParse, &pWInfo->sWC,
  119056. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  119057. if( db->mallocFailed ) goto whereBeginError;
  119058. }
  119059. #endif
  119060. addrExplain = sqlite3WhereExplainOneScan(
  119061. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  119062. );
  119063. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  119064. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  119065. pWInfo->iContinue = pLevel->addrCont;
  119066. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
  119067. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  119068. }
  119069. }
  119070. /* Done. */
  119071. VdbeModuleComment((v, "Begin WHERE-core"));
  119072. return pWInfo;
  119073. /* Jump here if malloc fails */
  119074. whereBeginError:
  119075. if( pWInfo ){
  119076. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  119077. whereInfoFree(db, pWInfo);
  119078. }
  119079. return 0;
  119080. }
  119081. /*
  119082. ** Generate the end of the WHERE loop. See comments on
  119083. ** sqlite3WhereBegin() for additional information.
  119084. */
  119085. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  119086. Parse *pParse = pWInfo->pParse;
  119087. Vdbe *v = pParse->pVdbe;
  119088. int i;
  119089. WhereLevel *pLevel;
  119090. WhereLoop *pLoop;
  119091. SrcList *pTabList = pWInfo->pTabList;
  119092. sqlite3 *db = pParse->db;
  119093. /* Generate loop termination code.
  119094. */
  119095. VdbeModuleComment((v, "End WHERE-core"));
  119096. sqlite3ExprCacheClear(pParse);
  119097. for(i=pWInfo->nLevel-1; i>=0; i--){
  119098. int addr;
  119099. pLevel = &pWInfo->a[i];
  119100. pLoop = pLevel->pWLoop;
  119101. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  119102. if( pLevel->op!=OP_Noop ){
  119103. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  119104. sqlite3VdbeChangeP5(v, pLevel->p5);
  119105. VdbeCoverage(v);
  119106. VdbeCoverageIf(v, pLevel->op==OP_Next);
  119107. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  119108. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  119109. }
  119110. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  119111. struct InLoop *pIn;
  119112. int j;
  119113. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  119114. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  119115. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  119116. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  119117. VdbeCoverage(v);
  119118. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  119119. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  119120. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  119121. }
  119122. }
  119123. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  119124. if( pLevel->addrSkip ){
  119125. sqlite3VdbeGoto(v, pLevel->addrSkip);
  119126. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  119127. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  119128. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  119129. }
  119130. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  119131. if( pLevel->addrLikeRep ){
  119132. int op;
  119133. if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
  119134. op = OP_DecrJumpZero;
  119135. }else{
  119136. op = OP_JumpZeroIncr;
  119137. }
  119138. sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
  119139. VdbeCoverage(v);
  119140. }
  119141. #endif
  119142. if( pLevel->iLeftJoin ){
  119143. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  119144. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  119145. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  119146. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  119147. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  119148. }
  119149. if( pLoop->wsFlags & WHERE_INDEXED ){
  119150. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  119151. }
  119152. if( pLevel->op==OP_Return ){
  119153. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  119154. }else{
  119155. sqlite3VdbeGoto(v, pLevel->addrFirst);
  119156. }
  119157. sqlite3VdbeJumpHere(v, addr);
  119158. }
  119159. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  119160. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  119161. }
  119162. /* The "break" point is here, just past the end of the outer loop.
  119163. ** Set it.
  119164. */
  119165. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  119166. assert( pWInfo->nLevel<=pTabList->nSrc );
  119167. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  119168. int k, last;
  119169. VdbeOp *pOp;
  119170. Index *pIdx = 0;
  119171. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  119172. Table *pTab = pTabItem->pTab;
  119173. assert( pTab!=0 );
  119174. pLoop = pLevel->pWLoop;
  119175. /* For a co-routine, change all OP_Column references to the table of
  119176. ** the co-routine into OP_Copy of result contained in a register.
  119177. ** OP_Rowid becomes OP_Null.
  119178. */
  119179. if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
  119180. translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
  119181. pTabItem->regResult, 0);
  119182. continue;
  119183. }
  119184. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  119185. ** Except, do not close cursors that will be reused by the OR optimization
  119186. ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
  119187. ** created for the ONEPASS optimization.
  119188. */
  119189. if( (pTab->tabFlags & TF_Ephemeral)==0
  119190. && pTab->pSelect==0
  119191. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  119192. ){
  119193. int ws = pLoop->wsFlags;
  119194. if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
  119195. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  119196. }
  119197. if( (ws & WHERE_INDEXED)!=0
  119198. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  119199. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  119200. ){
  119201. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  119202. }
  119203. }
  119204. /* If this scan uses an index, make VDBE code substitutions to read data
  119205. ** from the index instead of from the table where possible. In some cases
  119206. ** this optimization prevents the table from ever being read, which can
  119207. ** yield a significant performance boost.
  119208. **
  119209. ** Calls to the code generator in between sqlite3WhereBegin and
  119210. ** sqlite3WhereEnd will have created code that references the table
  119211. ** directly. This loop scans all that code looking for opcodes
  119212. ** that reference the table and converts them into opcodes that
  119213. ** reference the index.
  119214. */
  119215. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  119216. pIdx = pLoop->u.btree.pIndex;
  119217. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  119218. pIdx = pLevel->u.pCovidx;
  119219. }
  119220. if( pIdx
  119221. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  119222. && !db->mallocFailed
  119223. ){
  119224. last = sqlite3VdbeCurrentAddr(v);
  119225. k = pLevel->addrBody;
  119226. pOp = sqlite3VdbeGetOp(v, k);
  119227. for(; k<last; k++, pOp++){
  119228. if( pOp->p1!=pLevel->iTabCur ) continue;
  119229. if( pOp->opcode==OP_Column ){
  119230. int x = pOp->p2;
  119231. assert( pIdx->pTable==pTab );
  119232. if( !HasRowid(pTab) ){
  119233. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  119234. x = pPk->aiColumn[x];
  119235. assert( x>=0 );
  119236. }
  119237. x = sqlite3ColumnOfIndex(pIdx, x);
  119238. if( x>=0 ){
  119239. pOp->p2 = x;
  119240. pOp->p1 = pLevel->iIdxCur;
  119241. }
  119242. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
  119243. }else if( pOp->opcode==OP_Rowid ){
  119244. pOp->p1 = pLevel->iIdxCur;
  119245. pOp->opcode = OP_IdxRowid;
  119246. }
  119247. }
  119248. }
  119249. }
  119250. /* Final cleanup
  119251. */
  119252. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  119253. whereInfoFree(db, pWInfo);
  119254. return;
  119255. }
  119256. /************** End of where.c ***********************************************/
  119257. /************** Begin file parse.c *******************************************/
  119258. /*
  119259. ** 2000-05-29
  119260. **
  119261. ** The author disclaims copyright to this source code. In place of
  119262. ** a legal notice, here is a blessing:
  119263. **
  119264. ** May you do good and not evil.
  119265. ** May you find forgiveness for yourself and forgive others.
  119266. ** May you share freely, never taking more than you give.
  119267. **
  119268. *************************************************************************
  119269. ** Driver template for the LEMON parser generator.
  119270. **
  119271. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  119272. ** this template to construct a parser. The "lemon" program inserts text
  119273. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  119274. ** interstitial "-" characters) contained in this template is changed into
  119275. ** the value of the %name directive from the grammar. Otherwise, the content
  119276. ** of this template is copied straight through into the generate parser
  119277. ** source file.
  119278. **
  119279. ** The following is the concatenation of all %include directives from the
  119280. ** input grammar file:
  119281. */
  119282. /* #include <stdio.h> */
  119283. /************ Begin %include sections from the grammar ************************/
  119284. /* #include "sqliteInt.h" */
  119285. /*
  119286. ** Disable all error recovery processing in the parser push-down
  119287. ** automaton.
  119288. */
  119289. #define YYNOERRORRECOVERY 1
  119290. /*
  119291. ** Make yytestcase() the same as testcase()
  119292. */
  119293. #define yytestcase(X) testcase(X)
  119294. /*
  119295. ** Indicate that sqlite3ParserFree() will never be called with a null
  119296. ** pointer.
  119297. */
  119298. #define YYPARSEFREENEVERNULL 1
  119299. /*
  119300. ** Alternative datatype for the argument to the malloc() routine passed
  119301. ** into sqlite3ParserAlloc(). The default is size_t.
  119302. */
  119303. #define YYMALLOCARGTYPE u64
  119304. /*
  119305. ** An instance of this structure holds information about the
  119306. ** LIMIT clause of a SELECT statement.
  119307. */
  119308. struct LimitVal {
  119309. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  119310. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  119311. };
  119312. /*
  119313. ** An instance of this structure is used to store the LIKE,
  119314. ** GLOB, NOT LIKE, and NOT GLOB operators.
  119315. */
  119316. struct LikeOp {
  119317. Token eOperator; /* "like" or "glob" or "regexp" */
  119318. int bNot; /* True if the NOT keyword is present */
  119319. };
  119320. /*
  119321. ** An instance of the following structure describes the event of a
  119322. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  119323. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  119324. **
  119325. ** UPDATE ON (a,b,c)
  119326. **
  119327. ** Then the "b" IdList records the list "a,b,c".
  119328. */
  119329. struct TrigEvent { int a; IdList * b; };
  119330. /*
  119331. ** An instance of this structure holds the ATTACH key and the key type.
  119332. */
  119333. struct AttachKey { int type; Token key; };
  119334. /*
  119335. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  119336. ** all elements in the list. And make sure list length does not exceed
  119337. ** SQLITE_LIMIT_COMPOUND_SELECT.
  119338. */
  119339. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  119340. if( p->pPrior ){
  119341. Select *pNext = 0, *pLoop;
  119342. int mxSelect, cnt = 0;
  119343. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  119344. pLoop->pNext = pNext;
  119345. pLoop->selFlags |= SF_Compound;
  119346. }
  119347. if( (p->selFlags & SF_MultiValue)==0 &&
  119348. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  119349. cnt>mxSelect
  119350. ){
  119351. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  119352. }
  119353. }
  119354. }
  119355. /* This is a utility routine used to set the ExprSpan.zStart and
  119356. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  119357. ** range of text beginning with pStart and going to the end of pEnd.
  119358. */
  119359. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  119360. pOut->zStart = pStart->z;
  119361. pOut->zEnd = &pEnd->z[pEnd->n];
  119362. }
  119363. /* Construct a new Expr object from a single identifier. Use the
  119364. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  119365. ** that created the expression.
  119366. */
  119367. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  119368. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  119369. pOut->zStart = pValue->z;
  119370. pOut->zEnd = &pValue->z[pValue->n];
  119371. }
  119372. /* This routine constructs a binary expression node out of two ExprSpan
  119373. ** objects and uses the result to populate a new ExprSpan object.
  119374. */
  119375. static void spanBinaryExpr(
  119376. ExprSpan *pOut, /* Write the result here */
  119377. Parse *pParse, /* The parsing context. Errors accumulate here */
  119378. int op, /* The binary operation */
  119379. ExprSpan *pLeft, /* The left operand */
  119380. ExprSpan *pRight /* The right operand */
  119381. ){
  119382. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  119383. pOut->zStart = pLeft->zStart;
  119384. pOut->zEnd = pRight->zEnd;
  119385. }
  119386. /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
  119387. ** outside of *ppExpr.
  119388. */
  119389. static void exprNot(Parse *pParse, int doNot, Expr **ppExpr){
  119390. if( doNot ) *ppExpr = sqlite3PExpr(pParse, TK_NOT, *ppExpr, 0, 0);
  119391. }
  119392. /* Construct an expression node for a unary postfix operator
  119393. */
  119394. static void spanUnaryPostfix(
  119395. ExprSpan *pOut, /* Write the new expression node here */
  119396. Parse *pParse, /* Parsing context to record errors */
  119397. int op, /* The operator */
  119398. ExprSpan *pOperand, /* The operand */
  119399. Token *pPostOp /* The operand token for setting the span */
  119400. ){
  119401. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  119402. pOut->zStart = pOperand->zStart;
  119403. pOut->zEnd = &pPostOp->z[pPostOp->n];
  119404. }
  119405. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  119406. ** unary TK_ISNULL or TK_NOTNULL expression. */
  119407. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  119408. sqlite3 *db = pParse->db;
  119409. if( pY && pA && pY->op==TK_NULL ){
  119410. pA->op = (u8)op;
  119411. sqlite3ExprDelete(db, pA->pRight);
  119412. pA->pRight = 0;
  119413. }
  119414. }
  119415. /* Construct an expression node for a unary prefix operator
  119416. */
  119417. static void spanUnaryPrefix(
  119418. ExprSpan *pOut, /* Write the new expression node here */
  119419. Parse *pParse, /* Parsing context to record errors */
  119420. int op, /* The operator */
  119421. ExprSpan *pOperand, /* The operand */
  119422. Token *pPreOp /* The operand token for setting the span */
  119423. ){
  119424. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  119425. pOut->zStart = pPreOp->z;
  119426. pOut->zEnd = pOperand->zEnd;
  119427. }
  119428. /* Add a single new term to an ExprList that is used to store a
  119429. ** list of identifiers. Report an error if the ID list contains
  119430. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  119431. ** error while parsing a legacy schema.
  119432. */
  119433. static ExprList *parserAddExprIdListTerm(
  119434. Parse *pParse,
  119435. ExprList *pPrior,
  119436. Token *pIdToken,
  119437. int hasCollate,
  119438. int sortOrder
  119439. ){
  119440. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  119441. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  119442. && pParse->db->init.busy==0
  119443. ){
  119444. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  119445. pIdToken->n, pIdToken->z);
  119446. }
  119447. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  119448. return p;
  119449. }
  119450. /**************** End of %include directives **********************************/
  119451. /* These constants specify the various numeric values for terminal symbols
  119452. ** in a format understandable to "makeheaders". This section is blank unless
  119453. ** "lemon" is run with the "-m" command-line option.
  119454. ***************** Begin makeheaders token definitions *************************/
  119455. /**************** End makeheaders token definitions ***************************/
  119456. /* The next sections is a series of control #defines.
  119457. ** various aspects of the generated parser.
  119458. ** YYCODETYPE is the data type used to store the integer codes
  119459. ** that represent terminal and non-terminal symbols.
  119460. ** "unsigned char" is used if there are fewer than
  119461. ** 256 symbols. Larger types otherwise.
  119462. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  119463. ** any terminal or nonterminal symbol.
  119464. ** YYFALLBACK If defined, this indicates that one or more tokens
  119465. ** (also known as: "terminal symbols") have fall-back
  119466. ** values which should be used if the original symbol
  119467. ** would not parse. This permits keywords to sometimes
  119468. ** be used as identifiers, for example.
  119469. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  119470. ** that indicate what to do in response to the next
  119471. ** token.
  119472. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  119473. ** symbols. Background: A "minor type" is a semantic
  119474. ** value associated with a terminal or non-terminal
  119475. ** symbols. For example, for an "ID" terminal symbol,
  119476. ** the minor type might be the name of the identifier.
  119477. ** Each non-terminal can have a different minor type.
  119478. ** Terminal symbols all have the same minor type, though.
  119479. ** This macros defines the minor type for terminal
  119480. ** symbols.
  119481. ** YYMINORTYPE is the data type used for all minor types.
  119482. ** This is typically a union of many types, one of
  119483. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  119484. ** for terminal symbols is called "yy0".
  119485. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  119486. ** zero the stack is dynamically sized using realloc()
  119487. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  119488. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  119489. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  119490. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  119491. ** YYERRORSYMBOL is the code number of the error symbol. If not
  119492. ** defined, then do no error processing.
  119493. ** YYNSTATE the combined number of states.
  119494. ** YYNRULE the number of rules in the grammar
  119495. ** YY_MAX_SHIFT Maximum value for shift actions
  119496. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  119497. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  119498. ** YY_MIN_REDUCE Maximum value for reduce actions
  119499. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  119500. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  119501. ** YY_NO_ACTION The yy_action[] code for no-op
  119502. */
  119503. #ifndef INTERFACE
  119504. # define INTERFACE 1
  119505. #endif
  119506. /************* Begin control #defines *****************************************/
  119507. #define YYCODETYPE unsigned char
  119508. #define YYNOCODE 253
  119509. #define YYACTIONTYPE unsigned short int
  119510. #define YYWILDCARD 70
  119511. #define sqlite3ParserTOKENTYPE Token
  119512. typedef union {
  119513. int yyinit;
  119514. sqlite3ParserTOKENTYPE yy0;
  119515. int yy4;
  119516. struct TrigEvent yy90;
  119517. ExprSpan yy118;
  119518. TriggerStep* yy203;
  119519. struct {int value; int mask;} yy215;
  119520. SrcList* yy259;
  119521. struct LimitVal yy292;
  119522. Expr* yy314;
  119523. ExprList* yy322;
  119524. struct LikeOp yy342;
  119525. IdList* yy384;
  119526. Select* yy387;
  119527. With* yy451;
  119528. } YYMINORTYPE;
  119529. #ifndef YYSTACKDEPTH
  119530. #define YYSTACKDEPTH 100
  119531. #endif
  119532. #define sqlite3ParserARG_SDECL Parse *pParse;
  119533. #define sqlite3ParserARG_PDECL ,Parse *pParse
  119534. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  119535. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  119536. #define YYFALLBACK 1
  119537. #define YYNSTATE 436
  119538. #define YYNRULE 328
  119539. #define YY_MAX_SHIFT 435
  119540. #define YY_MIN_SHIFTREDUCE 649
  119541. #define YY_MAX_SHIFTREDUCE 976
  119542. #define YY_MIN_REDUCE 977
  119543. #define YY_MAX_REDUCE 1304
  119544. #define YY_ERROR_ACTION 1305
  119545. #define YY_ACCEPT_ACTION 1306
  119546. #define YY_NO_ACTION 1307
  119547. /************* End control #defines *******************************************/
  119548. /* The yyzerominor constant is used to initialize instances of
  119549. ** YYMINORTYPE objects to zero. */
  119550. static const YYMINORTYPE yyzerominor = { 0 };
  119551. /* Define the yytestcase() macro to be a no-op if is not already defined
  119552. ** otherwise.
  119553. **
  119554. ** Applications can choose to define yytestcase() in the %include section
  119555. ** to a macro that can assist in verifying code coverage. For production
  119556. ** code the yytestcase() macro should be turned off. But it is useful
  119557. ** for testing.
  119558. */
  119559. #ifndef yytestcase
  119560. # define yytestcase(X)
  119561. #endif
  119562. /* Next are the tables used to determine what action to take based on the
  119563. ** current state and lookahead token. These tables are used to implement
  119564. ** functions that take a state number and lookahead value and return an
  119565. ** action integer.
  119566. **
  119567. ** Suppose the action integer is N. Then the action is determined as
  119568. ** follows
  119569. **
  119570. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  119571. ** token onto the stack and goto state N.
  119572. **
  119573. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  119574. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  119575. **
  119576. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  119577. ** and YY_MAX_REDUCE
  119578. ** N == YY_ERROR_ACTION A syntax error has occurred.
  119579. **
  119580. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  119581. **
  119582. ** N == YY_NO_ACTION No such action. Denotes unused
  119583. ** slots in the yy_action[] table.
  119584. **
  119585. ** The action table is constructed as a single large table named yy_action[].
  119586. ** Given state S and lookahead X, the action is computed as
  119587. **
  119588. ** yy_action[ yy_shift_ofst[S] + X ]
  119589. **
  119590. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  119591. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  119592. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  119593. ** and that yy_default[S] should be used instead.
  119594. **
  119595. ** The formula above is for computing the action when the lookahead is
  119596. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  119597. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  119598. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  119599. ** YY_SHIFT_USE_DFLT.
  119600. **
  119601. ** The following are the tables generated in this section:
  119602. **
  119603. ** yy_action[] A single table containing all actions.
  119604. ** yy_lookahead[] A table containing the lookahead for each entry in
  119605. ** yy_action. Used to detect hash collisions.
  119606. ** yy_shift_ofst[] For each state, the offset into yy_action for
  119607. ** shifting terminals.
  119608. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  119609. ** shifting non-terminals after a reduce.
  119610. ** yy_default[] Default action for each state.
  119611. **
  119612. *********** Begin parsing tables **********************************************/
  119613. #define YY_ACTTAB_COUNT (1501)
  119614. static const YYACTIONTYPE yy_action[] = {
  119615. /* 0 */ 311, 1306, 145, 651, 2, 192, 652, 338, 780, 92,
  119616. /* 10 */ 92, 92, 92, 85, 90, 90, 90, 90, 89, 89,
  119617. /* 20 */ 88, 88, 88, 87, 335, 88, 88, 88, 87, 335,
  119618. /* 30 */ 327, 856, 856, 92, 92, 92, 92, 697, 90, 90,
  119619. /* 40 */ 90, 90, 89, 89, 88, 88, 88, 87, 335, 76,
  119620. /* 50 */ 807, 74, 93, 94, 84, 868, 871, 860, 860, 91,
  119621. /* 60 */ 91, 92, 92, 92, 92, 335, 90, 90, 90, 90,
  119622. /* 70 */ 89, 89, 88, 88, 88, 87, 335, 311, 780, 90,
  119623. /* 80 */ 90, 90, 90, 89, 89, 88, 88, 88, 87, 335,
  119624. /* 90 */ 356, 808, 776, 701, 689, 689, 86, 83, 166, 257,
  119625. /* 100 */ 809, 715, 430, 86, 83, 166, 324, 697, 856, 856,
  119626. /* 110 */ 201, 158, 276, 387, 271, 386, 188, 689, 689, 828,
  119627. /* 120 */ 86, 83, 166, 269, 833, 49, 123, 87, 335, 93,
  119628. /* 130 */ 94, 84, 868, 871, 860, 860, 91, 91, 92, 92,
  119629. /* 140 */ 92, 92, 239, 90, 90, 90, 90, 89, 89, 88,
  119630. /* 150 */ 88, 88, 87, 335, 311, 763, 333, 332, 216, 408,
  119631. /* 160 */ 394, 69, 231, 393, 690, 691, 396, 910, 251, 354,
  119632. /* 170 */ 250, 288, 315, 430, 908, 430, 909, 89, 89, 88,
  119633. /* 180 */ 88, 88, 87, 335, 391, 856, 856, 690, 691, 183,
  119634. /* 190 */ 95, 123, 384, 381, 380, 833, 31, 833, 49, 912,
  119635. /* 200 */ 912, 751, 752, 379, 123, 311, 93, 94, 84, 868,
  119636. /* 210 */ 871, 860, 860, 91, 91, 92, 92, 92, 92, 114,
  119637. /* 220 */ 90, 90, 90, 90, 89, 89, 88, 88, 88, 87,
  119638. /* 230 */ 335, 430, 408, 399, 435, 657, 856, 856, 346, 57,
  119639. /* 240 */ 232, 828, 109, 704, 366, 689, 689, 363, 825, 760,
  119640. /* 250 */ 97, 749, 752, 833, 49, 708, 708, 93, 94, 84,
  119641. /* 260 */ 868, 871, 860, 860, 91, 91, 92, 92, 92, 92,
  119642. /* 270 */ 423, 90, 90, 90, 90, 89, 89, 88, 88, 88,
  119643. /* 280 */ 87, 335, 311, 114, 22, 361, 688, 58, 408, 390,
  119644. /* 290 */ 251, 349, 240, 213, 762, 689, 689, 847, 685, 115,
  119645. /* 300 */ 361, 231, 393, 689, 689, 396, 183, 689, 689, 384,
  119646. /* 310 */ 381, 380, 361, 856, 856, 690, 691, 160, 159, 223,
  119647. /* 320 */ 379, 738, 25, 806, 707, 841, 143, 689, 689, 835,
  119648. /* 330 */ 392, 339, 766, 766, 93, 94, 84, 868, 871, 860,
  119649. /* 340 */ 860, 91, 91, 92, 92, 92, 92, 914, 90, 90,
  119650. /* 350 */ 90, 90, 89, 89, 88, 88, 88, 87, 335, 311,
  119651. /* 360 */ 840, 840, 840, 266, 257, 690, 691, 778, 706, 86,
  119652. /* 370 */ 83, 166, 219, 690, 691, 737, 1, 690, 691, 689,
  119653. /* 380 */ 689, 689, 689, 430, 86, 83, 166, 249, 688, 937,
  119654. /* 390 */ 856, 856, 427, 699, 700, 828, 298, 690, 691, 221,
  119655. /* 400 */ 686, 115, 123, 944, 795, 833, 48, 342, 305, 970,
  119656. /* 410 */ 847, 93, 94, 84, 868, 871, 860, 860, 91, 91,
  119657. /* 420 */ 92, 92, 92, 92, 114, 90, 90, 90, 90, 89,
  119658. /* 430 */ 89, 88, 88, 88, 87, 335, 311, 940, 841, 679,
  119659. /* 440 */ 713, 429, 835, 430, 251, 354, 250, 355, 288, 690,
  119660. /* 450 */ 691, 690, 691, 285, 941, 340, 971, 287, 210, 23,
  119661. /* 460 */ 174, 793, 832, 430, 353, 833, 10, 856, 856, 24,
  119662. /* 470 */ 942, 151, 753, 840, 840, 840, 794, 968, 1290, 321,
  119663. /* 480 */ 398, 1290, 356, 352, 754, 833, 49, 935, 93, 94,
  119664. /* 490 */ 84, 868, 871, 860, 860, 91, 91, 92, 92, 92,
  119665. /* 500 */ 92, 430, 90, 90, 90, 90, 89, 89, 88, 88,
  119666. /* 510 */ 88, 87, 335, 311, 376, 114, 907, 705, 430, 907,
  119667. /* 520 */ 328, 890, 114, 833, 10, 966, 430, 857, 857, 320,
  119668. /* 530 */ 189, 163, 832, 165, 430, 906, 344, 323, 906, 904,
  119669. /* 540 */ 833, 10, 965, 306, 856, 856, 187, 419, 833, 10,
  119670. /* 550 */ 220, 869, 872, 832, 222, 403, 833, 49, 1219, 793,
  119671. /* 560 */ 68, 937, 406, 245, 66, 93, 94, 84, 868, 871,
  119672. /* 570 */ 860, 860, 91, 91, 92, 92, 92, 92, 861, 90,
  119673. /* 580 */ 90, 90, 90, 89, 89, 88, 88, 88, 87, 335,
  119674. /* 590 */ 311, 404, 213, 762, 834, 345, 114, 940, 902, 368,
  119675. /* 600 */ 727, 5, 316, 192, 396, 772, 780, 269, 230, 242,
  119676. /* 610 */ 771, 244, 397, 164, 941, 385, 123, 347, 55, 355,
  119677. /* 620 */ 329, 856, 856, 728, 333, 332, 688, 968, 1291, 724,
  119678. /* 630 */ 942, 1291, 413, 214, 833, 9, 362, 286, 955, 115,
  119679. /* 640 */ 718, 311, 93, 94, 84, 868, 871, 860, 860, 91,
  119680. /* 650 */ 91, 92, 92, 92, 92, 430, 90, 90, 90, 90,
  119681. /* 660 */ 89, 89, 88, 88, 88, 87, 335, 912, 912, 1300,
  119682. /* 670 */ 1300, 758, 856, 856, 325, 966, 780, 833, 35, 747,
  119683. /* 680 */ 720, 334, 699, 700, 977, 652, 338, 243, 745, 920,
  119684. /* 690 */ 920, 369, 187, 93, 94, 84, 868, 871, 860, 860,
  119685. /* 700 */ 91, 91, 92, 92, 92, 92, 114, 90, 90, 90,
  119686. /* 710 */ 90, 89, 89, 88, 88, 88, 87, 335, 311, 430,
  119687. /* 720 */ 954, 430, 112, 310, 430, 693, 317, 698, 400, 430,
  119688. /* 730 */ 793, 359, 430, 1017, 430, 192, 430, 401, 780, 430,
  119689. /* 740 */ 360, 833, 36, 833, 12, 430, 833, 27, 316, 856,
  119690. /* 750 */ 856, 833, 37, 20, 833, 38, 833, 39, 833, 28,
  119691. /* 760 */ 72, 833, 29, 663, 664, 665, 264, 833, 40, 234,
  119692. /* 770 */ 93, 94, 84, 868, 871, 860, 860, 91, 91, 92,
  119693. /* 780 */ 92, 92, 92, 430, 90, 90, 90, 90, 89, 89,
  119694. /* 790 */ 88, 88, 88, 87, 335, 311, 430, 698, 430, 917,
  119695. /* 800 */ 147, 430, 165, 916, 275, 833, 41, 430, 780, 430,
  119696. /* 810 */ 21, 430, 259, 430, 262, 274, 430, 367, 833, 42,
  119697. /* 820 */ 833, 11, 430, 833, 43, 235, 856, 856, 793, 833,
  119698. /* 830 */ 99, 833, 44, 833, 45, 833, 32, 75, 833, 46,
  119699. /* 840 */ 305, 967, 257, 257, 833, 47, 311, 93, 94, 84,
  119700. /* 850 */ 868, 871, 860, 860, 91, 91, 92, 92, 92, 92,
  119701. /* 860 */ 430, 90, 90, 90, 90, 89, 89, 88, 88, 88,
  119702. /* 870 */ 87, 335, 430, 186, 185, 184, 238, 856, 856, 650,
  119703. /* 880 */ 2, 1064, 833, 33, 739, 217, 218, 257, 971, 257,
  119704. /* 890 */ 426, 317, 257, 774, 833, 117, 257, 311, 93, 94,
  119705. /* 900 */ 84, 868, 871, 860, 860, 91, 91, 92, 92, 92,
  119706. /* 910 */ 92, 430, 90, 90, 90, 90, 89, 89, 88, 88,
  119707. /* 920 */ 88, 87, 335, 430, 318, 124, 212, 163, 856, 856,
  119708. /* 930 */ 943, 900, 898, 833, 118, 759, 726, 725, 257, 755,
  119709. /* 940 */ 289, 289, 733, 734, 961, 833, 119, 682, 311, 93,
  119710. /* 950 */ 82, 84, 868, 871, 860, 860, 91, 91, 92, 92,
  119711. /* 960 */ 92, 92, 430, 90, 90, 90, 90, 89, 89, 88,
  119712. /* 970 */ 88, 88, 87, 335, 430, 716, 246, 322, 331, 856,
  119713. /* 980 */ 856, 256, 114, 357, 833, 53, 808, 913, 913, 932,
  119714. /* 990 */ 156, 416, 420, 424, 930, 809, 833, 34, 364, 311,
  119715. /* 1000 */ 253, 94, 84, 868, 871, 860, 860, 91, 91, 92,
  119716. /* 1010 */ 92, 92, 92, 430, 90, 90, 90, 90, 89, 89,
  119717. /* 1020 */ 88, 88, 88, 87, 335, 430, 114, 114, 114, 960,
  119718. /* 1030 */ 856, 856, 307, 258, 830, 833, 100, 191, 252, 377,
  119719. /* 1040 */ 267, 68, 197, 68, 261, 716, 769, 833, 50, 71,
  119720. /* 1050 */ 911, 911, 263, 84, 868, 871, 860, 860, 91, 91,
  119721. /* 1060 */ 92, 92, 92, 92, 430, 90, 90, 90, 90, 89,
  119722. /* 1070 */ 89, 88, 88, 88, 87, 335, 80, 425, 802, 3,
  119723. /* 1080 */ 1214, 191, 430, 265, 336, 336, 833, 101, 741, 80,
  119724. /* 1090 */ 425, 897, 3, 723, 722, 428, 721, 336, 336, 430,
  119725. /* 1100 */ 893, 270, 430, 197, 833, 102, 430, 800, 428, 430,
  119726. /* 1110 */ 695, 430, 843, 111, 414, 430, 784, 409, 430, 831,
  119727. /* 1120 */ 430, 833, 98, 123, 833, 116, 847, 414, 833, 49,
  119728. /* 1130 */ 779, 833, 113, 833, 106, 226, 123, 833, 105, 847,
  119729. /* 1140 */ 833, 103, 833, 104, 791, 411, 77, 78, 290, 412,
  119730. /* 1150 */ 430, 291, 114, 79, 432, 431, 389, 430, 835, 77,
  119731. /* 1160 */ 78, 897, 839, 408, 410, 430, 79, 432, 431, 372,
  119732. /* 1170 */ 703, 835, 833, 52, 430, 80, 425, 430, 3, 833,
  119733. /* 1180 */ 54, 772, 843, 336, 336, 684, 771, 833, 51, 840,
  119734. /* 1190 */ 840, 840, 842, 19, 428, 672, 833, 26, 671, 833,
  119735. /* 1200 */ 30, 673, 840, 840, 840, 842, 19, 207, 661, 278,
  119736. /* 1210 */ 304, 148, 280, 414, 282, 248, 358, 822, 382, 6,
  119737. /* 1220 */ 348, 161, 273, 80, 425, 847, 3, 934, 895, 720,
  119738. /* 1230 */ 894, 336, 336, 296, 157, 415, 241, 284, 674, 958,
  119739. /* 1240 */ 194, 953, 428, 951, 948, 77, 78, 777, 319, 56,
  119740. /* 1250 */ 59, 135, 79, 432, 431, 121, 66, 835, 146, 128,
  119741. /* 1260 */ 350, 414, 819, 130, 351, 131, 132, 133, 375, 173,
  119742. /* 1270 */ 107, 138, 149, 847, 365, 178, 62, 70, 425, 936,
  119743. /* 1280 */ 3, 827, 889, 371, 255, 336, 336, 792, 840, 840,
  119744. /* 1290 */ 840, 842, 19, 77, 78, 915, 428, 208, 179, 144,
  119745. /* 1300 */ 79, 432, 431, 373, 260, 835, 180, 326, 675, 181,
  119746. /* 1310 */ 308, 744, 388, 743, 731, 414, 718, 742, 730, 712,
  119747. /* 1320 */ 402, 309, 711, 272, 788, 65, 710, 847, 709, 277,
  119748. /* 1330 */ 193, 789, 787, 279, 876, 73, 840, 840, 840, 842,
  119749. /* 1340 */ 19, 786, 281, 418, 283, 422, 227, 77, 78, 330,
  119750. /* 1350 */ 228, 229, 96, 767, 79, 432, 431, 407, 67, 835,
  119751. /* 1360 */ 215, 292, 293, 405, 294, 303, 302, 301, 204, 299,
  119752. /* 1370 */ 295, 202, 676, 681, 7, 433, 669, 203, 205, 206,
  119753. /* 1380 */ 125, 110, 313, 434, 667, 666, 658, 168, 224, 237,
  119754. /* 1390 */ 840, 840, 840, 842, 19, 120, 656, 337, 236, 155,
  119755. /* 1400 */ 167, 341, 233, 314, 108, 905, 903, 826, 127, 126,
  119756. /* 1410 */ 756, 170, 129, 172, 247, 928, 134, 136, 171, 60,
  119757. /* 1420 */ 61, 123, 169, 137, 933, 175, 176, 927, 8, 13,
  119758. /* 1430 */ 177, 254, 918, 139, 191, 924, 140, 370, 678, 150,
  119759. /* 1440 */ 374, 182, 274, 268, 141, 122, 63, 14, 378, 15,
  119760. /* 1450 */ 383, 64, 225, 846, 845, 874, 16, 4, 729, 765,
  119761. /* 1460 */ 770, 162, 395, 209, 211, 142, 801, 878, 796, 312,
  119762. /* 1470 */ 71, 68, 875, 873, 939, 190, 417, 938, 17, 195,
  119763. /* 1480 */ 196, 152, 18, 975, 199, 976, 153, 198, 154, 421,
  119764. /* 1490 */ 877, 844, 696, 81, 200, 297, 343, 1019, 1018, 300,
  119765. /* 1500 */ 653,
  119766. };
  119767. static const YYCODETYPE yy_lookahead[] = {
  119768. /* 0 */ 19, 144, 145, 146, 147, 24, 1, 2, 27, 80,
  119769. /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  119770. /* 20 */ 91, 92, 93, 94, 95, 91, 92, 93, 94, 95,
  119771. /* 30 */ 19, 50, 51, 80, 81, 82, 83, 27, 85, 86,
  119772. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 137,
  119773. /* 50 */ 177, 139, 71, 72, 73, 74, 75, 76, 77, 78,
  119774. /* 60 */ 79, 80, 81, 82, 83, 95, 85, 86, 87, 88,
  119775. /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 85,
  119776. /* 80 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  119777. /* 90 */ 152, 33, 212, 173, 27, 28, 223, 224, 225, 152,
  119778. /* 100 */ 42, 181, 152, 223, 224, 225, 95, 97, 50, 51,
  119779. /* 110 */ 99, 100, 101, 102, 103, 104, 105, 27, 28, 59,
  119780. /* 120 */ 223, 224, 225, 112, 174, 175, 66, 94, 95, 71,
  119781. /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  119782. /* 140 */ 82, 83, 195, 85, 86, 87, 88, 89, 90, 91,
  119783. /* 150 */ 92, 93, 94, 95, 19, 197, 89, 90, 220, 209,
  119784. /* 160 */ 210, 26, 119, 120, 97, 98, 208, 100, 108, 109,
  119785. /* 170 */ 110, 152, 157, 152, 107, 152, 109, 89, 90, 91,
  119786. /* 180 */ 92, 93, 94, 95, 163, 50, 51, 97, 98, 99,
  119787. /* 190 */ 55, 66, 102, 103, 104, 174, 175, 174, 175, 132,
  119788. /* 200 */ 133, 192, 193, 113, 66, 19, 71, 72, 73, 74,
  119789. /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 198,
  119790. /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  119791. /* 230 */ 95, 152, 209, 210, 148, 149, 50, 51, 100, 53,
  119792. /* 240 */ 154, 59, 156, 174, 229, 27, 28, 232, 163, 163,
  119793. /* 250 */ 22, 192, 193, 174, 175, 27, 28, 71, 72, 73,
  119794. /* 260 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  119795. /* 270 */ 251, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  119796. /* 280 */ 94, 95, 19, 198, 198, 152, 152, 24, 209, 210,
  119797. /* 290 */ 108, 109, 110, 196, 197, 27, 28, 69, 164, 165,
  119798. /* 300 */ 152, 119, 120, 27, 28, 208, 99, 27, 28, 102,
  119799. /* 310 */ 103, 104, 152, 50, 51, 97, 98, 89, 90, 185,
  119800. /* 320 */ 113, 187, 22, 177, 174, 97, 58, 27, 28, 101,
  119801. /* 330 */ 115, 245, 117, 118, 71, 72, 73, 74, 75, 76,
  119802. /* 340 */ 77, 78, 79, 80, 81, 82, 83, 11, 85, 86,
  119803. /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
  119804. /* 360 */ 132, 133, 134, 23, 152, 97, 98, 91, 174, 223,
  119805. /* 370 */ 224, 225, 239, 97, 98, 187, 22, 97, 98, 27,
  119806. /* 380 */ 28, 27, 28, 152, 223, 224, 225, 239, 152, 163,
  119807. /* 390 */ 50, 51, 170, 171, 172, 59, 160, 97, 98, 239,
  119808. /* 400 */ 164, 165, 66, 242, 124, 174, 175, 195, 22, 23,
  119809. /* 410 */ 69, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  119810. /* 420 */ 80, 81, 82, 83, 198, 85, 86, 87, 88, 89,
  119811. /* 430 */ 90, 91, 92, 93, 94, 95, 19, 12, 97, 21,
  119812. /* 440 */ 23, 152, 101, 152, 108, 109, 110, 221, 152, 97,
  119813. /* 450 */ 98, 97, 98, 152, 29, 243, 70, 226, 23, 233,
  119814. /* 460 */ 26, 26, 152, 152, 238, 174, 175, 50, 51, 22,
  119815. /* 470 */ 45, 24, 47, 132, 133, 134, 124, 22, 23, 188,
  119816. /* 480 */ 163, 26, 152, 65, 59, 174, 175, 163, 71, 72,
  119817. /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  119818. /* 500 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  119819. /* 510 */ 93, 94, 95, 19, 19, 198, 152, 23, 152, 152,
  119820. /* 520 */ 209, 103, 198, 174, 175, 70, 152, 50, 51, 219,
  119821. /* 530 */ 213, 214, 152, 98, 152, 171, 172, 188, 171, 172,
  119822. /* 540 */ 174, 175, 248, 249, 50, 51, 51, 251, 174, 175,
  119823. /* 550 */ 220, 74, 75, 152, 188, 152, 174, 175, 140, 124,
  119824. /* 560 */ 26, 163, 188, 16, 130, 71, 72, 73, 74, 75,
  119825. /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 101, 85,
  119826. /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  119827. /* 590 */ 19, 209, 196, 197, 23, 231, 198, 12, 231, 219,
  119828. /* 600 */ 37, 22, 107, 24, 208, 116, 27, 112, 201, 62,
  119829. /* 610 */ 121, 64, 152, 152, 29, 52, 66, 221, 211, 221,
  119830. /* 620 */ 219, 50, 51, 60, 89, 90, 152, 22, 23, 183,
  119831. /* 630 */ 45, 26, 47, 22, 174, 175, 238, 152, 164, 165,
  119832. /* 640 */ 106, 19, 71, 72, 73, 74, 75, 76, 77, 78,
  119833. /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
  119834. /* 660 */ 89, 90, 91, 92, 93, 94, 95, 132, 133, 119,
  119835. /* 670 */ 120, 163, 50, 51, 111, 70, 97, 174, 175, 181,
  119836. /* 680 */ 182, 170, 171, 172, 0, 1, 2, 140, 190, 108,
  119837. /* 690 */ 109, 110, 51, 71, 72, 73, 74, 75, 76, 77,
  119838. /* 700 */ 78, 79, 80, 81, 82, 83, 198, 85, 86, 87,
  119839. /* 710 */ 88, 89, 90, 91, 92, 93, 94, 95, 19, 152,
  119840. /* 720 */ 152, 152, 22, 166, 152, 168, 169, 27, 19, 152,
  119841. /* 730 */ 26, 19, 152, 122, 152, 24, 152, 28, 27, 152,
  119842. /* 740 */ 28, 174, 175, 174, 175, 152, 174, 175, 107, 50,
  119843. /* 750 */ 51, 174, 175, 22, 174, 175, 174, 175, 174, 175,
  119844. /* 760 */ 138, 174, 175, 7, 8, 9, 16, 174, 175, 152,
  119845. /* 770 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  119846. /* 780 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  119847. /* 790 */ 91, 92, 93, 94, 95, 19, 152, 97, 152, 31,
  119848. /* 800 */ 24, 152, 98, 35, 101, 174, 175, 152, 97, 152,
  119849. /* 810 */ 79, 152, 62, 152, 64, 112, 152, 49, 174, 175,
  119850. /* 820 */ 174, 175, 152, 174, 175, 152, 50, 51, 124, 174,
  119851. /* 830 */ 175, 174, 175, 174, 175, 174, 175, 138, 174, 175,
  119852. /* 840 */ 22, 23, 152, 152, 174, 175, 19, 71, 72, 73,
  119853. /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  119854. /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  119855. /* 870 */ 94, 95, 152, 108, 109, 110, 152, 50, 51, 146,
  119856. /* 880 */ 147, 23, 174, 175, 26, 195, 195, 152, 70, 152,
  119857. /* 890 */ 168, 169, 152, 26, 174, 175, 152, 19, 71, 72,
  119858. /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  119859. /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  119860. /* 920 */ 93, 94, 95, 152, 246, 247, 213, 214, 50, 51,
  119861. /* 930 */ 195, 152, 195, 174, 175, 195, 100, 101, 152, 195,
  119862. /* 940 */ 152, 152, 7, 8, 152, 174, 175, 163, 19, 71,
  119863. /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  119864. /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  119865. /* 970 */ 92, 93, 94, 95, 152, 27, 152, 189, 189, 50,
  119866. /* 980 */ 51, 195, 198, 152, 174, 175, 33, 132, 133, 152,
  119867. /* 990 */ 123, 163, 163, 163, 152, 42, 174, 175, 152, 19,
  119868. /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  119869. /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  119870. /* 1020 */ 91, 92, 93, 94, 95, 152, 198, 198, 198, 23,
  119871. /* 1030 */ 50, 51, 26, 152, 23, 174, 175, 26, 23, 23,
  119872. /* 1040 */ 23, 26, 26, 26, 152, 97, 23, 174, 175, 26,
  119873. /* 1050 */ 132, 133, 152, 73, 74, 75, 76, 77, 78, 79,
  119874. /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
  119875. /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 23, 22,
  119876. /* 1080 */ 23, 26, 152, 152, 27, 28, 174, 175, 152, 19,
  119877. /* 1090 */ 20, 27, 22, 183, 183, 38, 152, 27, 28, 152,
  119878. /* 1100 */ 23, 152, 152, 26, 174, 175, 152, 152, 38, 152,
  119879. /* 1110 */ 23, 152, 27, 26, 57, 152, 215, 163, 152, 152,
  119880. /* 1120 */ 152, 174, 175, 66, 174, 175, 69, 57, 174, 175,
  119881. /* 1130 */ 152, 174, 175, 174, 175, 212, 66, 174, 175, 69,
  119882. /* 1140 */ 174, 175, 174, 175, 152, 152, 89, 90, 152, 193,
  119883. /* 1150 */ 152, 152, 198, 96, 97, 98, 91, 152, 101, 89,
  119884. /* 1160 */ 90, 97, 152, 209, 210, 152, 96, 97, 98, 235,
  119885. /* 1170 */ 152, 101, 174, 175, 152, 19, 20, 152, 22, 174,
  119886. /* 1180 */ 175, 116, 97, 27, 28, 152, 121, 174, 175, 132,
  119887. /* 1190 */ 133, 134, 135, 136, 38, 152, 174, 175, 152, 174,
  119888. /* 1200 */ 175, 152, 132, 133, 134, 135, 136, 234, 152, 212,
  119889. /* 1210 */ 150, 199, 212, 57, 212, 240, 240, 203, 178, 200,
  119890. /* 1220 */ 216, 186, 177, 19, 20, 69, 22, 203, 177, 182,
  119891. /* 1230 */ 177, 27, 28, 202, 200, 228, 216, 216, 155, 39,
  119892. /* 1240 */ 122, 159, 38, 159, 41, 89, 90, 91, 159, 241,
  119893. /* 1250 */ 241, 22, 96, 97, 98, 71, 130, 101, 222, 191,
  119894. /* 1260 */ 18, 57, 203, 194, 159, 194, 194, 194, 18, 158,
  119895. /* 1270 */ 244, 191, 222, 69, 159, 158, 137, 19, 20, 203,
  119896. /* 1280 */ 22, 191, 203, 46, 236, 27, 28, 159, 132, 133,
  119897. /* 1290 */ 134, 135, 136, 89, 90, 237, 38, 159, 158, 22,
  119898. /* 1300 */ 96, 97, 98, 179, 159, 101, 158, 48, 159, 158,
  119899. /* 1310 */ 179, 176, 107, 176, 184, 57, 106, 176, 184, 176,
  119900. /* 1320 */ 125, 179, 178, 176, 218, 107, 176, 69, 176, 217,
  119901. /* 1330 */ 159, 218, 218, 217, 159, 137, 132, 133, 134, 135,
  119902. /* 1340 */ 136, 218, 217, 179, 217, 179, 227, 89, 90, 95,
  119903. /* 1350 */ 230, 230, 129, 207, 96, 97, 98, 126, 128, 101,
  119904. /* 1360 */ 5, 206, 205, 127, 204, 10, 11, 12, 13, 14,
  119905. /* 1370 */ 203, 25, 17, 162, 26, 161, 13, 153, 153, 6,
  119906. /* 1380 */ 247, 180, 250, 151, 151, 151, 151, 32, 180, 34,
  119907. /* 1390 */ 132, 133, 134, 135, 136, 167, 4, 3, 43, 22,
  119908. /* 1400 */ 15, 68, 142, 250, 16, 23, 23, 120, 111, 131,
  119909. /* 1410 */ 20, 56, 123, 125, 16, 1, 123, 131, 63, 79,
  119910. /* 1420 */ 79, 66, 67, 111, 28, 36, 122, 1, 5, 22,
  119911. /* 1430 */ 107, 140, 54, 54, 26, 61, 107, 44, 20, 24,
  119912. /* 1440 */ 19, 105, 112, 23, 22, 40, 22, 22, 53, 22,
  119913. /* 1450 */ 53, 22, 53, 23, 23, 23, 22, 22, 30, 116,
  119914. /* 1460 */ 23, 122, 26, 23, 23, 22, 28, 11, 124, 114,
  119915. /* 1470 */ 26, 26, 23, 23, 23, 36, 24, 23, 36, 26,
  119916. /* 1480 */ 22, 22, 36, 23, 122, 23, 22, 26, 22, 24,
  119917. /* 1490 */ 23, 23, 23, 22, 122, 23, 141, 122, 122, 15,
  119918. /* 1500 */ 1,
  119919. };
  119920. #define YY_SHIFT_USE_DFLT (-89)
  119921. #define YY_SHIFT_COUNT (435)
  119922. #define YY_SHIFT_MIN (-88)
  119923. #define YY_SHIFT_MAX (1499)
  119924. static const short yy_shift_ofst[] = {
  119925. /* 0 */ 5, 1057, 1355, 1070, 1204, 1204, 1204, 90, 60, -19,
  119926. /* 10 */ 58, 58, 186, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  119927. /* 20 */ 67, 67, 182, 336, 218, 550, 135, 263, 340, 417,
  119928. /* 30 */ 494, 571, 622, 699, 776, 827, 827, 827, 827, 827,
  119929. /* 40 */ 827, 827, 827, 827, 827, 827, 827, 827, 827, 827,
  119930. /* 50 */ 878, 827, 929, 980, 980, 1156, 1204, 1204, 1204, 1204,
  119931. /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  119932. /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  119933. /* 80 */ 1204, 1204, 1204, 1204, 1258, 1204, 1204, 1204, 1204, 1204,
  119934. /* 90 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, -71, -47,
  119935. /* 100 */ -47, -47, -47, -47, -6, 88, -66, 218, 218, 418,
  119936. /* 110 */ 495, 535, 535, 33, 43, 10, -30, -89, -89, -89,
  119937. /* 120 */ 11, 425, 425, 268, 455, 605, 218, 218, 218, 218,
  119938. /* 130 */ 218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
  119939. /* 140 */ 218, 218, 218, 218, 218, 684, 138, 10, 43, 125,
  119940. /* 150 */ 125, 125, 125, 125, 125, -89, -89, -89, 228, 341,
  119941. /* 160 */ 341, 207, 276, 300, 280, 352, 354, 218, 218, 218,
  119942. /* 170 */ 218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
  119943. /* 180 */ 218, 218, 218, 218, 563, 563, 563, 218, 218, 435,
  119944. /* 190 */ 218, 218, 218, 579, 218, 218, 585, 218, 218, 218,
  119945. /* 200 */ 218, 218, 218, 218, 218, 218, 218, 581, 768, 711,
  119946. /* 210 */ 711, 711, 704, 215, 1065, 756, 434, 709, 709, 712,
  119947. /* 220 */ 434, 712, 534, 858, 641, 953, 709, -88, 953, 953,
  119948. /* 230 */ 867, 489, 447, 1200, 1118, 1118, 1203, 1203, 1118, 1229,
  119949. /* 240 */ 1184, 1126, 1242, 1242, 1242, 1242, 1118, 1250, 1126, 1229,
  119950. /* 250 */ 1184, 1184, 1126, 1118, 1250, 1139, 1237, 1118, 1118, 1250,
  119951. /* 260 */ 1277, 1118, 1250, 1118, 1250, 1277, 1205, 1205, 1205, 1259,
  119952. /* 270 */ 1277, 1205, 1210, 1205, 1259, 1205, 1205, 1195, 1218, 1195,
  119953. /* 280 */ 1218, 1195, 1218, 1195, 1218, 1118, 1118, 1198, 1277, 1254,
  119954. /* 290 */ 1254, 1277, 1223, 1231, 1230, 1236, 1126, 1346, 1348, 1363,
  119955. /* 300 */ 1363, 1373, 1373, 1373, 1373, -89, -89, -89, -89, -89,
  119956. /* 310 */ -89, 477, 547, 386, 818, 750, 765, 700, 1006, 731,
  119957. /* 320 */ 1011, 1015, 1016, 1017, 948, 836, 935, 703, 1023, 1055,
  119958. /* 330 */ 1064, 1077, 855, 918, 1087, 1085, 611, 1392, 1394, 1377,
  119959. /* 340 */ 1260, 1385, 1333, 1388, 1382, 1383, 1287, 1278, 1297, 1289,
  119960. /* 350 */ 1390, 1288, 1398, 1414, 1293, 1286, 1340, 1341, 1312, 1396,
  119961. /* 360 */ 1389, 1304, 1426, 1423, 1407, 1323, 1291, 1378, 1408, 1379,
  119962. /* 370 */ 1374, 1393, 1329, 1415, 1418, 1421, 1330, 1336, 1422, 1395,
  119963. /* 380 */ 1424, 1425, 1420, 1427, 1397, 1428, 1429, 1399, 1405, 1430,
  119964. /* 390 */ 1431, 1432, 1343, 1434, 1437, 1435, 1436, 1339, 1440, 1441,
  119965. /* 400 */ 1438, 1439, 1443, 1344, 1444, 1442, 1445, 1446, 1444, 1449,
  119966. /* 410 */ 1450, 1451, 1453, 1454, 1458, 1456, 1460, 1459, 1452, 1461,
  119967. /* 420 */ 1462, 1464, 1465, 1461, 1467, 1466, 1468, 1469, 1471, 1362,
  119968. /* 430 */ 1372, 1375, 1376, 1472, 1484, 1499,
  119969. };
  119970. #define YY_REDUCE_USE_DFLT (-144)
  119971. #define YY_REDUCE_COUNT (310)
  119972. #define YY_REDUCE_MIN (-143)
  119973. #define YY_REDUCE_MAX (1235)
  119974. static const short yy_reduce_ofst[] = {
  119975. /* 0 */ -143, 954, 86, 21, -50, 23, 79, 134, 226, -120,
  119976. /* 10 */ -127, 146, 161, 291, 349, 366, 311, 382, 374, 231,
  119977. /* 20 */ 364, 367, 396, 398, 236, 317, -103, -103, -103, -103,
  119978. /* 30 */ -103, -103, -103, -103, -103, -103, -103, -103, -103, -103,
  119979. /* 40 */ -103, -103, -103, -103, -103, -103, -103, -103, -103, -103,
  119980. /* 50 */ -103, -103, -103, -103, -103, 460, 503, 567, 569, 572,
  119981. /* 60 */ 577, 580, 582, 584, 587, 593, 631, 644, 646, 649,
  119982. /* 70 */ 655, 657, 659, 661, 664, 670, 708, 720, 759, 771,
  119983. /* 80 */ 810, 822, 861, 873, 912, 930, 947, 950, 957, 959,
  119984. /* 90 */ 963, 966, 968, 998, 1005, 1013, 1022, 1025, -103, -103,
  119985. /* 100 */ -103, -103, -103, -103, -103, -103, -103, 474, 212, 15,
  119986. /* 110 */ 498, 222, 511, -103, 97, 557, -103, -103, -103, -103,
  119987. /* 120 */ -80, 9, 59, 19, 294, 294, -53, -62, 690, 691,
  119988. /* 130 */ 735, 737, 740, 744, 133, 310, 148, 330, 160, 380,
  119989. /* 140 */ 786, 788, 401, 296, 789, 733, 85, 722, -42, 324,
  119990. /* 150 */ 508, 784, 828, 829, 830, 678, 713, 407, 69, 150,
  119991. /* 160 */ 194, 188, 289, 301, 403, 461, 485, 568, 617, 673,
  119992. /* 170 */ 724, 779, 792, 824, 831, 837, 842, 846, 848, 881,
  119993. /* 180 */ 892, 900, 931, 936, 446, 910, 911, 944, 949, 901,
  119994. /* 190 */ 955, 967, 978, 923, 992, 993, 956, 996, 999, 1010,
  119995. /* 200 */ 289, 1018, 1033, 1043, 1046, 1049, 1056, 934, 973, 997,
  119996. /* 210 */ 1000, 1002, 901, 1012, 1019, 1060, 1014, 1004, 1020, 975,
  119997. /* 220 */ 1024, 976, 1040, 1035, 1047, 1045, 1021, 1007, 1051, 1053,
  119998. /* 230 */ 1031, 1034, 1083, 1026, 1082, 1084, 1008, 1009, 1089, 1036,
  119999. /* 240 */ 1068, 1059, 1069, 1071, 1072, 1073, 1105, 1111, 1076, 1050,
  120000. /* 250 */ 1080, 1090, 1079, 1115, 1117, 1058, 1048, 1128, 1138, 1140,
  120001. /* 260 */ 1124, 1145, 1148, 1149, 1151, 1131, 1135, 1137, 1141, 1130,
  120002. /* 270 */ 1142, 1143, 1144, 1147, 1134, 1150, 1152, 1106, 1112, 1113,
  120003. /* 280 */ 1116, 1114, 1125, 1123, 1127, 1171, 1175, 1119, 1164, 1120,
  120004. /* 290 */ 1121, 1166, 1146, 1155, 1157, 1160, 1167, 1211, 1214, 1224,
  120005. /* 300 */ 1225, 1232, 1233, 1234, 1235, 1132, 1153, 1133, 1201, 1208,
  120006. /* 310 */ 1228,
  120007. };
  120008. static const YYACTIONTYPE yy_default[] = {
  120009. /* 0 */ 982, 1300, 1300, 1300, 1214, 1214, 1214, 1305, 1300, 1109,
  120010. /* 10 */ 1138, 1138, 1274, 1305, 1305, 1305, 1305, 1305, 1305, 1212,
  120011. /* 20 */ 1305, 1305, 1305, 1300, 1305, 1113, 1144, 1305, 1305, 1305,
  120012. /* 30 */ 1305, 1305, 1305, 1305, 1305, 1273, 1275, 1152, 1151, 1254,
  120013. /* 40 */ 1125, 1149, 1142, 1146, 1215, 1208, 1209, 1207, 1211, 1216,
  120014. /* 50 */ 1305, 1145, 1177, 1192, 1176, 1305, 1305, 1305, 1305, 1305,
  120015. /* 60 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120016. /* 70 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120017. /* 80 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120018. /* 90 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1186, 1191,
  120019. /* 100 */ 1198, 1190, 1187, 1179, 1178, 1180, 1181, 1305, 1305, 1008,
  120020. /* 110 */ 1074, 1305, 1305, 1182, 1305, 1020, 1183, 1195, 1194, 1193,
  120021. /* 120 */ 1015, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120022. /* 130 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120023. /* 140 */ 1305, 1305, 1305, 1305, 1305, 982, 1300, 1305, 1305, 1300,
  120024. /* 150 */ 1300, 1300, 1300, 1300, 1300, 1292, 1113, 1103, 1305, 1305,
  120025. /* 160 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1280, 1278,
  120026. /* 170 */ 1305, 1227, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120027. /* 180 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120028. /* 190 */ 1305, 1305, 1305, 1109, 1305, 1305, 1305, 1305, 1305, 1305,
  120029. /* 200 */ 1305, 1305, 1305, 1305, 1305, 1305, 988, 1305, 1247, 1109,
  120030. /* 210 */ 1109, 1109, 1111, 1089, 1101, 990, 1148, 1127, 1127, 1259,
  120031. /* 220 */ 1148, 1259, 1045, 1068, 1042, 1138, 1127, 1210, 1138, 1138,
  120032. /* 230 */ 1110, 1101, 1305, 1285, 1118, 1118, 1277, 1277, 1118, 1157,
  120033. /* 240 */ 1078, 1148, 1085, 1085, 1085, 1085, 1118, 1005, 1148, 1157,
  120034. /* 250 */ 1078, 1078, 1148, 1118, 1005, 1253, 1251, 1118, 1118, 1005,
  120035. /* 260 */ 1220, 1118, 1005, 1118, 1005, 1220, 1076, 1076, 1076, 1060,
  120036. /* 270 */ 1220, 1076, 1045, 1076, 1060, 1076, 1076, 1131, 1126, 1131,
  120037. /* 280 */ 1126, 1131, 1126, 1131, 1126, 1118, 1118, 1305, 1220, 1224,
  120038. /* 290 */ 1224, 1220, 1143, 1132, 1141, 1139, 1148, 1011, 1063, 998,
  120039. /* 300 */ 998, 987, 987, 987, 987, 1297, 1297, 1292, 1047, 1047,
  120040. /* 310 */ 1030, 1305, 1305, 1305, 1305, 1305, 1305, 1022, 1305, 1229,
  120041. /* 320 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120042. /* 330 */ 1305, 1305, 1305, 1305, 1305, 1305, 1164, 1305, 983, 1287,
  120043. /* 340 */ 1305, 1305, 1284, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120044. /* 350 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120045. /* 360 */ 1305, 1257, 1305, 1305, 1305, 1305, 1305, 1305, 1250, 1249,
  120046. /* 370 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120047. /* 380 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305,
  120048. /* 390 */ 1305, 1305, 1092, 1305, 1305, 1305, 1096, 1305, 1305, 1305,
  120049. /* 400 */ 1305, 1305, 1305, 1305, 1140, 1305, 1133, 1305, 1213, 1305,
  120050. /* 410 */ 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1305, 1302,
  120051. /* 420 */ 1305, 1305, 1305, 1301, 1305, 1305, 1305, 1305, 1305, 1166,
  120052. /* 430 */ 1305, 1165, 1169, 1305, 996, 1305,
  120053. };
  120054. /********** End of lemon-generated parsing tables *****************************/
  120055. /* The next table maps tokens (terminal symbols) into fallback tokens.
  120056. ** If a construct like the following:
  120057. **
  120058. ** %fallback ID X Y Z.
  120059. **
  120060. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  120061. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  120062. ** but it does not parse, the type of the token is changed to ID and
  120063. ** the parse is retried before an error is thrown.
  120064. **
  120065. ** This feature can be used, for example, to cause some keywords in a language
  120066. ** to revert to identifiers if they keyword does not apply in the context where
  120067. ** it appears.
  120068. */
  120069. #ifdef YYFALLBACK
  120070. static const YYCODETYPE yyFallback[] = {
  120071. 0, /* $ => nothing */
  120072. 0, /* SEMI => nothing */
  120073. 27, /* EXPLAIN => ID */
  120074. 27, /* QUERY => ID */
  120075. 27, /* PLAN => ID */
  120076. 27, /* BEGIN => ID */
  120077. 0, /* TRANSACTION => nothing */
  120078. 27, /* DEFERRED => ID */
  120079. 27, /* IMMEDIATE => ID */
  120080. 27, /* EXCLUSIVE => ID */
  120081. 0, /* COMMIT => nothing */
  120082. 27, /* END => ID */
  120083. 27, /* ROLLBACK => ID */
  120084. 27, /* SAVEPOINT => ID */
  120085. 27, /* RELEASE => ID */
  120086. 0, /* TO => nothing */
  120087. 0, /* TABLE => nothing */
  120088. 0, /* CREATE => nothing */
  120089. 27, /* IF => ID */
  120090. 0, /* NOT => nothing */
  120091. 0, /* EXISTS => nothing */
  120092. 27, /* TEMP => ID */
  120093. 0, /* LP => nothing */
  120094. 0, /* RP => nothing */
  120095. 0, /* AS => nothing */
  120096. 27, /* WITHOUT => ID */
  120097. 0, /* COMMA => nothing */
  120098. 0, /* ID => nothing */
  120099. 0, /* INDEXED => nothing */
  120100. 27, /* ABORT => ID */
  120101. 27, /* ACTION => ID */
  120102. 27, /* AFTER => ID */
  120103. 27, /* ANALYZE => ID */
  120104. 27, /* ASC => ID */
  120105. 27, /* ATTACH => ID */
  120106. 27, /* BEFORE => ID */
  120107. 27, /* BY => ID */
  120108. 27, /* CASCADE => ID */
  120109. 27, /* CAST => ID */
  120110. 27, /* COLUMNKW => ID */
  120111. 27, /* CONFLICT => ID */
  120112. 27, /* DATABASE => ID */
  120113. 27, /* DESC => ID */
  120114. 27, /* DETACH => ID */
  120115. 27, /* EACH => ID */
  120116. 27, /* FAIL => ID */
  120117. 27, /* FOR => ID */
  120118. 27, /* IGNORE => ID */
  120119. 27, /* INITIALLY => ID */
  120120. 27, /* INSTEAD => ID */
  120121. 27, /* LIKE_KW => ID */
  120122. 27, /* MATCH => ID */
  120123. 27, /* NO => ID */
  120124. 27, /* KEY => ID */
  120125. 27, /* OF => ID */
  120126. 27, /* OFFSET => ID */
  120127. 27, /* PRAGMA => ID */
  120128. 27, /* RAISE => ID */
  120129. 27, /* RECURSIVE => ID */
  120130. 27, /* REPLACE => ID */
  120131. 27, /* RESTRICT => ID */
  120132. 27, /* ROW => ID */
  120133. 27, /* TRIGGER => ID */
  120134. 27, /* VACUUM => ID */
  120135. 27, /* VIEW => ID */
  120136. 27, /* VIRTUAL => ID */
  120137. 27, /* WITH => ID */
  120138. 27, /* REINDEX => ID */
  120139. 27, /* RENAME => ID */
  120140. 27, /* CTIME_KW => ID */
  120141. };
  120142. #endif /* YYFALLBACK */
  120143. /* The following structure represents a single element of the
  120144. ** parser's stack. Information stored includes:
  120145. **
  120146. ** + The state number for the parser at this level of the stack.
  120147. **
  120148. ** + The value of the token stored at this level of the stack.
  120149. ** (In other words, the "major" token.)
  120150. **
  120151. ** + The semantic value stored at this level of the stack. This is
  120152. ** the information used by the action routines in the grammar.
  120153. ** It is sometimes called the "minor" token.
  120154. **
  120155. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  120156. ** actually contains the reduce action for the second half of the
  120157. ** SHIFTREDUCE.
  120158. */
  120159. struct yyStackEntry {
  120160. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  120161. YYCODETYPE major; /* The major token value. This is the code
  120162. ** number for the token at this stack level */
  120163. YYMINORTYPE minor; /* The user-supplied minor token value. This
  120164. ** is the value of the token */
  120165. };
  120166. typedef struct yyStackEntry yyStackEntry;
  120167. /* The state of the parser is completely contained in an instance of
  120168. ** the following structure */
  120169. struct yyParser {
  120170. int yyidx; /* Index of top element in stack */
  120171. #ifdef YYTRACKMAXSTACKDEPTH
  120172. int yyidxMax; /* Maximum value of yyidx */
  120173. #endif
  120174. int yyerrcnt; /* Shifts left before out of the error */
  120175. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  120176. #if YYSTACKDEPTH<=0
  120177. int yystksz; /* Current side of the stack */
  120178. yyStackEntry *yystack; /* The parser's stack */
  120179. #else
  120180. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  120181. #endif
  120182. };
  120183. typedef struct yyParser yyParser;
  120184. #ifndef NDEBUG
  120185. /* #include <stdio.h> */
  120186. static FILE *yyTraceFILE = 0;
  120187. static char *yyTracePrompt = 0;
  120188. #endif /* NDEBUG */
  120189. #ifndef NDEBUG
  120190. /*
  120191. ** Turn parser tracing on by giving a stream to which to write the trace
  120192. ** and a prompt to preface each trace message. Tracing is turned off
  120193. ** by making either argument NULL
  120194. **
  120195. ** Inputs:
  120196. ** <ul>
  120197. ** <li> A FILE* to which trace output should be written.
  120198. ** If NULL, then tracing is turned off.
  120199. ** <li> A prefix string written at the beginning of every
  120200. ** line of trace output. If NULL, then tracing is
  120201. ** turned off.
  120202. ** </ul>
  120203. **
  120204. ** Outputs:
  120205. ** None.
  120206. */
  120207. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  120208. yyTraceFILE = TraceFILE;
  120209. yyTracePrompt = zTracePrompt;
  120210. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  120211. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  120212. }
  120213. #endif /* NDEBUG */
  120214. #ifndef NDEBUG
  120215. /* For tracing shifts, the names of all terminals and nonterminals
  120216. ** are required. The following table supplies these names */
  120217. static const char *const yyTokenName[] = {
  120218. "$", "SEMI", "EXPLAIN", "QUERY",
  120219. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  120220. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  120221. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  120222. "TABLE", "CREATE", "IF", "NOT",
  120223. "EXISTS", "TEMP", "LP", "RP",
  120224. "AS", "WITHOUT", "COMMA", "ID",
  120225. "INDEXED", "ABORT", "ACTION", "AFTER",
  120226. "ANALYZE", "ASC", "ATTACH", "BEFORE",
  120227. "BY", "CASCADE", "CAST", "COLUMNKW",
  120228. "CONFLICT", "DATABASE", "DESC", "DETACH",
  120229. "EACH", "FAIL", "FOR", "IGNORE",
  120230. "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
  120231. "NO", "KEY", "OF", "OFFSET",
  120232. "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
  120233. "RESTRICT", "ROW", "TRIGGER", "VACUUM",
  120234. "VIEW", "VIRTUAL", "WITH", "REINDEX",
  120235. "RENAME", "CTIME_KW", "ANY", "OR",
  120236. "AND", "IS", "BETWEEN", "IN",
  120237. "ISNULL", "NOTNULL", "NE", "EQ",
  120238. "GT", "LE", "LT", "GE",
  120239. "ESCAPE", "BITAND", "BITOR", "LSHIFT",
  120240. "RSHIFT", "PLUS", "MINUS", "STAR",
  120241. "SLASH", "REM", "CONCAT", "COLLATE",
  120242. "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
  120243. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  120244. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  120245. "INSERT", "DELETE", "UPDATE", "SET",
  120246. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  120247. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  120248. "VALUES", "DISTINCT", "DOT", "FROM",
  120249. "JOIN", "USING", "ORDER", "GROUP",
  120250. "HAVING", "LIMIT", "WHERE", "INTO",
  120251. "INTEGER", "FLOAT", "BLOB", "VARIABLE",
  120252. "CASE", "WHEN", "THEN", "ELSE",
  120253. "INDEX", "ALTER", "ADD", "error",
  120254. "input", "cmdlist", "ecmd", "explain",
  120255. "cmdx", "cmd", "transtype", "trans_opt",
  120256. "nm", "savepoint_opt", "create_table", "create_table_args",
  120257. "createkw", "temp", "ifnotexists", "dbnm",
  120258. "columnlist", "conslist_opt", "table_options", "select",
  120259. "column", "columnid", "type", "carglist",
  120260. "typetoken", "typename", "signed", "plus_num",
  120261. "minus_num", "ccons", "term", "expr",
  120262. "onconf", "sortorder", "autoinc", "eidlist_opt",
  120263. "refargs", "defer_subclause", "refarg", "refact",
  120264. "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
  120265. "sortlist", "eidlist", "defer_subclause_opt", "orconf",
  120266. "resolvetype", "raisetype", "ifexists", "fullname",
  120267. "selectnowith", "oneselect", "with", "multiselect_op",
  120268. "distinct", "selcollist", "from", "where_opt",
  120269. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  120270. "values", "nexprlist", "exprlist", "sclp",
  120271. "as", "seltablist", "stl_prefix", "joinop",
  120272. "indexed_opt", "on_opt", "using_opt", "idlist",
  120273. "setlist", "insert_cmd", "idlist_opt", "likeop",
  120274. "between_op", "in_op", "case_operand", "case_exprlist",
  120275. "case_else", "uniqueflag", "collate", "nmnum",
  120276. "trigger_decl", "trigger_cmd_list", "trigger_time", "trigger_event",
  120277. "foreach_clause", "when_clause", "trigger_cmd", "trnm",
  120278. "tridxby", "database_kw_opt", "key_opt", "add_column_fullname",
  120279. "kwcolumn_opt", "create_vtab", "vtabarglist", "vtabarg",
  120280. "vtabargtoken", "lp", "anylist", "wqlist",
  120281. };
  120282. #endif /* NDEBUG */
  120283. #ifndef NDEBUG
  120284. /* For tracing reduce actions, the names of all rules are required.
  120285. */
  120286. static const char *const yyRuleName[] = {
  120287. /* 0 */ "input ::= cmdlist",
  120288. /* 1 */ "cmdlist ::= cmdlist ecmd",
  120289. /* 2 */ "cmdlist ::= ecmd",
  120290. /* 3 */ "ecmd ::= SEMI",
  120291. /* 4 */ "ecmd ::= explain cmdx SEMI",
  120292. /* 5 */ "explain ::=",
  120293. /* 6 */ "explain ::= EXPLAIN",
  120294. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  120295. /* 8 */ "cmdx ::= cmd",
  120296. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  120297. /* 10 */ "trans_opt ::=",
  120298. /* 11 */ "trans_opt ::= TRANSACTION",
  120299. /* 12 */ "trans_opt ::= TRANSACTION nm",
  120300. /* 13 */ "transtype ::=",
  120301. /* 14 */ "transtype ::= DEFERRED",
  120302. /* 15 */ "transtype ::= IMMEDIATE",
  120303. /* 16 */ "transtype ::= EXCLUSIVE",
  120304. /* 17 */ "cmd ::= COMMIT trans_opt",
  120305. /* 18 */ "cmd ::= END trans_opt",
  120306. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  120307. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  120308. /* 21 */ "savepoint_opt ::=",
  120309. /* 22 */ "cmd ::= SAVEPOINT nm",
  120310. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  120311. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  120312. /* 25 */ "cmd ::= create_table create_table_args",
  120313. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  120314. /* 27 */ "createkw ::= CREATE",
  120315. /* 28 */ "ifnotexists ::=",
  120316. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  120317. /* 30 */ "temp ::= TEMP",
  120318. /* 31 */ "temp ::=",
  120319. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  120320. /* 33 */ "create_table_args ::= AS select",
  120321. /* 34 */ "table_options ::=",
  120322. /* 35 */ "table_options ::= WITHOUT nm",
  120323. /* 36 */ "columnlist ::= columnlist COMMA column",
  120324. /* 37 */ "columnlist ::= column",
  120325. /* 38 */ "column ::= columnid type carglist",
  120326. /* 39 */ "columnid ::= nm",
  120327. /* 40 */ "nm ::= ID|INDEXED",
  120328. /* 41 */ "nm ::= STRING",
  120329. /* 42 */ "nm ::= JOIN_KW",
  120330. /* 43 */ "type ::=",
  120331. /* 44 */ "type ::= typetoken",
  120332. /* 45 */ "typetoken ::= typename",
  120333. /* 46 */ "typetoken ::= typename LP signed RP",
  120334. /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
  120335. /* 48 */ "typename ::= ID|STRING",
  120336. /* 49 */ "typename ::= typename ID|STRING",
  120337. /* 50 */ "signed ::= plus_num",
  120338. /* 51 */ "signed ::= minus_num",
  120339. /* 52 */ "carglist ::= carglist ccons",
  120340. /* 53 */ "carglist ::=",
  120341. /* 54 */ "ccons ::= CONSTRAINT nm",
  120342. /* 55 */ "ccons ::= DEFAULT term",
  120343. /* 56 */ "ccons ::= DEFAULT LP expr RP",
  120344. /* 57 */ "ccons ::= DEFAULT PLUS term",
  120345. /* 58 */ "ccons ::= DEFAULT MINUS term",
  120346. /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
  120347. /* 60 */ "ccons ::= NULL onconf",
  120348. /* 61 */ "ccons ::= NOT NULL onconf",
  120349. /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  120350. /* 63 */ "ccons ::= UNIQUE onconf",
  120351. /* 64 */ "ccons ::= CHECK LP expr RP",
  120352. /* 65 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  120353. /* 66 */ "ccons ::= defer_subclause",
  120354. /* 67 */ "ccons ::= COLLATE ID|STRING",
  120355. /* 68 */ "autoinc ::=",
  120356. /* 69 */ "autoinc ::= AUTOINCR",
  120357. /* 70 */ "refargs ::=",
  120358. /* 71 */ "refargs ::= refargs refarg",
  120359. /* 72 */ "refarg ::= MATCH nm",
  120360. /* 73 */ "refarg ::= ON INSERT refact",
  120361. /* 74 */ "refarg ::= ON DELETE refact",
  120362. /* 75 */ "refarg ::= ON UPDATE refact",
  120363. /* 76 */ "refact ::= SET NULL",
  120364. /* 77 */ "refact ::= SET DEFAULT",
  120365. /* 78 */ "refact ::= CASCADE",
  120366. /* 79 */ "refact ::= RESTRICT",
  120367. /* 80 */ "refact ::= NO ACTION",
  120368. /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  120369. /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  120370. /* 83 */ "init_deferred_pred_opt ::=",
  120371. /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  120372. /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  120373. /* 86 */ "conslist_opt ::=",
  120374. /* 87 */ "conslist_opt ::= COMMA conslist",
  120375. /* 88 */ "conslist ::= conslist tconscomma tcons",
  120376. /* 89 */ "conslist ::= tcons",
  120377. /* 90 */ "tconscomma ::= COMMA",
  120378. /* 91 */ "tconscomma ::=",
  120379. /* 92 */ "tcons ::= CONSTRAINT nm",
  120380. /* 93 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  120381. /* 94 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  120382. /* 95 */ "tcons ::= CHECK LP expr RP onconf",
  120383. /* 96 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  120384. /* 97 */ "defer_subclause_opt ::=",
  120385. /* 98 */ "defer_subclause_opt ::= defer_subclause",
  120386. /* 99 */ "onconf ::=",
  120387. /* 100 */ "onconf ::= ON CONFLICT resolvetype",
  120388. /* 101 */ "orconf ::=",
  120389. /* 102 */ "orconf ::= OR resolvetype",
  120390. /* 103 */ "resolvetype ::= raisetype",
  120391. /* 104 */ "resolvetype ::= IGNORE",
  120392. /* 105 */ "resolvetype ::= REPLACE",
  120393. /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
  120394. /* 107 */ "ifexists ::= IF EXISTS",
  120395. /* 108 */ "ifexists ::=",
  120396. /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  120397. /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
  120398. /* 111 */ "cmd ::= select",
  120399. /* 112 */ "select ::= with selectnowith",
  120400. /* 113 */ "selectnowith ::= oneselect",
  120401. /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  120402. /* 115 */ "multiselect_op ::= UNION",
  120403. /* 116 */ "multiselect_op ::= UNION ALL",
  120404. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  120405. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  120406. /* 119 */ "oneselect ::= values",
  120407. /* 120 */ "values ::= VALUES LP nexprlist RP",
  120408. /* 121 */ "values ::= values COMMA LP exprlist RP",
  120409. /* 122 */ "distinct ::= DISTINCT",
  120410. /* 123 */ "distinct ::= ALL",
  120411. /* 124 */ "distinct ::=",
  120412. /* 125 */ "sclp ::= selcollist COMMA",
  120413. /* 126 */ "sclp ::=",
  120414. /* 127 */ "selcollist ::= sclp expr as",
  120415. /* 128 */ "selcollist ::= sclp STAR",
  120416. /* 129 */ "selcollist ::= sclp nm DOT STAR",
  120417. /* 130 */ "as ::= AS nm",
  120418. /* 131 */ "as ::= ID|STRING",
  120419. /* 132 */ "as ::=",
  120420. /* 133 */ "from ::=",
  120421. /* 134 */ "from ::= FROM seltablist",
  120422. /* 135 */ "stl_prefix ::= seltablist joinop",
  120423. /* 136 */ "stl_prefix ::=",
  120424. /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  120425. /* 138 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  120426. /* 139 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  120427. /* 140 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  120428. /* 141 */ "dbnm ::=",
  120429. /* 142 */ "dbnm ::= DOT nm",
  120430. /* 143 */ "fullname ::= nm dbnm",
  120431. /* 144 */ "joinop ::= COMMA|JOIN",
  120432. /* 145 */ "joinop ::= JOIN_KW JOIN",
  120433. /* 146 */ "joinop ::= JOIN_KW nm JOIN",
  120434. /* 147 */ "joinop ::= JOIN_KW nm nm JOIN",
  120435. /* 148 */ "on_opt ::= ON expr",
  120436. /* 149 */ "on_opt ::=",
  120437. /* 150 */ "indexed_opt ::=",
  120438. /* 151 */ "indexed_opt ::= INDEXED BY nm",
  120439. /* 152 */ "indexed_opt ::= NOT INDEXED",
  120440. /* 153 */ "using_opt ::= USING LP idlist RP",
  120441. /* 154 */ "using_opt ::=",
  120442. /* 155 */ "orderby_opt ::=",
  120443. /* 156 */ "orderby_opt ::= ORDER BY sortlist",
  120444. /* 157 */ "sortlist ::= sortlist COMMA expr sortorder",
  120445. /* 158 */ "sortlist ::= expr sortorder",
  120446. /* 159 */ "sortorder ::= ASC",
  120447. /* 160 */ "sortorder ::= DESC",
  120448. /* 161 */ "sortorder ::=",
  120449. /* 162 */ "groupby_opt ::=",
  120450. /* 163 */ "groupby_opt ::= GROUP BY nexprlist",
  120451. /* 164 */ "having_opt ::=",
  120452. /* 165 */ "having_opt ::= HAVING expr",
  120453. /* 166 */ "limit_opt ::=",
  120454. /* 167 */ "limit_opt ::= LIMIT expr",
  120455. /* 168 */ "limit_opt ::= LIMIT expr OFFSET expr",
  120456. /* 169 */ "limit_opt ::= LIMIT expr COMMA expr",
  120457. /* 170 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  120458. /* 171 */ "where_opt ::=",
  120459. /* 172 */ "where_opt ::= WHERE expr",
  120460. /* 173 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  120461. /* 174 */ "setlist ::= setlist COMMA nm EQ expr",
  120462. /* 175 */ "setlist ::= nm EQ expr",
  120463. /* 176 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
  120464. /* 177 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
  120465. /* 178 */ "insert_cmd ::= INSERT orconf",
  120466. /* 179 */ "insert_cmd ::= REPLACE",
  120467. /* 180 */ "idlist_opt ::=",
  120468. /* 181 */ "idlist_opt ::= LP idlist RP",
  120469. /* 182 */ "idlist ::= idlist COMMA nm",
  120470. /* 183 */ "idlist ::= nm",
  120471. /* 184 */ "expr ::= term",
  120472. /* 185 */ "expr ::= LP expr RP",
  120473. /* 186 */ "term ::= NULL",
  120474. /* 187 */ "expr ::= ID|INDEXED",
  120475. /* 188 */ "expr ::= JOIN_KW",
  120476. /* 189 */ "expr ::= nm DOT nm",
  120477. /* 190 */ "expr ::= nm DOT nm DOT nm",
  120478. /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
  120479. /* 192 */ "term ::= STRING",
  120480. /* 193 */ "expr ::= VARIABLE",
  120481. /* 194 */ "expr ::= expr COLLATE ID|STRING",
  120482. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  120483. /* 196 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  120484. /* 197 */ "expr ::= ID|INDEXED LP STAR RP",
  120485. /* 198 */ "term ::= CTIME_KW",
  120486. /* 199 */ "expr ::= expr AND expr",
  120487. /* 200 */ "expr ::= expr OR expr",
  120488. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  120489. /* 202 */ "expr ::= expr EQ|NE expr",
  120490. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  120491. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  120492. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  120493. /* 206 */ "expr ::= expr CONCAT expr",
  120494. /* 207 */ "likeop ::= LIKE_KW|MATCH",
  120495. /* 208 */ "likeop ::= NOT LIKE_KW|MATCH",
  120496. /* 209 */ "expr ::= expr likeop expr",
  120497. /* 210 */ "expr ::= expr likeop expr ESCAPE expr",
  120498. /* 211 */ "expr ::= expr ISNULL|NOTNULL",
  120499. /* 212 */ "expr ::= expr NOT NULL",
  120500. /* 213 */ "expr ::= expr IS expr",
  120501. /* 214 */ "expr ::= expr IS NOT expr",
  120502. /* 215 */ "expr ::= NOT expr",
  120503. /* 216 */ "expr ::= BITNOT expr",
  120504. /* 217 */ "expr ::= MINUS expr",
  120505. /* 218 */ "expr ::= PLUS expr",
  120506. /* 219 */ "between_op ::= BETWEEN",
  120507. /* 220 */ "between_op ::= NOT BETWEEN",
  120508. /* 221 */ "expr ::= expr between_op expr AND expr",
  120509. /* 222 */ "in_op ::= IN",
  120510. /* 223 */ "in_op ::= NOT IN",
  120511. /* 224 */ "expr ::= expr in_op LP exprlist RP",
  120512. /* 225 */ "expr ::= LP select RP",
  120513. /* 226 */ "expr ::= expr in_op LP select RP",
  120514. /* 227 */ "expr ::= expr in_op nm dbnm",
  120515. /* 228 */ "expr ::= EXISTS LP select RP",
  120516. /* 229 */ "expr ::= CASE case_operand case_exprlist case_else END",
  120517. /* 230 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  120518. /* 231 */ "case_exprlist ::= WHEN expr THEN expr",
  120519. /* 232 */ "case_else ::= ELSE expr",
  120520. /* 233 */ "case_else ::=",
  120521. /* 234 */ "case_operand ::= expr",
  120522. /* 235 */ "case_operand ::=",
  120523. /* 236 */ "exprlist ::= nexprlist",
  120524. /* 237 */ "exprlist ::=",
  120525. /* 238 */ "nexprlist ::= nexprlist COMMA expr",
  120526. /* 239 */ "nexprlist ::= expr",
  120527. /* 240 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  120528. /* 241 */ "uniqueflag ::= UNIQUE",
  120529. /* 242 */ "uniqueflag ::=",
  120530. /* 243 */ "eidlist_opt ::=",
  120531. /* 244 */ "eidlist_opt ::= LP eidlist RP",
  120532. /* 245 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  120533. /* 246 */ "eidlist ::= nm collate sortorder",
  120534. /* 247 */ "collate ::=",
  120535. /* 248 */ "collate ::= COLLATE ID|STRING",
  120536. /* 249 */ "cmd ::= DROP INDEX ifexists fullname",
  120537. /* 250 */ "cmd ::= VACUUM",
  120538. /* 251 */ "cmd ::= VACUUM nm",
  120539. /* 252 */ "cmd ::= PRAGMA nm dbnm",
  120540. /* 253 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  120541. /* 254 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  120542. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  120543. /* 256 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  120544. /* 257 */ "nmnum ::= plus_num",
  120545. /* 258 */ "nmnum ::= nm",
  120546. /* 259 */ "nmnum ::= ON",
  120547. /* 260 */ "nmnum ::= DELETE",
  120548. /* 261 */ "nmnum ::= DEFAULT",
  120549. /* 262 */ "plus_num ::= PLUS INTEGER|FLOAT",
  120550. /* 263 */ "plus_num ::= INTEGER|FLOAT",
  120551. /* 264 */ "minus_num ::= MINUS INTEGER|FLOAT",
  120552. /* 265 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  120553. /* 266 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  120554. /* 267 */ "trigger_time ::= BEFORE",
  120555. /* 268 */ "trigger_time ::= AFTER",
  120556. /* 269 */ "trigger_time ::= INSTEAD OF",
  120557. /* 270 */ "trigger_time ::=",
  120558. /* 271 */ "trigger_event ::= DELETE|INSERT",
  120559. /* 272 */ "trigger_event ::= UPDATE",
  120560. /* 273 */ "trigger_event ::= UPDATE OF idlist",
  120561. /* 274 */ "foreach_clause ::=",
  120562. /* 275 */ "foreach_clause ::= FOR EACH ROW",
  120563. /* 276 */ "when_clause ::=",
  120564. /* 277 */ "when_clause ::= WHEN expr",
  120565. /* 278 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  120566. /* 279 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  120567. /* 280 */ "trnm ::= nm",
  120568. /* 281 */ "trnm ::= nm DOT nm",
  120569. /* 282 */ "tridxby ::=",
  120570. /* 283 */ "tridxby ::= INDEXED BY nm",
  120571. /* 284 */ "tridxby ::= NOT INDEXED",
  120572. /* 285 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  120573. /* 286 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
  120574. /* 287 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  120575. /* 288 */ "trigger_cmd ::= select",
  120576. /* 289 */ "expr ::= RAISE LP IGNORE RP",
  120577. /* 290 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  120578. /* 291 */ "raisetype ::= ROLLBACK",
  120579. /* 292 */ "raisetype ::= ABORT",
  120580. /* 293 */ "raisetype ::= FAIL",
  120581. /* 294 */ "cmd ::= DROP TRIGGER ifexists fullname",
  120582. /* 295 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  120583. /* 296 */ "cmd ::= DETACH database_kw_opt expr",
  120584. /* 297 */ "key_opt ::=",
  120585. /* 298 */ "key_opt ::= KEY expr",
  120586. /* 299 */ "database_kw_opt ::= DATABASE",
  120587. /* 300 */ "database_kw_opt ::=",
  120588. /* 301 */ "cmd ::= REINDEX",
  120589. /* 302 */ "cmd ::= REINDEX nm dbnm",
  120590. /* 303 */ "cmd ::= ANALYZE",
  120591. /* 304 */ "cmd ::= ANALYZE nm dbnm",
  120592. /* 305 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  120593. /* 306 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  120594. /* 307 */ "add_column_fullname ::= fullname",
  120595. /* 308 */ "kwcolumn_opt ::=",
  120596. /* 309 */ "kwcolumn_opt ::= COLUMNKW",
  120597. /* 310 */ "cmd ::= create_vtab",
  120598. /* 311 */ "cmd ::= create_vtab LP vtabarglist RP",
  120599. /* 312 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  120600. /* 313 */ "vtabarglist ::= vtabarg",
  120601. /* 314 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  120602. /* 315 */ "vtabarg ::=",
  120603. /* 316 */ "vtabarg ::= vtabarg vtabargtoken",
  120604. /* 317 */ "vtabargtoken ::= ANY",
  120605. /* 318 */ "vtabargtoken ::= lp anylist RP",
  120606. /* 319 */ "lp ::= LP",
  120607. /* 320 */ "anylist ::=",
  120608. /* 321 */ "anylist ::= anylist LP anylist RP",
  120609. /* 322 */ "anylist ::= anylist ANY",
  120610. /* 323 */ "with ::=",
  120611. /* 324 */ "with ::= WITH wqlist",
  120612. /* 325 */ "with ::= WITH RECURSIVE wqlist",
  120613. /* 326 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  120614. /* 327 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  120615. };
  120616. #endif /* NDEBUG */
  120617. #if YYSTACKDEPTH<=0
  120618. /*
  120619. ** Try to increase the size of the parser stack.
  120620. */
  120621. static void yyGrowStack(yyParser *p){
  120622. int newSize;
  120623. yyStackEntry *pNew;
  120624. newSize = p->yystksz*2 + 100;
  120625. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  120626. if( pNew ){
  120627. p->yystack = pNew;
  120628. p->yystksz = newSize;
  120629. #ifndef NDEBUG
  120630. if( yyTraceFILE ){
  120631. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  120632. yyTracePrompt, p->yystksz);
  120633. }
  120634. #endif
  120635. }
  120636. }
  120637. #endif
  120638. /* Datatype of the argument to the memory allocated passed as the
  120639. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  120640. ** putting an appropriate #define in the %include section of the input
  120641. ** grammar.
  120642. */
  120643. #ifndef YYMALLOCARGTYPE
  120644. # define YYMALLOCARGTYPE size_t
  120645. #endif
  120646. /*
  120647. ** This function allocates a new parser.
  120648. ** The only argument is a pointer to a function which works like
  120649. ** malloc.
  120650. **
  120651. ** Inputs:
  120652. ** A pointer to the function used to allocate memory.
  120653. **
  120654. ** Outputs:
  120655. ** A pointer to a parser. This pointer is used in subsequent calls
  120656. ** to sqlite3Parser and sqlite3ParserFree.
  120657. */
  120658. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
  120659. yyParser *pParser;
  120660. pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  120661. if( pParser ){
  120662. pParser->yyidx = -1;
  120663. #ifdef YYTRACKMAXSTACKDEPTH
  120664. pParser->yyidxMax = 0;
  120665. #endif
  120666. #if YYSTACKDEPTH<=0
  120667. pParser->yystack = NULL;
  120668. pParser->yystksz = 0;
  120669. yyGrowStack(pParser);
  120670. #endif
  120671. }
  120672. return pParser;
  120673. }
  120674. /* The following function deletes the "minor type" or semantic value
  120675. ** associated with a symbol. The symbol can be either a terminal
  120676. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  120677. ** a pointer to the value to be deleted. The code used to do the
  120678. ** deletions is derived from the %destructor and/or %token_destructor
  120679. ** directives of the input grammar.
  120680. */
  120681. static void yy_destructor(
  120682. yyParser *yypParser, /* The parser */
  120683. YYCODETYPE yymajor, /* Type code for object to destroy */
  120684. YYMINORTYPE *yypminor /* The object to be destroyed */
  120685. ){
  120686. sqlite3ParserARG_FETCH;
  120687. switch( yymajor ){
  120688. /* Here is inserted the actions which take place when a
  120689. ** terminal or non-terminal is destroyed. This can happen
  120690. ** when the symbol is popped from the stack during a
  120691. ** reduce or during error processing or when a parser is
  120692. ** being destroyed before it is finished parsing.
  120693. **
  120694. ** Note: during a reduce, the only symbols destroyed are those
  120695. ** which appear on the RHS of the rule, but which are *not* used
  120696. ** inside the C code.
  120697. */
  120698. /********* Begin destructor definitions ***************************************/
  120699. case 163: /* select */
  120700. case 196: /* selectnowith */
  120701. case 197: /* oneselect */
  120702. case 208: /* values */
  120703. {
  120704. sqlite3SelectDelete(pParse->db, (yypminor->yy387));
  120705. }
  120706. break;
  120707. case 174: /* term */
  120708. case 175: /* expr */
  120709. {
  120710. sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
  120711. }
  120712. break;
  120713. case 179: /* eidlist_opt */
  120714. case 188: /* sortlist */
  120715. case 189: /* eidlist */
  120716. case 201: /* selcollist */
  120717. case 204: /* groupby_opt */
  120718. case 206: /* orderby_opt */
  120719. case 209: /* nexprlist */
  120720. case 210: /* exprlist */
  120721. case 211: /* sclp */
  120722. case 220: /* setlist */
  120723. case 227: /* case_exprlist */
  120724. {
  120725. sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
  120726. }
  120727. break;
  120728. case 195: /* fullname */
  120729. case 202: /* from */
  120730. case 213: /* seltablist */
  120731. case 214: /* stl_prefix */
  120732. {
  120733. sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
  120734. }
  120735. break;
  120736. case 198: /* with */
  120737. case 251: /* wqlist */
  120738. {
  120739. sqlite3WithDelete(pParse->db, (yypminor->yy451));
  120740. }
  120741. break;
  120742. case 203: /* where_opt */
  120743. case 205: /* having_opt */
  120744. case 217: /* on_opt */
  120745. case 226: /* case_operand */
  120746. case 228: /* case_else */
  120747. case 237: /* when_clause */
  120748. case 242: /* key_opt */
  120749. {
  120750. sqlite3ExprDelete(pParse->db, (yypminor->yy314));
  120751. }
  120752. break;
  120753. case 218: /* using_opt */
  120754. case 219: /* idlist */
  120755. case 222: /* idlist_opt */
  120756. {
  120757. sqlite3IdListDelete(pParse->db, (yypminor->yy384));
  120758. }
  120759. break;
  120760. case 233: /* trigger_cmd_list */
  120761. case 238: /* trigger_cmd */
  120762. {
  120763. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
  120764. }
  120765. break;
  120766. case 235: /* trigger_event */
  120767. {
  120768. sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
  120769. }
  120770. break;
  120771. /********* End destructor definitions *****************************************/
  120772. default: break; /* If no destructor action specified: do nothing */
  120773. }
  120774. }
  120775. /*
  120776. ** Pop the parser's stack once.
  120777. **
  120778. ** If there is a destructor routine associated with the token which
  120779. ** is popped from the stack, then call it.
  120780. */
  120781. static void yy_pop_parser_stack(yyParser *pParser){
  120782. yyStackEntry *yytos;
  120783. assert( pParser->yyidx>=0 );
  120784. yytos = &pParser->yystack[pParser->yyidx--];
  120785. #ifndef NDEBUG
  120786. if( yyTraceFILE ){
  120787. fprintf(yyTraceFILE,"%sPopping %s\n",
  120788. yyTracePrompt,
  120789. yyTokenName[yytos->major]);
  120790. }
  120791. #endif
  120792. yy_destructor(pParser, yytos->major, &yytos->minor);
  120793. }
  120794. /*
  120795. ** Deallocate and destroy a parser. Destructors are called for
  120796. ** all stack elements before shutting the parser down.
  120797. **
  120798. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  120799. ** is defined in a %include section of the input grammar) then it is
  120800. ** assumed that the input pointer is never NULL.
  120801. */
  120802. SQLITE_PRIVATE void sqlite3ParserFree(
  120803. void *p, /* The parser to be deleted */
  120804. void (*freeProc)(void*) /* Function used to reclaim memory */
  120805. ){
  120806. yyParser *pParser = (yyParser*)p;
  120807. #ifndef YYPARSEFREENEVERNULL
  120808. if( pParser==0 ) return;
  120809. #endif
  120810. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  120811. #if YYSTACKDEPTH<=0
  120812. free(pParser->yystack);
  120813. #endif
  120814. (*freeProc)((void*)pParser);
  120815. }
  120816. /*
  120817. ** Return the peak depth of the stack for a parser.
  120818. */
  120819. #ifdef YYTRACKMAXSTACKDEPTH
  120820. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  120821. yyParser *pParser = (yyParser*)p;
  120822. return pParser->yyidxMax;
  120823. }
  120824. #endif
  120825. /*
  120826. ** Find the appropriate action for a parser given the terminal
  120827. ** look-ahead token iLookAhead.
  120828. */
  120829. static int yy_find_shift_action(
  120830. yyParser *pParser, /* The parser */
  120831. YYCODETYPE iLookAhead /* The look-ahead token */
  120832. ){
  120833. int i;
  120834. int stateno = pParser->yystack[pParser->yyidx].stateno;
  120835. if( stateno>=YY_MIN_REDUCE ) return stateno;
  120836. assert( stateno <= YY_SHIFT_COUNT );
  120837. do{
  120838. i = yy_shift_ofst[stateno];
  120839. if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
  120840. assert( iLookAhead!=YYNOCODE );
  120841. i += iLookAhead;
  120842. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  120843. if( iLookAhead>0 ){
  120844. #ifdef YYFALLBACK
  120845. YYCODETYPE iFallback; /* Fallback token */
  120846. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  120847. && (iFallback = yyFallback[iLookAhead])!=0 ){
  120848. #ifndef NDEBUG
  120849. if( yyTraceFILE ){
  120850. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  120851. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  120852. }
  120853. #endif
  120854. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  120855. iLookAhead = iFallback;
  120856. continue;
  120857. }
  120858. #endif
  120859. #ifdef YYWILDCARD
  120860. {
  120861. int j = i - iLookAhead + YYWILDCARD;
  120862. if(
  120863. #if YY_SHIFT_MIN+YYWILDCARD<0
  120864. j>=0 &&
  120865. #endif
  120866. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  120867. j<YY_ACTTAB_COUNT &&
  120868. #endif
  120869. yy_lookahead[j]==YYWILDCARD
  120870. ){
  120871. #ifndef NDEBUG
  120872. if( yyTraceFILE ){
  120873. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  120874. yyTracePrompt, yyTokenName[iLookAhead],
  120875. yyTokenName[YYWILDCARD]);
  120876. }
  120877. #endif /* NDEBUG */
  120878. return yy_action[j];
  120879. }
  120880. }
  120881. #endif /* YYWILDCARD */
  120882. }
  120883. return yy_default[stateno];
  120884. }else{
  120885. return yy_action[i];
  120886. }
  120887. }while(1);
  120888. }
  120889. /*
  120890. ** Find the appropriate action for a parser given the non-terminal
  120891. ** look-ahead token iLookAhead.
  120892. */
  120893. static int yy_find_reduce_action(
  120894. int stateno, /* Current state number */
  120895. YYCODETYPE iLookAhead /* The look-ahead token */
  120896. ){
  120897. int i;
  120898. #ifdef YYERRORSYMBOL
  120899. if( stateno>YY_REDUCE_COUNT ){
  120900. return yy_default[stateno];
  120901. }
  120902. #else
  120903. assert( stateno<=YY_REDUCE_COUNT );
  120904. #endif
  120905. i = yy_reduce_ofst[stateno];
  120906. assert( i!=YY_REDUCE_USE_DFLT );
  120907. assert( iLookAhead!=YYNOCODE );
  120908. i += iLookAhead;
  120909. #ifdef YYERRORSYMBOL
  120910. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  120911. return yy_default[stateno];
  120912. }
  120913. #else
  120914. assert( i>=0 && i<YY_ACTTAB_COUNT );
  120915. assert( yy_lookahead[i]==iLookAhead );
  120916. #endif
  120917. return yy_action[i];
  120918. }
  120919. /*
  120920. ** The following routine is called if the stack overflows.
  120921. */
  120922. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  120923. sqlite3ParserARG_FETCH;
  120924. yypParser->yyidx--;
  120925. #ifndef NDEBUG
  120926. if( yyTraceFILE ){
  120927. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  120928. }
  120929. #endif
  120930. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  120931. /* Here code is inserted which will execute if the parser
  120932. ** stack every overflows */
  120933. /******** Begin %stack_overflow code ******************************************/
  120934. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  120935. sqlite3ErrorMsg(pParse, "parser stack overflow");
  120936. /******** End %stack_overflow code ********************************************/
  120937. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  120938. }
  120939. /*
  120940. ** Print tracing information for a SHIFT action
  120941. */
  120942. #ifndef NDEBUG
  120943. static void yyTraceShift(yyParser *yypParser, int yyNewState){
  120944. if( yyTraceFILE ){
  120945. if( yyNewState<YYNSTATE ){
  120946. fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
  120947. yyTracePrompt,yyTokenName[yypParser->yystack[yypParser->yyidx].major],
  120948. yyNewState);
  120949. }else{
  120950. fprintf(yyTraceFILE,"%sShift '%s'\n",
  120951. yyTracePrompt,yyTokenName[yypParser->yystack[yypParser->yyidx].major]);
  120952. }
  120953. }
  120954. }
  120955. #else
  120956. # define yyTraceShift(X,Y)
  120957. #endif
  120958. /*
  120959. ** Perform a shift action.
  120960. */
  120961. static void yy_shift(
  120962. yyParser *yypParser, /* The parser to be shifted */
  120963. int yyNewState, /* The new state to shift in */
  120964. int yyMajor, /* The major token to shift in */
  120965. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  120966. ){
  120967. yyStackEntry *yytos;
  120968. yypParser->yyidx++;
  120969. #ifdef YYTRACKMAXSTACKDEPTH
  120970. if( yypParser->yyidx>yypParser->yyidxMax ){
  120971. yypParser->yyidxMax = yypParser->yyidx;
  120972. }
  120973. #endif
  120974. #if YYSTACKDEPTH>0
  120975. if( yypParser->yyidx>=YYSTACKDEPTH ){
  120976. yyStackOverflow(yypParser, yypMinor);
  120977. return;
  120978. }
  120979. #else
  120980. if( yypParser->yyidx>=yypParser->yystksz ){
  120981. yyGrowStack(yypParser);
  120982. if( yypParser->yyidx>=yypParser->yystksz ){
  120983. yyStackOverflow(yypParser, yypMinor);
  120984. return;
  120985. }
  120986. }
  120987. #endif
  120988. yytos = &yypParser->yystack[yypParser->yyidx];
  120989. yytos->stateno = (YYACTIONTYPE)yyNewState;
  120990. yytos->major = (YYCODETYPE)yyMajor;
  120991. yytos->minor = *yypMinor;
  120992. yyTraceShift(yypParser, yyNewState);
  120993. }
  120994. /* The following table contains information about every rule that
  120995. ** is used during the reduce.
  120996. */
  120997. static const struct {
  120998. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  120999. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  121000. } yyRuleInfo[] = {
  121001. { 144, 1 },
  121002. { 145, 2 },
  121003. { 145, 1 },
  121004. { 146, 1 },
  121005. { 146, 3 },
  121006. { 147, 0 },
  121007. { 147, 1 },
  121008. { 147, 3 },
  121009. { 148, 1 },
  121010. { 149, 3 },
  121011. { 151, 0 },
  121012. { 151, 1 },
  121013. { 151, 2 },
  121014. { 150, 0 },
  121015. { 150, 1 },
  121016. { 150, 1 },
  121017. { 150, 1 },
  121018. { 149, 2 },
  121019. { 149, 2 },
  121020. { 149, 2 },
  121021. { 153, 1 },
  121022. { 153, 0 },
  121023. { 149, 2 },
  121024. { 149, 3 },
  121025. { 149, 5 },
  121026. { 149, 2 },
  121027. { 154, 6 },
  121028. { 156, 1 },
  121029. { 158, 0 },
  121030. { 158, 3 },
  121031. { 157, 1 },
  121032. { 157, 0 },
  121033. { 155, 5 },
  121034. { 155, 2 },
  121035. { 162, 0 },
  121036. { 162, 2 },
  121037. { 160, 3 },
  121038. { 160, 1 },
  121039. { 164, 3 },
  121040. { 165, 1 },
  121041. { 152, 1 },
  121042. { 152, 1 },
  121043. { 152, 1 },
  121044. { 166, 0 },
  121045. { 166, 1 },
  121046. { 168, 1 },
  121047. { 168, 4 },
  121048. { 168, 6 },
  121049. { 169, 1 },
  121050. { 169, 2 },
  121051. { 170, 1 },
  121052. { 170, 1 },
  121053. { 167, 2 },
  121054. { 167, 0 },
  121055. { 173, 2 },
  121056. { 173, 2 },
  121057. { 173, 4 },
  121058. { 173, 3 },
  121059. { 173, 3 },
  121060. { 173, 2 },
  121061. { 173, 2 },
  121062. { 173, 3 },
  121063. { 173, 5 },
  121064. { 173, 2 },
  121065. { 173, 4 },
  121066. { 173, 4 },
  121067. { 173, 1 },
  121068. { 173, 2 },
  121069. { 178, 0 },
  121070. { 178, 1 },
  121071. { 180, 0 },
  121072. { 180, 2 },
  121073. { 182, 2 },
  121074. { 182, 3 },
  121075. { 182, 3 },
  121076. { 182, 3 },
  121077. { 183, 2 },
  121078. { 183, 2 },
  121079. { 183, 1 },
  121080. { 183, 1 },
  121081. { 183, 2 },
  121082. { 181, 3 },
  121083. { 181, 2 },
  121084. { 184, 0 },
  121085. { 184, 2 },
  121086. { 184, 2 },
  121087. { 161, 0 },
  121088. { 161, 2 },
  121089. { 185, 3 },
  121090. { 185, 1 },
  121091. { 186, 1 },
  121092. { 186, 0 },
  121093. { 187, 2 },
  121094. { 187, 7 },
  121095. { 187, 5 },
  121096. { 187, 5 },
  121097. { 187, 10 },
  121098. { 190, 0 },
  121099. { 190, 1 },
  121100. { 176, 0 },
  121101. { 176, 3 },
  121102. { 191, 0 },
  121103. { 191, 2 },
  121104. { 192, 1 },
  121105. { 192, 1 },
  121106. { 192, 1 },
  121107. { 149, 4 },
  121108. { 194, 2 },
  121109. { 194, 0 },
  121110. { 149, 9 },
  121111. { 149, 4 },
  121112. { 149, 1 },
  121113. { 163, 2 },
  121114. { 196, 1 },
  121115. { 196, 3 },
  121116. { 199, 1 },
  121117. { 199, 2 },
  121118. { 199, 1 },
  121119. { 197, 9 },
  121120. { 197, 1 },
  121121. { 208, 4 },
  121122. { 208, 5 },
  121123. { 200, 1 },
  121124. { 200, 1 },
  121125. { 200, 0 },
  121126. { 211, 2 },
  121127. { 211, 0 },
  121128. { 201, 3 },
  121129. { 201, 2 },
  121130. { 201, 4 },
  121131. { 212, 2 },
  121132. { 212, 1 },
  121133. { 212, 0 },
  121134. { 202, 0 },
  121135. { 202, 2 },
  121136. { 214, 2 },
  121137. { 214, 0 },
  121138. { 213, 7 },
  121139. { 213, 9 },
  121140. { 213, 7 },
  121141. { 213, 7 },
  121142. { 159, 0 },
  121143. { 159, 2 },
  121144. { 195, 2 },
  121145. { 215, 1 },
  121146. { 215, 2 },
  121147. { 215, 3 },
  121148. { 215, 4 },
  121149. { 217, 2 },
  121150. { 217, 0 },
  121151. { 216, 0 },
  121152. { 216, 3 },
  121153. { 216, 2 },
  121154. { 218, 4 },
  121155. { 218, 0 },
  121156. { 206, 0 },
  121157. { 206, 3 },
  121158. { 188, 4 },
  121159. { 188, 2 },
  121160. { 177, 1 },
  121161. { 177, 1 },
  121162. { 177, 0 },
  121163. { 204, 0 },
  121164. { 204, 3 },
  121165. { 205, 0 },
  121166. { 205, 2 },
  121167. { 207, 0 },
  121168. { 207, 2 },
  121169. { 207, 4 },
  121170. { 207, 4 },
  121171. { 149, 6 },
  121172. { 203, 0 },
  121173. { 203, 2 },
  121174. { 149, 8 },
  121175. { 220, 5 },
  121176. { 220, 3 },
  121177. { 149, 6 },
  121178. { 149, 7 },
  121179. { 221, 2 },
  121180. { 221, 1 },
  121181. { 222, 0 },
  121182. { 222, 3 },
  121183. { 219, 3 },
  121184. { 219, 1 },
  121185. { 175, 1 },
  121186. { 175, 3 },
  121187. { 174, 1 },
  121188. { 175, 1 },
  121189. { 175, 1 },
  121190. { 175, 3 },
  121191. { 175, 5 },
  121192. { 174, 1 },
  121193. { 174, 1 },
  121194. { 175, 1 },
  121195. { 175, 3 },
  121196. { 175, 6 },
  121197. { 175, 5 },
  121198. { 175, 4 },
  121199. { 174, 1 },
  121200. { 175, 3 },
  121201. { 175, 3 },
  121202. { 175, 3 },
  121203. { 175, 3 },
  121204. { 175, 3 },
  121205. { 175, 3 },
  121206. { 175, 3 },
  121207. { 175, 3 },
  121208. { 223, 1 },
  121209. { 223, 2 },
  121210. { 175, 3 },
  121211. { 175, 5 },
  121212. { 175, 2 },
  121213. { 175, 3 },
  121214. { 175, 3 },
  121215. { 175, 4 },
  121216. { 175, 2 },
  121217. { 175, 2 },
  121218. { 175, 2 },
  121219. { 175, 2 },
  121220. { 224, 1 },
  121221. { 224, 2 },
  121222. { 175, 5 },
  121223. { 225, 1 },
  121224. { 225, 2 },
  121225. { 175, 5 },
  121226. { 175, 3 },
  121227. { 175, 5 },
  121228. { 175, 4 },
  121229. { 175, 4 },
  121230. { 175, 5 },
  121231. { 227, 5 },
  121232. { 227, 4 },
  121233. { 228, 2 },
  121234. { 228, 0 },
  121235. { 226, 1 },
  121236. { 226, 0 },
  121237. { 210, 1 },
  121238. { 210, 0 },
  121239. { 209, 3 },
  121240. { 209, 1 },
  121241. { 149, 12 },
  121242. { 229, 1 },
  121243. { 229, 0 },
  121244. { 179, 0 },
  121245. { 179, 3 },
  121246. { 189, 5 },
  121247. { 189, 3 },
  121248. { 230, 0 },
  121249. { 230, 2 },
  121250. { 149, 4 },
  121251. { 149, 1 },
  121252. { 149, 2 },
  121253. { 149, 3 },
  121254. { 149, 5 },
  121255. { 149, 6 },
  121256. { 149, 5 },
  121257. { 149, 6 },
  121258. { 231, 1 },
  121259. { 231, 1 },
  121260. { 231, 1 },
  121261. { 231, 1 },
  121262. { 231, 1 },
  121263. { 171, 2 },
  121264. { 171, 1 },
  121265. { 172, 2 },
  121266. { 149, 5 },
  121267. { 232, 11 },
  121268. { 234, 1 },
  121269. { 234, 1 },
  121270. { 234, 2 },
  121271. { 234, 0 },
  121272. { 235, 1 },
  121273. { 235, 1 },
  121274. { 235, 3 },
  121275. { 236, 0 },
  121276. { 236, 3 },
  121277. { 237, 0 },
  121278. { 237, 2 },
  121279. { 233, 3 },
  121280. { 233, 2 },
  121281. { 239, 1 },
  121282. { 239, 3 },
  121283. { 240, 0 },
  121284. { 240, 3 },
  121285. { 240, 2 },
  121286. { 238, 7 },
  121287. { 238, 5 },
  121288. { 238, 5 },
  121289. { 238, 1 },
  121290. { 175, 4 },
  121291. { 175, 6 },
  121292. { 193, 1 },
  121293. { 193, 1 },
  121294. { 193, 1 },
  121295. { 149, 4 },
  121296. { 149, 6 },
  121297. { 149, 3 },
  121298. { 242, 0 },
  121299. { 242, 2 },
  121300. { 241, 1 },
  121301. { 241, 0 },
  121302. { 149, 1 },
  121303. { 149, 3 },
  121304. { 149, 1 },
  121305. { 149, 3 },
  121306. { 149, 6 },
  121307. { 149, 6 },
  121308. { 243, 1 },
  121309. { 244, 0 },
  121310. { 244, 1 },
  121311. { 149, 1 },
  121312. { 149, 4 },
  121313. { 245, 8 },
  121314. { 246, 1 },
  121315. { 246, 3 },
  121316. { 247, 0 },
  121317. { 247, 2 },
  121318. { 248, 1 },
  121319. { 248, 3 },
  121320. { 249, 1 },
  121321. { 250, 0 },
  121322. { 250, 4 },
  121323. { 250, 2 },
  121324. { 198, 0 },
  121325. { 198, 2 },
  121326. { 198, 3 },
  121327. { 251, 6 },
  121328. { 251, 8 },
  121329. };
  121330. static void yy_accept(yyParser*); /* Forward Declaration */
  121331. /*
  121332. ** Perform a reduce action and the shift that must immediately
  121333. ** follow the reduce.
  121334. */
  121335. static void yy_reduce(
  121336. yyParser *yypParser, /* The parser */
  121337. int yyruleno /* Number of the rule by which to reduce */
  121338. ){
  121339. int yygoto; /* The next state */
  121340. int yyact; /* The next action */
  121341. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  121342. yyStackEntry *yymsp; /* The top of the parser's stack */
  121343. int yysize; /* Amount to pop the stack */
  121344. sqlite3ParserARG_FETCH;
  121345. yymsp = &yypParser->yystack[yypParser->yyidx];
  121346. #ifndef NDEBUG
  121347. if( yyTraceFILE && yyruleno>=0
  121348. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  121349. yysize = yyRuleInfo[yyruleno].nrhs;
  121350. fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
  121351. yyRuleName[yyruleno], yymsp[-yysize].stateno);
  121352. }
  121353. #endif /* NDEBUG */
  121354. yygotominor = yyzerominor;
  121355. switch( yyruleno ){
  121356. /* Beginning here are the reduction cases. A typical example
  121357. ** follows:
  121358. ** case 0:
  121359. ** #line <lineno> <grammarfile>
  121360. ** { ... } // User supplied code
  121361. ** #line <lineno> <thisfile>
  121362. ** break;
  121363. */
  121364. /********** Begin reduce actions **********************************************/
  121365. case 5: /* explain ::= */
  121366. { sqlite3BeginParse(pParse, 0); }
  121367. break;
  121368. case 6: /* explain ::= EXPLAIN */
  121369. { sqlite3BeginParse(pParse, 1); }
  121370. break;
  121371. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  121372. { sqlite3BeginParse(pParse, 2); }
  121373. break;
  121374. case 8: /* cmdx ::= cmd */
  121375. { sqlite3FinishCoding(pParse); }
  121376. break;
  121377. case 9: /* cmd ::= BEGIN transtype trans_opt */
  121378. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
  121379. break;
  121380. case 13: /* transtype ::= */
  121381. {yygotominor.yy4 = TK_DEFERRED;}
  121382. break;
  121383. case 14: /* transtype ::= DEFERRED */
  121384. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  121385. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  121386. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  121387. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  121388. {yygotominor.yy4 = yymsp[0].major;}
  121389. break;
  121390. case 17: /* cmd ::= COMMIT trans_opt */
  121391. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  121392. {sqlite3CommitTransaction(pParse);}
  121393. break;
  121394. case 19: /* cmd ::= ROLLBACK trans_opt */
  121395. {sqlite3RollbackTransaction(pParse);}
  121396. break;
  121397. case 22: /* cmd ::= SAVEPOINT nm */
  121398. {
  121399. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  121400. }
  121401. break;
  121402. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  121403. {
  121404. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  121405. }
  121406. break;
  121407. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  121408. {
  121409. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  121410. }
  121411. break;
  121412. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  121413. {
  121414. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
  121415. }
  121416. break;
  121417. case 27: /* createkw ::= CREATE */
  121418. {
  121419. pParse->db->lookaside.bEnabled = 0;
  121420. yygotominor.yy0 = yymsp[0].minor.yy0;
  121421. }
  121422. break;
  121423. case 28: /* ifnotexists ::= */
  121424. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  121425. case 34: /* table_options ::= */ yytestcase(yyruleno==34);
  121426. case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
  121427. case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
  121428. case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
  121429. case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
  121430. case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
  121431. case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
  121432. case 124: /* distinct ::= */ yytestcase(yyruleno==124);
  121433. case 219: /* between_op ::= BETWEEN */ yytestcase(yyruleno==219);
  121434. case 222: /* in_op ::= IN */ yytestcase(yyruleno==222);
  121435. case 247: /* collate ::= */ yytestcase(yyruleno==247);
  121436. {yygotominor.yy4 = 0;}
  121437. break;
  121438. case 29: /* ifnotexists ::= IF NOT EXISTS */
  121439. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  121440. case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
  121441. case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
  121442. case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
  121443. case 220: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==220);
  121444. case 223: /* in_op ::= NOT IN */ yytestcase(yyruleno==223);
  121445. case 248: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==248);
  121446. {yygotominor.yy4 = 1;}
  121447. break;
  121448. case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  121449. {
  121450. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy4,0);
  121451. }
  121452. break;
  121453. case 33: /* create_table_args ::= AS select */
  121454. {
  121455. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy387);
  121456. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
  121457. }
  121458. break;
  121459. case 35: /* table_options ::= WITHOUT nm */
  121460. {
  121461. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  121462. yygotominor.yy4 = TF_WithoutRowid | TF_NoVisibleRowid;
  121463. }else{
  121464. yygotominor.yy4 = 0;
  121465. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  121466. }
  121467. }
  121468. break;
  121469. case 38: /* column ::= columnid type carglist */
  121470. {
  121471. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  121472. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  121473. }
  121474. break;
  121475. case 39: /* columnid ::= nm */
  121476. {
  121477. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  121478. yygotominor.yy0 = yymsp[0].minor.yy0;
  121479. pParse->constraintName.n = 0;
  121480. }
  121481. break;
  121482. case 40: /* nm ::= ID|INDEXED */
  121483. case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
  121484. case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
  121485. case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
  121486. case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
  121487. case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
  121488. case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
  121489. case 142: /* dbnm ::= DOT nm */ yytestcase(yyruleno==142);
  121490. case 151: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==151);
  121491. case 257: /* nmnum ::= plus_num */ yytestcase(yyruleno==257);
  121492. case 258: /* nmnum ::= nm */ yytestcase(yyruleno==258);
  121493. case 259: /* nmnum ::= ON */ yytestcase(yyruleno==259);
  121494. case 260: /* nmnum ::= DELETE */ yytestcase(yyruleno==260);
  121495. case 261: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==261);
  121496. case 262: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==262);
  121497. case 263: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==263);
  121498. case 264: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==264);
  121499. case 280: /* trnm ::= nm */ yytestcase(yyruleno==280);
  121500. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  121501. break;
  121502. case 44: /* type ::= typetoken */
  121503. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  121504. break;
  121505. case 46: /* typetoken ::= typename LP signed RP */
  121506. {
  121507. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  121508. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  121509. }
  121510. break;
  121511. case 47: /* typetoken ::= typename LP signed COMMA signed RP */
  121512. {
  121513. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  121514. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  121515. }
  121516. break;
  121517. case 49: /* typename ::= typename ID|STRING */
  121518. {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);}
  121519. break;
  121520. case 54: /* ccons ::= CONSTRAINT nm */
  121521. case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
  121522. {pParse->constraintName = yymsp[0].minor.yy0;}
  121523. break;
  121524. case 55: /* ccons ::= DEFAULT term */
  121525. case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
  121526. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
  121527. break;
  121528. case 56: /* ccons ::= DEFAULT LP expr RP */
  121529. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
  121530. break;
  121531. case 58: /* ccons ::= DEFAULT MINUS term */
  121532. {
  121533. ExprSpan v;
  121534. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
  121535. v.zStart = yymsp[-1].minor.yy0.z;
  121536. v.zEnd = yymsp[0].minor.yy118.zEnd;
  121537. sqlite3AddDefaultValue(pParse,&v);
  121538. }
  121539. break;
  121540. case 59: /* ccons ::= DEFAULT ID|INDEXED */
  121541. {
  121542. ExprSpan v;
  121543. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  121544. sqlite3AddDefaultValue(pParse,&v);
  121545. }
  121546. break;
  121547. case 61: /* ccons ::= NOT NULL onconf */
  121548. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
  121549. break;
  121550. case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  121551. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
  121552. break;
  121553. case 63: /* ccons ::= UNIQUE onconf */
  121554. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
  121555. break;
  121556. case 64: /* ccons ::= CHECK LP expr RP */
  121557. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
  121558. break;
  121559. case 65: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  121560. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
  121561. break;
  121562. case 66: /* ccons ::= defer_subclause */
  121563. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
  121564. break;
  121565. case 67: /* ccons ::= COLLATE ID|STRING */
  121566. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  121567. break;
  121568. case 70: /* refargs ::= */
  121569. { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
  121570. break;
  121571. case 71: /* refargs ::= refargs refarg */
  121572. { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
  121573. break;
  121574. case 72: /* refarg ::= MATCH nm */
  121575. case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
  121576. { yygotominor.yy215.value = 0; yygotominor.yy215.mask = 0x000000; }
  121577. break;
  121578. case 74: /* refarg ::= ON DELETE refact */
  121579. { yygotominor.yy215.value = yymsp[0].minor.yy4; yygotominor.yy215.mask = 0x0000ff; }
  121580. break;
  121581. case 75: /* refarg ::= ON UPDATE refact */
  121582. { yygotominor.yy215.value = yymsp[0].minor.yy4<<8; yygotominor.yy215.mask = 0x00ff00; }
  121583. break;
  121584. case 76: /* refact ::= SET NULL */
  121585. { yygotominor.yy4 = OE_SetNull; /* EV: R-33326-45252 */}
  121586. break;
  121587. case 77: /* refact ::= SET DEFAULT */
  121588. { yygotominor.yy4 = OE_SetDflt; /* EV: R-33326-45252 */}
  121589. break;
  121590. case 78: /* refact ::= CASCADE */
  121591. { yygotominor.yy4 = OE_Cascade; /* EV: R-33326-45252 */}
  121592. break;
  121593. case 79: /* refact ::= RESTRICT */
  121594. { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
  121595. break;
  121596. case 80: /* refact ::= NO ACTION */
  121597. { yygotominor.yy4 = OE_None; /* EV: R-33326-45252 */}
  121598. break;
  121599. case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  121600. case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
  121601. case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
  121602. case 102: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==102);
  121603. case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
  121604. case 178: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==178);
  121605. {yygotominor.yy4 = yymsp[0].minor.yy4;}
  121606. break;
  121607. case 86: /* conslist_opt ::= */
  121608. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  121609. break;
  121610. case 87: /* conslist_opt ::= COMMA conslist */
  121611. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  121612. break;
  121613. case 90: /* tconscomma ::= COMMA */
  121614. {pParse->constraintName.n = 0;}
  121615. break;
  121616. case 93: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  121617. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
  121618. break;
  121619. case 94: /* tcons ::= UNIQUE LP sortlist RP onconf */
  121620. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
  121621. break;
  121622. case 95: /* tcons ::= CHECK LP expr RP onconf */
  121623. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
  121624. break;
  121625. case 96: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  121626. {
  121627. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
  121628. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
  121629. }
  121630. break;
  121631. case 99: /* onconf ::= */
  121632. case 101: /* orconf ::= */ yytestcase(yyruleno==101);
  121633. {yygotominor.yy4 = OE_Default;}
  121634. break;
  121635. case 104: /* resolvetype ::= IGNORE */
  121636. {yygotominor.yy4 = OE_Ignore;}
  121637. break;
  121638. case 105: /* resolvetype ::= REPLACE */
  121639. case 179: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==179);
  121640. {yygotominor.yy4 = OE_Replace;}
  121641. break;
  121642. case 106: /* cmd ::= DROP TABLE ifexists fullname */
  121643. {
  121644. sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
  121645. }
  121646. break;
  121647. case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  121648. {
  121649. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[0].minor.yy387, yymsp[-7].minor.yy4, yymsp[-5].minor.yy4);
  121650. }
  121651. break;
  121652. case 110: /* cmd ::= DROP VIEW ifexists fullname */
  121653. {
  121654. sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
  121655. }
  121656. break;
  121657. case 111: /* cmd ::= select */
  121658. {
  121659. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  121660. sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
  121661. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
  121662. }
  121663. break;
  121664. case 112: /* select ::= with selectnowith */
  121665. {
  121666. Select *p = yymsp[0].minor.yy387;
  121667. if( p ){
  121668. p->pWith = yymsp[-1].minor.yy451;
  121669. parserDoubleLinkSelect(pParse, p);
  121670. }else{
  121671. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy451);
  121672. }
  121673. yygotominor.yy387 = p;
  121674. }
  121675. break;
  121676. case 113: /* selectnowith ::= oneselect */
  121677. case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
  121678. {yygotominor.yy387 = yymsp[0].minor.yy387;}
  121679. break;
  121680. case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
  121681. {
  121682. Select *pRhs = yymsp[0].minor.yy387;
  121683. Select *pLhs = yymsp[-2].minor.yy387;
  121684. if( pRhs && pRhs->pPrior ){
  121685. SrcList *pFrom;
  121686. Token x;
  121687. x.n = 0;
  121688. parserDoubleLinkSelect(pParse, pRhs);
  121689. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  121690. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  121691. }
  121692. if( pRhs ){
  121693. pRhs->op = (u8)yymsp[-1].minor.yy4;
  121694. pRhs->pPrior = pLhs;
  121695. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  121696. pRhs->selFlags &= ~SF_MultiValue;
  121697. if( yymsp[-1].minor.yy4!=TK_ALL ) pParse->hasCompound = 1;
  121698. }else{
  121699. sqlite3SelectDelete(pParse->db, pLhs);
  121700. }
  121701. yygotominor.yy387 = pRhs;
  121702. }
  121703. break;
  121704. case 116: /* multiselect_op ::= UNION ALL */
  121705. {yygotominor.yy4 = TK_ALL;}
  121706. break;
  121707. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  121708. {
  121709. yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
  121710. #if SELECTTRACE_ENABLED
  121711. /* Populate the Select.zSelName[] string that is used to help with
  121712. ** query planner debugging, to differentiate between multiple Select
  121713. ** objects in a complex query.
  121714. **
  121715. ** If the SELECT keyword is immediately followed by a C-style comment
  121716. ** then extract the first few alphanumeric characters from within that
  121717. ** comment to be the zSelName value. Otherwise, the label is #N where
  121718. ** is an integer that is incremented with each SELECT statement seen.
  121719. */
  121720. if( yygotominor.yy387!=0 ){
  121721. const char *z = yymsp[-8].minor.yy0.z+6;
  121722. int i;
  121723. sqlite3_snprintf(sizeof(yygotominor.yy387->zSelName), yygotominor.yy387->zSelName, "#%d",
  121724. ++pParse->nSelect);
  121725. while( z[0]==' ' ) z++;
  121726. if( z[0]=='/' && z[1]=='*' ){
  121727. z += 2;
  121728. while( z[0]==' ' ) z++;
  121729. for(i=0; sqlite3Isalnum(z[i]); i++){}
  121730. sqlite3_snprintf(sizeof(yygotominor.yy387->zSelName), yygotominor.yy387->zSelName, "%.*s", i, z);
  121731. }
  121732. }
  121733. #endif /* SELECTRACE_ENABLED */
  121734. }
  121735. break;
  121736. case 120: /* values ::= VALUES LP nexprlist RP */
  121737. {
  121738. yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values,0,0);
  121739. }
  121740. break;
  121741. case 121: /* values ::= values COMMA LP exprlist RP */
  121742. {
  121743. Select *pRight, *pLeft = yymsp[-4].minor.yy387;
  121744. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
  121745. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  121746. if( pRight ){
  121747. pRight->op = TK_ALL;
  121748. pLeft = yymsp[-4].minor.yy387;
  121749. pRight->pPrior = pLeft;
  121750. yygotominor.yy387 = pRight;
  121751. }else{
  121752. yygotominor.yy387 = pLeft;
  121753. }
  121754. }
  121755. break;
  121756. case 122: /* distinct ::= DISTINCT */
  121757. {yygotominor.yy4 = SF_Distinct;}
  121758. break;
  121759. case 123: /* distinct ::= ALL */
  121760. {yygotominor.yy4 = SF_All;}
  121761. break;
  121762. case 125: /* sclp ::= selcollist COMMA */
  121763. case 244: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==244);
  121764. {yygotominor.yy322 = yymsp[-1].minor.yy322;}
  121765. break;
  121766. case 126: /* sclp ::= */
  121767. case 155: /* orderby_opt ::= */ yytestcase(yyruleno==155);
  121768. case 162: /* groupby_opt ::= */ yytestcase(yyruleno==162);
  121769. case 237: /* exprlist ::= */ yytestcase(yyruleno==237);
  121770. case 243: /* eidlist_opt ::= */ yytestcase(yyruleno==243);
  121771. {yygotominor.yy322 = 0;}
  121772. break;
  121773. case 127: /* selcollist ::= sclp expr as */
  121774. {
  121775. yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
  121776. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
  121777. sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
  121778. }
  121779. break;
  121780. case 128: /* selcollist ::= sclp STAR */
  121781. {
  121782. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  121783. yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
  121784. }
  121785. break;
  121786. case 129: /* selcollist ::= sclp nm DOT STAR */
  121787. {
  121788. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, &yymsp[0].minor.yy0);
  121789. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  121790. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  121791. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
  121792. }
  121793. break;
  121794. case 132: /* as ::= */
  121795. {yygotominor.yy0.n = 0;}
  121796. break;
  121797. case 133: /* from ::= */
  121798. {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
  121799. break;
  121800. case 134: /* from ::= FROM seltablist */
  121801. {
  121802. yygotominor.yy259 = yymsp[0].minor.yy259;
  121803. sqlite3SrcListShiftJoinType(yygotominor.yy259);
  121804. }
  121805. break;
  121806. case 135: /* stl_prefix ::= seltablist joinop */
  121807. {
  121808. yygotominor.yy259 = yymsp[-1].minor.yy259;
  121809. if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy4;
  121810. }
  121811. break;
  121812. case 136: /* stl_prefix ::= */
  121813. {yygotominor.yy259 = 0;}
  121814. break;
  121815. case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  121816. {
  121817. yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  121818. sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
  121819. }
  121820. break;
  121821. case 138: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  121822. {
  121823. yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy259,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  121824. sqlite3SrcListFuncArgs(pParse, yygotominor.yy259, yymsp[-4].minor.yy322);
  121825. }
  121826. break;
  121827. case 139: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  121828. {
  121829. yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  121830. }
  121831. break;
  121832. case 140: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  121833. {
  121834. if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
  121835. yygotominor.yy259 = yymsp[-4].minor.yy259;
  121836. }else if( yymsp[-4].minor.yy259->nSrc==1 ){
  121837. yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  121838. if( yygotominor.yy259 ){
  121839. struct SrcList_item *pNew = &yygotominor.yy259->a[yygotominor.yy259->nSrc-1];
  121840. struct SrcList_item *pOld = yymsp[-4].minor.yy259->a;
  121841. pNew->zName = pOld->zName;
  121842. pNew->zDatabase = pOld->zDatabase;
  121843. pNew->pSelect = pOld->pSelect;
  121844. pOld->zName = pOld->zDatabase = 0;
  121845. pOld->pSelect = 0;
  121846. }
  121847. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy259);
  121848. }else{
  121849. Select *pSubquery;
  121850. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
  121851. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,SF_NestedFrom,0,0);
  121852. yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  121853. }
  121854. }
  121855. break;
  121856. case 141: /* dbnm ::= */
  121857. case 150: /* indexed_opt ::= */ yytestcase(yyruleno==150);
  121858. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  121859. break;
  121860. case 143: /* fullname ::= nm dbnm */
  121861. {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  121862. break;
  121863. case 144: /* joinop ::= COMMA|JOIN */
  121864. { yygotominor.yy4 = JT_INNER; }
  121865. break;
  121866. case 145: /* joinop ::= JOIN_KW JOIN */
  121867. { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  121868. break;
  121869. case 146: /* joinop ::= JOIN_KW nm JOIN */
  121870. { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  121871. break;
  121872. case 147: /* joinop ::= JOIN_KW nm nm JOIN */
  121873. { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  121874. break;
  121875. case 148: /* on_opt ::= ON expr */
  121876. case 165: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==165);
  121877. case 172: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==172);
  121878. case 232: /* case_else ::= ELSE expr */ yytestcase(yyruleno==232);
  121879. case 234: /* case_operand ::= expr */ yytestcase(yyruleno==234);
  121880. {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
  121881. break;
  121882. case 149: /* on_opt ::= */
  121883. case 164: /* having_opt ::= */ yytestcase(yyruleno==164);
  121884. case 171: /* where_opt ::= */ yytestcase(yyruleno==171);
  121885. case 233: /* case_else ::= */ yytestcase(yyruleno==233);
  121886. case 235: /* case_operand ::= */ yytestcase(yyruleno==235);
  121887. {yygotominor.yy314 = 0;}
  121888. break;
  121889. case 152: /* indexed_opt ::= NOT INDEXED */
  121890. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  121891. break;
  121892. case 153: /* using_opt ::= USING LP idlist RP */
  121893. case 181: /* idlist_opt ::= LP idlist RP */ yytestcase(yyruleno==181);
  121894. {yygotominor.yy384 = yymsp[-1].minor.yy384;}
  121895. break;
  121896. case 154: /* using_opt ::= */
  121897. case 180: /* idlist_opt ::= */ yytestcase(yyruleno==180);
  121898. {yygotominor.yy384 = 0;}
  121899. break;
  121900. case 156: /* orderby_opt ::= ORDER BY sortlist */
  121901. case 163: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==163);
  121902. case 236: /* exprlist ::= nexprlist */ yytestcase(yyruleno==236);
  121903. {yygotominor.yy322 = yymsp[0].minor.yy322;}
  121904. break;
  121905. case 157: /* sortlist ::= sortlist COMMA expr sortorder */
  121906. {
  121907. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy118.pExpr);
  121908. sqlite3ExprListSetSortOrder(yygotominor.yy322,yymsp[0].minor.yy4);
  121909. }
  121910. break;
  121911. case 158: /* sortlist ::= expr sortorder */
  121912. {
  121913. yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy118.pExpr);
  121914. sqlite3ExprListSetSortOrder(yygotominor.yy322,yymsp[0].minor.yy4);
  121915. }
  121916. break;
  121917. case 159: /* sortorder ::= ASC */
  121918. {yygotominor.yy4 = SQLITE_SO_ASC;}
  121919. break;
  121920. case 160: /* sortorder ::= DESC */
  121921. {yygotominor.yy4 = SQLITE_SO_DESC;}
  121922. break;
  121923. case 161: /* sortorder ::= */
  121924. {yygotominor.yy4 = SQLITE_SO_UNDEFINED;}
  121925. break;
  121926. case 166: /* limit_opt ::= */
  121927. {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
  121928. break;
  121929. case 167: /* limit_opt ::= LIMIT expr */
  121930. {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
  121931. break;
  121932. case 168: /* limit_opt ::= LIMIT expr OFFSET expr */
  121933. {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
  121934. break;
  121935. case 169: /* limit_opt ::= LIMIT expr COMMA expr */
  121936. {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
  121937. break;
  121938. case 170: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  121939. {
  121940. sqlite3WithPush(pParse, yymsp[-5].minor.yy451, 1);
  121941. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
  121942. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
  121943. }
  121944. break;
  121945. case 173: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  121946. {
  121947. sqlite3WithPush(pParse, yymsp[-7].minor.yy451, 1);
  121948. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
  121949. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
  121950. sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy4);
  121951. }
  121952. break;
  121953. case 174: /* setlist ::= setlist COMMA nm EQ expr */
  121954. {
  121955. yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
  121956. sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
  121957. }
  121958. break;
  121959. case 175: /* setlist ::= nm EQ expr */
  121960. {
  121961. yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
  121962. sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
  121963. }
  121964. break;
  121965. case 176: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
  121966. {
  121967. sqlite3WithPush(pParse, yymsp[-5].minor.yy451, 1);
  121968. sqlite3Insert(pParse, yymsp[-2].minor.yy259, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy4);
  121969. }
  121970. break;
  121971. case 177: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
  121972. {
  121973. sqlite3WithPush(pParse, yymsp[-6].minor.yy451, 1);
  121974. sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy4);
  121975. }
  121976. break;
  121977. case 182: /* idlist ::= idlist COMMA nm */
  121978. {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
  121979. break;
  121980. case 183: /* idlist ::= nm */
  121981. {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  121982. break;
  121983. case 184: /* expr ::= term */
  121984. {yygotominor.yy118 = yymsp[0].minor.yy118;}
  121985. break;
  121986. case 185: /* expr ::= LP expr RP */
  121987. {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  121988. break;
  121989. case 186: /* term ::= NULL */
  121990. case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
  121991. case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
  121992. {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  121993. break;
  121994. case 187: /* expr ::= ID|INDEXED */
  121995. case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
  121996. {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
  121997. break;
  121998. case 189: /* expr ::= nm DOT nm */
  121999. {
  122000. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  122001. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  122002. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  122003. spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  122004. }
  122005. break;
  122006. case 190: /* expr ::= nm DOT nm DOT nm */
  122007. {
  122008. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  122009. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  122010. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  122011. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  122012. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  122013. spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  122014. }
  122015. break;
  122016. case 193: /* expr ::= VARIABLE */
  122017. {
  122018. if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
  122019. /* When doing a nested parse, one can include terms in an expression
  122020. ** that look like this: #1 #2 ... These terms refer to registers
  122021. ** in the virtual machine. #N is the N-th register. */
  122022. if( pParse->nested==0 ){
  122023. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  122024. yygotominor.yy118.pExpr = 0;
  122025. }else{
  122026. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  122027. if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
  122028. }
  122029. }else{
  122030. spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  122031. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
  122032. }
  122033. spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  122034. }
  122035. break;
  122036. case 194: /* expr ::= expr COLLATE ID|STRING */
  122037. {
  122038. yygotominor.yy118.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0, 1);
  122039. yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
  122040. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  122041. }
  122042. break;
  122043. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  122044. {
  122045. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
  122046. spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  122047. }
  122048. break;
  122049. case 196: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  122050. {
  122051. if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  122052. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  122053. }
  122054. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
  122055. spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  122056. if( yymsp[-2].minor.yy4==SF_Distinct && yygotominor.yy118.pExpr ){
  122057. yygotominor.yy118.pExpr->flags |= EP_Distinct;
  122058. }
  122059. }
  122060. break;
  122061. case 197: /* expr ::= ID|INDEXED LP STAR RP */
  122062. {
  122063. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  122064. spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  122065. }
  122066. break;
  122067. case 198: /* term ::= CTIME_KW */
  122068. {
  122069. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  122070. spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  122071. }
  122072. break;
  122073. case 199: /* expr ::= expr AND expr */
  122074. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  122075. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  122076. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  122077. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  122078. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  122079. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  122080. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  122081. {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
  122082. break;
  122083. case 207: /* likeop ::= LIKE_KW|MATCH */
  122084. {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.bNot = 0;}
  122085. break;
  122086. case 208: /* likeop ::= NOT LIKE_KW|MATCH */
  122087. {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.bNot = 1;}
  122088. break;
  122089. case 209: /* expr ::= expr likeop expr */
  122090. {
  122091. ExprList *pList;
  122092. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
  122093. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
  122094. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
  122095. exprNot(pParse, yymsp[-1].minor.yy342.bNot, &yygotominor.yy118.pExpr);
  122096. yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
  122097. yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
  122098. if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
  122099. }
  122100. break;
  122101. case 210: /* expr ::= expr likeop expr ESCAPE expr */
  122102. {
  122103. ExprList *pList;
  122104. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
  122105. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
  122106. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
  122107. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
  122108. exprNot(pParse, yymsp[-3].minor.yy342.bNot, &yygotominor.yy118.pExpr);
  122109. yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
  122110. yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
  122111. if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
  122112. }
  122113. break;
  122114. case 211: /* expr ::= expr ISNULL|NOTNULL */
  122115. {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
  122116. break;
  122117. case 212: /* expr ::= expr NOT NULL */
  122118. {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
  122119. break;
  122120. case 213: /* expr ::= expr IS expr */
  122121. {
  122122. spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
  122123. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
  122124. }
  122125. break;
  122126. case 214: /* expr ::= expr IS NOT expr */
  122127. {
  122128. spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
  122129. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
  122130. }
  122131. break;
  122132. case 215: /* expr ::= NOT expr */
  122133. case 216: /* expr ::= BITNOT expr */ yytestcase(yyruleno==216);
  122134. {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
  122135. break;
  122136. case 217: /* expr ::= MINUS expr */
  122137. {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
  122138. break;
  122139. case 218: /* expr ::= PLUS expr */
  122140. {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
  122141. break;
  122142. case 221: /* expr ::= expr between_op expr AND expr */
  122143. {
  122144. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
  122145. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
  122146. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
  122147. if( yygotominor.yy118.pExpr ){
  122148. yygotominor.yy118.pExpr->x.pList = pList;
  122149. }else{
  122150. sqlite3ExprListDelete(pParse->db, pList);
  122151. }
  122152. exprNot(pParse, yymsp[-3].minor.yy4, &yygotominor.yy118.pExpr);
  122153. yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
  122154. yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
  122155. }
  122156. break;
  122157. case 224: /* expr ::= expr in_op LP exprlist RP */
  122158. {
  122159. if( yymsp[-1].minor.yy322==0 ){
  122160. /* Expressions of the form
  122161. **
  122162. ** expr1 IN ()
  122163. ** expr1 NOT IN ()
  122164. **
  122165. ** simplify to constants 0 (false) and 1 (true), respectively,
  122166. ** regardless of the value of expr1.
  122167. */
  122168. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
  122169. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
  122170. }else if( yymsp[-1].minor.yy322->nExpr==1 ){
  122171. /* Expressions of the form:
  122172. **
  122173. ** expr1 IN (?1)
  122174. ** expr1 NOT IN (?2)
  122175. **
  122176. ** with exactly one value on the RHS can be simplified to something
  122177. ** like this:
  122178. **
  122179. ** expr1 == ?1
  122180. ** expr1 <> ?2
  122181. **
  122182. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  122183. ** so that it may not contribute to the computation of comparison
  122184. ** affinity or the collating sequence to use for comparison. Otherwise,
  122185. ** the semantics would be subtly different from IN or NOT IN.
  122186. */
  122187. Expr *pRHS = yymsp[-1].minor.yy322->a[0].pExpr;
  122188. yymsp[-1].minor.yy322->a[0].pExpr = 0;
  122189. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
  122190. /* pRHS cannot be NULL because a malloc error would have been detected
  122191. ** before now and control would have never reached this point */
  122192. if( ALWAYS(pRHS) ){
  122193. pRHS->flags &= ~EP_Collate;
  122194. pRHS->flags |= EP_Generic;
  122195. }
  122196. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy4 ? TK_NE : TK_EQ, yymsp[-4].minor.yy118.pExpr, pRHS, 0);
  122197. }else{
  122198. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
  122199. if( yygotominor.yy118.pExpr ){
  122200. yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
  122201. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
  122202. }else{
  122203. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
  122204. }
  122205. exprNot(pParse, yymsp[-3].minor.yy4, &yygotominor.yy118.pExpr);
  122206. }
  122207. yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
  122208. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  122209. }
  122210. break;
  122211. case 225: /* expr ::= LP select RP */
  122212. {
  122213. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  122214. if( yygotominor.yy118.pExpr ){
  122215. yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
  122216. ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect|EP_Subquery);
  122217. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
  122218. }else{
  122219. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
  122220. }
  122221. yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
  122222. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  122223. }
  122224. break;
  122225. case 226: /* expr ::= expr in_op LP select RP */
  122226. {
  122227. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
  122228. if( yygotominor.yy118.pExpr ){
  122229. yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
  122230. ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect|EP_Subquery);
  122231. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
  122232. }else{
  122233. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
  122234. }
  122235. exprNot(pParse, yymsp[-3].minor.yy4, &yygotominor.yy118.pExpr);
  122236. yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
  122237. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  122238. }
  122239. break;
  122240. case 227: /* expr ::= expr in_op nm dbnm */
  122241. {
  122242. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  122243. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
  122244. if( yygotominor.yy118.pExpr ){
  122245. yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  122246. ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect|EP_Subquery);
  122247. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
  122248. }else{
  122249. sqlite3SrcListDelete(pParse->db, pSrc);
  122250. }
  122251. exprNot(pParse, yymsp[-2].minor.yy4, &yygotominor.yy118.pExpr);
  122252. yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
  122253. yygotominor.yy118.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];
  122254. }
  122255. break;
  122256. case 228: /* expr ::= EXISTS LP select RP */
  122257. {
  122258. Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  122259. if( p ){
  122260. p->x.pSelect = yymsp[-1].minor.yy387;
  122261. ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
  122262. sqlite3ExprSetHeightAndFlags(pParse, p);
  122263. }else{
  122264. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
  122265. }
  122266. yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
  122267. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  122268. }
  122269. break;
  122270. case 229: /* expr ::= CASE case_operand case_exprlist case_else END */
  122271. {
  122272. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, 0, 0);
  122273. if( yygotominor.yy118.pExpr ){
  122274. yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy314 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[-1].minor.yy314) : yymsp[-2].minor.yy322;
  122275. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy118.pExpr);
  122276. }else{
  122277. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
  122278. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy314);
  122279. }
  122280. yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
  122281. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  122282. }
  122283. break;
  122284. case 230: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  122285. {
  122286. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
  122287. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
  122288. }
  122289. break;
  122290. case 231: /* case_exprlist ::= WHEN expr THEN expr */
  122291. {
  122292. yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
  122293. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
  122294. }
  122295. break;
  122296. case 238: /* nexprlist ::= nexprlist COMMA expr */
  122297. {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
  122298. break;
  122299. case 239: /* nexprlist ::= expr */
  122300. {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
  122301. break;
  122302. case 240: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  122303. {
  122304. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  122305. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy4,
  122306. &yymsp[-11].minor.yy0, yymsp[0].minor.yy314, SQLITE_SO_ASC, yymsp[-8].minor.yy4);
  122307. }
  122308. break;
  122309. case 241: /* uniqueflag ::= UNIQUE */
  122310. case 292: /* raisetype ::= ABORT */ yytestcase(yyruleno==292);
  122311. {yygotominor.yy4 = OE_Abort;}
  122312. break;
  122313. case 242: /* uniqueflag ::= */
  122314. {yygotominor.yy4 = OE_None;}
  122315. break;
  122316. case 245: /* eidlist ::= eidlist COMMA nm collate sortorder */
  122317. {
  122318. yygotominor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4);
  122319. }
  122320. break;
  122321. case 246: /* eidlist ::= nm collate sortorder */
  122322. {
  122323. yygotominor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4);
  122324. }
  122325. break;
  122326. case 249: /* cmd ::= DROP INDEX ifexists fullname */
  122327. {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
  122328. break;
  122329. case 250: /* cmd ::= VACUUM */
  122330. case 251: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==251);
  122331. {sqlite3Vacuum(pParse);}
  122332. break;
  122333. case 252: /* cmd ::= PRAGMA nm dbnm */
  122334. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  122335. break;
  122336. case 253: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  122337. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  122338. break;
  122339. case 254: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  122340. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  122341. break;
  122342. case 255: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  122343. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  122344. break;
  122345. case 256: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  122346. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  122347. break;
  122348. case 265: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  122349. {
  122350. Token all;
  122351. all.z = yymsp[-3].minor.yy0.z;
  122352. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  122353. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
  122354. }
  122355. break;
  122356. case 266: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  122357. {
  122358. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
  122359. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  122360. }
  122361. break;
  122362. case 267: /* trigger_time ::= BEFORE */
  122363. case 270: /* trigger_time ::= */ yytestcase(yyruleno==270);
  122364. { yygotominor.yy4 = TK_BEFORE; }
  122365. break;
  122366. case 268: /* trigger_time ::= AFTER */
  122367. { yygotominor.yy4 = TK_AFTER; }
  122368. break;
  122369. case 269: /* trigger_time ::= INSTEAD OF */
  122370. { yygotominor.yy4 = TK_INSTEAD;}
  122371. break;
  122372. case 271: /* trigger_event ::= DELETE|INSERT */
  122373. case 272: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==272);
  122374. {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
  122375. break;
  122376. case 273: /* trigger_event ::= UPDATE OF idlist */
  122377. {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
  122378. break;
  122379. case 276: /* when_clause ::= */
  122380. case 297: /* key_opt ::= */ yytestcase(yyruleno==297);
  122381. { yygotominor.yy314 = 0; }
  122382. break;
  122383. case 277: /* when_clause ::= WHEN expr */
  122384. case 298: /* key_opt ::= KEY expr */ yytestcase(yyruleno==298);
  122385. { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
  122386. break;
  122387. case 278: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  122388. {
  122389. assert( yymsp[-2].minor.yy203!=0 );
  122390. yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
  122391. yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
  122392. yygotominor.yy203 = yymsp[-2].minor.yy203;
  122393. }
  122394. break;
  122395. case 279: /* trigger_cmd_list ::= trigger_cmd SEMI */
  122396. {
  122397. assert( yymsp[-1].minor.yy203!=0 );
  122398. yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
  122399. yygotominor.yy203 = yymsp[-1].minor.yy203;
  122400. }
  122401. break;
  122402. case 281: /* trnm ::= nm DOT nm */
  122403. {
  122404. yygotominor.yy0 = yymsp[0].minor.yy0;
  122405. sqlite3ErrorMsg(pParse,
  122406. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  122407. "statements within triggers");
  122408. }
  122409. break;
  122410. case 283: /* tridxby ::= INDEXED BY nm */
  122411. {
  122412. sqlite3ErrorMsg(pParse,
  122413. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  122414. "within triggers");
  122415. }
  122416. break;
  122417. case 284: /* tridxby ::= NOT INDEXED */
  122418. {
  122419. sqlite3ErrorMsg(pParse,
  122420. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  122421. "within triggers");
  122422. }
  122423. break;
  122424. case 285: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  122425. { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy4); }
  122426. break;
  122427. case 286: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
  122428. {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, yymsp[0].minor.yy387, yymsp[-4].minor.yy4);}
  122429. break;
  122430. case 287: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  122431. {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
  122432. break;
  122433. case 288: /* trigger_cmd ::= select */
  122434. {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
  122435. break;
  122436. case 289: /* expr ::= RAISE LP IGNORE RP */
  122437. {
  122438. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  122439. if( yygotominor.yy118.pExpr ){
  122440. yygotominor.yy118.pExpr->affinity = OE_Ignore;
  122441. }
  122442. yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
  122443. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  122444. }
  122445. break;
  122446. case 290: /* expr ::= RAISE LP raisetype COMMA nm RP */
  122447. {
  122448. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  122449. if( yygotominor.yy118.pExpr ) {
  122450. yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
  122451. }
  122452. yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
  122453. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  122454. }
  122455. break;
  122456. case 291: /* raisetype ::= ROLLBACK */
  122457. {yygotominor.yy4 = OE_Rollback;}
  122458. break;
  122459. case 293: /* raisetype ::= FAIL */
  122460. {yygotominor.yy4 = OE_Fail;}
  122461. break;
  122462. case 294: /* cmd ::= DROP TRIGGER ifexists fullname */
  122463. {
  122464. sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
  122465. }
  122466. break;
  122467. case 295: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  122468. {
  122469. sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
  122470. }
  122471. break;
  122472. case 296: /* cmd ::= DETACH database_kw_opt expr */
  122473. {
  122474. sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
  122475. }
  122476. break;
  122477. case 301: /* cmd ::= REINDEX */
  122478. {sqlite3Reindex(pParse, 0, 0);}
  122479. break;
  122480. case 302: /* cmd ::= REINDEX nm dbnm */
  122481. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  122482. break;
  122483. case 303: /* cmd ::= ANALYZE */
  122484. {sqlite3Analyze(pParse, 0, 0);}
  122485. break;
  122486. case 304: /* cmd ::= ANALYZE nm dbnm */
  122487. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  122488. break;
  122489. case 305: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  122490. {
  122491. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
  122492. }
  122493. break;
  122494. case 306: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  122495. {
  122496. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  122497. }
  122498. break;
  122499. case 307: /* add_column_fullname ::= fullname */
  122500. {
  122501. pParse->db->lookaside.bEnabled = 0;
  122502. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
  122503. }
  122504. break;
  122505. case 310: /* cmd ::= create_vtab */
  122506. {sqlite3VtabFinishParse(pParse,0);}
  122507. break;
  122508. case 311: /* cmd ::= create_vtab LP vtabarglist RP */
  122509. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  122510. break;
  122511. case 312: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  122512. {
  122513. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy4);
  122514. }
  122515. break;
  122516. case 315: /* vtabarg ::= */
  122517. {sqlite3VtabArgInit(pParse);}
  122518. break;
  122519. case 317: /* vtabargtoken ::= ANY */
  122520. case 318: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==318);
  122521. case 319: /* lp ::= LP */ yytestcase(yyruleno==319);
  122522. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  122523. break;
  122524. case 323: /* with ::= */
  122525. {yygotominor.yy451 = 0;}
  122526. break;
  122527. case 324: /* with ::= WITH wqlist */
  122528. case 325: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==325);
  122529. { yygotominor.yy451 = yymsp[0].minor.yy451; }
  122530. break;
  122531. case 326: /* wqlist ::= nm eidlist_opt AS LP select RP */
  122532. {
  122533. yygotominor.yy451 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy387);
  122534. }
  122535. break;
  122536. case 327: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  122537. {
  122538. yygotominor.yy451 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy451, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy387);
  122539. }
  122540. break;
  122541. default:
  122542. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  122543. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  122544. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  122545. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  122546. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  122547. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  122548. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  122549. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  122550. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  122551. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  122552. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  122553. /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
  122554. /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
  122555. /* (43) type ::= */ yytestcase(yyruleno==43);
  122556. /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
  122557. /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
  122558. /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
  122559. /* (53) carglist ::= */ yytestcase(yyruleno==53);
  122560. /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
  122561. /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
  122562. /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
  122563. /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
  122564. /* (274) foreach_clause ::= */ yytestcase(yyruleno==274);
  122565. /* (275) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==275);
  122566. /* (282) tridxby ::= */ yytestcase(yyruleno==282);
  122567. /* (299) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==299);
  122568. /* (300) database_kw_opt ::= */ yytestcase(yyruleno==300);
  122569. /* (308) kwcolumn_opt ::= */ yytestcase(yyruleno==308);
  122570. /* (309) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==309);
  122571. /* (313) vtabarglist ::= vtabarg */ yytestcase(yyruleno==313);
  122572. /* (314) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==314);
  122573. /* (316) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==316);
  122574. /* (320) anylist ::= */ yytestcase(yyruleno==320);
  122575. /* (321) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==321);
  122576. /* (322) anylist ::= anylist ANY */ yytestcase(yyruleno==322);
  122577. break;
  122578. /********** End reduce actions ************************************************/
  122579. };
  122580. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  122581. yygoto = yyRuleInfo[yyruleno].lhs;
  122582. yysize = yyRuleInfo[yyruleno].nrhs;
  122583. yypParser->yyidx -= yysize;
  122584. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  122585. if( yyact <= YY_MAX_SHIFTREDUCE ){
  122586. if( yyact>YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  122587. /* If the reduce action popped at least
  122588. ** one element off the stack, then we can push the new element back
  122589. ** onto the stack here, and skip the stack overflow test in yy_shift().
  122590. ** That gives a significant speed improvement. */
  122591. if( yysize ){
  122592. yypParser->yyidx++;
  122593. yymsp -= yysize-1;
  122594. yymsp->stateno = (YYACTIONTYPE)yyact;
  122595. yymsp->major = (YYCODETYPE)yygoto;
  122596. yymsp->minor = yygotominor;
  122597. yyTraceShift(yypParser, yyact);
  122598. }else{
  122599. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  122600. }
  122601. }else{
  122602. assert( yyact == YY_ACCEPT_ACTION );
  122603. yy_accept(yypParser);
  122604. }
  122605. }
  122606. /*
  122607. ** The following code executes when the parse fails
  122608. */
  122609. #ifndef YYNOERRORRECOVERY
  122610. static void yy_parse_failed(
  122611. yyParser *yypParser /* The parser */
  122612. ){
  122613. sqlite3ParserARG_FETCH;
  122614. #ifndef NDEBUG
  122615. if( yyTraceFILE ){
  122616. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  122617. }
  122618. #endif
  122619. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  122620. /* Here code is inserted which will be executed whenever the
  122621. ** parser fails */
  122622. /************ Begin %parse_failure code ***************************************/
  122623. /************ End %parse_failure code *****************************************/
  122624. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  122625. }
  122626. #endif /* YYNOERRORRECOVERY */
  122627. /*
  122628. ** The following code executes when a syntax error first occurs.
  122629. */
  122630. static void yy_syntax_error(
  122631. yyParser *yypParser, /* The parser */
  122632. int yymajor, /* The major type of the error token */
  122633. YYMINORTYPE yyminor /* The minor type of the error token */
  122634. ){
  122635. sqlite3ParserARG_FETCH;
  122636. #define TOKEN (yyminor.yy0)
  122637. /************ Begin %syntax_error code ****************************************/
  122638. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  122639. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  122640. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  122641. /************ End %syntax_error code ******************************************/
  122642. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  122643. }
  122644. /*
  122645. ** The following is executed when the parser accepts
  122646. */
  122647. static void yy_accept(
  122648. yyParser *yypParser /* The parser */
  122649. ){
  122650. sqlite3ParserARG_FETCH;
  122651. #ifndef NDEBUG
  122652. if( yyTraceFILE ){
  122653. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  122654. }
  122655. #endif
  122656. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  122657. /* Here code is inserted which will be executed whenever the
  122658. ** parser accepts */
  122659. /*********** Begin %parse_accept code *****************************************/
  122660. /*********** End %parse_accept code *******************************************/
  122661. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  122662. }
  122663. /* The main parser program.
  122664. ** The first argument is a pointer to a structure obtained from
  122665. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  122666. ** The second argument is the major token number. The third is
  122667. ** the minor token. The fourth optional argument is whatever the
  122668. ** user wants (and specified in the grammar) and is available for
  122669. ** use by the action routines.
  122670. **
  122671. ** Inputs:
  122672. ** <ul>
  122673. ** <li> A pointer to the parser (an opaque structure.)
  122674. ** <li> The major token number.
  122675. ** <li> The minor token number.
  122676. ** <li> An option argument of a grammar-specified type.
  122677. ** </ul>
  122678. **
  122679. ** Outputs:
  122680. ** None.
  122681. */
  122682. SQLITE_PRIVATE void sqlite3Parser(
  122683. void *yyp, /* The parser */
  122684. int yymajor, /* The major token code number */
  122685. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  122686. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  122687. ){
  122688. YYMINORTYPE yyminorunion;
  122689. int yyact; /* The parser action. */
  122690. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  122691. int yyendofinput; /* True if we are at the end of input */
  122692. #endif
  122693. #ifdef YYERRORSYMBOL
  122694. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  122695. #endif
  122696. yyParser *yypParser; /* The parser */
  122697. /* (re)initialize the parser, if necessary */
  122698. yypParser = (yyParser*)yyp;
  122699. if( yypParser->yyidx<0 ){
  122700. #if YYSTACKDEPTH<=0
  122701. if( yypParser->yystksz <=0 ){
  122702. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  122703. yyminorunion = yyzerominor;
  122704. yyStackOverflow(yypParser, &yyminorunion);
  122705. return;
  122706. }
  122707. #endif
  122708. yypParser->yyidx = 0;
  122709. yypParser->yyerrcnt = -1;
  122710. yypParser->yystack[0].stateno = 0;
  122711. yypParser->yystack[0].major = 0;
  122712. #ifndef NDEBUG
  122713. if( yyTraceFILE ){
  122714. fprintf(yyTraceFILE,"%sInitialize. Empty stack. State 0\n",
  122715. yyTracePrompt);
  122716. }
  122717. #endif
  122718. }
  122719. yyminorunion.yy0 = yyminor;
  122720. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  122721. yyendofinput = (yymajor==0);
  122722. #endif
  122723. sqlite3ParserARG_STORE;
  122724. #ifndef NDEBUG
  122725. if( yyTraceFILE ){
  122726. fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
  122727. }
  122728. #endif
  122729. do{
  122730. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  122731. if( yyact <= YY_MAX_SHIFTREDUCE ){
  122732. if( yyact > YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  122733. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  122734. yypParser->yyerrcnt--;
  122735. yymajor = YYNOCODE;
  122736. }else if( yyact <= YY_MAX_REDUCE ){
  122737. yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
  122738. }else{
  122739. assert( yyact == YY_ERROR_ACTION );
  122740. #ifdef YYERRORSYMBOL
  122741. int yymx;
  122742. #endif
  122743. #ifndef NDEBUG
  122744. if( yyTraceFILE ){
  122745. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  122746. }
  122747. #endif
  122748. #ifdef YYERRORSYMBOL
  122749. /* A syntax error has occurred.
  122750. ** The response to an error depends upon whether or not the
  122751. ** grammar defines an error token "ERROR".
  122752. **
  122753. ** This is what we do if the grammar does define ERROR:
  122754. **
  122755. ** * Call the %syntax_error function.
  122756. **
  122757. ** * Begin popping the stack until we enter a state where
  122758. ** it is legal to shift the error symbol, then shift
  122759. ** the error symbol.
  122760. **
  122761. ** * Set the error count to three.
  122762. **
  122763. ** * Begin accepting and shifting new tokens. No new error
  122764. ** processing will occur until three tokens have been
  122765. ** shifted successfully.
  122766. **
  122767. */
  122768. if( yypParser->yyerrcnt<0 ){
  122769. yy_syntax_error(yypParser,yymajor,yyminorunion);
  122770. }
  122771. yymx = yypParser->yystack[yypParser->yyidx].major;
  122772. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  122773. #ifndef NDEBUG
  122774. if( yyTraceFILE ){
  122775. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  122776. yyTracePrompt,yyTokenName[yymajor]);
  122777. }
  122778. #endif
  122779. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  122780. yymajor = YYNOCODE;
  122781. }else{
  122782. while(
  122783. yypParser->yyidx >= 0 &&
  122784. yymx != YYERRORSYMBOL &&
  122785. (yyact = yy_find_reduce_action(
  122786. yypParser->yystack[yypParser->yyidx].stateno,
  122787. YYERRORSYMBOL)) >= YY_MIN_REDUCE
  122788. ){
  122789. yy_pop_parser_stack(yypParser);
  122790. }
  122791. if( yypParser->yyidx < 0 || yymajor==0 ){
  122792. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  122793. yy_parse_failed(yypParser);
  122794. yymajor = YYNOCODE;
  122795. }else if( yymx!=YYERRORSYMBOL ){
  122796. YYMINORTYPE u2;
  122797. u2.YYERRSYMDT = 0;
  122798. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  122799. }
  122800. }
  122801. yypParser->yyerrcnt = 3;
  122802. yyerrorhit = 1;
  122803. #elif defined(YYNOERRORRECOVERY)
  122804. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  122805. ** do any kind of error recovery. Instead, simply invoke the syntax
  122806. ** error routine and continue going as if nothing had happened.
  122807. **
  122808. ** Applications can set this macro (for example inside %include) if
  122809. ** they intend to abandon the parse upon the first syntax error seen.
  122810. */
  122811. yy_syntax_error(yypParser,yymajor,yyminorunion);
  122812. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  122813. yymajor = YYNOCODE;
  122814. #else /* YYERRORSYMBOL is not defined */
  122815. /* This is what we do if the grammar does not define ERROR:
  122816. **
  122817. ** * Report an error message, and throw away the input token.
  122818. **
  122819. ** * If the input token is $, then fail the parse.
  122820. **
  122821. ** As before, subsequent error messages are suppressed until
  122822. ** three input tokens have been successfully shifted.
  122823. */
  122824. if( yypParser->yyerrcnt<=0 ){
  122825. yy_syntax_error(yypParser,yymajor,yyminorunion);
  122826. }
  122827. yypParser->yyerrcnt = 3;
  122828. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  122829. if( yyendofinput ){
  122830. yy_parse_failed(yypParser);
  122831. }
  122832. yymajor = YYNOCODE;
  122833. #endif
  122834. }
  122835. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  122836. #ifndef NDEBUG
  122837. if( yyTraceFILE ){
  122838. int i;
  122839. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  122840. for(i=1; i<=yypParser->yyidx; i++)
  122841. fprintf(yyTraceFILE,"%c%s", i==1 ? '[' : ' ',
  122842. yyTokenName[yypParser->yystack[i].major]);
  122843. fprintf(yyTraceFILE,"]\n");
  122844. }
  122845. #endif
  122846. return;
  122847. }
  122848. /************** End of parse.c ***********************************************/
  122849. /************** Begin file tokenize.c ****************************************/
  122850. /*
  122851. ** 2001 September 15
  122852. **
  122853. ** The author disclaims copyright to this source code. In place of
  122854. ** a legal notice, here is a blessing:
  122855. **
  122856. ** May you do good and not evil.
  122857. ** May you find forgiveness for yourself and forgive others.
  122858. ** May you share freely, never taking more than you give.
  122859. **
  122860. *************************************************************************
  122861. ** An tokenizer for SQL
  122862. **
  122863. ** This file contains C code that splits an SQL input string up into
  122864. ** individual tokens and sends those tokens one-by-one over to the
  122865. ** parser for analysis.
  122866. */
  122867. /* #include "sqliteInt.h" */
  122868. /* #include <stdlib.h> */
  122869. /*
  122870. ** The charMap() macro maps alphabetic characters into their
  122871. ** lower-case ASCII equivalent. On ASCII machines, this is just
  122872. ** an upper-to-lower case map. On EBCDIC machines we also need
  122873. ** to adjust the encoding. Only alphabetic characters and underscores
  122874. ** need to be translated.
  122875. */
  122876. #ifdef SQLITE_ASCII
  122877. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  122878. #endif
  122879. #ifdef SQLITE_EBCDIC
  122880. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  122881. const unsigned char ebcdicToAscii[] = {
  122882. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  122891. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  122892. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  122893. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  122895. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  122896. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  122897. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  122899. };
  122900. #endif
  122901. /*
  122902. ** The sqlite3KeywordCode function looks up an identifier to determine if
  122903. ** it is a keyword. If it is a keyword, the token code of that keyword is
  122904. ** returned. If the input is not a keyword, TK_ID is returned.
  122905. **
  122906. ** The implementation of this routine was generated by a program,
  122907. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  122908. ** The output of the mkkeywordhash.c program is written into a file
  122909. ** named keywordhash.h and then included into this source file by
  122910. ** the #include below.
  122911. */
  122912. /************** Include keywordhash.h in the middle of tokenize.c ************/
  122913. /************** Begin file keywordhash.h *************************************/
  122914. /***** This file contains automatically generated code ******
  122915. **
  122916. ** The code in this file has been automatically generated by
  122917. **
  122918. ** sqlite/tool/mkkeywordhash.c
  122919. **
  122920. ** The code in this file implements a function that determines whether
  122921. ** or not a given identifier is really an SQL keyword. The same thing
  122922. ** might be implemented more directly using a hand-written hash table.
  122923. ** But by using this automatically generated code, the size of the code
  122924. ** is substantially reduced. This is important for embedded applications
  122925. ** on platforms with limited memory.
  122926. */
  122927. /* Hash score: 182 */
  122928. static int keywordCode(const char *z, int n, int *pType){
  122929. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  122930. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  122931. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  122932. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  122933. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  122934. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  122935. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  122936. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  122937. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  122938. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  122939. /* VACUUMVIEWINITIALLY */
  122940. static const char zText[553] = {
  122941. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  122942. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  122943. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  122944. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  122945. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  122946. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  122947. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  122948. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  122949. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  122950. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  122951. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  122952. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  122953. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  122954. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  122955. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  122956. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  122957. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  122958. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  122959. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  122960. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  122961. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  122962. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  122963. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  122964. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  122965. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  122966. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  122967. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  122968. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  122969. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  122970. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  122971. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  122972. };
  122973. static const unsigned char aHash[127] = {
  122974. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  122975. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  122976. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  122977. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  122978. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  122979. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  122980. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  122981. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  122982. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  122983. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  122984. };
  122985. static const unsigned char aNext[124] = {
  122986. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  122987. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  122988. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122989. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  122990. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  122991. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  122992. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  122993. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  122994. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  122995. 73, 83, 0, 35, 68, 0, 0,
  122996. };
  122997. static const unsigned char aLen[124] = {
  122998. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  122999. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  123000. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  123001. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  123002. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  123003. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  123004. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  123005. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  123006. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  123007. 3, 5, 5, 6, 4, 9, 3,
  123008. };
  123009. static const unsigned short int aOffset[124] = {
  123010. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  123011. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  123012. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  123013. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  123014. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  123015. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  123016. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  123017. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  123018. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  123019. 521, 524, 529, 534, 540, 544, 549,
  123020. };
  123021. static const unsigned char aCode[124] = {
  123022. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  123023. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  123024. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  123025. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  123026. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  123027. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  123028. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  123029. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  123030. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  123031. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  123032. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  123033. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  123034. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  123035. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  123036. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  123037. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  123038. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  123039. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  123040. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  123041. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  123042. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  123043. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  123044. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  123045. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  123046. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  123047. };
  123048. int h, i;
  123049. if( n>=2 ){
  123050. h = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  123051. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  123052. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  123053. testcase( i==0 ); /* REINDEX */
  123054. testcase( i==1 ); /* INDEXED */
  123055. testcase( i==2 ); /* INDEX */
  123056. testcase( i==3 ); /* DESC */
  123057. testcase( i==4 ); /* ESCAPE */
  123058. testcase( i==5 ); /* EACH */
  123059. testcase( i==6 ); /* CHECK */
  123060. testcase( i==7 ); /* KEY */
  123061. testcase( i==8 ); /* BEFORE */
  123062. testcase( i==9 ); /* FOREIGN */
  123063. testcase( i==10 ); /* FOR */
  123064. testcase( i==11 ); /* IGNORE */
  123065. testcase( i==12 ); /* REGEXP */
  123066. testcase( i==13 ); /* EXPLAIN */
  123067. testcase( i==14 ); /* INSTEAD */
  123068. testcase( i==15 ); /* ADD */
  123069. testcase( i==16 ); /* DATABASE */
  123070. testcase( i==17 ); /* AS */
  123071. testcase( i==18 ); /* SELECT */
  123072. testcase( i==19 ); /* TABLE */
  123073. testcase( i==20 ); /* LEFT */
  123074. testcase( i==21 ); /* THEN */
  123075. testcase( i==22 ); /* END */
  123076. testcase( i==23 ); /* DEFERRABLE */
  123077. testcase( i==24 ); /* ELSE */
  123078. testcase( i==25 ); /* EXCEPT */
  123079. testcase( i==26 ); /* TRANSACTION */
  123080. testcase( i==27 ); /* ACTION */
  123081. testcase( i==28 ); /* ON */
  123082. testcase( i==29 ); /* NATURAL */
  123083. testcase( i==30 ); /* ALTER */
  123084. testcase( i==31 ); /* RAISE */
  123085. testcase( i==32 ); /* EXCLUSIVE */
  123086. testcase( i==33 ); /* EXISTS */
  123087. testcase( i==34 ); /* SAVEPOINT */
  123088. testcase( i==35 ); /* INTERSECT */
  123089. testcase( i==36 ); /* TRIGGER */
  123090. testcase( i==37 ); /* REFERENCES */
  123091. testcase( i==38 ); /* CONSTRAINT */
  123092. testcase( i==39 ); /* INTO */
  123093. testcase( i==40 ); /* OFFSET */
  123094. testcase( i==41 ); /* OF */
  123095. testcase( i==42 ); /* SET */
  123096. testcase( i==43 ); /* TEMPORARY */
  123097. testcase( i==44 ); /* TEMP */
  123098. testcase( i==45 ); /* OR */
  123099. testcase( i==46 ); /* UNIQUE */
  123100. testcase( i==47 ); /* QUERY */
  123101. testcase( i==48 ); /* WITHOUT */
  123102. testcase( i==49 ); /* WITH */
  123103. testcase( i==50 ); /* OUTER */
  123104. testcase( i==51 ); /* RELEASE */
  123105. testcase( i==52 ); /* ATTACH */
  123106. testcase( i==53 ); /* HAVING */
  123107. testcase( i==54 ); /* GROUP */
  123108. testcase( i==55 ); /* UPDATE */
  123109. testcase( i==56 ); /* BEGIN */
  123110. testcase( i==57 ); /* INNER */
  123111. testcase( i==58 ); /* RECURSIVE */
  123112. testcase( i==59 ); /* BETWEEN */
  123113. testcase( i==60 ); /* NOTNULL */
  123114. testcase( i==61 ); /* NOT */
  123115. testcase( i==62 ); /* NO */
  123116. testcase( i==63 ); /* NULL */
  123117. testcase( i==64 ); /* LIKE */
  123118. testcase( i==65 ); /* CASCADE */
  123119. testcase( i==66 ); /* ASC */
  123120. testcase( i==67 ); /* DELETE */
  123121. testcase( i==68 ); /* CASE */
  123122. testcase( i==69 ); /* COLLATE */
  123123. testcase( i==70 ); /* CREATE */
  123124. testcase( i==71 ); /* CURRENT_DATE */
  123125. testcase( i==72 ); /* DETACH */
  123126. testcase( i==73 ); /* IMMEDIATE */
  123127. testcase( i==74 ); /* JOIN */
  123128. testcase( i==75 ); /* INSERT */
  123129. testcase( i==76 ); /* MATCH */
  123130. testcase( i==77 ); /* PLAN */
  123131. testcase( i==78 ); /* ANALYZE */
  123132. testcase( i==79 ); /* PRAGMA */
  123133. testcase( i==80 ); /* ABORT */
  123134. testcase( i==81 ); /* VALUES */
  123135. testcase( i==82 ); /* VIRTUAL */
  123136. testcase( i==83 ); /* LIMIT */
  123137. testcase( i==84 ); /* WHEN */
  123138. testcase( i==85 ); /* WHERE */
  123139. testcase( i==86 ); /* RENAME */
  123140. testcase( i==87 ); /* AFTER */
  123141. testcase( i==88 ); /* REPLACE */
  123142. testcase( i==89 ); /* AND */
  123143. testcase( i==90 ); /* DEFAULT */
  123144. testcase( i==91 ); /* AUTOINCREMENT */
  123145. testcase( i==92 ); /* TO */
  123146. testcase( i==93 ); /* IN */
  123147. testcase( i==94 ); /* CAST */
  123148. testcase( i==95 ); /* COLUMN */
  123149. testcase( i==96 ); /* COMMIT */
  123150. testcase( i==97 ); /* CONFLICT */
  123151. testcase( i==98 ); /* CROSS */
  123152. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  123153. testcase( i==100 ); /* CURRENT_TIME */
  123154. testcase( i==101 ); /* PRIMARY */
  123155. testcase( i==102 ); /* DEFERRED */
  123156. testcase( i==103 ); /* DISTINCT */
  123157. testcase( i==104 ); /* IS */
  123158. testcase( i==105 ); /* DROP */
  123159. testcase( i==106 ); /* FAIL */
  123160. testcase( i==107 ); /* FROM */
  123161. testcase( i==108 ); /* FULL */
  123162. testcase( i==109 ); /* GLOB */
  123163. testcase( i==110 ); /* BY */
  123164. testcase( i==111 ); /* IF */
  123165. testcase( i==112 ); /* ISNULL */
  123166. testcase( i==113 ); /* ORDER */
  123167. testcase( i==114 ); /* RESTRICT */
  123168. testcase( i==115 ); /* RIGHT */
  123169. testcase( i==116 ); /* ROLLBACK */
  123170. testcase( i==117 ); /* ROW */
  123171. testcase( i==118 ); /* UNION */
  123172. testcase( i==119 ); /* USING */
  123173. testcase( i==120 ); /* VACUUM */
  123174. testcase( i==121 ); /* VIEW */
  123175. testcase( i==122 ); /* INITIALLY */
  123176. testcase( i==123 ); /* ALL */
  123177. *pType = aCode[i];
  123178. break;
  123179. }
  123180. }
  123181. }
  123182. return n;
  123183. }
  123184. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  123185. int id = TK_ID;
  123186. keywordCode((char*)z, n, &id);
  123187. return id;
  123188. }
  123189. #define SQLITE_N_KEYWORD 124
  123190. /************** End of keywordhash.h *****************************************/
  123191. /************** Continuing where we left off in tokenize.c *******************/
  123192. /*
  123193. ** If X is a character that can be used in an identifier then
  123194. ** IdChar(X) will be true. Otherwise it is false.
  123195. **
  123196. ** For ASCII, any character with the high-order bit set is
  123197. ** allowed in an identifier. For 7-bit characters,
  123198. ** sqlite3IsIdChar[X] must be 1.
  123199. **
  123200. ** For EBCDIC, the rules are more complex but have the same
  123201. ** end result.
  123202. **
  123203. ** Ticket #1066. the SQL standard does not allow '$' in the
  123204. ** middle of identifiers. But many SQL implementations do.
  123205. ** SQLite will allow '$' in identifiers for compatibility.
  123206. ** But the feature is undocumented.
  123207. */
  123208. #ifdef SQLITE_ASCII
  123209. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  123210. #endif
  123211. #ifdef SQLITE_EBCDIC
  123212. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  123213. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  123214. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  123215. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  123216. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  123217. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  123218. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  123219. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  123220. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  123221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  123222. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  123223. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  123224. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  123225. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  123226. };
  123227. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  123228. #endif
  123229. /* Make the IdChar function accessible from ctime.c */
  123230. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  123231. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  123232. #endif
  123233. /*
  123234. ** Return the length of the token that begins at z[0].
  123235. ** Store the token type in *tokenType before returning.
  123236. */
  123237. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  123238. int i, c;
  123239. switch( *z ){
  123240. case ' ': case '\t': case '\n': case '\f': case '\r': {
  123241. testcase( z[0]==' ' );
  123242. testcase( z[0]=='\t' );
  123243. testcase( z[0]=='\n' );
  123244. testcase( z[0]=='\f' );
  123245. testcase( z[0]=='\r' );
  123246. for(i=1; sqlite3Isspace(z[i]); i++){}
  123247. *tokenType = TK_SPACE;
  123248. return i;
  123249. }
  123250. case '-': {
  123251. if( z[1]=='-' ){
  123252. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  123253. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  123254. return i;
  123255. }
  123256. *tokenType = TK_MINUS;
  123257. return 1;
  123258. }
  123259. case '(': {
  123260. *tokenType = TK_LP;
  123261. return 1;
  123262. }
  123263. case ')': {
  123264. *tokenType = TK_RP;
  123265. return 1;
  123266. }
  123267. case ';': {
  123268. *tokenType = TK_SEMI;
  123269. return 1;
  123270. }
  123271. case '+': {
  123272. *tokenType = TK_PLUS;
  123273. return 1;
  123274. }
  123275. case '*': {
  123276. *tokenType = TK_STAR;
  123277. return 1;
  123278. }
  123279. case '/': {
  123280. if( z[1]!='*' || z[2]==0 ){
  123281. *tokenType = TK_SLASH;
  123282. return 1;
  123283. }
  123284. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  123285. if( c ) i++;
  123286. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  123287. return i;
  123288. }
  123289. case '%': {
  123290. *tokenType = TK_REM;
  123291. return 1;
  123292. }
  123293. case '=': {
  123294. *tokenType = TK_EQ;
  123295. return 1 + (z[1]=='=');
  123296. }
  123297. case '<': {
  123298. if( (c=z[1])=='=' ){
  123299. *tokenType = TK_LE;
  123300. return 2;
  123301. }else if( c=='>' ){
  123302. *tokenType = TK_NE;
  123303. return 2;
  123304. }else if( c=='<' ){
  123305. *tokenType = TK_LSHIFT;
  123306. return 2;
  123307. }else{
  123308. *tokenType = TK_LT;
  123309. return 1;
  123310. }
  123311. }
  123312. case '>': {
  123313. if( (c=z[1])=='=' ){
  123314. *tokenType = TK_GE;
  123315. return 2;
  123316. }else if( c=='>' ){
  123317. *tokenType = TK_RSHIFT;
  123318. return 2;
  123319. }else{
  123320. *tokenType = TK_GT;
  123321. return 1;
  123322. }
  123323. }
  123324. case '!': {
  123325. if( z[1]!='=' ){
  123326. *tokenType = TK_ILLEGAL;
  123327. return 2;
  123328. }else{
  123329. *tokenType = TK_NE;
  123330. return 2;
  123331. }
  123332. }
  123333. case '|': {
  123334. if( z[1]!='|' ){
  123335. *tokenType = TK_BITOR;
  123336. return 1;
  123337. }else{
  123338. *tokenType = TK_CONCAT;
  123339. return 2;
  123340. }
  123341. }
  123342. case ',': {
  123343. *tokenType = TK_COMMA;
  123344. return 1;
  123345. }
  123346. case '&': {
  123347. *tokenType = TK_BITAND;
  123348. return 1;
  123349. }
  123350. case '~': {
  123351. *tokenType = TK_BITNOT;
  123352. return 1;
  123353. }
  123354. case '`':
  123355. case '\'':
  123356. case '"': {
  123357. int delim = z[0];
  123358. testcase( delim=='`' );
  123359. testcase( delim=='\'' );
  123360. testcase( delim=='"' );
  123361. for(i=1; (c=z[i])!=0; i++){
  123362. if( c==delim ){
  123363. if( z[i+1]==delim ){
  123364. i++;
  123365. }else{
  123366. break;
  123367. }
  123368. }
  123369. }
  123370. if( c=='\'' ){
  123371. *tokenType = TK_STRING;
  123372. return i+1;
  123373. }else if( c!=0 ){
  123374. *tokenType = TK_ID;
  123375. return i+1;
  123376. }else{
  123377. *tokenType = TK_ILLEGAL;
  123378. return i;
  123379. }
  123380. }
  123381. case '.': {
  123382. #ifndef SQLITE_OMIT_FLOATING_POINT
  123383. if( !sqlite3Isdigit(z[1]) )
  123384. #endif
  123385. {
  123386. *tokenType = TK_DOT;
  123387. return 1;
  123388. }
  123389. /* If the next character is a digit, this is a floating point
  123390. ** number that begins with ".". Fall thru into the next case */
  123391. }
  123392. case '0': case '1': case '2': case '3': case '4':
  123393. case '5': case '6': case '7': case '8': case '9': {
  123394. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  123395. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  123396. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  123397. testcase( z[0]=='9' );
  123398. *tokenType = TK_INTEGER;
  123399. #ifndef SQLITE_OMIT_HEX_INTEGER
  123400. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  123401. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  123402. return i;
  123403. }
  123404. #endif
  123405. for(i=0; sqlite3Isdigit(z[i]); i++){}
  123406. #ifndef SQLITE_OMIT_FLOATING_POINT
  123407. if( z[i]=='.' ){
  123408. i++;
  123409. while( sqlite3Isdigit(z[i]) ){ i++; }
  123410. *tokenType = TK_FLOAT;
  123411. }
  123412. if( (z[i]=='e' || z[i]=='E') &&
  123413. ( sqlite3Isdigit(z[i+1])
  123414. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  123415. )
  123416. ){
  123417. i += 2;
  123418. while( sqlite3Isdigit(z[i]) ){ i++; }
  123419. *tokenType = TK_FLOAT;
  123420. }
  123421. #endif
  123422. while( IdChar(z[i]) ){
  123423. *tokenType = TK_ILLEGAL;
  123424. i++;
  123425. }
  123426. return i;
  123427. }
  123428. case '[': {
  123429. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  123430. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  123431. return i;
  123432. }
  123433. case '?': {
  123434. *tokenType = TK_VARIABLE;
  123435. for(i=1; sqlite3Isdigit(z[i]); i++){}
  123436. return i;
  123437. }
  123438. #ifndef SQLITE_OMIT_TCL_VARIABLE
  123439. case '$':
  123440. #endif
  123441. case '@': /* For compatibility with MS SQL Server */
  123442. case '#':
  123443. case ':': {
  123444. int n = 0;
  123445. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  123446. testcase( z[0]==':' ); testcase( z[0]=='#' );
  123447. *tokenType = TK_VARIABLE;
  123448. for(i=1; (c=z[i])!=0; i++){
  123449. if( IdChar(c) ){
  123450. n++;
  123451. #ifndef SQLITE_OMIT_TCL_VARIABLE
  123452. }else if( c=='(' && n>0 ){
  123453. do{
  123454. i++;
  123455. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  123456. if( c==')' ){
  123457. i++;
  123458. }else{
  123459. *tokenType = TK_ILLEGAL;
  123460. }
  123461. break;
  123462. }else if( c==':' && z[i+1]==':' ){
  123463. i++;
  123464. #endif
  123465. }else{
  123466. break;
  123467. }
  123468. }
  123469. if( n==0 ) *tokenType = TK_ILLEGAL;
  123470. return i;
  123471. }
  123472. #ifndef SQLITE_OMIT_BLOB_LITERAL
  123473. case 'x': case 'X': {
  123474. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  123475. if( z[1]=='\'' ){
  123476. *tokenType = TK_BLOB;
  123477. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  123478. if( z[i]!='\'' || i%2 ){
  123479. *tokenType = TK_ILLEGAL;
  123480. while( z[i] && z[i]!='\'' ){ i++; }
  123481. }
  123482. if( z[i] ) i++;
  123483. return i;
  123484. }
  123485. /* Otherwise fall through to the next case */
  123486. }
  123487. #endif
  123488. default: {
  123489. if( !IdChar(*z) ){
  123490. break;
  123491. }
  123492. for(i=1; IdChar(z[i]); i++){}
  123493. *tokenType = TK_ID;
  123494. return keywordCode((char*)z, i, tokenType);
  123495. }
  123496. }
  123497. *tokenType = TK_ILLEGAL;
  123498. return 1;
  123499. }
  123500. /*
  123501. ** Run the parser on the given SQL string. The parser structure is
  123502. ** passed in. An SQLITE_ status code is returned. If an error occurs
  123503. ** then an and attempt is made to write an error message into
  123504. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  123505. ** error message.
  123506. */
  123507. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  123508. int nErr = 0; /* Number of errors encountered */
  123509. int i; /* Loop counter */
  123510. void *pEngine; /* The LEMON-generated LALR(1) parser */
  123511. int tokenType; /* type of the next token */
  123512. int lastTokenParsed = -1; /* type of the previous token */
  123513. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  123514. sqlite3 *db = pParse->db; /* The database connection */
  123515. int mxSqlLen; /* Max length of an SQL string */
  123516. assert( zSql!=0 );
  123517. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  123518. if( db->nVdbeActive==0 ){
  123519. db->u1.isInterrupted = 0;
  123520. }
  123521. pParse->rc = SQLITE_OK;
  123522. pParse->zTail = zSql;
  123523. i = 0;
  123524. assert( pzErrMsg!=0 );
  123525. /* sqlite3ParserTrace(stdout, "parser: "); */
  123526. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  123527. if( pEngine==0 ){
  123528. db->mallocFailed = 1;
  123529. return SQLITE_NOMEM;
  123530. }
  123531. assert( pParse->pNewTable==0 );
  123532. assert( pParse->pNewTrigger==0 );
  123533. assert( pParse->nVar==0 );
  123534. assert( pParse->nzVar==0 );
  123535. assert( pParse->azVar==0 );
  123536. enableLookaside = db->lookaside.bEnabled;
  123537. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  123538. while( zSql[i]!=0 ){
  123539. assert( i>=0 );
  123540. pParse->sLastToken.z = &zSql[i];
  123541. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  123542. i += pParse->sLastToken.n;
  123543. if( i>mxSqlLen ){
  123544. pParse->rc = SQLITE_TOOBIG;
  123545. break;
  123546. }
  123547. if( tokenType>=TK_SPACE ){
  123548. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  123549. if( db->u1.isInterrupted ){
  123550. sqlite3ErrorMsg(pParse, "interrupt");
  123551. pParse->rc = SQLITE_INTERRUPT;
  123552. break;
  123553. }
  123554. if( tokenType==TK_ILLEGAL ){
  123555. sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
  123556. &pParse->sLastToken);
  123557. break;
  123558. }
  123559. }else{
  123560. if( tokenType==TK_SEMI ) pParse->zTail = &zSql[i];
  123561. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  123562. lastTokenParsed = tokenType;
  123563. if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
  123564. }
  123565. }
  123566. assert( nErr==0 );
  123567. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  123568. assert( zSql[i]==0 );
  123569. if( lastTokenParsed!=TK_SEMI ){
  123570. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  123571. pParse->zTail = &zSql[i];
  123572. }
  123573. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  123574. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  123575. }
  123576. }
  123577. #ifdef YYTRACKMAXSTACKDEPTH
  123578. sqlite3_mutex_enter(sqlite3MallocMutex());
  123579. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  123580. sqlite3ParserStackPeak(pEngine)
  123581. );
  123582. sqlite3_mutex_leave(sqlite3MallocMutex());
  123583. #endif /* YYDEBUG */
  123584. sqlite3ParserFree(pEngine, sqlite3_free);
  123585. db->lookaside.bEnabled = enableLookaside;
  123586. if( db->mallocFailed ){
  123587. pParse->rc = SQLITE_NOMEM;
  123588. }
  123589. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  123590. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  123591. }
  123592. assert( pzErrMsg!=0 );
  123593. if( pParse->zErrMsg ){
  123594. *pzErrMsg = pParse->zErrMsg;
  123595. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  123596. pParse->zErrMsg = 0;
  123597. nErr++;
  123598. }
  123599. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  123600. sqlite3VdbeDelete(pParse->pVdbe);
  123601. pParse->pVdbe = 0;
  123602. }
  123603. #ifndef SQLITE_OMIT_SHARED_CACHE
  123604. if( pParse->nested==0 ){
  123605. sqlite3DbFree(db, pParse->aTableLock);
  123606. pParse->aTableLock = 0;
  123607. pParse->nTableLock = 0;
  123608. }
  123609. #endif
  123610. #ifndef SQLITE_OMIT_VIRTUALTABLE
  123611. sqlite3_free(pParse->apVtabLock);
  123612. #endif
  123613. if( !IN_DECLARE_VTAB ){
  123614. /* If the pParse->declareVtab flag is set, do not delete any table
  123615. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  123616. ** will take responsibility for freeing the Table structure.
  123617. */
  123618. sqlite3DeleteTable(db, pParse->pNewTable);
  123619. }
  123620. sqlite3WithDelete(db, pParse->pWithToFree);
  123621. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  123622. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  123623. sqlite3DbFree(db, pParse->azVar);
  123624. while( pParse->pAinc ){
  123625. AutoincInfo *p = pParse->pAinc;
  123626. pParse->pAinc = p->pNext;
  123627. sqlite3DbFree(db, p);
  123628. }
  123629. while( pParse->pZombieTab ){
  123630. Table *p = pParse->pZombieTab;
  123631. pParse->pZombieTab = p->pNextZombie;
  123632. sqlite3DeleteTable(db, p);
  123633. }
  123634. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  123635. return nErr;
  123636. }
  123637. /************** End of tokenize.c ********************************************/
  123638. /************** Begin file complete.c ****************************************/
  123639. /*
  123640. ** 2001 September 15
  123641. **
  123642. ** The author disclaims copyright to this source code. In place of
  123643. ** a legal notice, here is a blessing:
  123644. **
  123645. ** May you do good and not evil.
  123646. ** May you find forgiveness for yourself and forgive others.
  123647. ** May you share freely, never taking more than you give.
  123648. **
  123649. *************************************************************************
  123650. ** An tokenizer for SQL
  123651. **
  123652. ** This file contains C code that implements the sqlite3_complete() API.
  123653. ** This code used to be part of the tokenizer.c source file. But by
  123654. ** separating it out, the code will be automatically omitted from
  123655. ** static links that do not use it.
  123656. */
  123657. /* #include "sqliteInt.h" */
  123658. #ifndef SQLITE_OMIT_COMPLETE
  123659. /*
  123660. ** This is defined in tokenize.c. We just have to import the definition.
  123661. */
  123662. #ifndef SQLITE_AMALGAMATION
  123663. #ifdef SQLITE_ASCII
  123664. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  123665. #endif
  123666. #ifdef SQLITE_EBCDIC
  123667. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  123668. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  123669. #endif
  123670. #endif /* SQLITE_AMALGAMATION */
  123671. /*
  123672. ** Token types used by the sqlite3_complete() routine. See the header
  123673. ** comments on that procedure for additional information.
  123674. */
  123675. #define tkSEMI 0
  123676. #define tkWS 1
  123677. #define tkOTHER 2
  123678. #ifndef SQLITE_OMIT_TRIGGER
  123679. #define tkEXPLAIN 3
  123680. #define tkCREATE 4
  123681. #define tkTEMP 5
  123682. #define tkTRIGGER 6
  123683. #define tkEND 7
  123684. #endif
  123685. /*
  123686. ** Return TRUE if the given SQL string ends in a semicolon.
  123687. **
  123688. ** Special handling is require for CREATE TRIGGER statements.
  123689. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  123690. ** must end with ";END;".
  123691. **
  123692. ** This implementation uses a state machine with 8 states:
  123693. **
  123694. ** (0) INVALID We have not yet seen a non-whitespace character.
  123695. **
  123696. ** (1) START At the beginning or end of an SQL statement. This routine
  123697. ** returns 1 if it ends in the START state and 0 if it ends
  123698. ** in any other state.
  123699. **
  123700. ** (2) NORMAL We are in the middle of statement which ends with a single
  123701. ** semicolon.
  123702. **
  123703. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  123704. ** a statement.
  123705. **
  123706. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  123707. ** statement, possibly preceded by EXPLAIN and/or followed by
  123708. ** TEMP or TEMPORARY
  123709. **
  123710. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  123711. ** ended by a semicolon, the keyword END, and another semicolon.
  123712. **
  123713. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  123714. ** the end of a trigger definition.
  123715. **
  123716. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  123717. ** of a trigger definition.
  123718. **
  123719. ** Transitions between states above are determined by tokens extracted
  123720. ** from the input. The following tokens are significant:
  123721. **
  123722. ** (0) tkSEMI A semicolon.
  123723. ** (1) tkWS Whitespace.
  123724. ** (2) tkOTHER Any other SQL token.
  123725. ** (3) tkEXPLAIN The "explain" keyword.
  123726. ** (4) tkCREATE The "create" keyword.
  123727. ** (5) tkTEMP The "temp" or "temporary" keyword.
  123728. ** (6) tkTRIGGER The "trigger" keyword.
  123729. ** (7) tkEND The "end" keyword.
  123730. **
  123731. ** Whitespace never causes a state transition and is always ignored.
  123732. ** This means that a SQL string of all whitespace is invalid.
  123733. **
  123734. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  123735. ** to recognize the end of a trigger can be omitted. All we have to do
  123736. ** is look for a semicolon that is not part of an string or comment.
  123737. */
  123738. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
  123739. u8 state = 0; /* Current state, using numbers defined in header comment */
  123740. u8 token; /* Value of the next token */
  123741. #ifndef SQLITE_OMIT_TRIGGER
  123742. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  123743. ** statement. This is the normal case.
  123744. */
  123745. static const u8 trans[8][8] = {
  123746. /* Token: */
  123747. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  123748. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  123749. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  123750. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  123751. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  123752. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  123753. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  123754. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  123755. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  123756. };
  123757. #else
  123758. /* If triggers are not supported by this compile then the statement machine
  123759. ** used to detect the end of a statement is much simpler
  123760. */
  123761. static const u8 trans[3][3] = {
  123762. /* Token: */
  123763. /* State: ** SEMI WS OTHER */
  123764. /* 0 INVALID: */ { 1, 0, 2, },
  123765. /* 1 START: */ { 1, 1, 2, },
  123766. /* 2 NORMAL: */ { 1, 2, 2, },
  123767. };
  123768. #endif /* SQLITE_OMIT_TRIGGER */
  123769. #ifdef SQLITE_ENABLE_API_ARMOR
  123770. if( zSql==0 ){
  123771. (void)SQLITE_MISUSE_BKPT;
  123772. return 0;
  123773. }
  123774. #endif
  123775. while( *zSql ){
  123776. switch( *zSql ){
  123777. case ';': { /* A semicolon */
  123778. token = tkSEMI;
  123779. break;
  123780. }
  123781. case ' ':
  123782. case '\r':
  123783. case '\t':
  123784. case '\n':
  123785. case '\f': { /* White space is ignored */
  123786. token = tkWS;
  123787. break;
  123788. }
  123789. case '/': { /* C-style comments */
  123790. if( zSql[1]!='*' ){
  123791. token = tkOTHER;
  123792. break;
  123793. }
  123794. zSql += 2;
  123795. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  123796. if( zSql[0]==0 ) return 0;
  123797. zSql++;
  123798. token = tkWS;
  123799. break;
  123800. }
  123801. case '-': { /* SQL-style comments from "--" to end of line */
  123802. if( zSql[1]!='-' ){
  123803. token = tkOTHER;
  123804. break;
  123805. }
  123806. while( *zSql && *zSql!='\n' ){ zSql++; }
  123807. if( *zSql==0 ) return state==1;
  123808. token = tkWS;
  123809. break;
  123810. }
  123811. case '[': { /* Microsoft-style identifiers in [...] */
  123812. zSql++;
  123813. while( *zSql && *zSql!=']' ){ zSql++; }
  123814. if( *zSql==0 ) return 0;
  123815. token = tkOTHER;
  123816. break;
  123817. }
  123818. case '`': /* Grave-accent quoted symbols used by MySQL */
  123819. case '"': /* single- and double-quoted strings */
  123820. case '\'': {
  123821. int c = *zSql;
  123822. zSql++;
  123823. while( *zSql && *zSql!=c ){ zSql++; }
  123824. if( *zSql==0 ) return 0;
  123825. token = tkOTHER;
  123826. break;
  123827. }
  123828. default: {
  123829. #ifdef SQLITE_EBCDIC
  123830. unsigned char c;
  123831. #endif
  123832. if( IdChar((u8)*zSql) ){
  123833. /* Keywords and unquoted identifiers */
  123834. int nId;
  123835. for(nId=1; IdChar(zSql[nId]); nId++){}
  123836. #ifdef SQLITE_OMIT_TRIGGER
  123837. token = tkOTHER;
  123838. #else
  123839. switch( *zSql ){
  123840. case 'c': case 'C': {
  123841. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  123842. token = tkCREATE;
  123843. }else{
  123844. token = tkOTHER;
  123845. }
  123846. break;
  123847. }
  123848. case 't': case 'T': {
  123849. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  123850. token = tkTRIGGER;
  123851. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  123852. token = tkTEMP;
  123853. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  123854. token = tkTEMP;
  123855. }else{
  123856. token = tkOTHER;
  123857. }
  123858. break;
  123859. }
  123860. case 'e': case 'E': {
  123861. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  123862. token = tkEND;
  123863. }else
  123864. #ifndef SQLITE_OMIT_EXPLAIN
  123865. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  123866. token = tkEXPLAIN;
  123867. }else
  123868. #endif
  123869. {
  123870. token = tkOTHER;
  123871. }
  123872. break;
  123873. }
  123874. default: {
  123875. token = tkOTHER;
  123876. break;
  123877. }
  123878. }
  123879. #endif /* SQLITE_OMIT_TRIGGER */
  123880. zSql += nId-1;
  123881. }else{
  123882. /* Operators and special symbols */
  123883. token = tkOTHER;
  123884. }
  123885. break;
  123886. }
  123887. }
  123888. state = trans[state][token];
  123889. zSql++;
  123890. }
  123891. return state==1;
  123892. }
  123893. #ifndef SQLITE_OMIT_UTF16
  123894. /*
  123895. ** This routine is the same as the sqlite3_complete() routine described
  123896. ** above, except that the parameter is required to be UTF-16 encoded, not
  123897. ** UTF-8.
  123898. */
  123899. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
  123900. sqlite3_value *pVal;
  123901. char const *zSql8;
  123902. int rc;
  123903. #ifndef SQLITE_OMIT_AUTOINIT
  123904. rc = sqlite3_initialize();
  123905. if( rc ) return rc;
  123906. #endif
  123907. pVal = sqlite3ValueNew(0);
  123908. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  123909. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  123910. if( zSql8 ){
  123911. rc = sqlite3_complete(zSql8);
  123912. }else{
  123913. rc = SQLITE_NOMEM;
  123914. }
  123915. sqlite3ValueFree(pVal);
  123916. return rc & 0xff;
  123917. }
  123918. #endif /* SQLITE_OMIT_UTF16 */
  123919. #endif /* SQLITE_OMIT_COMPLETE */
  123920. /************** End of complete.c ********************************************/
  123921. /************** Begin file main.c ********************************************/
  123922. /*
  123923. ** 2001 September 15
  123924. **
  123925. ** The author disclaims copyright to this source code. In place of
  123926. ** a legal notice, here is a blessing:
  123927. **
  123928. ** May you do good and not evil.
  123929. ** May you find forgiveness for yourself and forgive others.
  123930. ** May you share freely, never taking more than you give.
  123931. **
  123932. *************************************************************************
  123933. ** Main file for the SQLite library. The routines in this file
  123934. ** implement the programmer interface to the library. Routines in
  123935. ** other files are for internal use by SQLite and should not be
  123936. ** accessed by users of the library.
  123937. */
  123938. /* #include "sqliteInt.h" */
  123939. #ifdef SQLITE_ENABLE_FTS3
  123940. /************** Include fts3.h in the middle of main.c ***********************/
  123941. /************** Begin file fts3.h ********************************************/
  123942. /*
  123943. ** 2006 Oct 10
  123944. **
  123945. ** The author disclaims copyright to this source code. In place of
  123946. ** a legal notice, here is a blessing:
  123947. **
  123948. ** May you do good and not evil.
  123949. ** May you find forgiveness for yourself and forgive others.
  123950. ** May you share freely, never taking more than you give.
  123951. **
  123952. ******************************************************************************
  123953. **
  123954. ** This header file is used by programs that want to link against the
  123955. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  123956. */
  123957. /* #include "sqlite3.h" */
  123958. #if 0
  123959. extern "C" {
  123960. #endif /* __cplusplus */
  123961. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  123962. #if 0
  123963. } /* extern "C" */
  123964. #endif /* __cplusplus */
  123965. /************** End of fts3.h ************************************************/
  123966. /************** Continuing where we left off in main.c ***********************/
  123967. #endif
  123968. #ifdef SQLITE_ENABLE_RTREE
  123969. /************** Include rtree.h in the middle of main.c **********************/
  123970. /************** Begin file rtree.h *******************************************/
  123971. /*
  123972. ** 2008 May 26
  123973. **
  123974. ** The author disclaims copyright to this source code. In place of
  123975. ** a legal notice, here is a blessing:
  123976. **
  123977. ** May you do good and not evil.
  123978. ** May you find forgiveness for yourself and forgive others.
  123979. ** May you share freely, never taking more than you give.
  123980. **
  123981. ******************************************************************************
  123982. **
  123983. ** This header file is used by programs that want to link against the
  123984. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  123985. */
  123986. /* #include "sqlite3.h" */
  123987. #if 0
  123988. extern "C" {
  123989. #endif /* __cplusplus */
  123990. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  123991. #if 0
  123992. } /* extern "C" */
  123993. #endif /* __cplusplus */
  123994. /************** End of rtree.h ***********************************************/
  123995. /************** Continuing where we left off in main.c ***********************/
  123996. #endif
  123997. #ifdef SQLITE_ENABLE_ICU
  123998. /************** Include sqliteicu.h in the middle of main.c ******************/
  123999. /************** Begin file sqliteicu.h ***************************************/
  124000. /*
  124001. ** 2008 May 26
  124002. **
  124003. ** The author disclaims copyright to this source code. In place of
  124004. ** a legal notice, here is a blessing:
  124005. **
  124006. ** May you do good and not evil.
  124007. ** May you find forgiveness for yourself and forgive others.
  124008. ** May you share freely, never taking more than you give.
  124009. **
  124010. ******************************************************************************
  124011. **
  124012. ** This header file is used by programs that want to link against the
  124013. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  124014. */
  124015. /* #include "sqlite3.h" */
  124016. #if 0
  124017. extern "C" {
  124018. #endif /* __cplusplus */
  124019. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  124020. #if 0
  124021. } /* extern "C" */
  124022. #endif /* __cplusplus */
  124023. /************** End of sqliteicu.h *******************************************/
  124024. /************** Continuing where we left off in main.c ***********************/
  124025. #endif
  124026. #ifdef SQLITE_ENABLE_JSON1
  124027. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  124028. #endif
  124029. #ifdef SQLITE_ENABLE_FTS5
  124030. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  124031. #endif
  124032. #ifndef SQLITE_AMALGAMATION
  124033. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  124034. ** contains the text of SQLITE_VERSION macro.
  124035. */
  124036. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  124037. #endif
  124038. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  124039. ** a pointer to the to the sqlite3_version[] string constant.
  124040. */
  124041. SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
  124042. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  124043. ** pointer to a string constant whose value is the same as the
  124044. ** SQLITE_SOURCE_ID C preprocessor macro.
  124045. */
  124046. SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  124047. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  124048. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  124049. */
  124050. SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  124051. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  124052. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  124053. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  124054. */
  124055. SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  124056. /*
  124057. ** When compiling the test fixture or with debugging enabled (on Win32),
  124058. ** this variable being set to non-zero will cause OSTRACE macros to emit
  124059. ** extra diagnostic information.
  124060. */
  124061. #ifdef SQLITE_HAVE_OS_TRACE
  124062. # ifndef SQLITE_DEBUG_OS_TRACE
  124063. # define SQLITE_DEBUG_OS_TRACE 0
  124064. # endif
  124065. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  124066. #endif
  124067. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  124068. /*
  124069. ** If the following function pointer is not NULL and if
  124070. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  124071. ** I/O active are written using this function. These messages
  124072. ** are intended for debugging activity only.
  124073. */
  124074. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  124075. #endif
  124076. /*
  124077. ** If the following global variable points to a string which is the
  124078. ** name of a directory, then that directory will be used to store
  124079. ** temporary files.
  124080. **
  124081. ** See also the "PRAGMA temp_store_directory" SQL command.
  124082. */
  124083. SQLITE_API char *sqlite3_temp_directory = 0;
  124084. /*
  124085. ** If the following global variable points to a string which is the
  124086. ** name of a directory, then that directory will be used to store
  124087. ** all database files specified with a relative pathname.
  124088. **
  124089. ** See also the "PRAGMA data_store_directory" SQL command.
  124090. */
  124091. SQLITE_API char *sqlite3_data_directory = 0;
  124092. /*
  124093. ** Initialize SQLite.
  124094. **
  124095. ** This routine must be called to initialize the memory allocation,
  124096. ** VFS, and mutex subsystems prior to doing any serious work with
  124097. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  124098. ** this routine will be called automatically by key routines such as
  124099. ** sqlite3_open().
  124100. **
  124101. ** This routine is a no-op except on its very first call for the process,
  124102. ** or for the first call after a call to sqlite3_shutdown.
  124103. **
  124104. ** The first thread to call this routine runs the initialization to
  124105. ** completion. If subsequent threads call this routine before the first
  124106. ** thread has finished the initialization process, then the subsequent
  124107. ** threads must block until the first thread finishes with the initialization.
  124108. **
  124109. ** The first thread might call this routine recursively. Recursive
  124110. ** calls to this routine should not block, of course. Otherwise the
  124111. ** initialization process would never complete.
  124112. **
  124113. ** Let X be the first thread to enter this routine. Let Y be some other
  124114. ** thread. Then while the initial invocation of this routine by X is
  124115. ** incomplete, it is required that:
  124116. **
  124117. ** * Calls to this routine from Y must block until the outer-most
  124118. ** call by X completes.
  124119. **
  124120. ** * Recursive calls to this routine from thread X return immediately
  124121. ** without blocking.
  124122. */
  124123. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
  124124. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  124125. int rc; /* Result code */
  124126. #ifdef SQLITE_EXTRA_INIT
  124127. int bRunExtraInit = 0; /* Extra initialization needed */
  124128. #endif
  124129. #ifdef SQLITE_OMIT_WSD
  124130. rc = sqlite3_wsd_init(4096, 24);
  124131. if( rc!=SQLITE_OK ){
  124132. return rc;
  124133. }
  124134. #endif
  124135. /* If the following assert() fails on some obscure processor/compiler
  124136. ** combination, the work-around is to set the correct pointer
  124137. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  124138. assert( SQLITE_PTRSIZE==sizeof(char*) );
  124139. /* If SQLite is already completely initialized, then this call
  124140. ** to sqlite3_initialize() should be a no-op. But the initialization
  124141. ** must be complete. So isInit must not be set until the very end
  124142. ** of this routine.
  124143. */
  124144. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  124145. /* Make sure the mutex subsystem is initialized. If unable to
  124146. ** initialize the mutex subsystem, return early with the error.
  124147. ** If the system is so sick that we are unable to allocate a mutex,
  124148. ** there is not much SQLite is going to be able to do.
  124149. **
  124150. ** The mutex subsystem must take care of serializing its own
  124151. ** initialization.
  124152. */
  124153. rc = sqlite3MutexInit();
  124154. if( rc ) return rc;
  124155. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  124156. ** This operation is protected by the STATIC_MASTER mutex. Note that
  124157. ** MutexAlloc() is called for a static mutex prior to initializing the
  124158. ** malloc subsystem - this implies that the allocation of a static
  124159. ** mutex must not require support from the malloc subsystem.
  124160. */
  124161. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  124162. sqlite3_mutex_enter(pMaster);
  124163. sqlite3GlobalConfig.isMutexInit = 1;
  124164. if( !sqlite3GlobalConfig.isMallocInit ){
  124165. rc = sqlite3MallocInit();
  124166. }
  124167. if( rc==SQLITE_OK ){
  124168. sqlite3GlobalConfig.isMallocInit = 1;
  124169. if( !sqlite3GlobalConfig.pInitMutex ){
  124170. sqlite3GlobalConfig.pInitMutex =
  124171. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  124172. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  124173. rc = SQLITE_NOMEM;
  124174. }
  124175. }
  124176. }
  124177. if( rc==SQLITE_OK ){
  124178. sqlite3GlobalConfig.nRefInitMutex++;
  124179. }
  124180. sqlite3_mutex_leave(pMaster);
  124181. /* If rc is not SQLITE_OK at this point, then either the malloc
  124182. ** subsystem could not be initialized or the system failed to allocate
  124183. ** the pInitMutex mutex. Return an error in either case. */
  124184. if( rc!=SQLITE_OK ){
  124185. return rc;
  124186. }
  124187. /* Do the rest of the initialization under the recursive mutex so
  124188. ** that we will be able to handle recursive calls into
  124189. ** sqlite3_initialize(). The recursive calls normally come through
  124190. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  124191. ** recursive calls might also be possible.
  124192. **
  124193. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  124194. ** to the xInit method, so the xInit method need not be threadsafe.
  124195. **
  124196. ** The following mutex is what serializes access to the appdef pcache xInit
  124197. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  124198. ** call to sqlite3PcacheInitialize().
  124199. */
  124200. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  124201. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  124202. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  124203. sqlite3GlobalConfig.inProgress = 1;
  124204. #ifdef SQLITE_ENABLE_SQLLOG
  124205. {
  124206. extern void sqlite3_init_sqllog(void);
  124207. sqlite3_init_sqllog();
  124208. }
  124209. #endif
  124210. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  124211. sqlite3RegisterGlobalFunctions();
  124212. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  124213. rc = sqlite3PcacheInitialize();
  124214. }
  124215. if( rc==SQLITE_OK ){
  124216. sqlite3GlobalConfig.isPCacheInit = 1;
  124217. rc = sqlite3OsInit();
  124218. }
  124219. if( rc==SQLITE_OK ){
  124220. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  124221. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  124222. sqlite3GlobalConfig.isInit = 1;
  124223. #ifdef SQLITE_EXTRA_INIT
  124224. bRunExtraInit = 1;
  124225. #endif
  124226. }
  124227. sqlite3GlobalConfig.inProgress = 0;
  124228. }
  124229. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  124230. /* Go back under the static mutex and clean up the recursive
  124231. ** mutex to prevent a resource leak.
  124232. */
  124233. sqlite3_mutex_enter(pMaster);
  124234. sqlite3GlobalConfig.nRefInitMutex--;
  124235. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  124236. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  124237. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  124238. sqlite3GlobalConfig.pInitMutex = 0;
  124239. }
  124240. sqlite3_mutex_leave(pMaster);
  124241. /* The following is just a sanity check to make sure SQLite has
  124242. ** been compiled correctly. It is important to run this code, but
  124243. ** we don't want to run it too often and soak up CPU cycles for no
  124244. ** reason. So we run it once during initialization.
  124245. */
  124246. #ifndef NDEBUG
  124247. #ifndef SQLITE_OMIT_FLOATING_POINT
  124248. /* This section of code's only "output" is via assert() statements. */
  124249. if ( rc==SQLITE_OK ){
  124250. u64 x = (((u64)1)<<63)-1;
  124251. double y;
  124252. assert(sizeof(x)==8);
  124253. assert(sizeof(x)==sizeof(y));
  124254. memcpy(&y, &x, 8);
  124255. assert( sqlite3IsNaN(y) );
  124256. }
  124257. #endif
  124258. #endif
  124259. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  124260. ** compile-time option.
  124261. */
  124262. #ifdef SQLITE_EXTRA_INIT
  124263. if( bRunExtraInit ){
  124264. int SQLITE_EXTRA_INIT(const char*);
  124265. rc = SQLITE_EXTRA_INIT(0);
  124266. }
  124267. #endif
  124268. return rc;
  124269. }
  124270. /*
  124271. ** Undo the effects of sqlite3_initialize(). Must not be called while
  124272. ** there are outstanding database connections or memory allocations or
  124273. ** while any part of SQLite is otherwise in use in any thread. This
  124274. ** routine is not threadsafe. But it is safe to invoke this routine
  124275. ** on when SQLite is already shut down. If SQLite is already shut down
  124276. ** when this routine is invoked, then this routine is a harmless no-op.
  124277. */
  124278. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
  124279. #ifdef SQLITE_OMIT_WSD
  124280. int rc = sqlite3_wsd_init(4096, 24);
  124281. if( rc!=SQLITE_OK ){
  124282. return rc;
  124283. }
  124284. #endif
  124285. if( sqlite3GlobalConfig.isInit ){
  124286. #ifdef SQLITE_EXTRA_SHUTDOWN
  124287. void SQLITE_EXTRA_SHUTDOWN(void);
  124288. SQLITE_EXTRA_SHUTDOWN();
  124289. #endif
  124290. sqlite3_os_end();
  124291. sqlite3_reset_auto_extension();
  124292. sqlite3GlobalConfig.isInit = 0;
  124293. }
  124294. if( sqlite3GlobalConfig.isPCacheInit ){
  124295. sqlite3PcacheShutdown();
  124296. sqlite3GlobalConfig.isPCacheInit = 0;
  124297. }
  124298. if( sqlite3GlobalConfig.isMallocInit ){
  124299. sqlite3MallocEnd();
  124300. sqlite3GlobalConfig.isMallocInit = 0;
  124301. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  124302. /* The heap subsystem has now been shutdown and these values are supposed
  124303. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  124304. ** which would rely on that heap subsystem; therefore, make sure these
  124305. ** values cannot refer to heap memory that was just invalidated when the
  124306. ** heap subsystem was shutdown. This is only done if the current call to
  124307. ** this function resulted in the heap subsystem actually being shutdown.
  124308. */
  124309. sqlite3_data_directory = 0;
  124310. sqlite3_temp_directory = 0;
  124311. #endif
  124312. }
  124313. if( sqlite3GlobalConfig.isMutexInit ){
  124314. sqlite3MutexEnd();
  124315. sqlite3GlobalConfig.isMutexInit = 0;
  124316. }
  124317. return SQLITE_OK;
  124318. }
  124319. /*
  124320. ** This API allows applications to modify the global configuration of
  124321. ** the SQLite library at run-time.
  124322. **
  124323. ** This routine should only be called when there are no outstanding
  124324. ** database connections or memory allocations. This routine is not
  124325. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  124326. ** behavior.
  124327. */
  124328. SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
  124329. va_list ap;
  124330. int rc = SQLITE_OK;
  124331. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  124332. ** the SQLite library is in use. */
  124333. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  124334. va_start(ap, op);
  124335. switch( op ){
  124336. /* Mutex configuration options are only available in a threadsafe
  124337. ** compile.
  124338. */
  124339. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  124340. case SQLITE_CONFIG_SINGLETHREAD: {
  124341. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  124342. ** Single-thread. */
  124343. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  124344. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  124345. break;
  124346. }
  124347. #endif
  124348. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  124349. case SQLITE_CONFIG_MULTITHREAD: {
  124350. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  124351. ** Multi-thread. */
  124352. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  124353. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  124354. break;
  124355. }
  124356. #endif
  124357. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  124358. case SQLITE_CONFIG_SERIALIZED: {
  124359. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  124360. ** Serialized. */
  124361. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  124362. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  124363. break;
  124364. }
  124365. #endif
  124366. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  124367. case SQLITE_CONFIG_MUTEX: {
  124368. /* Specify an alternative mutex implementation */
  124369. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  124370. break;
  124371. }
  124372. #endif
  124373. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  124374. case SQLITE_CONFIG_GETMUTEX: {
  124375. /* Retrieve the current mutex implementation */
  124376. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  124377. break;
  124378. }
  124379. #endif
  124380. case SQLITE_CONFIG_MALLOC: {
  124381. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  124382. ** single argument which is a pointer to an instance of the
  124383. ** sqlite3_mem_methods structure. The argument specifies alternative
  124384. ** low-level memory allocation routines to be used in place of the memory
  124385. ** allocation routines built into SQLite. */
  124386. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  124387. break;
  124388. }
  124389. case SQLITE_CONFIG_GETMALLOC: {
  124390. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  124391. ** single argument which is a pointer to an instance of the
  124392. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  124393. ** filled with the currently defined memory allocation routines. */
  124394. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  124395. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  124396. break;
  124397. }
  124398. case SQLITE_CONFIG_MEMSTATUS: {
  124399. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  124400. ** single argument of type int, interpreted as a boolean, which enables
  124401. ** or disables the collection of memory allocation statistics. */
  124402. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  124403. break;
  124404. }
  124405. case SQLITE_CONFIG_SCRATCH: {
  124406. /* EVIDENCE-OF: R-08404-60887 There are three arguments to
  124407. ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
  124408. ** which the scratch allocations will be drawn, the size of each scratch
  124409. ** allocation (sz), and the maximum number of scratch allocations (N). */
  124410. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  124411. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  124412. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  124413. break;
  124414. }
  124415. case SQLITE_CONFIG_PAGECACHE: {
  124416. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  124417. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  124418. ** the size of each page cache line (sz), and the number of cache lines
  124419. ** (N). */
  124420. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  124421. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  124422. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  124423. break;
  124424. }
  124425. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  124426. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  124427. ** a single parameter which is a pointer to an integer and writes into
  124428. ** that integer the number of extra bytes per page required for each page
  124429. ** in SQLITE_CONFIG_PAGECACHE. */
  124430. *va_arg(ap, int*) =
  124431. sqlite3HeaderSizeBtree() +
  124432. sqlite3HeaderSizePcache() +
  124433. sqlite3HeaderSizePcache1();
  124434. break;
  124435. }
  124436. case SQLITE_CONFIG_PCACHE: {
  124437. /* no-op */
  124438. break;
  124439. }
  124440. case SQLITE_CONFIG_GETPCACHE: {
  124441. /* now an error */
  124442. rc = SQLITE_ERROR;
  124443. break;
  124444. }
  124445. case SQLITE_CONFIG_PCACHE2: {
  124446. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  124447. ** single argument which is a pointer to an sqlite3_pcache_methods2
  124448. ** object. This object specifies the interface to a custom page cache
  124449. ** implementation. */
  124450. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  124451. break;
  124452. }
  124453. case SQLITE_CONFIG_GETPCACHE2: {
  124454. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  124455. ** single argument which is a pointer to an sqlite3_pcache_methods2
  124456. ** object. SQLite copies of the current page cache implementation into
  124457. ** that object. */
  124458. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  124459. sqlite3PCacheSetDefault();
  124460. }
  124461. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  124462. break;
  124463. }
  124464. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  124465. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  124466. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  124467. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  124468. case SQLITE_CONFIG_HEAP: {
  124469. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  124470. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  124471. ** number of bytes in the memory buffer, and the minimum allocation size.
  124472. */
  124473. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  124474. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  124475. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  124476. if( sqlite3GlobalConfig.mnReq<1 ){
  124477. sqlite3GlobalConfig.mnReq = 1;
  124478. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  124479. /* cap min request size at 2^12 */
  124480. sqlite3GlobalConfig.mnReq = (1<<12);
  124481. }
  124482. if( sqlite3GlobalConfig.pHeap==0 ){
  124483. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  124484. ** is NULL, then SQLite reverts to using its default memory allocator
  124485. ** (the system malloc() implementation), undoing any prior invocation of
  124486. ** SQLITE_CONFIG_MALLOC.
  124487. **
  124488. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  124489. ** revert to its default implementation when sqlite3_initialize() is run
  124490. */
  124491. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  124492. }else{
  124493. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  124494. ** alternative memory allocator is engaged to handle all of SQLites
  124495. ** memory allocation needs. */
  124496. #ifdef SQLITE_ENABLE_MEMSYS3
  124497. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  124498. #endif
  124499. #ifdef SQLITE_ENABLE_MEMSYS5
  124500. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  124501. #endif
  124502. }
  124503. break;
  124504. }
  124505. #endif
  124506. case SQLITE_CONFIG_LOOKASIDE: {
  124507. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  124508. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  124509. break;
  124510. }
  124511. /* Record a pointer to the logger function and its first argument.
  124512. ** The default is NULL. Logging is disabled if the function pointer is
  124513. ** NULL.
  124514. */
  124515. case SQLITE_CONFIG_LOG: {
  124516. /* MSVC is picky about pulling func ptrs from va lists.
  124517. ** http://support.microsoft.com/kb/47961
  124518. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  124519. */
  124520. typedef void(*LOGFUNC_t)(void*,int,const char*);
  124521. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  124522. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  124523. break;
  124524. }
  124525. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  124526. ** can be changed at start-time using the
  124527. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  124528. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  124529. */
  124530. case SQLITE_CONFIG_URI: {
  124531. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  124532. ** argument of type int. If non-zero, then URI handling is globally
  124533. ** enabled. If the parameter is zero, then URI handling is globally
  124534. ** disabled. */
  124535. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  124536. break;
  124537. }
  124538. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  124539. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  124540. ** option takes a single integer argument which is interpreted as a
  124541. ** boolean in order to enable or disable the use of covering indices for
  124542. ** full table scans in the query optimizer. */
  124543. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  124544. break;
  124545. }
  124546. #ifdef SQLITE_ENABLE_SQLLOG
  124547. case SQLITE_CONFIG_SQLLOG: {
  124548. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  124549. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  124550. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  124551. break;
  124552. }
  124553. #endif
  124554. case SQLITE_CONFIG_MMAP_SIZE: {
  124555. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  124556. ** integer (sqlite3_int64) values that are the default mmap size limit
  124557. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  124558. ** mmap size limit. */
  124559. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  124560. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  124561. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  124562. ** negative, then that argument is changed to its compile-time default.
  124563. **
  124564. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  124565. ** silently truncated if necessary so that it does not exceed the
  124566. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  124567. ** compile-time option.
  124568. */
  124569. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  124570. mxMmap = SQLITE_MAX_MMAP_SIZE;
  124571. }
  124572. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  124573. if( szMmap>mxMmap) szMmap = mxMmap;
  124574. sqlite3GlobalConfig.mxMmap = mxMmap;
  124575. sqlite3GlobalConfig.szMmap = szMmap;
  124576. break;
  124577. }
  124578. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  124579. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  124580. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  124581. ** unsigned integer value that specifies the maximum size of the created
  124582. ** heap. */
  124583. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  124584. break;
  124585. }
  124586. #endif
  124587. case SQLITE_CONFIG_PMASZ: {
  124588. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  124589. break;
  124590. }
  124591. default: {
  124592. rc = SQLITE_ERROR;
  124593. break;
  124594. }
  124595. }
  124596. va_end(ap);
  124597. return rc;
  124598. }
  124599. /*
  124600. ** Set up the lookaside buffers for a database connection.
  124601. ** Return SQLITE_OK on success.
  124602. ** If lookaside is already active, return SQLITE_BUSY.
  124603. **
  124604. ** The sz parameter is the number of bytes in each lookaside slot.
  124605. ** The cnt parameter is the number of slots. If pStart is NULL the
  124606. ** space for the lookaside memory is obtained from sqlite3_malloc().
  124607. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  124608. ** the lookaside memory.
  124609. */
  124610. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  124611. #ifndef SQLITE_OMIT_LOOKASIDE
  124612. void *pStart;
  124613. if( db->lookaside.nOut ){
  124614. return SQLITE_BUSY;
  124615. }
  124616. /* Free any existing lookaside buffer for this handle before
  124617. ** allocating a new one so we don't have to have space for
  124618. ** both at the same time.
  124619. */
  124620. if( db->lookaside.bMalloced ){
  124621. sqlite3_free(db->lookaside.pStart);
  124622. }
  124623. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  124624. ** than a pointer to be useful.
  124625. */
  124626. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  124627. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  124628. if( cnt<0 ) cnt = 0;
  124629. if( sz==0 || cnt==0 ){
  124630. sz = 0;
  124631. pStart = 0;
  124632. }else if( pBuf==0 ){
  124633. sqlite3BeginBenignMalloc();
  124634. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  124635. sqlite3EndBenignMalloc();
  124636. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  124637. }else{
  124638. pStart = pBuf;
  124639. }
  124640. db->lookaside.pStart = pStart;
  124641. db->lookaside.pFree = 0;
  124642. db->lookaside.sz = (u16)sz;
  124643. if( pStart ){
  124644. int i;
  124645. LookasideSlot *p;
  124646. assert( sz > (int)sizeof(LookasideSlot*) );
  124647. p = (LookasideSlot*)pStart;
  124648. for(i=cnt-1; i>=0; i--){
  124649. p->pNext = db->lookaside.pFree;
  124650. db->lookaside.pFree = p;
  124651. p = (LookasideSlot*)&((u8*)p)[sz];
  124652. }
  124653. db->lookaside.pEnd = p;
  124654. db->lookaside.bEnabled = 1;
  124655. db->lookaside.bMalloced = pBuf==0 ?1:0;
  124656. }else{
  124657. db->lookaside.pStart = db;
  124658. db->lookaside.pEnd = db;
  124659. db->lookaside.bEnabled = 0;
  124660. db->lookaside.bMalloced = 0;
  124661. }
  124662. #endif /* SQLITE_OMIT_LOOKASIDE */
  124663. return SQLITE_OK;
  124664. }
  124665. /*
  124666. ** Return the mutex associated with a database connection.
  124667. */
  124668. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
  124669. #ifdef SQLITE_ENABLE_API_ARMOR
  124670. if( !sqlite3SafetyCheckOk(db) ){
  124671. (void)SQLITE_MISUSE_BKPT;
  124672. return 0;
  124673. }
  124674. #endif
  124675. return db->mutex;
  124676. }
  124677. /*
  124678. ** Free up as much memory as we can from the given database
  124679. ** connection.
  124680. */
  124681. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
  124682. int i;
  124683. #ifdef SQLITE_ENABLE_API_ARMOR
  124684. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124685. #endif
  124686. sqlite3_mutex_enter(db->mutex);
  124687. sqlite3BtreeEnterAll(db);
  124688. for(i=0; i<db->nDb; i++){
  124689. Btree *pBt = db->aDb[i].pBt;
  124690. if( pBt ){
  124691. Pager *pPager = sqlite3BtreePager(pBt);
  124692. sqlite3PagerShrink(pPager);
  124693. }
  124694. }
  124695. sqlite3BtreeLeaveAll(db);
  124696. sqlite3_mutex_leave(db->mutex);
  124697. return SQLITE_OK;
  124698. }
  124699. /*
  124700. ** Flush any dirty pages in the pager-cache for any attached database
  124701. ** to disk.
  124702. */
  124703. SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3 *db){
  124704. int i;
  124705. int rc = SQLITE_OK;
  124706. int bSeenBusy = 0;
  124707. #ifdef SQLITE_ENABLE_API_ARMOR
  124708. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124709. #endif
  124710. sqlite3_mutex_enter(db->mutex);
  124711. sqlite3BtreeEnterAll(db);
  124712. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  124713. Btree *pBt = db->aDb[i].pBt;
  124714. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  124715. Pager *pPager = sqlite3BtreePager(pBt);
  124716. rc = sqlite3PagerFlush(pPager);
  124717. if( rc==SQLITE_BUSY ){
  124718. bSeenBusy = 1;
  124719. rc = SQLITE_OK;
  124720. }
  124721. }
  124722. }
  124723. sqlite3BtreeLeaveAll(db);
  124724. sqlite3_mutex_leave(db->mutex);
  124725. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  124726. }
  124727. /*
  124728. ** Configuration settings for an individual database connection
  124729. */
  124730. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
  124731. va_list ap;
  124732. int rc;
  124733. va_start(ap, op);
  124734. switch( op ){
  124735. case SQLITE_DBCONFIG_LOOKASIDE: {
  124736. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  124737. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  124738. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  124739. rc = setupLookaside(db, pBuf, sz, cnt);
  124740. break;
  124741. }
  124742. default: {
  124743. static const struct {
  124744. int op; /* The opcode */
  124745. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  124746. } aFlagOp[] = {
  124747. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  124748. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  124749. };
  124750. unsigned int i;
  124751. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  124752. for(i=0; i<ArraySize(aFlagOp); i++){
  124753. if( aFlagOp[i].op==op ){
  124754. int onoff = va_arg(ap, int);
  124755. int *pRes = va_arg(ap, int*);
  124756. int oldFlags = db->flags;
  124757. if( onoff>0 ){
  124758. db->flags |= aFlagOp[i].mask;
  124759. }else if( onoff==0 ){
  124760. db->flags &= ~aFlagOp[i].mask;
  124761. }
  124762. if( oldFlags!=db->flags ){
  124763. sqlite3ExpirePreparedStatements(db);
  124764. }
  124765. if( pRes ){
  124766. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  124767. }
  124768. rc = SQLITE_OK;
  124769. break;
  124770. }
  124771. }
  124772. break;
  124773. }
  124774. }
  124775. va_end(ap);
  124776. return rc;
  124777. }
  124778. /*
  124779. ** Return true if the buffer z[0..n-1] contains all spaces.
  124780. */
  124781. static int allSpaces(const char *z, int n){
  124782. while( n>0 && z[n-1]==' ' ){ n--; }
  124783. return n==0;
  124784. }
  124785. /*
  124786. ** This is the default collating function named "BINARY" which is always
  124787. ** available.
  124788. **
  124789. ** If the padFlag argument is not NULL then space padding at the end
  124790. ** of strings is ignored. This implements the RTRIM collation.
  124791. */
  124792. static int binCollFunc(
  124793. void *padFlag,
  124794. int nKey1, const void *pKey1,
  124795. int nKey2, const void *pKey2
  124796. ){
  124797. int rc, n;
  124798. n = nKey1<nKey2 ? nKey1 : nKey2;
  124799. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  124800. ** strings byte by byte using the memcmp() function from the standard C
  124801. ** library. */
  124802. rc = memcmp(pKey1, pKey2, n);
  124803. if( rc==0 ){
  124804. if( padFlag
  124805. && allSpaces(((char*)pKey1)+n, nKey1-n)
  124806. && allSpaces(((char*)pKey2)+n, nKey2-n)
  124807. ){
  124808. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  124809. ** spaces at the end of either string do not change the result. In other
  124810. ** words, strings will compare equal to one another as long as they
  124811. ** differ only in the number of spaces at the end.
  124812. */
  124813. }else{
  124814. rc = nKey1 - nKey2;
  124815. }
  124816. }
  124817. return rc;
  124818. }
  124819. /*
  124820. ** Another built-in collating sequence: NOCASE.
  124821. **
  124822. ** This collating sequence is intended to be used for "case independent
  124823. ** comparison". SQLite's knowledge of upper and lower case equivalents
  124824. ** extends only to the 26 characters used in the English language.
  124825. **
  124826. ** At the moment there is only a UTF-8 implementation.
  124827. */
  124828. static int nocaseCollatingFunc(
  124829. void *NotUsed,
  124830. int nKey1, const void *pKey1,
  124831. int nKey2, const void *pKey2
  124832. ){
  124833. int r = sqlite3StrNICmp(
  124834. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  124835. UNUSED_PARAMETER(NotUsed);
  124836. if( 0==r ){
  124837. r = nKey1-nKey2;
  124838. }
  124839. return r;
  124840. }
  124841. /*
  124842. ** Return the ROWID of the most recent insert
  124843. */
  124844. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
  124845. #ifdef SQLITE_ENABLE_API_ARMOR
  124846. if( !sqlite3SafetyCheckOk(db) ){
  124847. (void)SQLITE_MISUSE_BKPT;
  124848. return 0;
  124849. }
  124850. #endif
  124851. return db->lastRowid;
  124852. }
  124853. /*
  124854. ** Return the number of changes in the most recent call to sqlite3_exec().
  124855. */
  124856. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
  124857. #ifdef SQLITE_ENABLE_API_ARMOR
  124858. if( !sqlite3SafetyCheckOk(db) ){
  124859. (void)SQLITE_MISUSE_BKPT;
  124860. return 0;
  124861. }
  124862. #endif
  124863. return db->nChange;
  124864. }
  124865. /*
  124866. ** Return the number of changes since the database handle was opened.
  124867. */
  124868. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
  124869. #ifdef SQLITE_ENABLE_API_ARMOR
  124870. if( !sqlite3SafetyCheckOk(db) ){
  124871. (void)SQLITE_MISUSE_BKPT;
  124872. return 0;
  124873. }
  124874. #endif
  124875. return db->nTotalChange;
  124876. }
  124877. /*
  124878. ** Close all open savepoints. This function only manipulates fields of the
  124879. ** database handle object, it does not close any savepoints that may be open
  124880. ** at the b-tree/pager level.
  124881. */
  124882. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  124883. while( db->pSavepoint ){
  124884. Savepoint *pTmp = db->pSavepoint;
  124885. db->pSavepoint = pTmp->pNext;
  124886. sqlite3DbFree(db, pTmp);
  124887. }
  124888. db->nSavepoint = 0;
  124889. db->nStatement = 0;
  124890. db->isTransactionSavepoint = 0;
  124891. }
  124892. /*
  124893. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  124894. ** if this is not the last copy of the function, do not invoke it. Multiple
  124895. ** copies of a single function are created when create_function() is called
  124896. ** with SQLITE_ANY as the encoding.
  124897. */
  124898. static void functionDestroy(sqlite3 *db, FuncDef *p){
  124899. FuncDestructor *pDestructor = p->pDestructor;
  124900. if( pDestructor ){
  124901. pDestructor->nRef--;
  124902. if( pDestructor->nRef==0 ){
  124903. pDestructor->xDestroy(pDestructor->pUserData);
  124904. sqlite3DbFree(db, pDestructor);
  124905. }
  124906. }
  124907. }
  124908. /*
  124909. ** Disconnect all sqlite3_vtab objects that belong to database connection
  124910. ** db. This is called when db is being closed.
  124911. */
  124912. static void disconnectAllVtab(sqlite3 *db){
  124913. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124914. int i;
  124915. HashElem *p;
  124916. sqlite3BtreeEnterAll(db);
  124917. for(i=0; i<db->nDb; i++){
  124918. Schema *pSchema = db->aDb[i].pSchema;
  124919. if( db->aDb[i].pSchema ){
  124920. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  124921. Table *pTab = (Table *)sqliteHashData(p);
  124922. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  124923. }
  124924. }
  124925. }
  124926. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  124927. Module *pMod = (Module *)sqliteHashData(p);
  124928. if( pMod->pEpoTab ){
  124929. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  124930. }
  124931. }
  124932. sqlite3VtabUnlockList(db);
  124933. sqlite3BtreeLeaveAll(db);
  124934. #else
  124935. UNUSED_PARAMETER(db);
  124936. #endif
  124937. }
  124938. /*
  124939. ** Return TRUE if database connection db has unfinalized prepared
  124940. ** statements or unfinished sqlite3_backup objects.
  124941. */
  124942. static int connectionIsBusy(sqlite3 *db){
  124943. int j;
  124944. assert( sqlite3_mutex_held(db->mutex) );
  124945. if( db->pVdbe ) return 1;
  124946. for(j=0; j<db->nDb; j++){
  124947. Btree *pBt = db->aDb[j].pBt;
  124948. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  124949. }
  124950. return 0;
  124951. }
  124952. /*
  124953. ** Close an existing SQLite database
  124954. */
  124955. static int sqlite3Close(sqlite3 *db, int forceZombie){
  124956. if( !db ){
  124957. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  124958. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  124959. return SQLITE_OK;
  124960. }
  124961. if( !sqlite3SafetyCheckSickOrOk(db) ){
  124962. return SQLITE_MISUSE_BKPT;
  124963. }
  124964. sqlite3_mutex_enter(db->mutex);
  124965. /* Force xDisconnect calls on all virtual tables */
  124966. disconnectAllVtab(db);
  124967. /* If a transaction is open, the disconnectAllVtab() call above
  124968. ** will not have called the xDisconnect() method on any virtual
  124969. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  124970. ** call will do so. We need to do this before the check for active
  124971. ** SQL statements below, as the v-table implementation may be storing
  124972. ** some prepared statements internally.
  124973. */
  124974. sqlite3VtabRollback(db);
  124975. /* Legacy behavior (sqlite3_close() behavior) is to return
  124976. ** SQLITE_BUSY if the connection can not be closed immediately.
  124977. */
  124978. if( !forceZombie && connectionIsBusy(db) ){
  124979. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  124980. "statements or unfinished backups");
  124981. sqlite3_mutex_leave(db->mutex);
  124982. return SQLITE_BUSY;
  124983. }
  124984. #ifdef SQLITE_ENABLE_SQLLOG
  124985. if( sqlite3GlobalConfig.xSqllog ){
  124986. /* Closing the handle. Fourth parameter is passed the value 2. */
  124987. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  124988. }
  124989. #endif
  124990. /* Convert the connection into a zombie and then close it.
  124991. */
  124992. db->magic = SQLITE_MAGIC_ZOMBIE;
  124993. sqlite3LeaveMutexAndCloseZombie(db);
  124994. return SQLITE_OK;
  124995. }
  124996. /*
  124997. ** Two variations on the public interface for closing a database
  124998. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  124999. ** leaves the connection option if there are unfinalized prepared
  125000. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  125001. ** version forces the connection to become a zombie if there are
  125002. ** unclosed resources, and arranges for deallocation when the last
  125003. ** prepare statement or sqlite3_backup closes.
  125004. */
  125005. SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  125006. SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  125007. /*
  125008. ** Close the mutex on database connection db.
  125009. **
  125010. ** Furthermore, if database connection db is a zombie (meaning that there
  125011. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  125012. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  125013. ** finished, then free all resources.
  125014. */
  125015. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  125016. HashElem *i; /* Hash table iterator */
  125017. int j;
  125018. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  125019. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  125020. ** then just leave the mutex and return.
  125021. */
  125022. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  125023. sqlite3_mutex_leave(db->mutex);
  125024. return;
  125025. }
  125026. /* If we reach this point, it means that the database connection has
  125027. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  125028. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  125029. ** go ahead and free all resources.
  125030. */
  125031. /* If a transaction is open, roll it back. This also ensures that if
  125032. ** any database schemas have been modified by an uncommitted transaction
  125033. ** they are reset. And that the required b-tree mutex is held to make
  125034. ** the pager rollback and schema reset an atomic operation. */
  125035. sqlite3RollbackAll(db, SQLITE_OK);
  125036. /* Free any outstanding Savepoint structures. */
  125037. sqlite3CloseSavepoints(db);
  125038. /* Close all database connections */
  125039. for(j=0; j<db->nDb; j++){
  125040. struct Db *pDb = &db->aDb[j];
  125041. if( pDb->pBt ){
  125042. sqlite3BtreeClose(pDb->pBt);
  125043. pDb->pBt = 0;
  125044. if( j!=1 ){
  125045. pDb->pSchema = 0;
  125046. }
  125047. }
  125048. }
  125049. /* Clear the TEMP schema separately and last */
  125050. if( db->aDb[1].pSchema ){
  125051. sqlite3SchemaClear(db->aDb[1].pSchema);
  125052. }
  125053. sqlite3VtabUnlockList(db);
  125054. /* Free up the array of auxiliary databases */
  125055. sqlite3CollapseDatabaseArray(db);
  125056. assert( db->nDb<=2 );
  125057. assert( db->aDb==db->aDbStatic );
  125058. /* Tell the code in notify.c that the connection no longer holds any
  125059. ** locks and does not require any further unlock-notify callbacks.
  125060. */
  125061. sqlite3ConnectionClosed(db);
  125062. for(j=0; j<ArraySize(db->aFunc.a); j++){
  125063. FuncDef *pNext, *pHash, *p;
  125064. for(p=db->aFunc.a[j]; p; p=pHash){
  125065. pHash = p->pHash;
  125066. while( p ){
  125067. functionDestroy(db, p);
  125068. pNext = p->pNext;
  125069. sqlite3DbFree(db, p);
  125070. p = pNext;
  125071. }
  125072. }
  125073. }
  125074. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  125075. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  125076. /* Invoke any destructors registered for collation sequence user data. */
  125077. for(j=0; j<3; j++){
  125078. if( pColl[j].xDel ){
  125079. pColl[j].xDel(pColl[j].pUser);
  125080. }
  125081. }
  125082. sqlite3DbFree(db, pColl);
  125083. }
  125084. sqlite3HashClear(&db->aCollSeq);
  125085. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125086. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  125087. Module *pMod = (Module *)sqliteHashData(i);
  125088. if( pMod->xDestroy ){
  125089. pMod->xDestroy(pMod->pAux);
  125090. }
  125091. sqlite3VtabEponymousTableClear(db, pMod);
  125092. sqlite3DbFree(db, pMod);
  125093. }
  125094. sqlite3HashClear(&db->aModule);
  125095. #endif
  125096. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  125097. sqlite3ValueFree(db->pErr);
  125098. sqlite3CloseExtensions(db);
  125099. #if SQLITE_USER_AUTHENTICATION
  125100. sqlite3_free(db->auth.zAuthUser);
  125101. sqlite3_free(db->auth.zAuthPW);
  125102. #endif
  125103. db->magic = SQLITE_MAGIC_ERROR;
  125104. /* The temp-database schema is allocated differently from the other schema
  125105. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  125106. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  125107. ** the same sqliteMalloc() as the one that allocates the database
  125108. ** structure?
  125109. */
  125110. sqlite3DbFree(db, db->aDb[1].pSchema);
  125111. sqlite3_mutex_leave(db->mutex);
  125112. db->magic = SQLITE_MAGIC_CLOSED;
  125113. sqlite3_mutex_free(db->mutex);
  125114. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  125115. if( db->lookaside.bMalloced ){
  125116. sqlite3_free(db->lookaside.pStart);
  125117. }
  125118. sqlite3_free(db);
  125119. }
  125120. /*
  125121. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  125122. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  125123. ** breaker") and made to return tripCode if there are any further
  125124. ** attempts to use that cursor. Read cursors remain open and valid
  125125. ** but are "saved" in case the table pages are moved around.
  125126. */
  125127. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  125128. int i;
  125129. int inTrans = 0;
  125130. int schemaChange;
  125131. assert( sqlite3_mutex_held(db->mutex) );
  125132. sqlite3BeginBenignMalloc();
  125133. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  125134. ** This is important in case the transaction being rolled back has
  125135. ** modified the database schema. If the b-tree mutexes are not taken
  125136. ** here, then another shared-cache connection might sneak in between
  125137. ** the database rollback and schema reset, which can cause false
  125138. ** corruption reports in some cases. */
  125139. sqlite3BtreeEnterAll(db);
  125140. schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
  125141. for(i=0; i<db->nDb; i++){
  125142. Btree *p = db->aDb[i].pBt;
  125143. if( p ){
  125144. if( sqlite3BtreeIsInTrans(p) ){
  125145. inTrans = 1;
  125146. }
  125147. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  125148. }
  125149. }
  125150. sqlite3VtabRollback(db);
  125151. sqlite3EndBenignMalloc();
  125152. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  125153. sqlite3ExpirePreparedStatements(db);
  125154. sqlite3ResetAllSchemasOfConnection(db);
  125155. }
  125156. sqlite3BtreeLeaveAll(db);
  125157. /* Any deferred constraint violations have now been resolved. */
  125158. db->nDeferredCons = 0;
  125159. db->nDeferredImmCons = 0;
  125160. db->flags &= ~SQLITE_DeferFKs;
  125161. /* If one has been configured, invoke the rollback-hook callback */
  125162. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  125163. db->xRollbackCallback(db->pRollbackArg);
  125164. }
  125165. }
  125166. /*
  125167. ** Return a static string containing the name corresponding to the error code
  125168. ** specified in the argument.
  125169. */
  125170. #if defined(SQLITE_NEED_ERR_NAME)
  125171. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  125172. const char *zName = 0;
  125173. int i, origRc = rc;
  125174. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  125175. switch( rc ){
  125176. case SQLITE_OK: zName = "SQLITE_OK"; break;
  125177. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  125178. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  125179. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  125180. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  125181. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  125182. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  125183. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  125184. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  125185. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  125186. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  125187. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  125188. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  125189. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  125190. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  125191. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  125192. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  125193. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  125194. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  125195. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  125196. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  125197. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  125198. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  125199. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  125200. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  125201. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  125202. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  125203. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  125204. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  125205. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  125206. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  125207. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  125208. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  125209. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  125210. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  125211. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  125212. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  125213. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  125214. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  125215. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  125216. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  125217. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  125218. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  125219. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  125220. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  125221. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  125222. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  125223. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  125224. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  125225. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  125226. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  125227. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  125228. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  125229. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  125230. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  125231. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  125232. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  125233. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  125234. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  125235. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  125236. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  125237. case SQLITE_CONSTRAINT_FOREIGNKEY:
  125238. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  125239. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  125240. case SQLITE_CONSTRAINT_PRIMARYKEY:
  125241. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  125242. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  125243. case SQLITE_CONSTRAINT_COMMITHOOK:
  125244. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  125245. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  125246. case SQLITE_CONSTRAINT_FUNCTION:
  125247. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  125248. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  125249. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  125250. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  125251. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  125252. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  125253. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  125254. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  125255. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  125256. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  125257. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  125258. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  125259. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  125260. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  125261. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  125262. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  125263. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  125264. }
  125265. }
  125266. if( zName==0 ){
  125267. static char zBuf[50];
  125268. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  125269. zName = zBuf;
  125270. }
  125271. return zName;
  125272. }
  125273. #endif
  125274. /*
  125275. ** Return a static string that describes the kind of error specified in the
  125276. ** argument.
  125277. */
  125278. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  125279. static const char* const aMsg[] = {
  125280. /* SQLITE_OK */ "not an error",
  125281. /* SQLITE_ERROR */ "SQL logic error or missing database",
  125282. /* SQLITE_INTERNAL */ 0,
  125283. /* SQLITE_PERM */ "access permission denied",
  125284. /* SQLITE_ABORT */ "callback requested query abort",
  125285. /* SQLITE_BUSY */ "database is locked",
  125286. /* SQLITE_LOCKED */ "database table is locked",
  125287. /* SQLITE_NOMEM */ "out of memory",
  125288. /* SQLITE_READONLY */ "attempt to write a readonly database",
  125289. /* SQLITE_INTERRUPT */ "interrupted",
  125290. /* SQLITE_IOERR */ "disk I/O error",
  125291. /* SQLITE_CORRUPT */ "database disk image is malformed",
  125292. /* SQLITE_NOTFOUND */ "unknown operation",
  125293. /* SQLITE_FULL */ "database or disk is full",
  125294. /* SQLITE_CANTOPEN */ "unable to open database file",
  125295. /* SQLITE_PROTOCOL */ "locking protocol",
  125296. /* SQLITE_EMPTY */ "table contains no data",
  125297. /* SQLITE_SCHEMA */ "database schema has changed",
  125298. /* SQLITE_TOOBIG */ "string or blob too big",
  125299. /* SQLITE_CONSTRAINT */ "constraint failed",
  125300. /* SQLITE_MISMATCH */ "datatype mismatch",
  125301. /* SQLITE_MISUSE */ "library routine called out of sequence",
  125302. /* SQLITE_NOLFS */ "large file support is disabled",
  125303. /* SQLITE_AUTH */ "authorization denied",
  125304. /* SQLITE_FORMAT */ "auxiliary database format error",
  125305. /* SQLITE_RANGE */ "bind or column index out of range",
  125306. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  125307. };
  125308. const char *zErr = "unknown error";
  125309. switch( rc ){
  125310. case SQLITE_ABORT_ROLLBACK: {
  125311. zErr = "abort due to ROLLBACK";
  125312. break;
  125313. }
  125314. default: {
  125315. rc &= 0xff;
  125316. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  125317. zErr = aMsg[rc];
  125318. }
  125319. break;
  125320. }
  125321. }
  125322. return zErr;
  125323. }
  125324. /*
  125325. ** This routine implements a busy callback that sleeps and tries
  125326. ** again until a timeout value is reached. The timeout value is
  125327. ** an integer number of milliseconds passed in as the first
  125328. ** argument.
  125329. */
  125330. static int sqliteDefaultBusyCallback(
  125331. void *ptr, /* Database connection */
  125332. int count /* Number of times table has been busy */
  125333. ){
  125334. #if SQLITE_OS_WIN || HAVE_USLEEP
  125335. static const u8 delays[] =
  125336. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  125337. static const u8 totals[] =
  125338. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  125339. # define NDELAY ArraySize(delays)
  125340. sqlite3 *db = (sqlite3 *)ptr;
  125341. int timeout = db->busyTimeout;
  125342. int delay, prior;
  125343. assert( count>=0 );
  125344. if( count < NDELAY ){
  125345. delay = delays[count];
  125346. prior = totals[count];
  125347. }else{
  125348. delay = delays[NDELAY-1];
  125349. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  125350. }
  125351. if( prior + delay > timeout ){
  125352. delay = timeout - prior;
  125353. if( delay<=0 ) return 0;
  125354. }
  125355. sqlite3OsSleep(db->pVfs, delay*1000);
  125356. return 1;
  125357. #else
  125358. sqlite3 *db = (sqlite3 *)ptr;
  125359. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  125360. if( (count+1)*1000 > timeout ){
  125361. return 0;
  125362. }
  125363. sqlite3OsSleep(db->pVfs, 1000000);
  125364. return 1;
  125365. #endif
  125366. }
  125367. /*
  125368. ** Invoke the given busy handler.
  125369. **
  125370. ** This routine is called when an operation failed with a lock.
  125371. ** If this routine returns non-zero, the lock is retried. If it
  125372. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  125373. */
  125374. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  125375. int rc;
  125376. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  125377. rc = p->xFunc(p->pArg, p->nBusy);
  125378. if( rc==0 ){
  125379. p->nBusy = -1;
  125380. }else{
  125381. p->nBusy++;
  125382. }
  125383. return rc;
  125384. }
  125385. /*
  125386. ** This routine sets the busy callback for an Sqlite database to the
  125387. ** given callback function with the given argument.
  125388. */
  125389. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
  125390. sqlite3 *db,
  125391. int (*xBusy)(void*,int),
  125392. void *pArg
  125393. ){
  125394. #ifdef SQLITE_ENABLE_API_ARMOR
  125395. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125396. #endif
  125397. sqlite3_mutex_enter(db->mutex);
  125398. db->busyHandler.xFunc = xBusy;
  125399. db->busyHandler.pArg = pArg;
  125400. db->busyHandler.nBusy = 0;
  125401. db->busyTimeout = 0;
  125402. sqlite3_mutex_leave(db->mutex);
  125403. return SQLITE_OK;
  125404. }
  125405. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  125406. /*
  125407. ** This routine sets the progress callback for an Sqlite database to the
  125408. ** given callback function with the given argument. The progress callback will
  125409. ** be invoked every nOps opcodes.
  125410. */
  125411. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
  125412. sqlite3 *db,
  125413. int nOps,
  125414. int (*xProgress)(void*),
  125415. void *pArg
  125416. ){
  125417. #ifdef SQLITE_ENABLE_API_ARMOR
  125418. if( !sqlite3SafetyCheckOk(db) ){
  125419. (void)SQLITE_MISUSE_BKPT;
  125420. return;
  125421. }
  125422. #endif
  125423. sqlite3_mutex_enter(db->mutex);
  125424. if( nOps>0 ){
  125425. db->xProgress = xProgress;
  125426. db->nProgressOps = (unsigned)nOps;
  125427. db->pProgressArg = pArg;
  125428. }else{
  125429. db->xProgress = 0;
  125430. db->nProgressOps = 0;
  125431. db->pProgressArg = 0;
  125432. }
  125433. sqlite3_mutex_leave(db->mutex);
  125434. }
  125435. #endif
  125436. /*
  125437. ** This routine installs a default busy handler that waits for the
  125438. ** specified number of milliseconds before returning 0.
  125439. */
  125440. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
  125441. #ifdef SQLITE_ENABLE_API_ARMOR
  125442. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125443. #endif
  125444. if( ms>0 ){
  125445. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  125446. db->busyTimeout = ms;
  125447. }else{
  125448. sqlite3_busy_handler(db, 0, 0);
  125449. }
  125450. return SQLITE_OK;
  125451. }
  125452. /*
  125453. ** Cause any pending operation to stop at its earliest opportunity.
  125454. */
  125455. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
  125456. #ifdef SQLITE_ENABLE_API_ARMOR
  125457. if( !sqlite3SafetyCheckOk(db) ){
  125458. (void)SQLITE_MISUSE_BKPT;
  125459. return;
  125460. }
  125461. #endif
  125462. db->u1.isInterrupted = 1;
  125463. }
  125464. /*
  125465. ** This function is exactly the same as sqlite3_create_function(), except
  125466. ** that it is designed to be called by internal code. The difference is
  125467. ** that if a malloc() fails in sqlite3_create_function(), an error code
  125468. ** is returned and the mallocFailed flag cleared.
  125469. */
  125470. SQLITE_PRIVATE int sqlite3CreateFunc(
  125471. sqlite3 *db,
  125472. const char *zFunctionName,
  125473. int nArg,
  125474. int enc,
  125475. void *pUserData,
  125476. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  125477. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  125478. void (*xFinal)(sqlite3_context*),
  125479. FuncDestructor *pDestructor
  125480. ){
  125481. FuncDef *p;
  125482. int nName;
  125483. int extraFlags;
  125484. assert( sqlite3_mutex_held(db->mutex) );
  125485. if( zFunctionName==0 ||
  125486. (xFunc && (xFinal || xStep)) ||
  125487. (!xFunc && (xFinal && !xStep)) ||
  125488. (!xFunc && (!xFinal && xStep)) ||
  125489. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  125490. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  125491. return SQLITE_MISUSE_BKPT;
  125492. }
  125493. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  125494. extraFlags = enc & SQLITE_DETERMINISTIC;
  125495. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  125496. #ifndef SQLITE_OMIT_UTF16
  125497. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  125498. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  125499. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  125500. **
  125501. ** If SQLITE_ANY is specified, add three versions of the function
  125502. ** to the hash table.
  125503. */
  125504. if( enc==SQLITE_UTF16 ){
  125505. enc = SQLITE_UTF16NATIVE;
  125506. }else if( enc==SQLITE_ANY ){
  125507. int rc;
  125508. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  125509. pUserData, xFunc, xStep, xFinal, pDestructor);
  125510. if( rc==SQLITE_OK ){
  125511. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  125512. pUserData, xFunc, xStep, xFinal, pDestructor);
  125513. }
  125514. if( rc!=SQLITE_OK ){
  125515. return rc;
  125516. }
  125517. enc = SQLITE_UTF16BE;
  125518. }
  125519. #else
  125520. enc = SQLITE_UTF8;
  125521. #endif
  125522. /* Check if an existing function is being overridden or deleted. If so,
  125523. ** and there are active VMs, then return SQLITE_BUSY. If a function
  125524. ** is being overridden/deleted but there are no active VMs, allow the
  125525. ** operation to continue but invalidate all precompiled statements.
  125526. */
  125527. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  125528. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  125529. if( db->nVdbeActive ){
  125530. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  125531. "unable to delete/modify user-function due to active statements");
  125532. assert( !db->mallocFailed );
  125533. return SQLITE_BUSY;
  125534. }else{
  125535. sqlite3ExpirePreparedStatements(db);
  125536. }
  125537. }
  125538. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  125539. assert(p || db->mallocFailed);
  125540. if( !p ){
  125541. return SQLITE_NOMEM;
  125542. }
  125543. /* If an older version of the function with a configured destructor is
  125544. ** being replaced invoke the destructor function here. */
  125545. functionDestroy(db, p);
  125546. if( pDestructor ){
  125547. pDestructor->nRef++;
  125548. }
  125549. p->pDestructor = pDestructor;
  125550. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  125551. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  125552. p->xFunc = xFunc;
  125553. p->xStep = xStep;
  125554. p->xFinalize = xFinal;
  125555. p->pUserData = pUserData;
  125556. p->nArg = (u16)nArg;
  125557. return SQLITE_OK;
  125558. }
  125559. /*
  125560. ** Create new user functions.
  125561. */
  125562. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  125563. sqlite3 *db,
  125564. const char *zFunc,
  125565. int nArg,
  125566. int enc,
  125567. void *p,
  125568. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  125569. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  125570. void (*xFinal)(sqlite3_context*)
  125571. ){
  125572. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  125573. xFinal, 0);
  125574. }
  125575. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  125576. sqlite3 *db,
  125577. const char *zFunc,
  125578. int nArg,
  125579. int enc,
  125580. void *p,
  125581. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  125582. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  125583. void (*xFinal)(sqlite3_context*),
  125584. void (*xDestroy)(void *)
  125585. ){
  125586. int rc = SQLITE_ERROR;
  125587. FuncDestructor *pArg = 0;
  125588. #ifdef SQLITE_ENABLE_API_ARMOR
  125589. if( !sqlite3SafetyCheckOk(db) ){
  125590. return SQLITE_MISUSE_BKPT;
  125591. }
  125592. #endif
  125593. sqlite3_mutex_enter(db->mutex);
  125594. if( xDestroy ){
  125595. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  125596. if( !pArg ){
  125597. xDestroy(p);
  125598. goto out;
  125599. }
  125600. pArg->xDestroy = xDestroy;
  125601. pArg->pUserData = p;
  125602. }
  125603. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  125604. if( pArg && pArg->nRef==0 ){
  125605. assert( rc!=SQLITE_OK );
  125606. xDestroy(p);
  125607. sqlite3DbFree(db, pArg);
  125608. }
  125609. out:
  125610. rc = sqlite3ApiExit(db, rc);
  125611. sqlite3_mutex_leave(db->mutex);
  125612. return rc;
  125613. }
  125614. #ifndef SQLITE_OMIT_UTF16
  125615. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  125616. sqlite3 *db,
  125617. const void *zFunctionName,
  125618. int nArg,
  125619. int eTextRep,
  125620. void *p,
  125621. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  125622. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  125623. void (*xFinal)(sqlite3_context*)
  125624. ){
  125625. int rc;
  125626. char *zFunc8;
  125627. #ifdef SQLITE_ENABLE_API_ARMOR
  125628. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  125629. #endif
  125630. sqlite3_mutex_enter(db->mutex);
  125631. assert( !db->mallocFailed );
  125632. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  125633. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  125634. sqlite3DbFree(db, zFunc8);
  125635. rc = sqlite3ApiExit(db, rc);
  125636. sqlite3_mutex_leave(db->mutex);
  125637. return rc;
  125638. }
  125639. #endif
  125640. /*
  125641. ** Declare that a function has been overloaded by a virtual table.
  125642. **
  125643. ** If the function already exists as a regular global function, then
  125644. ** this routine is a no-op. If the function does not exist, then create
  125645. ** a new one that always throws a run-time error.
  125646. **
  125647. ** When virtual tables intend to provide an overloaded function, they
  125648. ** should call this routine to make sure the global function exists.
  125649. ** A global function must exist in order for name resolution to work
  125650. ** properly.
  125651. */
  125652. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
  125653. sqlite3 *db,
  125654. const char *zName,
  125655. int nArg
  125656. ){
  125657. int nName = sqlite3Strlen30(zName);
  125658. int rc = SQLITE_OK;
  125659. #ifdef SQLITE_ENABLE_API_ARMOR
  125660. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  125661. return SQLITE_MISUSE_BKPT;
  125662. }
  125663. #endif
  125664. sqlite3_mutex_enter(db->mutex);
  125665. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  125666. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  125667. 0, sqlite3InvalidFunction, 0, 0, 0);
  125668. }
  125669. rc = sqlite3ApiExit(db, rc);
  125670. sqlite3_mutex_leave(db->mutex);
  125671. return rc;
  125672. }
  125673. #ifndef SQLITE_OMIT_TRACE
  125674. /*
  125675. ** Register a trace function. The pArg from the previously registered trace
  125676. ** is returned.
  125677. **
  125678. ** A NULL trace function means that no tracing is executes. A non-NULL
  125679. ** trace is a pointer to a function that is invoked at the start of each
  125680. ** SQL statement.
  125681. */
  125682. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  125683. void *pOld;
  125684. #ifdef SQLITE_ENABLE_API_ARMOR
  125685. if( !sqlite3SafetyCheckOk(db) ){
  125686. (void)SQLITE_MISUSE_BKPT;
  125687. return 0;
  125688. }
  125689. #endif
  125690. sqlite3_mutex_enter(db->mutex);
  125691. pOld = db->pTraceArg;
  125692. db->xTrace = xTrace;
  125693. db->pTraceArg = pArg;
  125694. sqlite3_mutex_leave(db->mutex);
  125695. return pOld;
  125696. }
  125697. /*
  125698. ** Register a profile function. The pArg from the previously registered
  125699. ** profile function is returned.
  125700. **
  125701. ** A NULL profile function means that no profiling is executes. A non-NULL
  125702. ** profile is a pointer to a function that is invoked at the conclusion of
  125703. ** each SQL statement that is run.
  125704. */
  125705. SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
  125706. sqlite3 *db,
  125707. void (*xProfile)(void*,const char*,sqlite_uint64),
  125708. void *pArg
  125709. ){
  125710. void *pOld;
  125711. #ifdef SQLITE_ENABLE_API_ARMOR
  125712. if( !sqlite3SafetyCheckOk(db) ){
  125713. (void)SQLITE_MISUSE_BKPT;
  125714. return 0;
  125715. }
  125716. #endif
  125717. sqlite3_mutex_enter(db->mutex);
  125718. pOld = db->pProfileArg;
  125719. db->xProfile = xProfile;
  125720. db->pProfileArg = pArg;
  125721. sqlite3_mutex_leave(db->mutex);
  125722. return pOld;
  125723. }
  125724. #endif /* SQLITE_OMIT_TRACE */
  125725. /*
  125726. ** Register a function to be invoked when a transaction commits.
  125727. ** If the invoked function returns non-zero, then the commit becomes a
  125728. ** rollback.
  125729. */
  125730. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
  125731. sqlite3 *db, /* Attach the hook to this database */
  125732. int (*xCallback)(void*), /* Function to invoke on each commit */
  125733. void *pArg /* Argument to the function */
  125734. ){
  125735. void *pOld;
  125736. #ifdef SQLITE_ENABLE_API_ARMOR
  125737. if( !sqlite3SafetyCheckOk(db) ){
  125738. (void)SQLITE_MISUSE_BKPT;
  125739. return 0;
  125740. }
  125741. #endif
  125742. sqlite3_mutex_enter(db->mutex);
  125743. pOld = db->pCommitArg;
  125744. db->xCommitCallback = xCallback;
  125745. db->pCommitArg = pArg;
  125746. sqlite3_mutex_leave(db->mutex);
  125747. return pOld;
  125748. }
  125749. /*
  125750. ** Register a callback to be invoked each time a row is updated,
  125751. ** inserted or deleted using this database connection.
  125752. */
  125753. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  125754. sqlite3 *db, /* Attach the hook to this database */
  125755. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  125756. void *pArg /* Argument to the function */
  125757. ){
  125758. void *pRet;
  125759. #ifdef SQLITE_ENABLE_API_ARMOR
  125760. if( !sqlite3SafetyCheckOk(db) ){
  125761. (void)SQLITE_MISUSE_BKPT;
  125762. return 0;
  125763. }
  125764. #endif
  125765. sqlite3_mutex_enter(db->mutex);
  125766. pRet = db->pUpdateArg;
  125767. db->xUpdateCallback = xCallback;
  125768. db->pUpdateArg = pArg;
  125769. sqlite3_mutex_leave(db->mutex);
  125770. return pRet;
  125771. }
  125772. /*
  125773. ** Register a callback to be invoked each time a transaction is rolled
  125774. ** back by this database connection.
  125775. */
  125776. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
  125777. sqlite3 *db, /* Attach the hook to this database */
  125778. void (*xCallback)(void*), /* Callback function */
  125779. void *pArg /* Argument to the function */
  125780. ){
  125781. void *pRet;
  125782. #ifdef SQLITE_ENABLE_API_ARMOR
  125783. if( !sqlite3SafetyCheckOk(db) ){
  125784. (void)SQLITE_MISUSE_BKPT;
  125785. return 0;
  125786. }
  125787. #endif
  125788. sqlite3_mutex_enter(db->mutex);
  125789. pRet = db->pRollbackArg;
  125790. db->xRollbackCallback = xCallback;
  125791. db->pRollbackArg = pArg;
  125792. sqlite3_mutex_leave(db->mutex);
  125793. return pRet;
  125794. }
  125795. #ifndef SQLITE_OMIT_WAL
  125796. /*
  125797. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  125798. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  125799. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  125800. ** wal_autocheckpoint()).
  125801. */
  125802. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  125803. void *pClientData, /* Argument */
  125804. sqlite3 *db, /* Connection */
  125805. const char *zDb, /* Database */
  125806. int nFrame /* Size of WAL */
  125807. ){
  125808. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  125809. sqlite3BeginBenignMalloc();
  125810. sqlite3_wal_checkpoint(db, zDb);
  125811. sqlite3EndBenignMalloc();
  125812. }
  125813. return SQLITE_OK;
  125814. }
  125815. #endif /* SQLITE_OMIT_WAL */
  125816. /*
  125817. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  125818. ** a database after committing a transaction if there are nFrame or
  125819. ** more frames in the log file. Passing zero or a negative value as the
  125820. ** nFrame parameter disables automatic checkpoints entirely.
  125821. **
  125822. ** The callback registered by this function replaces any existing callback
  125823. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  125824. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  125825. ** configured by this function.
  125826. */
  125827. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  125828. #ifdef SQLITE_OMIT_WAL
  125829. UNUSED_PARAMETER(db);
  125830. UNUSED_PARAMETER(nFrame);
  125831. #else
  125832. #ifdef SQLITE_ENABLE_API_ARMOR
  125833. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125834. #endif
  125835. if( nFrame>0 ){
  125836. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  125837. }else{
  125838. sqlite3_wal_hook(db, 0, 0);
  125839. }
  125840. #endif
  125841. return SQLITE_OK;
  125842. }
  125843. /*
  125844. ** Register a callback to be invoked each time a transaction is written
  125845. ** into the write-ahead-log by this database connection.
  125846. */
  125847. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  125848. sqlite3 *db, /* Attach the hook to this db handle */
  125849. int(*xCallback)(void *, sqlite3*, const char*, int),
  125850. void *pArg /* First argument passed to xCallback() */
  125851. ){
  125852. #ifndef SQLITE_OMIT_WAL
  125853. void *pRet;
  125854. #ifdef SQLITE_ENABLE_API_ARMOR
  125855. if( !sqlite3SafetyCheckOk(db) ){
  125856. (void)SQLITE_MISUSE_BKPT;
  125857. return 0;
  125858. }
  125859. #endif
  125860. sqlite3_mutex_enter(db->mutex);
  125861. pRet = db->pWalArg;
  125862. db->xWalCallback = xCallback;
  125863. db->pWalArg = pArg;
  125864. sqlite3_mutex_leave(db->mutex);
  125865. return pRet;
  125866. #else
  125867. return 0;
  125868. #endif
  125869. }
  125870. /*
  125871. ** Checkpoint database zDb.
  125872. */
  125873. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  125874. sqlite3 *db, /* Database handle */
  125875. const char *zDb, /* Name of attached database (or NULL) */
  125876. int eMode, /* SQLITE_CHECKPOINT_* value */
  125877. int *pnLog, /* OUT: Size of WAL log in frames */
  125878. int *pnCkpt /* OUT: Total number of frames checkpointed */
  125879. ){
  125880. #ifdef SQLITE_OMIT_WAL
  125881. return SQLITE_OK;
  125882. #else
  125883. int rc; /* Return code */
  125884. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  125885. #ifdef SQLITE_ENABLE_API_ARMOR
  125886. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  125887. #endif
  125888. /* Initialize the output variables to -1 in case an error occurs. */
  125889. if( pnLog ) *pnLog = -1;
  125890. if( pnCkpt ) *pnCkpt = -1;
  125891. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  125892. assert( SQLITE_CHECKPOINT_FULL==1 );
  125893. assert( SQLITE_CHECKPOINT_RESTART==2 );
  125894. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  125895. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  125896. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  125897. ** mode: */
  125898. return SQLITE_MISUSE;
  125899. }
  125900. sqlite3_mutex_enter(db->mutex);
  125901. if( zDb && zDb[0] ){
  125902. iDb = sqlite3FindDbName(db, zDb);
  125903. }
  125904. if( iDb<0 ){
  125905. rc = SQLITE_ERROR;
  125906. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  125907. }else{
  125908. db->busyHandler.nBusy = 0;
  125909. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  125910. sqlite3Error(db, rc);
  125911. }
  125912. rc = sqlite3ApiExit(db, rc);
  125913. sqlite3_mutex_leave(db->mutex);
  125914. return rc;
  125915. #endif
  125916. }
  125917. /*
  125918. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  125919. ** to contains a zero-length string, all attached databases are
  125920. ** checkpointed.
  125921. */
  125922. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  125923. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  125924. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  125925. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  125926. }
  125927. #ifndef SQLITE_OMIT_WAL
  125928. /*
  125929. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  125930. ** not currently open in WAL mode.
  125931. **
  125932. ** If a transaction is open on the database being checkpointed, this
  125933. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  125934. ** an error occurs while running the checkpoint, an SQLite error code is
  125935. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  125936. **
  125937. ** The mutex on database handle db should be held by the caller. The mutex
  125938. ** associated with the specific b-tree being checkpointed is taken by
  125939. ** this function while the checkpoint is running.
  125940. **
  125941. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  125942. ** checkpointed. If an error is encountered it is returned immediately -
  125943. ** no attempt is made to checkpoint any remaining databases.
  125944. **
  125945. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  125946. */
  125947. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  125948. int rc = SQLITE_OK; /* Return code */
  125949. int i; /* Used to iterate through attached dbs */
  125950. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  125951. assert( sqlite3_mutex_held(db->mutex) );
  125952. assert( !pnLog || *pnLog==-1 );
  125953. assert( !pnCkpt || *pnCkpt==-1 );
  125954. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  125955. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  125956. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  125957. pnLog = 0;
  125958. pnCkpt = 0;
  125959. if( rc==SQLITE_BUSY ){
  125960. bBusy = 1;
  125961. rc = SQLITE_OK;
  125962. }
  125963. }
  125964. }
  125965. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  125966. }
  125967. #endif /* SQLITE_OMIT_WAL */
  125968. /*
  125969. ** This function returns true if main-memory should be used instead of
  125970. ** a temporary file for transient pager files and statement journals.
  125971. ** The value returned depends on the value of db->temp_store (runtime
  125972. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  125973. ** following table describes the relationship between these two values
  125974. ** and this functions return value.
  125975. **
  125976. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  125977. ** ----------------- -------------- ------------------------------
  125978. ** 0 any file (return 0)
  125979. ** 1 1 file (return 0)
  125980. ** 1 2 memory (return 1)
  125981. ** 1 0 file (return 0)
  125982. ** 2 1 file (return 0)
  125983. ** 2 2 memory (return 1)
  125984. ** 2 0 memory (return 1)
  125985. ** 3 any memory (return 1)
  125986. */
  125987. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  125988. #if SQLITE_TEMP_STORE==1
  125989. return ( db->temp_store==2 );
  125990. #endif
  125991. #if SQLITE_TEMP_STORE==2
  125992. return ( db->temp_store!=1 );
  125993. #endif
  125994. #if SQLITE_TEMP_STORE==3
  125995. UNUSED_PARAMETER(db);
  125996. return 1;
  125997. #endif
  125998. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  125999. UNUSED_PARAMETER(db);
  126000. return 0;
  126001. #endif
  126002. }
  126003. /*
  126004. ** Return UTF-8 encoded English language explanation of the most recent
  126005. ** error.
  126006. */
  126007. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
  126008. const char *z;
  126009. if( !db ){
  126010. return sqlite3ErrStr(SQLITE_NOMEM);
  126011. }
  126012. if( !sqlite3SafetyCheckSickOrOk(db) ){
  126013. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  126014. }
  126015. sqlite3_mutex_enter(db->mutex);
  126016. if( db->mallocFailed ){
  126017. z = sqlite3ErrStr(SQLITE_NOMEM);
  126018. }else{
  126019. testcase( db->pErr==0 );
  126020. z = (char*)sqlite3_value_text(db->pErr);
  126021. assert( !db->mallocFailed );
  126022. if( z==0 ){
  126023. z = sqlite3ErrStr(db->errCode);
  126024. }
  126025. }
  126026. sqlite3_mutex_leave(db->mutex);
  126027. return z;
  126028. }
  126029. #ifndef SQLITE_OMIT_UTF16
  126030. /*
  126031. ** Return UTF-16 encoded English language explanation of the most recent
  126032. ** error.
  126033. */
  126034. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
  126035. static const u16 outOfMem[] = {
  126036. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  126037. };
  126038. static const u16 misuse[] = {
  126039. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  126040. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  126041. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  126042. 'o', 'u', 't', ' ',
  126043. 'o', 'f', ' ',
  126044. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  126045. };
  126046. const void *z;
  126047. if( !db ){
  126048. return (void *)outOfMem;
  126049. }
  126050. if( !sqlite3SafetyCheckSickOrOk(db) ){
  126051. return (void *)misuse;
  126052. }
  126053. sqlite3_mutex_enter(db->mutex);
  126054. if( db->mallocFailed ){
  126055. z = (void *)outOfMem;
  126056. }else{
  126057. z = sqlite3_value_text16(db->pErr);
  126058. if( z==0 ){
  126059. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  126060. z = sqlite3_value_text16(db->pErr);
  126061. }
  126062. /* A malloc() may have failed within the call to sqlite3_value_text16()
  126063. ** above. If this is the case, then the db->mallocFailed flag needs to
  126064. ** be cleared before returning. Do this directly, instead of via
  126065. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  126066. */
  126067. db->mallocFailed = 0;
  126068. }
  126069. sqlite3_mutex_leave(db->mutex);
  126070. return z;
  126071. }
  126072. #endif /* SQLITE_OMIT_UTF16 */
  126073. /*
  126074. ** Return the most recent error code generated by an SQLite routine. If NULL is
  126075. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  126076. */
  126077. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
  126078. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  126079. return SQLITE_MISUSE_BKPT;
  126080. }
  126081. if( !db || db->mallocFailed ){
  126082. return SQLITE_NOMEM;
  126083. }
  126084. return db->errCode & db->errMask;
  126085. }
  126086. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
  126087. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  126088. return SQLITE_MISUSE_BKPT;
  126089. }
  126090. if( !db || db->mallocFailed ){
  126091. return SQLITE_NOMEM;
  126092. }
  126093. return db->errCode;
  126094. }
  126095. /*
  126096. ** Return a string that describes the kind of error specified in the
  126097. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  126098. ** function.
  126099. */
  126100. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
  126101. return sqlite3ErrStr(rc);
  126102. }
  126103. /*
  126104. ** Create a new collating function for database "db". The name is zName
  126105. ** and the encoding is enc.
  126106. */
  126107. static int createCollation(
  126108. sqlite3* db,
  126109. const char *zName,
  126110. u8 enc,
  126111. void* pCtx,
  126112. int(*xCompare)(void*,int,const void*,int,const void*),
  126113. void(*xDel)(void*)
  126114. ){
  126115. CollSeq *pColl;
  126116. int enc2;
  126117. assert( sqlite3_mutex_held(db->mutex) );
  126118. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  126119. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  126120. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  126121. */
  126122. enc2 = enc;
  126123. testcase( enc2==SQLITE_UTF16 );
  126124. testcase( enc2==SQLITE_UTF16_ALIGNED );
  126125. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  126126. enc2 = SQLITE_UTF16NATIVE;
  126127. }
  126128. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  126129. return SQLITE_MISUSE_BKPT;
  126130. }
  126131. /* Check if this call is removing or replacing an existing collation
  126132. ** sequence. If so, and there are active VMs, return busy. If there
  126133. ** are no active VMs, invalidate any pre-compiled statements.
  126134. */
  126135. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  126136. if( pColl && pColl->xCmp ){
  126137. if( db->nVdbeActive ){
  126138. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  126139. "unable to delete/modify collation sequence due to active statements");
  126140. return SQLITE_BUSY;
  126141. }
  126142. sqlite3ExpirePreparedStatements(db);
  126143. /* If collation sequence pColl was created directly by a call to
  126144. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  126145. ** then any copies made by synthCollSeq() need to be invalidated.
  126146. ** Also, collation destructor - CollSeq.xDel() - function may need
  126147. ** to be called.
  126148. */
  126149. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  126150. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  126151. int j;
  126152. for(j=0; j<3; j++){
  126153. CollSeq *p = &aColl[j];
  126154. if( p->enc==pColl->enc ){
  126155. if( p->xDel ){
  126156. p->xDel(p->pUser);
  126157. }
  126158. p->xCmp = 0;
  126159. }
  126160. }
  126161. }
  126162. }
  126163. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  126164. if( pColl==0 ) return SQLITE_NOMEM;
  126165. pColl->xCmp = xCompare;
  126166. pColl->pUser = pCtx;
  126167. pColl->xDel = xDel;
  126168. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  126169. sqlite3Error(db, SQLITE_OK);
  126170. return SQLITE_OK;
  126171. }
  126172. /*
  126173. ** This array defines hard upper bounds on limit values. The
  126174. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  126175. ** #defines in sqlite3.h.
  126176. */
  126177. static const int aHardLimit[] = {
  126178. SQLITE_MAX_LENGTH,
  126179. SQLITE_MAX_SQL_LENGTH,
  126180. SQLITE_MAX_COLUMN,
  126181. SQLITE_MAX_EXPR_DEPTH,
  126182. SQLITE_MAX_COMPOUND_SELECT,
  126183. SQLITE_MAX_VDBE_OP,
  126184. SQLITE_MAX_FUNCTION_ARG,
  126185. SQLITE_MAX_ATTACHED,
  126186. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  126187. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  126188. SQLITE_MAX_TRIGGER_DEPTH,
  126189. SQLITE_MAX_WORKER_THREADS,
  126190. };
  126191. /*
  126192. ** Make sure the hard limits are set to reasonable values
  126193. */
  126194. #if SQLITE_MAX_LENGTH<100
  126195. # error SQLITE_MAX_LENGTH must be at least 100
  126196. #endif
  126197. #if SQLITE_MAX_SQL_LENGTH<100
  126198. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  126199. #endif
  126200. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  126201. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  126202. #endif
  126203. #if SQLITE_MAX_COMPOUND_SELECT<2
  126204. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  126205. #endif
  126206. #if SQLITE_MAX_VDBE_OP<40
  126207. # error SQLITE_MAX_VDBE_OP must be at least 40
  126208. #endif
  126209. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  126210. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  126211. #endif
  126212. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  126213. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  126214. #endif
  126215. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  126216. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  126217. #endif
  126218. #if SQLITE_MAX_COLUMN>32767
  126219. # error SQLITE_MAX_COLUMN must not exceed 32767
  126220. #endif
  126221. #if SQLITE_MAX_TRIGGER_DEPTH<1
  126222. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  126223. #endif
  126224. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  126225. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  126226. #endif
  126227. /*
  126228. ** Change the value of a limit. Report the old value.
  126229. ** If an invalid limit index is supplied, report -1.
  126230. ** Make no changes but still report the old value if the
  126231. ** new limit is negative.
  126232. **
  126233. ** A new lower limit does not shrink existing constructs.
  126234. ** It merely prevents new constructs that exceed the limit
  126235. ** from forming.
  126236. */
  126237. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  126238. int oldLimit;
  126239. #ifdef SQLITE_ENABLE_API_ARMOR
  126240. if( !sqlite3SafetyCheckOk(db) ){
  126241. (void)SQLITE_MISUSE_BKPT;
  126242. return -1;
  126243. }
  126244. #endif
  126245. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  126246. ** there is a hard upper bound set at compile-time by a C preprocessor
  126247. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  126248. ** "_MAX_".)
  126249. */
  126250. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  126251. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  126252. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  126253. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  126254. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  126255. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  126256. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  126257. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  126258. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  126259. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  126260. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  126261. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  126262. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  126263. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  126264. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  126265. return -1;
  126266. }
  126267. oldLimit = db->aLimit[limitId];
  126268. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  126269. if( newLimit>aHardLimit[limitId] ){
  126270. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  126271. }
  126272. db->aLimit[limitId] = newLimit;
  126273. }
  126274. return oldLimit; /* IMP: R-53341-35419 */
  126275. }
  126276. /*
  126277. ** This function is used to parse both URIs and non-URI filenames passed by the
  126278. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  126279. ** URIs specified as part of ATTACH statements.
  126280. **
  126281. ** The first argument to this function is the name of the VFS to use (or
  126282. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  126283. ** query parameter. The second argument contains the URI (or non-URI filename)
  126284. ** itself. When this function is called the *pFlags variable should contain
  126285. ** the default flags to open the database handle with. The value stored in
  126286. ** *pFlags may be updated before returning if the URI filename contains
  126287. ** "cache=xxx" or "mode=xxx" query parameters.
  126288. **
  126289. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  126290. ** the VFS that should be used to open the database file. *pzFile is set to
  126291. ** point to a buffer containing the name of the file to open. It is the
  126292. ** responsibility of the caller to eventually call sqlite3_free() to release
  126293. ** this buffer.
  126294. **
  126295. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  126296. ** may be set to point to a buffer containing an English language error
  126297. ** message. It is the responsibility of the caller to eventually release
  126298. ** this buffer by calling sqlite3_free().
  126299. */
  126300. SQLITE_PRIVATE int sqlite3ParseUri(
  126301. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  126302. const char *zUri, /* Nul-terminated URI to parse */
  126303. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  126304. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  126305. char **pzFile, /* OUT: Filename component of URI */
  126306. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  126307. ){
  126308. int rc = SQLITE_OK;
  126309. unsigned int flags = *pFlags;
  126310. const char *zVfs = zDefaultVfs;
  126311. char *zFile;
  126312. char c;
  126313. int nUri = sqlite3Strlen30(zUri);
  126314. assert( *pzErrMsg==0 );
  126315. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  126316. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  126317. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  126318. ){
  126319. char *zOpt;
  126320. int eState; /* Parser state when parsing URI */
  126321. int iIn; /* Input character index */
  126322. int iOut = 0; /* Output character index */
  126323. u64 nByte = nUri+2; /* Bytes of space to allocate */
  126324. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  126325. ** method that there may be extra parameters following the file-name. */
  126326. flags |= SQLITE_OPEN_URI;
  126327. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  126328. zFile = sqlite3_malloc64(nByte);
  126329. if( !zFile ) return SQLITE_NOMEM;
  126330. iIn = 5;
  126331. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  126332. if( strncmp(zUri+5, "///", 3)==0 ){
  126333. iIn = 7;
  126334. /* The following condition causes URIs with five leading / characters
  126335. ** like file://///host/path to be converted into UNCs like //host/path.
  126336. ** The correct URI for that UNC has only two or four leading / characters
  126337. ** file://host/path or file:////host/path. But 5 leading slashes is a
  126338. ** common error, we are told, so we handle it as a special case. */
  126339. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  126340. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  126341. iIn = 16;
  126342. }
  126343. #else
  126344. /* Discard the scheme and authority segments of the URI. */
  126345. if( zUri[5]=='/' && zUri[6]=='/' ){
  126346. iIn = 7;
  126347. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  126348. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  126349. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  126350. iIn-7, &zUri[7]);
  126351. rc = SQLITE_ERROR;
  126352. goto parse_uri_out;
  126353. }
  126354. }
  126355. #endif
  126356. /* Copy the filename and any query parameters into the zFile buffer.
  126357. ** Decode %HH escape codes along the way.
  126358. **
  126359. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  126360. ** on the parsing context. As follows:
  126361. **
  126362. ** 0: Parsing file-name.
  126363. ** 1: Parsing name section of a name=value query parameter.
  126364. ** 2: Parsing value section of a name=value query parameter.
  126365. */
  126366. eState = 0;
  126367. while( (c = zUri[iIn])!=0 && c!='#' ){
  126368. iIn++;
  126369. if( c=='%'
  126370. && sqlite3Isxdigit(zUri[iIn])
  126371. && sqlite3Isxdigit(zUri[iIn+1])
  126372. ){
  126373. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  126374. octet += sqlite3HexToInt(zUri[iIn++]);
  126375. assert( octet>=0 && octet<256 );
  126376. if( octet==0 ){
  126377. /* This branch is taken when "%00" appears within the URI. In this
  126378. ** case we ignore all text in the remainder of the path, name or
  126379. ** value currently being parsed. So ignore the current character
  126380. ** and skip to the next "?", "=" or "&", as appropriate. */
  126381. while( (c = zUri[iIn])!=0 && c!='#'
  126382. && (eState!=0 || c!='?')
  126383. && (eState!=1 || (c!='=' && c!='&'))
  126384. && (eState!=2 || c!='&')
  126385. ){
  126386. iIn++;
  126387. }
  126388. continue;
  126389. }
  126390. c = octet;
  126391. }else if( eState==1 && (c=='&' || c=='=') ){
  126392. if( zFile[iOut-1]==0 ){
  126393. /* An empty option name. Ignore this option altogether. */
  126394. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  126395. continue;
  126396. }
  126397. if( c=='&' ){
  126398. zFile[iOut++] = '\0';
  126399. }else{
  126400. eState = 2;
  126401. }
  126402. c = 0;
  126403. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  126404. c = 0;
  126405. eState = 1;
  126406. }
  126407. zFile[iOut++] = c;
  126408. }
  126409. if( eState==1 ) zFile[iOut++] = '\0';
  126410. zFile[iOut++] = '\0';
  126411. zFile[iOut++] = '\0';
  126412. /* Check if there were any options specified that should be interpreted
  126413. ** here. Options that are interpreted here include "vfs" and those that
  126414. ** correspond to flags that may be passed to the sqlite3_open_v2()
  126415. ** method. */
  126416. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  126417. while( zOpt[0] ){
  126418. int nOpt = sqlite3Strlen30(zOpt);
  126419. char *zVal = &zOpt[nOpt+1];
  126420. int nVal = sqlite3Strlen30(zVal);
  126421. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  126422. zVfs = zVal;
  126423. }else{
  126424. struct OpenMode {
  126425. const char *z;
  126426. int mode;
  126427. } *aMode = 0;
  126428. char *zModeType = 0;
  126429. int mask = 0;
  126430. int limit = 0;
  126431. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  126432. static struct OpenMode aCacheMode[] = {
  126433. { "shared", SQLITE_OPEN_SHAREDCACHE },
  126434. { "private", SQLITE_OPEN_PRIVATECACHE },
  126435. { 0, 0 }
  126436. };
  126437. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  126438. aMode = aCacheMode;
  126439. limit = mask;
  126440. zModeType = "cache";
  126441. }
  126442. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  126443. static struct OpenMode aOpenMode[] = {
  126444. { "ro", SQLITE_OPEN_READONLY },
  126445. { "rw", SQLITE_OPEN_READWRITE },
  126446. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  126447. { "memory", SQLITE_OPEN_MEMORY },
  126448. { 0, 0 }
  126449. };
  126450. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  126451. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  126452. aMode = aOpenMode;
  126453. limit = mask & flags;
  126454. zModeType = "access";
  126455. }
  126456. if( aMode ){
  126457. int i;
  126458. int mode = 0;
  126459. for(i=0; aMode[i].z; i++){
  126460. const char *z = aMode[i].z;
  126461. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  126462. mode = aMode[i].mode;
  126463. break;
  126464. }
  126465. }
  126466. if( mode==0 ){
  126467. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  126468. rc = SQLITE_ERROR;
  126469. goto parse_uri_out;
  126470. }
  126471. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  126472. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  126473. zModeType, zVal);
  126474. rc = SQLITE_PERM;
  126475. goto parse_uri_out;
  126476. }
  126477. flags = (flags & ~mask) | mode;
  126478. }
  126479. }
  126480. zOpt = &zVal[nVal+1];
  126481. }
  126482. }else{
  126483. zFile = sqlite3_malloc64(nUri+2);
  126484. if( !zFile ) return SQLITE_NOMEM;
  126485. memcpy(zFile, zUri, nUri);
  126486. zFile[nUri] = '\0';
  126487. zFile[nUri+1] = '\0';
  126488. flags &= ~SQLITE_OPEN_URI;
  126489. }
  126490. *ppVfs = sqlite3_vfs_find(zVfs);
  126491. if( *ppVfs==0 ){
  126492. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  126493. rc = SQLITE_ERROR;
  126494. }
  126495. parse_uri_out:
  126496. if( rc!=SQLITE_OK ){
  126497. sqlite3_free(zFile);
  126498. zFile = 0;
  126499. }
  126500. *pFlags = flags;
  126501. *pzFile = zFile;
  126502. return rc;
  126503. }
  126504. /*
  126505. ** This routine does the work of opening a database on behalf of
  126506. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  126507. ** is UTF-8 encoded.
  126508. */
  126509. static int openDatabase(
  126510. const char *zFilename, /* Database filename UTF-8 encoded */
  126511. sqlite3 **ppDb, /* OUT: Returned database handle */
  126512. unsigned int flags, /* Operational flags */
  126513. const char *zVfs /* Name of the VFS to use */
  126514. ){
  126515. sqlite3 *db; /* Store allocated handle here */
  126516. int rc; /* Return code */
  126517. int isThreadsafe; /* True for threadsafe connections */
  126518. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  126519. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  126520. #ifdef SQLITE_ENABLE_API_ARMOR
  126521. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  126522. #endif
  126523. *ppDb = 0;
  126524. #ifndef SQLITE_OMIT_AUTOINIT
  126525. rc = sqlite3_initialize();
  126526. if( rc ) return rc;
  126527. #endif
  126528. /* Only allow sensible combinations of bits in the flags argument.
  126529. ** Throw an error if any non-sense combination is used. If we
  126530. ** do not block illegal combinations here, it could trigger
  126531. ** assert() statements in deeper layers. Sensible combinations
  126532. ** are:
  126533. **
  126534. ** 1: SQLITE_OPEN_READONLY
  126535. ** 2: SQLITE_OPEN_READWRITE
  126536. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  126537. */
  126538. assert( SQLITE_OPEN_READONLY == 0x01 );
  126539. assert( SQLITE_OPEN_READWRITE == 0x02 );
  126540. assert( SQLITE_OPEN_CREATE == 0x04 );
  126541. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  126542. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  126543. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  126544. if( ((1<<(flags&7)) & 0x46)==0 ){
  126545. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  126546. }
  126547. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  126548. isThreadsafe = 0;
  126549. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  126550. isThreadsafe = 0;
  126551. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  126552. isThreadsafe = 1;
  126553. }else{
  126554. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  126555. }
  126556. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  126557. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  126558. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  126559. flags |= SQLITE_OPEN_SHAREDCACHE;
  126560. }
  126561. /* Remove harmful bits from the flags parameter
  126562. **
  126563. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  126564. ** dealt with in the previous code block. Besides these, the only
  126565. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  126566. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  126567. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  126568. ** off all other flags.
  126569. */
  126570. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  126571. SQLITE_OPEN_EXCLUSIVE |
  126572. SQLITE_OPEN_MAIN_DB |
  126573. SQLITE_OPEN_TEMP_DB |
  126574. SQLITE_OPEN_TRANSIENT_DB |
  126575. SQLITE_OPEN_MAIN_JOURNAL |
  126576. SQLITE_OPEN_TEMP_JOURNAL |
  126577. SQLITE_OPEN_SUBJOURNAL |
  126578. SQLITE_OPEN_MASTER_JOURNAL |
  126579. SQLITE_OPEN_NOMUTEX |
  126580. SQLITE_OPEN_FULLMUTEX |
  126581. SQLITE_OPEN_WAL
  126582. );
  126583. /* Allocate the sqlite data structure */
  126584. db = sqlite3MallocZero( sizeof(sqlite3) );
  126585. if( db==0 ) goto opendb_out;
  126586. if( isThreadsafe ){
  126587. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  126588. if( db->mutex==0 ){
  126589. sqlite3_free(db);
  126590. db = 0;
  126591. goto opendb_out;
  126592. }
  126593. }
  126594. sqlite3_mutex_enter(db->mutex);
  126595. db->errMask = 0xff;
  126596. db->nDb = 2;
  126597. db->magic = SQLITE_MAGIC_BUSY;
  126598. db->aDb = db->aDbStatic;
  126599. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  126600. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  126601. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  126602. db->autoCommit = 1;
  126603. db->nextAutovac = -1;
  126604. db->szMmap = sqlite3GlobalConfig.szMmap;
  126605. db->nextPagesize = 0;
  126606. db->nMaxSorterMmap = 0x7FFFFFFF;
  126607. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  126608. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  126609. | SQLITE_AutoIndex
  126610. #endif
  126611. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  126612. | SQLITE_CkptFullFSync
  126613. #endif
  126614. #if SQLITE_DEFAULT_FILE_FORMAT<4
  126615. | SQLITE_LegacyFileFmt
  126616. #endif
  126617. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  126618. | SQLITE_LoadExtension
  126619. #endif
  126620. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  126621. | SQLITE_RecTriggers
  126622. #endif
  126623. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  126624. | SQLITE_ForeignKeys
  126625. #endif
  126626. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  126627. | SQLITE_ReverseOrder
  126628. #endif
  126629. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  126630. | SQLITE_CellSizeCk
  126631. #endif
  126632. ;
  126633. sqlite3HashInit(&db->aCollSeq);
  126634. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126635. sqlite3HashInit(&db->aModule);
  126636. #endif
  126637. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  126638. ** and UTF-16, so add a version for each to avoid any unnecessary
  126639. ** conversions. The only error that can occur here is a malloc() failure.
  126640. **
  126641. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  126642. ** functions:
  126643. */
  126644. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  126645. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  126646. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  126647. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  126648. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  126649. if( db->mallocFailed ){
  126650. goto opendb_out;
  126651. }
  126652. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  126653. ** strings is BINARY.
  126654. */
  126655. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  126656. assert( db->pDfltColl!=0 );
  126657. /* Parse the filename/URI argument. */
  126658. db->openFlags = flags;
  126659. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  126660. if( rc!=SQLITE_OK ){
  126661. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  126662. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  126663. sqlite3_free(zErrMsg);
  126664. goto opendb_out;
  126665. }
  126666. /* Open the backend database driver */
  126667. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  126668. flags | SQLITE_OPEN_MAIN_DB);
  126669. if( rc!=SQLITE_OK ){
  126670. if( rc==SQLITE_IOERR_NOMEM ){
  126671. rc = SQLITE_NOMEM;
  126672. }
  126673. sqlite3Error(db, rc);
  126674. goto opendb_out;
  126675. }
  126676. sqlite3BtreeEnter(db->aDb[0].pBt);
  126677. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  126678. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  126679. sqlite3BtreeLeave(db->aDb[0].pBt);
  126680. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  126681. /* The default safety_level for the main database is 'full'; for the temp
  126682. ** database it is 'NONE'. This matches the pager layer defaults.
  126683. */
  126684. db->aDb[0].zName = "main";
  126685. db->aDb[0].safety_level = 3;
  126686. db->aDb[1].zName = "temp";
  126687. db->aDb[1].safety_level = 1;
  126688. db->magic = SQLITE_MAGIC_OPEN;
  126689. if( db->mallocFailed ){
  126690. goto opendb_out;
  126691. }
  126692. /* Register all built-in functions, but do not attempt to read the
  126693. ** database schema yet. This is delayed until the first time the database
  126694. ** is accessed.
  126695. */
  126696. sqlite3Error(db, SQLITE_OK);
  126697. sqlite3RegisterBuiltinFunctions(db);
  126698. /* Load automatic extensions - extensions that have been registered
  126699. ** using the sqlite3_automatic_extension() API.
  126700. */
  126701. rc = sqlite3_errcode(db);
  126702. if( rc==SQLITE_OK ){
  126703. sqlite3AutoLoadExtensions(db);
  126704. rc = sqlite3_errcode(db);
  126705. if( rc!=SQLITE_OK ){
  126706. goto opendb_out;
  126707. }
  126708. }
  126709. #ifdef SQLITE_ENABLE_FTS1
  126710. if( !db->mallocFailed ){
  126711. extern int sqlite3Fts1Init(sqlite3*);
  126712. rc = sqlite3Fts1Init(db);
  126713. }
  126714. #endif
  126715. #ifdef SQLITE_ENABLE_FTS2
  126716. if( !db->mallocFailed && rc==SQLITE_OK ){
  126717. extern int sqlite3Fts2Init(sqlite3*);
  126718. rc = sqlite3Fts2Init(db);
  126719. }
  126720. #endif
  126721. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  126722. if( !db->mallocFailed && rc==SQLITE_OK ){
  126723. rc = sqlite3Fts3Init(db);
  126724. }
  126725. #endif
  126726. #ifdef SQLITE_ENABLE_FTS5
  126727. if( !db->mallocFailed && rc==SQLITE_OK ){
  126728. rc = sqlite3Fts5Init(db);
  126729. }
  126730. #endif
  126731. #ifdef SQLITE_ENABLE_ICU
  126732. if( !db->mallocFailed && rc==SQLITE_OK ){
  126733. rc = sqlite3IcuInit(db);
  126734. }
  126735. #endif
  126736. #ifdef SQLITE_ENABLE_RTREE
  126737. if( !db->mallocFailed && rc==SQLITE_OK){
  126738. rc = sqlite3RtreeInit(db);
  126739. }
  126740. #endif
  126741. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  126742. if( !db->mallocFailed && rc==SQLITE_OK){
  126743. rc = sqlite3DbstatRegister(db);
  126744. }
  126745. #endif
  126746. #ifdef SQLITE_ENABLE_JSON1
  126747. if( !db->mallocFailed && rc==SQLITE_OK){
  126748. rc = sqlite3Json1Init(db);
  126749. }
  126750. #endif
  126751. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  126752. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  126753. ** mode. Doing nothing at all also makes NORMAL the default.
  126754. */
  126755. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  126756. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  126757. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  126758. SQLITE_DEFAULT_LOCKING_MODE);
  126759. #endif
  126760. if( rc ) sqlite3Error(db, rc);
  126761. /* Enable the lookaside-malloc subsystem */
  126762. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  126763. sqlite3GlobalConfig.nLookaside);
  126764. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  126765. opendb_out:
  126766. sqlite3_free(zOpen);
  126767. if( db ){
  126768. assert( db->mutex!=0 || isThreadsafe==0
  126769. || sqlite3GlobalConfig.bFullMutex==0 );
  126770. sqlite3_mutex_leave(db->mutex);
  126771. }
  126772. rc = sqlite3_errcode(db);
  126773. assert( db!=0 || rc==SQLITE_NOMEM );
  126774. if( rc==SQLITE_NOMEM ){
  126775. sqlite3_close(db);
  126776. db = 0;
  126777. }else if( rc!=SQLITE_OK ){
  126778. db->magic = SQLITE_MAGIC_SICK;
  126779. }
  126780. *ppDb = db;
  126781. #ifdef SQLITE_ENABLE_SQLLOG
  126782. if( sqlite3GlobalConfig.xSqllog ){
  126783. /* Opening a db handle. Fourth parameter is passed 0. */
  126784. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  126785. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  126786. }
  126787. #endif
  126788. #if defined(SQLITE_HAS_CODEC)
  126789. if( rc==SQLITE_OK ){
  126790. const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
  126791. if( zHexKey && zHexKey[0] ){
  126792. u8 iByte;
  126793. int i;
  126794. char zKey[40];
  126795. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
  126796. iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
  126797. if( (i&1)!=0 ) zKey[i/2] = iByte;
  126798. }
  126799. sqlite3_key_v2(db, 0, zKey, i/2);
  126800. }
  126801. }
  126802. #endif
  126803. return rc & 0xff;
  126804. }
  126805. /*
  126806. ** Open a new database handle.
  126807. */
  126808. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  126809. const char *zFilename,
  126810. sqlite3 **ppDb
  126811. ){
  126812. return openDatabase(zFilename, ppDb,
  126813. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  126814. }
  126815. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  126816. const char *filename, /* Database filename (UTF-8) */
  126817. sqlite3 **ppDb, /* OUT: SQLite db handle */
  126818. int flags, /* Flags */
  126819. const char *zVfs /* Name of VFS module to use */
  126820. ){
  126821. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  126822. }
  126823. #ifndef SQLITE_OMIT_UTF16
  126824. /*
  126825. ** Open a new database handle.
  126826. */
  126827. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  126828. const void *zFilename,
  126829. sqlite3 **ppDb
  126830. ){
  126831. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  126832. sqlite3_value *pVal;
  126833. int rc;
  126834. #ifdef SQLITE_ENABLE_API_ARMOR
  126835. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  126836. #endif
  126837. *ppDb = 0;
  126838. #ifndef SQLITE_OMIT_AUTOINIT
  126839. rc = sqlite3_initialize();
  126840. if( rc ) return rc;
  126841. #endif
  126842. if( zFilename==0 ) zFilename = "\000\000";
  126843. pVal = sqlite3ValueNew(0);
  126844. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  126845. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  126846. if( zFilename8 ){
  126847. rc = openDatabase(zFilename8, ppDb,
  126848. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  126849. assert( *ppDb || rc==SQLITE_NOMEM );
  126850. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  126851. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  126852. }
  126853. }else{
  126854. rc = SQLITE_NOMEM;
  126855. }
  126856. sqlite3ValueFree(pVal);
  126857. return rc & 0xff;
  126858. }
  126859. #endif /* SQLITE_OMIT_UTF16 */
  126860. /*
  126861. ** Register a new collation sequence with the database handle db.
  126862. */
  126863. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  126864. sqlite3* db,
  126865. const char *zName,
  126866. int enc,
  126867. void* pCtx,
  126868. int(*xCompare)(void*,int,const void*,int,const void*)
  126869. ){
  126870. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  126871. }
  126872. /*
  126873. ** Register a new collation sequence with the database handle db.
  126874. */
  126875. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  126876. sqlite3* db,
  126877. const char *zName,
  126878. int enc,
  126879. void* pCtx,
  126880. int(*xCompare)(void*,int,const void*,int,const void*),
  126881. void(*xDel)(void*)
  126882. ){
  126883. int rc;
  126884. #ifdef SQLITE_ENABLE_API_ARMOR
  126885. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  126886. #endif
  126887. sqlite3_mutex_enter(db->mutex);
  126888. assert( !db->mallocFailed );
  126889. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  126890. rc = sqlite3ApiExit(db, rc);
  126891. sqlite3_mutex_leave(db->mutex);
  126892. return rc;
  126893. }
  126894. #ifndef SQLITE_OMIT_UTF16
  126895. /*
  126896. ** Register a new collation sequence with the database handle db.
  126897. */
  126898. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  126899. sqlite3* db,
  126900. const void *zName,
  126901. int enc,
  126902. void* pCtx,
  126903. int(*xCompare)(void*,int,const void*,int,const void*)
  126904. ){
  126905. int rc = SQLITE_OK;
  126906. char *zName8;
  126907. #ifdef SQLITE_ENABLE_API_ARMOR
  126908. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  126909. #endif
  126910. sqlite3_mutex_enter(db->mutex);
  126911. assert( !db->mallocFailed );
  126912. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  126913. if( zName8 ){
  126914. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  126915. sqlite3DbFree(db, zName8);
  126916. }
  126917. rc = sqlite3ApiExit(db, rc);
  126918. sqlite3_mutex_leave(db->mutex);
  126919. return rc;
  126920. }
  126921. #endif /* SQLITE_OMIT_UTF16 */
  126922. /*
  126923. ** Register a collation sequence factory callback with the database handle
  126924. ** db. Replace any previously installed collation sequence factory.
  126925. */
  126926. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  126927. sqlite3 *db,
  126928. void *pCollNeededArg,
  126929. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  126930. ){
  126931. #ifdef SQLITE_ENABLE_API_ARMOR
  126932. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  126933. #endif
  126934. sqlite3_mutex_enter(db->mutex);
  126935. db->xCollNeeded = xCollNeeded;
  126936. db->xCollNeeded16 = 0;
  126937. db->pCollNeededArg = pCollNeededArg;
  126938. sqlite3_mutex_leave(db->mutex);
  126939. return SQLITE_OK;
  126940. }
  126941. #ifndef SQLITE_OMIT_UTF16
  126942. /*
  126943. ** Register a collation sequence factory callback with the database handle
  126944. ** db. Replace any previously installed collation sequence factory.
  126945. */
  126946. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  126947. sqlite3 *db,
  126948. void *pCollNeededArg,
  126949. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  126950. ){
  126951. #ifdef SQLITE_ENABLE_API_ARMOR
  126952. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  126953. #endif
  126954. sqlite3_mutex_enter(db->mutex);
  126955. db->xCollNeeded = 0;
  126956. db->xCollNeeded16 = xCollNeeded16;
  126957. db->pCollNeededArg = pCollNeededArg;
  126958. sqlite3_mutex_leave(db->mutex);
  126959. return SQLITE_OK;
  126960. }
  126961. #endif /* SQLITE_OMIT_UTF16 */
  126962. #ifndef SQLITE_OMIT_DEPRECATED
  126963. /*
  126964. ** This function is now an anachronism. It used to be used to recover from a
  126965. ** malloc() failure, but SQLite now does this automatically.
  126966. */
  126967. SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
  126968. return SQLITE_OK;
  126969. }
  126970. #endif
  126971. /*
  126972. ** Test to see whether or not the database connection is in autocommit
  126973. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  126974. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  126975. ** by the next COMMIT or ROLLBACK.
  126976. */
  126977. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
  126978. #ifdef SQLITE_ENABLE_API_ARMOR
  126979. if( !sqlite3SafetyCheckOk(db) ){
  126980. (void)SQLITE_MISUSE_BKPT;
  126981. return 0;
  126982. }
  126983. #endif
  126984. return db->autoCommit;
  126985. }
  126986. /*
  126987. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  126988. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  126989. ** constants. They serve two purposes:
  126990. **
  126991. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  126992. ** to detect when version error conditions occurs.
  126993. **
  126994. ** 2. Invoke sqlite3_log() to provide the source code location where
  126995. ** a low-level error is first detected.
  126996. */
  126997. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  126998. testcase( sqlite3GlobalConfig.xLog!=0 );
  126999. sqlite3_log(SQLITE_CORRUPT,
  127000. "database corruption at line %d of [%.10s]",
  127001. lineno, 20+sqlite3_sourceid());
  127002. return SQLITE_CORRUPT;
  127003. }
  127004. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  127005. testcase( sqlite3GlobalConfig.xLog!=0 );
  127006. sqlite3_log(SQLITE_MISUSE,
  127007. "misuse at line %d of [%.10s]",
  127008. lineno, 20+sqlite3_sourceid());
  127009. return SQLITE_MISUSE;
  127010. }
  127011. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  127012. testcase( sqlite3GlobalConfig.xLog!=0 );
  127013. sqlite3_log(SQLITE_CANTOPEN,
  127014. "cannot open file at line %d of [%.10s]",
  127015. lineno, 20+sqlite3_sourceid());
  127016. return SQLITE_CANTOPEN;
  127017. }
  127018. #ifndef SQLITE_OMIT_DEPRECATED
  127019. /*
  127020. ** This is a convenience routine that makes sure that all thread-specific
  127021. ** data for this thread has been deallocated.
  127022. **
  127023. ** SQLite no longer uses thread-specific data so this routine is now a
  127024. ** no-op. It is retained for historical compatibility.
  127025. */
  127026. SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
  127027. }
  127028. #endif
  127029. /*
  127030. ** Return meta information about a specific column of a database table.
  127031. ** See comment in sqlite3.h (sqlite.h.in) for details.
  127032. */
  127033. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  127034. sqlite3 *db, /* Connection handle */
  127035. const char *zDbName, /* Database name or NULL */
  127036. const char *zTableName, /* Table name */
  127037. const char *zColumnName, /* Column name */
  127038. char const **pzDataType, /* OUTPUT: Declared data type */
  127039. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  127040. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  127041. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  127042. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  127043. ){
  127044. int rc;
  127045. char *zErrMsg = 0;
  127046. Table *pTab = 0;
  127047. Column *pCol = 0;
  127048. int iCol = 0;
  127049. char const *zDataType = 0;
  127050. char const *zCollSeq = 0;
  127051. int notnull = 0;
  127052. int primarykey = 0;
  127053. int autoinc = 0;
  127054. #ifdef SQLITE_ENABLE_API_ARMOR
  127055. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  127056. return SQLITE_MISUSE_BKPT;
  127057. }
  127058. #endif
  127059. /* Ensure the database schema has been loaded */
  127060. sqlite3_mutex_enter(db->mutex);
  127061. sqlite3BtreeEnterAll(db);
  127062. rc = sqlite3Init(db, &zErrMsg);
  127063. if( SQLITE_OK!=rc ){
  127064. goto error_out;
  127065. }
  127066. /* Locate the table in question */
  127067. pTab = sqlite3FindTable(db, zTableName, zDbName);
  127068. if( !pTab || pTab->pSelect ){
  127069. pTab = 0;
  127070. goto error_out;
  127071. }
  127072. /* Find the column for which info is requested */
  127073. if( zColumnName==0 ){
  127074. /* Query for existance of table only */
  127075. }else{
  127076. for(iCol=0; iCol<pTab->nCol; iCol++){
  127077. pCol = &pTab->aCol[iCol];
  127078. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  127079. break;
  127080. }
  127081. }
  127082. if( iCol==pTab->nCol ){
  127083. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  127084. iCol = pTab->iPKey;
  127085. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  127086. }else{
  127087. pTab = 0;
  127088. goto error_out;
  127089. }
  127090. }
  127091. }
  127092. /* The following block stores the meta information that will be returned
  127093. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  127094. ** and autoinc. At this point there are two possibilities:
  127095. **
  127096. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  127097. ** and there is no explicitly declared IPK column.
  127098. **
  127099. ** 2. The table is not a view and the column name identified an
  127100. ** explicitly declared column. Copy meta information from *pCol.
  127101. */
  127102. if( pCol ){
  127103. zDataType = pCol->zType;
  127104. zCollSeq = pCol->zColl;
  127105. notnull = pCol->notNull!=0;
  127106. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  127107. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  127108. }else{
  127109. zDataType = "INTEGER";
  127110. primarykey = 1;
  127111. }
  127112. if( !zCollSeq ){
  127113. zCollSeq = sqlite3StrBINARY;
  127114. }
  127115. error_out:
  127116. sqlite3BtreeLeaveAll(db);
  127117. /* Whether the function call succeeded or failed, set the output parameters
  127118. ** to whatever their local counterparts contain. If an error did occur,
  127119. ** this has the effect of zeroing all output parameters.
  127120. */
  127121. if( pzDataType ) *pzDataType = zDataType;
  127122. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  127123. if( pNotNull ) *pNotNull = notnull;
  127124. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  127125. if( pAutoinc ) *pAutoinc = autoinc;
  127126. if( SQLITE_OK==rc && !pTab ){
  127127. sqlite3DbFree(db, zErrMsg);
  127128. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  127129. zColumnName);
  127130. rc = SQLITE_ERROR;
  127131. }
  127132. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  127133. sqlite3DbFree(db, zErrMsg);
  127134. rc = sqlite3ApiExit(db, rc);
  127135. sqlite3_mutex_leave(db->mutex);
  127136. return rc;
  127137. }
  127138. /*
  127139. ** Sleep for a little while. Return the amount of time slept.
  127140. */
  127141. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
  127142. sqlite3_vfs *pVfs;
  127143. int rc;
  127144. pVfs = sqlite3_vfs_find(0);
  127145. if( pVfs==0 ) return 0;
  127146. /* This function works in milliseconds, but the underlying OsSleep()
  127147. ** API uses microseconds. Hence the 1000's.
  127148. */
  127149. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  127150. return rc;
  127151. }
  127152. /*
  127153. ** Enable or disable the extended result codes.
  127154. */
  127155. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  127156. #ifdef SQLITE_ENABLE_API_ARMOR
  127157. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  127158. #endif
  127159. sqlite3_mutex_enter(db->mutex);
  127160. db->errMask = onoff ? 0xffffffff : 0xff;
  127161. sqlite3_mutex_leave(db->mutex);
  127162. return SQLITE_OK;
  127163. }
  127164. /*
  127165. ** Invoke the xFileControl method on a particular database.
  127166. */
  127167. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  127168. int rc = SQLITE_ERROR;
  127169. Btree *pBtree;
  127170. #ifdef SQLITE_ENABLE_API_ARMOR
  127171. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  127172. #endif
  127173. sqlite3_mutex_enter(db->mutex);
  127174. pBtree = sqlite3DbNameToBtree(db, zDbName);
  127175. if( pBtree ){
  127176. Pager *pPager;
  127177. sqlite3_file *fd;
  127178. sqlite3BtreeEnter(pBtree);
  127179. pPager = sqlite3BtreePager(pBtree);
  127180. assert( pPager!=0 );
  127181. fd = sqlite3PagerFile(pPager);
  127182. assert( fd!=0 );
  127183. if( op==SQLITE_FCNTL_FILE_POINTER ){
  127184. *(sqlite3_file**)pArg = fd;
  127185. rc = SQLITE_OK;
  127186. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  127187. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  127188. rc = SQLITE_OK;
  127189. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  127190. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  127191. rc = SQLITE_OK;
  127192. }else if( fd->pMethods ){
  127193. rc = sqlite3OsFileControl(fd, op, pArg);
  127194. }else{
  127195. rc = SQLITE_NOTFOUND;
  127196. }
  127197. sqlite3BtreeLeave(pBtree);
  127198. }
  127199. sqlite3_mutex_leave(db->mutex);
  127200. return rc;
  127201. }
  127202. /*
  127203. ** Interface to the testing logic.
  127204. */
  127205. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
  127206. int rc = 0;
  127207. #ifdef SQLITE_OMIT_BUILTIN_TEST
  127208. UNUSED_PARAMETER(op);
  127209. #else
  127210. va_list ap;
  127211. va_start(ap, op);
  127212. switch( op ){
  127213. /*
  127214. ** Save the current state of the PRNG.
  127215. */
  127216. case SQLITE_TESTCTRL_PRNG_SAVE: {
  127217. sqlite3PrngSaveState();
  127218. break;
  127219. }
  127220. /*
  127221. ** Restore the state of the PRNG to the last state saved using
  127222. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  127223. ** this verb acts like PRNG_RESET.
  127224. */
  127225. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  127226. sqlite3PrngRestoreState();
  127227. break;
  127228. }
  127229. /*
  127230. ** Reset the PRNG back to its uninitialized state. The next call
  127231. ** to sqlite3_randomness() will reseed the PRNG using a single call
  127232. ** to the xRandomness method of the default VFS.
  127233. */
  127234. case SQLITE_TESTCTRL_PRNG_RESET: {
  127235. sqlite3_randomness(0,0);
  127236. break;
  127237. }
  127238. /*
  127239. ** sqlite3_test_control(BITVEC_TEST, size, program)
  127240. **
  127241. ** Run a test against a Bitvec object of size. The program argument
  127242. ** is an array of integers that defines the test. Return -1 on a
  127243. ** memory allocation error, 0 on success, or non-zero for an error.
  127244. ** See the sqlite3BitvecBuiltinTest() for additional information.
  127245. */
  127246. case SQLITE_TESTCTRL_BITVEC_TEST: {
  127247. int sz = va_arg(ap, int);
  127248. int *aProg = va_arg(ap, int*);
  127249. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  127250. break;
  127251. }
  127252. /*
  127253. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  127254. **
  127255. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  127256. ** if xCallback is not NULL.
  127257. **
  127258. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  127259. ** is called immediately after installing the new callback and the return
  127260. ** value from sqlite3FaultSim(0) becomes the return from
  127261. ** sqlite3_test_control().
  127262. */
  127263. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  127264. /* MSVC is picky about pulling func ptrs from va lists.
  127265. ** http://support.microsoft.com/kb/47961
  127266. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  127267. */
  127268. typedef int(*TESTCALLBACKFUNC_t)(int);
  127269. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  127270. rc = sqlite3FaultSim(0);
  127271. break;
  127272. }
  127273. /*
  127274. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  127275. **
  127276. ** Register hooks to call to indicate which malloc() failures
  127277. ** are benign.
  127278. */
  127279. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  127280. typedef void (*void_function)(void);
  127281. void_function xBenignBegin;
  127282. void_function xBenignEnd;
  127283. xBenignBegin = va_arg(ap, void_function);
  127284. xBenignEnd = va_arg(ap, void_function);
  127285. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  127286. break;
  127287. }
  127288. /*
  127289. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  127290. **
  127291. ** Set the PENDING byte to the value in the argument, if X>0.
  127292. ** Make no changes if X==0. Return the value of the pending byte
  127293. ** as it existing before this routine was called.
  127294. **
  127295. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  127296. ** an incompatible database file format. Changing the PENDING byte
  127297. ** while any database connection is open results in undefined and
  127298. ** deleterious behavior.
  127299. */
  127300. case SQLITE_TESTCTRL_PENDING_BYTE: {
  127301. rc = PENDING_BYTE;
  127302. #ifndef SQLITE_OMIT_WSD
  127303. {
  127304. unsigned int newVal = va_arg(ap, unsigned int);
  127305. if( newVal ) sqlite3PendingByte = newVal;
  127306. }
  127307. #endif
  127308. break;
  127309. }
  127310. /*
  127311. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  127312. **
  127313. ** This action provides a run-time test to see whether or not
  127314. ** assert() was enabled at compile-time. If X is true and assert()
  127315. ** is enabled, then the return value is true. If X is true and
  127316. ** assert() is disabled, then the return value is zero. If X is
  127317. ** false and assert() is enabled, then the assertion fires and the
  127318. ** process aborts. If X is false and assert() is disabled, then the
  127319. ** return value is zero.
  127320. */
  127321. case SQLITE_TESTCTRL_ASSERT: {
  127322. volatile int x = 0;
  127323. assert( (x = va_arg(ap,int))!=0 );
  127324. rc = x;
  127325. break;
  127326. }
  127327. /*
  127328. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  127329. **
  127330. ** This action provides a run-time test to see how the ALWAYS and
  127331. ** NEVER macros were defined at compile-time.
  127332. **
  127333. ** The return value is ALWAYS(X).
  127334. **
  127335. ** The recommended test is X==2. If the return value is 2, that means
  127336. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  127337. ** default setting. If the return value is 1, then ALWAYS() is either
  127338. ** hard-coded to true or else it asserts if its argument is false.
  127339. ** The first behavior (hard-coded to true) is the case if
  127340. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  127341. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  127342. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  127343. **
  127344. ** The run-time test procedure might look something like this:
  127345. **
  127346. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  127347. ** // ALWAYS() and NEVER() are no-op pass-through macros
  127348. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  127349. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  127350. ** }else{
  127351. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  127352. ** }
  127353. */
  127354. case SQLITE_TESTCTRL_ALWAYS: {
  127355. int x = va_arg(ap,int);
  127356. rc = ALWAYS(x);
  127357. break;
  127358. }
  127359. /*
  127360. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  127361. **
  127362. ** The integer returned reveals the byte-order of the computer on which
  127363. ** SQLite is running:
  127364. **
  127365. ** 1 big-endian, determined at run-time
  127366. ** 10 little-endian, determined at run-time
  127367. ** 432101 big-endian, determined at compile-time
  127368. ** 123410 little-endian, determined at compile-time
  127369. */
  127370. case SQLITE_TESTCTRL_BYTEORDER: {
  127371. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  127372. break;
  127373. }
  127374. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  127375. **
  127376. ** Set the nReserve size to N for the main database on the database
  127377. ** connection db.
  127378. */
  127379. case SQLITE_TESTCTRL_RESERVE: {
  127380. sqlite3 *db = va_arg(ap, sqlite3*);
  127381. int x = va_arg(ap,int);
  127382. sqlite3_mutex_enter(db->mutex);
  127383. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  127384. sqlite3_mutex_leave(db->mutex);
  127385. break;
  127386. }
  127387. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  127388. **
  127389. ** Enable or disable various optimizations for testing purposes. The
  127390. ** argument N is a bitmask of optimizations to be disabled. For normal
  127391. ** operation N should be 0. The idea is that a test program (like the
  127392. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  127393. ** with various optimizations disabled to verify that the same answer
  127394. ** is obtained in every case.
  127395. */
  127396. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  127397. sqlite3 *db = va_arg(ap, sqlite3*);
  127398. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  127399. break;
  127400. }
  127401. #ifdef SQLITE_N_KEYWORD
  127402. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  127403. **
  127404. ** If zWord is a keyword recognized by the parser, then return the
  127405. ** number of keywords. Or if zWord is not a keyword, return 0.
  127406. **
  127407. ** This test feature is only available in the amalgamation since
  127408. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  127409. ** is built using separate source files.
  127410. */
  127411. case SQLITE_TESTCTRL_ISKEYWORD: {
  127412. const char *zWord = va_arg(ap, const char*);
  127413. int n = sqlite3Strlen30(zWord);
  127414. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  127415. break;
  127416. }
  127417. #endif
  127418. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  127419. **
  127420. ** Pass pFree into sqlite3ScratchFree().
  127421. ** If sz>0 then allocate a scratch buffer into pNew.
  127422. */
  127423. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  127424. void *pFree, **ppNew;
  127425. int sz;
  127426. sz = va_arg(ap, int);
  127427. ppNew = va_arg(ap, void**);
  127428. pFree = va_arg(ap, void*);
  127429. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  127430. sqlite3ScratchFree(pFree);
  127431. break;
  127432. }
  127433. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  127434. **
  127435. ** If parameter onoff is non-zero, configure the wrappers so that all
  127436. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  127437. ** undo this setting.
  127438. */
  127439. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  127440. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  127441. break;
  127442. }
  127443. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  127444. **
  127445. ** Set or clear a flag that indicates that the database file is always well-
  127446. ** formed and never corrupt. This flag is clear by default, indicating that
  127447. ** database files might have arbitrary corruption. Setting the flag during
  127448. ** testing causes certain assert() statements in the code to be activated
  127449. ** that demonstrat invariants on well-formed database files.
  127450. */
  127451. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  127452. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  127453. break;
  127454. }
  127455. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  127456. **
  127457. ** Set the VDBE coverage callback function to xCallback with context
  127458. ** pointer ptr.
  127459. */
  127460. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  127461. #ifdef SQLITE_VDBE_COVERAGE
  127462. typedef void (*branch_callback)(void*,int,u8,u8);
  127463. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  127464. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  127465. #endif
  127466. break;
  127467. }
  127468. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  127469. case SQLITE_TESTCTRL_SORTER_MMAP: {
  127470. sqlite3 *db = va_arg(ap, sqlite3*);
  127471. db->nMaxSorterMmap = va_arg(ap, int);
  127472. break;
  127473. }
  127474. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  127475. **
  127476. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  127477. ** not.
  127478. */
  127479. case SQLITE_TESTCTRL_ISINIT: {
  127480. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  127481. break;
  127482. }
  127483. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  127484. **
  127485. ** This test control is used to create imposter tables. "db" is a pointer
  127486. ** to the database connection. dbName is the database name (ex: "main" or
  127487. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  127488. ** or off. "tnum" is the root page of the b-tree to which the imposter
  127489. ** table should connect.
  127490. **
  127491. ** Enable imposter mode only when the schema has already been parsed. Then
  127492. ** run a single CREATE TABLE statement to construct the imposter table in
  127493. ** the parsed schema. Then turn imposter mode back off again.
  127494. **
  127495. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  127496. ** the schema to be reparsed the next time it is needed. This has the
  127497. ** effect of erasing all imposter tables.
  127498. */
  127499. case SQLITE_TESTCTRL_IMPOSTER: {
  127500. sqlite3 *db = va_arg(ap, sqlite3*);
  127501. sqlite3_mutex_enter(db->mutex);
  127502. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  127503. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  127504. db->init.newTnum = va_arg(ap,int);
  127505. if( db->init.busy==0 && db->init.newTnum>0 ){
  127506. sqlite3ResetAllSchemasOfConnection(db);
  127507. }
  127508. sqlite3_mutex_leave(db->mutex);
  127509. break;
  127510. }
  127511. }
  127512. va_end(ap);
  127513. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  127514. return rc;
  127515. }
  127516. /*
  127517. ** This is a utility routine, useful to VFS implementations, that checks
  127518. ** to see if a database file was a URI that contained a specific query
  127519. ** parameter, and if so obtains the value of the query parameter.
  127520. **
  127521. ** The zFilename argument is the filename pointer passed into the xOpen()
  127522. ** method of a VFS implementation. The zParam argument is the name of the
  127523. ** query parameter we seek. This routine returns the value of the zParam
  127524. ** parameter if it exists. If the parameter does not exist, this routine
  127525. ** returns a NULL pointer.
  127526. */
  127527. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  127528. if( zFilename==0 || zParam==0 ) return 0;
  127529. zFilename += sqlite3Strlen30(zFilename) + 1;
  127530. while( zFilename[0] ){
  127531. int x = strcmp(zFilename, zParam);
  127532. zFilename += sqlite3Strlen30(zFilename) + 1;
  127533. if( x==0 ) return zFilename;
  127534. zFilename += sqlite3Strlen30(zFilename) + 1;
  127535. }
  127536. return 0;
  127537. }
  127538. /*
  127539. ** Return a boolean value for a query parameter.
  127540. */
  127541. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  127542. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  127543. bDflt = bDflt!=0;
  127544. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  127545. }
  127546. /*
  127547. ** Return a 64-bit integer value for a query parameter.
  127548. */
  127549. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
  127550. const char *zFilename, /* Filename as passed to xOpen */
  127551. const char *zParam, /* URI parameter sought */
  127552. sqlite3_int64 bDflt /* return if parameter is missing */
  127553. ){
  127554. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  127555. sqlite3_int64 v;
  127556. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  127557. bDflt = v;
  127558. }
  127559. return bDflt;
  127560. }
  127561. /*
  127562. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  127563. */
  127564. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  127565. int i;
  127566. for(i=0; i<db->nDb; i++){
  127567. if( db->aDb[i].pBt
  127568. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  127569. ){
  127570. return db->aDb[i].pBt;
  127571. }
  127572. }
  127573. return 0;
  127574. }
  127575. /*
  127576. ** Return the filename of the database associated with a database
  127577. ** connection.
  127578. */
  127579. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  127580. Btree *pBt;
  127581. #ifdef SQLITE_ENABLE_API_ARMOR
  127582. if( !sqlite3SafetyCheckOk(db) ){
  127583. (void)SQLITE_MISUSE_BKPT;
  127584. return 0;
  127585. }
  127586. #endif
  127587. pBt = sqlite3DbNameToBtree(db, zDbName);
  127588. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  127589. }
  127590. /*
  127591. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  127592. ** no such database exists.
  127593. */
  127594. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  127595. Btree *pBt;
  127596. #ifdef SQLITE_ENABLE_API_ARMOR
  127597. if( !sqlite3SafetyCheckOk(db) ){
  127598. (void)SQLITE_MISUSE_BKPT;
  127599. return -1;
  127600. }
  127601. #endif
  127602. pBt = sqlite3DbNameToBtree(db, zDbName);
  127603. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  127604. }
  127605. #ifdef SQLITE_ENABLE_SNAPSHOT
  127606. /*
  127607. ** Obtain a snapshot handle for the snapshot of database zDb currently
  127608. ** being read by handle db.
  127609. */
  127610. SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_get(
  127611. sqlite3 *db,
  127612. const char *zDb,
  127613. sqlite3_snapshot **ppSnapshot
  127614. ){
  127615. int rc = SQLITE_ERROR;
  127616. #ifndef SQLITE_OMIT_WAL
  127617. int iDb;
  127618. #ifdef SQLITE_ENABLE_API_ARMOR
  127619. if( !sqlite3SafetyCheckOk(db) ){
  127620. return SQLITE_MISUSE_BKPT;
  127621. }
  127622. #endif
  127623. sqlite3_mutex_enter(db->mutex);
  127624. iDb = sqlite3FindDbName(db, zDb);
  127625. if( iDb==0 || iDb>1 ){
  127626. Btree *pBt = db->aDb[iDb].pBt;
  127627. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  127628. rc = sqlite3BtreeBeginTrans(pBt, 0);
  127629. if( rc==SQLITE_OK ){
  127630. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  127631. }
  127632. }
  127633. }
  127634. sqlite3_mutex_leave(db->mutex);
  127635. #endif /* SQLITE_OMIT_WAL */
  127636. return rc;
  127637. }
  127638. /*
  127639. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  127640. */
  127641. SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_open(
  127642. sqlite3 *db,
  127643. const char *zDb,
  127644. sqlite3_snapshot *pSnapshot
  127645. ){
  127646. int rc = SQLITE_ERROR;
  127647. #ifndef SQLITE_OMIT_WAL
  127648. #ifdef SQLITE_ENABLE_API_ARMOR
  127649. if( !sqlite3SafetyCheckOk(db) ){
  127650. return SQLITE_MISUSE_BKPT;
  127651. }
  127652. #endif
  127653. sqlite3_mutex_enter(db->mutex);
  127654. if( db->autoCommit==0 ){
  127655. int iDb;
  127656. iDb = sqlite3FindDbName(db, zDb);
  127657. if( iDb==0 || iDb>1 ){
  127658. Btree *pBt = db->aDb[iDb].pBt;
  127659. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  127660. rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
  127661. if( rc==SQLITE_OK ){
  127662. rc = sqlite3BtreeBeginTrans(pBt, 0);
  127663. sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
  127664. }
  127665. }
  127666. }
  127667. }
  127668. sqlite3_mutex_leave(db->mutex);
  127669. #endif /* SQLITE_OMIT_WAL */
  127670. return rc;
  127671. }
  127672. /*
  127673. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  127674. */
  127675. SQLITE_API void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  127676. sqlite3_free(pSnapshot);
  127677. }
  127678. #endif /* SQLITE_ENABLE_SNAPSHOT */
  127679. /************** End of main.c ************************************************/
  127680. /************** Begin file notify.c ******************************************/
  127681. /*
  127682. ** 2009 March 3
  127683. **
  127684. ** The author disclaims copyright to this source code. In place of
  127685. ** a legal notice, here is a blessing:
  127686. **
  127687. ** May you do good and not evil.
  127688. ** May you find forgiveness for yourself and forgive others.
  127689. ** May you share freely, never taking more than you give.
  127690. **
  127691. *************************************************************************
  127692. **
  127693. ** This file contains the implementation of the sqlite3_unlock_notify()
  127694. ** API method and its associated functionality.
  127695. */
  127696. /* #include "sqliteInt.h" */
  127697. /* #include "btreeInt.h" */
  127698. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  127699. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  127700. /*
  127701. ** Public interfaces:
  127702. **
  127703. ** sqlite3ConnectionBlocked()
  127704. ** sqlite3ConnectionUnlocked()
  127705. ** sqlite3ConnectionClosed()
  127706. ** sqlite3_unlock_notify()
  127707. */
  127708. #define assertMutexHeld() \
  127709. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  127710. /*
  127711. ** Head of a linked list of all sqlite3 objects created by this process
  127712. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  127713. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  127714. ** mutex is held.
  127715. */
  127716. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  127717. #ifndef NDEBUG
  127718. /*
  127719. ** This function is a complex assert() that verifies the following
  127720. ** properties of the blocked connections list:
  127721. **
  127722. ** 1) Each entry in the list has a non-NULL value for either
  127723. ** pUnlockConnection or pBlockingConnection, or both.
  127724. **
  127725. ** 2) All entries in the list that share a common value for
  127726. ** xUnlockNotify are grouped together.
  127727. **
  127728. ** 3) If the argument db is not NULL, then none of the entries in the
  127729. ** blocked connections list have pUnlockConnection or pBlockingConnection
  127730. ** set to db. This is used when closing connection db.
  127731. */
  127732. static void checkListProperties(sqlite3 *db){
  127733. sqlite3 *p;
  127734. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  127735. int seen = 0;
  127736. sqlite3 *p2;
  127737. /* Verify property (1) */
  127738. assert( p->pUnlockConnection || p->pBlockingConnection );
  127739. /* Verify property (2) */
  127740. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  127741. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  127742. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  127743. assert( db==0 || p->pUnlockConnection!=db );
  127744. assert( db==0 || p->pBlockingConnection!=db );
  127745. }
  127746. }
  127747. }
  127748. #else
  127749. # define checkListProperties(x)
  127750. #endif
  127751. /*
  127752. ** Remove connection db from the blocked connections list. If connection
  127753. ** db is not currently a part of the list, this function is a no-op.
  127754. */
  127755. static void removeFromBlockedList(sqlite3 *db){
  127756. sqlite3 **pp;
  127757. assertMutexHeld();
  127758. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  127759. if( *pp==db ){
  127760. *pp = (*pp)->pNextBlocked;
  127761. break;
  127762. }
  127763. }
  127764. }
  127765. /*
  127766. ** Add connection db to the blocked connections list. It is assumed
  127767. ** that it is not already a part of the list.
  127768. */
  127769. static void addToBlockedList(sqlite3 *db){
  127770. sqlite3 **pp;
  127771. assertMutexHeld();
  127772. for(
  127773. pp=&sqlite3BlockedList;
  127774. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  127775. pp=&(*pp)->pNextBlocked
  127776. );
  127777. db->pNextBlocked = *pp;
  127778. *pp = db;
  127779. }
  127780. /*
  127781. ** Obtain the STATIC_MASTER mutex.
  127782. */
  127783. static void enterMutex(void){
  127784. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  127785. checkListProperties(0);
  127786. }
  127787. /*
  127788. ** Release the STATIC_MASTER mutex.
  127789. */
  127790. static void leaveMutex(void){
  127791. assertMutexHeld();
  127792. checkListProperties(0);
  127793. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  127794. }
  127795. /*
  127796. ** Register an unlock-notify callback.
  127797. **
  127798. ** This is called after connection "db" has attempted some operation
  127799. ** but has received an SQLITE_LOCKED error because another connection
  127800. ** (call it pOther) in the same process was busy using the same shared
  127801. ** cache. pOther is found by looking at db->pBlockingConnection.
  127802. **
  127803. ** If there is no blocking connection, the callback is invoked immediately,
  127804. ** before this routine returns.
  127805. **
  127806. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  127807. ** a deadlock.
  127808. **
  127809. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  127810. ** its locks.
  127811. **
  127812. ** Each call to this routine overrides any prior callbacks registered
  127813. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  127814. ** cancelled.
  127815. */
  127816. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  127817. sqlite3 *db,
  127818. void (*xNotify)(void **, int),
  127819. void *pArg
  127820. ){
  127821. int rc = SQLITE_OK;
  127822. sqlite3_mutex_enter(db->mutex);
  127823. enterMutex();
  127824. if( xNotify==0 ){
  127825. removeFromBlockedList(db);
  127826. db->pBlockingConnection = 0;
  127827. db->pUnlockConnection = 0;
  127828. db->xUnlockNotify = 0;
  127829. db->pUnlockArg = 0;
  127830. }else if( 0==db->pBlockingConnection ){
  127831. /* The blocking transaction has been concluded. Or there never was a
  127832. ** blocking transaction. In either case, invoke the notify callback
  127833. ** immediately.
  127834. */
  127835. xNotify(&pArg, 1);
  127836. }else{
  127837. sqlite3 *p;
  127838. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  127839. if( p ){
  127840. rc = SQLITE_LOCKED; /* Deadlock detected. */
  127841. }else{
  127842. db->pUnlockConnection = db->pBlockingConnection;
  127843. db->xUnlockNotify = xNotify;
  127844. db->pUnlockArg = pArg;
  127845. removeFromBlockedList(db);
  127846. addToBlockedList(db);
  127847. }
  127848. }
  127849. leaveMutex();
  127850. assert( !db->mallocFailed );
  127851. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  127852. sqlite3_mutex_leave(db->mutex);
  127853. return rc;
  127854. }
  127855. /*
  127856. ** This function is called while stepping or preparing a statement
  127857. ** associated with connection db. The operation will return SQLITE_LOCKED
  127858. ** to the user because it requires a lock that will not be available
  127859. ** until connection pBlocker concludes its current transaction.
  127860. */
  127861. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  127862. enterMutex();
  127863. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  127864. addToBlockedList(db);
  127865. }
  127866. db->pBlockingConnection = pBlocker;
  127867. leaveMutex();
  127868. }
  127869. /*
  127870. ** This function is called when
  127871. ** the transaction opened by database db has just finished. Locks held
  127872. ** by database connection db have been released.
  127873. **
  127874. ** This function loops through each entry in the blocked connections
  127875. ** list and does the following:
  127876. **
  127877. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  127878. ** set to db, then set pBlockingConnection=0.
  127879. **
  127880. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  127881. ** set to db, then invoke the configured unlock-notify callback and
  127882. ** set pUnlockConnection=0.
  127883. **
  127884. ** 3) If the two steps above mean that pBlockingConnection==0 and
  127885. ** pUnlockConnection==0, remove the entry from the blocked connections
  127886. ** list.
  127887. */
  127888. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  127889. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  127890. int nArg = 0; /* Number of entries in aArg[] */
  127891. sqlite3 **pp; /* Iterator variable */
  127892. void **aArg; /* Arguments to the unlock callback */
  127893. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  127894. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  127895. aArg = aStatic;
  127896. enterMutex(); /* Enter STATIC_MASTER mutex */
  127897. /* This loop runs once for each entry in the blocked-connections list. */
  127898. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  127899. sqlite3 *p = *pp;
  127900. /* Step 1. */
  127901. if( p->pBlockingConnection==db ){
  127902. p->pBlockingConnection = 0;
  127903. }
  127904. /* Step 2. */
  127905. if( p->pUnlockConnection==db ){
  127906. assert( p->xUnlockNotify );
  127907. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  127908. xUnlockNotify(aArg, nArg);
  127909. nArg = 0;
  127910. }
  127911. sqlite3BeginBenignMalloc();
  127912. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  127913. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  127914. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  127915. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  127916. ){
  127917. /* The aArg[] array needs to grow. */
  127918. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  127919. if( pNew ){
  127920. memcpy(pNew, aArg, nArg*sizeof(void *));
  127921. sqlite3_free(aDyn);
  127922. aDyn = aArg = pNew;
  127923. }else{
  127924. /* This occurs when the array of context pointers that need to
  127925. ** be passed to the unlock-notify callback is larger than the
  127926. ** aStatic[] array allocated on the stack and the attempt to
  127927. ** allocate a larger array from the heap has failed.
  127928. **
  127929. ** This is a difficult situation to handle. Returning an error
  127930. ** code to the caller is insufficient, as even if an error code
  127931. ** is returned the transaction on connection db will still be
  127932. ** closed and the unlock-notify callbacks on blocked connections
  127933. ** will go unissued. This might cause the application to wait
  127934. ** indefinitely for an unlock-notify callback that will never
  127935. ** arrive.
  127936. **
  127937. ** Instead, invoke the unlock-notify callback with the context
  127938. ** array already accumulated. We can then clear the array and
  127939. ** begin accumulating any further context pointers without
  127940. ** requiring any dynamic allocation. This is sub-optimal because
  127941. ** it means that instead of one callback with a large array of
  127942. ** context pointers the application will receive two or more
  127943. ** callbacks with smaller arrays of context pointers, which will
  127944. ** reduce the applications ability to prioritize multiple
  127945. ** connections. But it is the best that can be done under the
  127946. ** circumstances.
  127947. */
  127948. xUnlockNotify(aArg, nArg);
  127949. nArg = 0;
  127950. }
  127951. }
  127952. sqlite3EndBenignMalloc();
  127953. aArg[nArg++] = p->pUnlockArg;
  127954. xUnlockNotify = p->xUnlockNotify;
  127955. p->pUnlockConnection = 0;
  127956. p->xUnlockNotify = 0;
  127957. p->pUnlockArg = 0;
  127958. }
  127959. /* Step 3. */
  127960. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  127961. /* Remove connection p from the blocked connections list. */
  127962. *pp = p->pNextBlocked;
  127963. p->pNextBlocked = 0;
  127964. }else{
  127965. pp = &p->pNextBlocked;
  127966. }
  127967. }
  127968. if( nArg!=0 ){
  127969. xUnlockNotify(aArg, nArg);
  127970. }
  127971. sqlite3_free(aDyn);
  127972. leaveMutex(); /* Leave STATIC_MASTER mutex */
  127973. }
  127974. /*
  127975. ** This is called when the database connection passed as an argument is
  127976. ** being closed. The connection is removed from the blocked list.
  127977. */
  127978. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  127979. sqlite3ConnectionUnlocked(db);
  127980. enterMutex();
  127981. removeFromBlockedList(db);
  127982. checkListProperties(db);
  127983. leaveMutex();
  127984. }
  127985. #endif
  127986. /************** End of notify.c **********************************************/
  127987. /************** Begin file fts3.c ********************************************/
  127988. /*
  127989. ** 2006 Oct 10
  127990. **
  127991. ** The author disclaims copyright to this source code. In place of
  127992. ** a legal notice, here is a blessing:
  127993. **
  127994. ** May you do good and not evil.
  127995. ** May you find forgiveness for yourself and forgive others.
  127996. ** May you share freely, never taking more than you give.
  127997. **
  127998. ******************************************************************************
  127999. **
  128000. ** This is an SQLite module implementing full-text search.
  128001. */
  128002. /*
  128003. ** The code in this file is only compiled if:
  128004. **
  128005. ** * The FTS3 module is being built as an extension
  128006. ** (in which case SQLITE_CORE is not defined), or
  128007. **
  128008. ** * The FTS3 module is being built into the core of
  128009. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  128010. */
  128011. /* The full-text index is stored in a series of b+tree (-like)
  128012. ** structures called segments which map terms to doclists. The
  128013. ** structures are like b+trees in layout, but are constructed from the
  128014. ** bottom up in optimal fashion and are not updatable. Since trees
  128015. ** are built from the bottom up, things will be described from the
  128016. ** bottom up.
  128017. **
  128018. **
  128019. **** Varints ****
  128020. ** The basic unit of encoding is a variable-length integer called a
  128021. ** varint. We encode variable-length integers in little-endian order
  128022. ** using seven bits * per byte as follows:
  128023. **
  128024. ** KEY:
  128025. ** A = 0xxxxxxx 7 bits of data and one flag bit
  128026. ** B = 1xxxxxxx 7 bits of data and one flag bit
  128027. **
  128028. ** 7 bits - A
  128029. ** 14 bits - BA
  128030. ** 21 bits - BBA
  128031. ** and so on.
  128032. **
  128033. ** This is similar in concept to how sqlite encodes "varints" but
  128034. ** the encoding is not the same. SQLite varints are big-endian
  128035. ** are are limited to 9 bytes in length whereas FTS3 varints are
  128036. ** little-endian and can be up to 10 bytes in length (in theory).
  128037. **
  128038. ** Example encodings:
  128039. **
  128040. ** 1: 0x01
  128041. ** 127: 0x7f
  128042. ** 128: 0x81 0x00
  128043. **
  128044. **
  128045. **** Document lists ****
  128046. ** A doclist (document list) holds a docid-sorted list of hits for a
  128047. ** given term. Doclists hold docids and associated token positions.
  128048. ** A docid is the unique integer identifier for a single document.
  128049. ** A position is the index of a word within the document. The first
  128050. ** word of the document has a position of 0.
  128051. **
  128052. ** FTS3 used to optionally store character offsets using a compile-time
  128053. ** option. But that functionality is no longer supported.
  128054. **
  128055. ** A doclist is stored like this:
  128056. **
  128057. ** array {
  128058. ** varint docid; (delta from previous doclist)
  128059. ** array { (position list for column 0)
  128060. ** varint position; (2 more than the delta from previous position)
  128061. ** }
  128062. ** array {
  128063. ** varint POS_COLUMN; (marks start of position list for new column)
  128064. ** varint column; (index of new column)
  128065. ** array {
  128066. ** varint position; (2 more than the delta from previous position)
  128067. ** }
  128068. ** }
  128069. ** varint POS_END; (marks end of positions for this document.
  128070. ** }
  128071. **
  128072. ** Here, array { X } means zero or more occurrences of X, adjacent in
  128073. ** memory. A "position" is an index of a token in the token stream
  128074. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  128075. ** in the same logical place as the position element, and act as sentinals
  128076. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  128077. ** The positions numbers are not stored literally but rather as two more
  128078. ** than the difference from the prior position, or the just the position plus
  128079. ** 2 for the first position. Example:
  128080. **
  128081. ** label: A B C D E F G H I J K
  128082. ** value: 123 5 9 1 1 14 35 0 234 72 0
  128083. **
  128084. ** The 123 value is the first docid. For column zero in this document
  128085. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  128086. ** at D signals the start of a new column; the 1 at E indicates that the
  128087. ** new column is column number 1. There are two positions at 12 and 45
  128088. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  128089. ** 234 at I is the delta to next docid (357). It has one position 70
  128090. ** (72-2) and then terminates with the 0 at K.
  128091. **
  128092. ** A "position-list" is the list of positions for multiple columns for
  128093. ** a single docid. A "column-list" is the set of positions for a single
  128094. ** column. Hence, a position-list consists of one or more column-lists,
  128095. ** a document record consists of a docid followed by a position-list and
  128096. ** a doclist consists of one or more document records.
  128097. **
  128098. ** A bare doclist omits the position information, becoming an
  128099. ** array of varint-encoded docids.
  128100. **
  128101. **** Segment leaf nodes ****
  128102. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  128103. ** nodes are written using LeafWriter, and read using LeafReader (to
  128104. ** iterate through a single leaf node's data) and LeavesReader (to
  128105. ** iterate through a segment's entire leaf layer). Leaf nodes have
  128106. ** the format:
  128107. **
  128108. ** varint iHeight; (height from leaf level, always 0)
  128109. ** varint nTerm; (length of first term)
  128110. ** char pTerm[nTerm]; (content of first term)
  128111. ** varint nDoclist; (length of term's associated doclist)
  128112. ** char pDoclist[nDoclist]; (content of doclist)
  128113. ** array {
  128114. ** (further terms are delta-encoded)
  128115. ** varint nPrefix; (length of prefix shared with previous term)
  128116. ** varint nSuffix; (length of unshared suffix)
  128117. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  128118. ** varint nDoclist; (length of term's associated doclist)
  128119. ** char pDoclist[nDoclist]; (content of doclist)
  128120. ** }
  128121. **
  128122. ** Here, array { X } means zero or more occurrences of X, adjacent in
  128123. ** memory.
  128124. **
  128125. ** Leaf nodes are broken into blocks which are stored contiguously in
  128126. ** the %_segments table in sorted order. This means that when the end
  128127. ** of a node is reached, the next term is in the node with the next
  128128. ** greater node id.
  128129. **
  128130. ** New data is spilled to a new leaf node when the current node
  128131. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  128132. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  128133. ** node (a leaf node with a single term and doclist). The goal of
  128134. ** these settings is to pack together groups of small doclists while
  128135. ** making it efficient to directly access large doclists. The
  128136. ** assumption is that large doclists represent terms which are more
  128137. ** likely to be query targets.
  128138. **
  128139. ** TODO(shess) It may be useful for blocking decisions to be more
  128140. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  128141. ** node rather than splitting into 2k and .5k nodes. My intuition is
  128142. ** that this might extend through 2x or 4x the pagesize.
  128143. **
  128144. **
  128145. **** Segment interior nodes ****
  128146. ** Segment interior nodes store blockids for subtree nodes and terms
  128147. ** to describe what data is stored by the each subtree. Interior
  128148. ** nodes are written using InteriorWriter, and read using
  128149. ** InteriorReader. InteriorWriters are created as needed when
  128150. ** SegmentWriter creates new leaf nodes, or when an interior node
  128151. ** itself grows too big and must be split. The format of interior
  128152. ** nodes:
  128153. **
  128154. ** varint iHeight; (height from leaf level, always >0)
  128155. ** varint iBlockid; (block id of node's leftmost subtree)
  128156. ** optional {
  128157. ** varint nTerm; (length of first term)
  128158. ** char pTerm[nTerm]; (content of first term)
  128159. ** array {
  128160. ** (further terms are delta-encoded)
  128161. ** varint nPrefix; (length of shared prefix with previous term)
  128162. ** varint nSuffix; (length of unshared suffix)
  128163. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  128164. ** }
  128165. ** }
  128166. **
  128167. ** Here, optional { X } means an optional element, while array { X }
  128168. ** means zero or more occurrences of X, adjacent in memory.
  128169. **
  128170. ** An interior node encodes n terms separating n+1 subtrees. The
  128171. ** subtree blocks are contiguous, so only the first subtree's blockid
  128172. ** is encoded. The subtree at iBlockid will contain all terms less
  128173. ** than the first term encoded (or all terms if no term is encoded).
  128174. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  128175. ** than pTerm[i+1], the subtree for that term will be rooted at
  128176. ** iBlockid+i. Interior nodes only store enough term data to
  128177. ** distinguish adjacent children (if the rightmost term of the left
  128178. ** child is "something", and the leftmost term of the right child is
  128179. ** "wicked", only "w" is stored).
  128180. **
  128181. ** New data is spilled to a new interior node at the same height when
  128182. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  128183. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  128184. ** interior nodes and making the tree too skinny. The interior nodes
  128185. ** at a given height are naturally tracked by interior nodes at
  128186. ** height+1, and so on.
  128187. **
  128188. **
  128189. **** Segment directory ****
  128190. ** The segment directory in table %_segdir stores meta-information for
  128191. ** merging and deleting segments, and also the root node of the
  128192. ** segment's tree.
  128193. **
  128194. ** The root node is the top node of the segment's tree after encoding
  128195. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  128196. ** This could be either a leaf node or an interior node. If the top
  128197. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  128198. ** and a new root interior node is generated (which should always fit
  128199. ** within ROOT_MAX because it only needs space for 2 varints, the
  128200. ** height and the blockid of the previous root).
  128201. **
  128202. ** The meta-information in the segment directory is:
  128203. ** level - segment level (see below)
  128204. ** idx - index within level
  128205. ** - (level,idx uniquely identify a segment)
  128206. ** start_block - first leaf node
  128207. ** leaves_end_block - last leaf node
  128208. ** end_block - last block (including interior nodes)
  128209. ** root - contents of root node
  128210. **
  128211. ** If the root node is a leaf node, then start_block,
  128212. ** leaves_end_block, and end_block are all 0.
  128213. **
  128214. **
  128215. **** Segment merging ****
  128216. ** To amortize update costs, segments are grouped into levels and
  128217. ** merged in batches. Each increase in level represents exponentially
  128218. ** more documents.
  128219. **
  128220. ** New documents (actually, document updates) are tokenized and
  128221. ** written individually (using LeafWriter) to a level 0 segment, with
  128222. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  128223. ** level 0 segments are merged into a single level 1 segment. Level 1
  128224. ** is populated like level 0, and eventually MERGE_COUNT level 1
  128225. ** segments are merged to a single level 2 segment (representing
  128226. ** MERGE_COUNT^2 updates), and so on.
  128227. **
  128228. ** A segment merge traverses all segments at a given level in
  128229. ** parallel, performing a straightforward sorted merge. Since segment
  128230. ** leaf nodes are written in to the %_segments table in order, this
  128231. ** merge traverses the underlying sqlite disk structures efficiently.
  128232. ** After the merge, all segment blocks from the merged level are
  128233. ** deleted.
  128234. **
  128235. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  128236. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  128237. ** very similar performance numbers to 16 on insertion, though they're
  128238. ** a tiny bit slower (perhaps due to more overhead in merge-time
  128239. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  128240. ** 16, 2 about 66% slower than 16.
  128241. **
  128242. ** At query time, high MERGE_COUNT increases the number of segments
  128243. ** which need to be scanned and merged. For instance, with 100k docs
  128244. ** inserted:
  128245. **
  128246. ** MERGE_COUNT segments
  128247. ** 16 25
  128248. ** 8 12
  128249. ** 4 10
  128250. ** 2 6
  128251. **
  128252. ** This appears to have only a moderate impact on queries for very
  128253. ** frequent terms (which are somewhat dominated by segment merge
  128254. ** costs), and infrequent and non-existent terms still seem to be fast
  128255. ** even with many segments.
  128256. **
  128257. ** TODO(shess) That said, it would be nice to have a better query-side
  128258. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  128259. ** optimizations to things like doclist merging will swing the sweet
  128260. ** spot around.
  128261. **
  128262. **
  128263. **
  128264. **** Handling of deletions and updates ****
  128265. ** Since we're using a segmented structure, with no docid-oriented
  128266. ** index into the term index, we clearly cannot simply update the term
  128267. ** index when a document is deleted or updated. For deletions, we
  128268. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  128269. ** we simply write the new doclist. Segment merges overwrite older
  128270. ** data for a particular docid with newer data, so deletes or updates
  128271. ** will eventually overtake the earlier data and knock it out. The
  128272. ** query logic likewise merges doclists so that newer data knocks out
  128273. ** older data.
  128274. */
  128275. /************** Include fts3Int.h in the middle of fts3.c ********************/
  128276. /************** Begin file fts3Int.h *****************************************/
  128277. /*
  128278. ** 2009 Nov 12
  128279. **
  128280. ** The author disclaims copyright to this source code. In place of
  128281. ** a legal notice, here is a blessing:
  128282. **
  128283. ** May you do good and not evil.
  128284. ** May you find forgiveness for yourself and forgive others.
  128285. ** May you share freely, never taking more than you give.
  128286. **
  128287. ******************************************************************************
  128288. **
  128289. */
  128290. #ifndef _FTSINT_H
  128291. #define _FTSINT_H
  128292. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  128293. # define NDEBUG 1
  128294. #endif
  128295. /*
  128296. ** FTS4 is really an extension for FTS3. It is enabled using the
  128297. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  128298. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  128299. */
  128300. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  128301. # define SQLITE_ENABLE_FTS3
  128302. #endif
  128303. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  128304. /* If not building as part of the core, include sqlite3ext.h. */
  128305. #ifndef SQLITE_CORE
  128306. /* # include "sqlite3ext.h" */
  128307. SQLITE_EXTENSION_INIT3
  128308. #endif
  128309. /* #include "sqlite3.h" */
  128310. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  128311. /************** Begin file fts3_tokenizer.h **********************************/
  128312. /*
  128313. ** 2006 July 10
  128314. **
  128315. ** The author disclaims copyright to this source code.
  128316. **
  128317. *************************************************************************
  128318. ** Defines the interface to tokenizers used by fulltext-search. There
  128319. ** are three basic components:
  128320. **
  128321. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  128322. ** interface functions. This is essentially the class structure for
  128323. ** tokenizers.
  128324. **
  128325. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  128326. ** including customization information defined at creation time.
  128327. **
  128328. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  128329. ** tokens from a particular input.
  128330. */
  128331. #ifndef _FTS3_TOKENIZER_H_
  128332. #define _FTS3_TOKENIZER_H_
  128333. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  128334. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  128335. ** we will need a way to register the API consistently.
  128336. */
  128337. /* #include "sqlite3.h" */
  128338. /*
  128339. ** Structures used by the tokenizer interface. When a new tokenizer
  128340. ** implementation is registered, the caller provides a pointer to
  128341. ** an sqlite3_tokenizer_module containing pointers to the callback
  128342. ** functions that make up an implementation.
  128343. **
  128344. ** When an fts3 table is created, it passes any arguments passed to
  128345. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  128346. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  128347. ** implementation. The xCreate() function in turn returns an
  128348. ** sqlite3_tokenizer structure representing the specific tokenizer to
  128349. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  128350. **
  128351. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  128352. ** method is called. It returns an sqlite3_tokenizer_cursor object
  128353. ** that may be used to tokenize a specific input buffer based on
  128354. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  128355. ** object.
  128356. */
  128357. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  128358. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  128359. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  128360. struct sqlite3_tokenizer_module {
  128361. /*
  128362. ** Structure version. Should always be set to 0 or 1.
  128363. */
  128364. int iVersion;
  128365. /*
  128366. ** Create a new tokenizer. The values in the argv[] array are the
  128367. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  128368. ** TABLE statement that created the fts3 table. For example, if
  128369. ** the following SQL is executed:
  128370. **
  128371. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  128372. **
  128373. ** then argc is set to 2, and the argv[] array contains pointers
  128374. ** to the strings "arg1" and "arg2".
  128375. **
  128376. ** This method should return either SQLITE_OK (0), or an SQLite error
  128377. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  128378. ** to point at the newly created tokenizer structure. The generic
  128379. ** sqlite3_tokenizer.pModule variable should not be initialized by
  128380. ** this callback. The caller will do so.
  128381. */
  128382. int (*xCreate)(
  128383. int argc, /* Size of argv array */
  128384. const char *const*argv, /* Tokenizer argument strings */
  128385. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  128386. );
  128387. /*
  128388. ** Destroy an existing tokenizer. The fts3 module calls this method
  128389. ** exactly once for each successful call to xCreate().
  128390. */
  128391. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  128392. /*
  128393. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  128394. ** is responsible for ensuring that the input buffer remains valid
  128395. ** until the cursor is closed (using the xClose() method).
  128396. */
  128397. int (*xOpen)(
  128398. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  128399. const char *pInput, int nBytes, /* Input buffer */
  128400. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  128401. );
  128402. /*
  128403. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  128404. ** method exactly once for each successful call to xOpen().
  128405. */
  128406. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  128407. /*
  128408. ** Retrieve the next token from the tokenizer cursor pCursor. This
  128409. ** method should either return SQLITE_OK and set the values of the
  128410. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  128411. ** the end of the buffer has been reached, or an SQLite error code.
  128412. **
  128413. ** *ppToken should be set to point at a buffer containing the
  128414. ** normalized version of the token (i.e. after any case-folding and/or
  128415. ** stemming has been performed). *pnBytes should be set to the length
  128416. ** of this buffer in bytes. The input text that generated the token is
  128417. ** identified by the byte offsets returned in *piStartOffset and
  128418. ** *piEndOffset. *piStartOffset should be set to the index of the first
  128419. ** byte of the token in the input buffer. *piEndOffset should be set
  128420. ** to the index of the first byte just past the end of the token in
  128421. ** the input buffer.
  128422. **
  128423. ** The buffer *ppToken is set to point at is managed by the tokenizer
  128424. ** implementation. It is only required to be valid until the next call
  128425. ** to xNext() or xClose().
  128426. */
  128427. /* TODO(shess) current implementation requires pInput to be
  128428. ** nul-terminated. This should either be fixed, or pInput/nBytes
  128429. ** should be converted to zInput.
  128430. */
  128431. int (*xNext)(
  128432. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  128433. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  128434. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  128435. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  128436. int *piPosition /* OUT: Number of tokens returned before this one */
  128437. );
  128438. /***********************************************************************
  128439. ** Methods below this point are only available if iVersion>=1.
  128440. */
  128441. /*
  128442. ** Configure the language id of a tokenizer cursor.
  128443. */
  128444. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  128445. };
  128446. struct sqlite3_tokenizer {
  128447. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  128448. /* Tokenizer implementations will typically add additional fields */
  128449. };
  128450. struct sqlite3_tokenizer_cursor {
  128451. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  128452. /* Tokenizer implementations will typically add additional fields */
  128453. };
  128454. int fts3_global_term_cnt(int iTerm, int iCol);
  128455. int fts3_term_cnt(int iTerm, int iCol);
  128456. #endif /* _FTS3_TOKENIZER_H_ */
  128457. /************** End of fts3_tokenizer.h **************************************/
  128458. /************** Continuing where we left off in fts3Int.h ********************/
  128459. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  128460. /************** Begin file fts3_hash.h ***************************************/
  128461. /*
  128462. ** 2001 September 22
  128463. **
  128464. ** The author disclaims copyright to this source code. In place of
  128465. ** a legal notice, here is a blessing:
  128466. **
  128467. ** May you do good and not evil.
  128468. ** May you find forgiveness for yourself and forgive others.
  128469. ** May you share freely, never taking more than you give.
  128470. **
  128471. *************************************************************************
  128472. ** This is the header file for the generic hash-table implementation
  128473. ** used in SQLite. We've modified it slightly to serve as a standalone
  128474. ** hash table implementation for the full-text indexing module.
  128475. **
  128476. */
  128477. #ifndef _FTS3_HASH_H_
  128478. #define _FTS3_HASH_H_
  128479. /* Forward declarations of structures. */
  128480. typedef struct Fts3Hash Fts3Hash;
  128481. typedef struct Fts3HashElem Fts3HashElem;
  128482. /* A complete hash table is an instance of the following structure.
  128483. ** The internals of this structure are intended to be opaque -- client
  128484. ** code should not attempt to access or modify the fields of this structure
  128485. ** directly. Change this structure only by using the routines below.
  128486. ** However, many of the "procedures" and "functions" for modifying and
  128487. ** accessing this structure are really macros, so we can't really make
  128488. ** this structure opaque.
  128489. */
  128490. struct Fts3Hash {
  128491. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  128492. char copyKey; /* True if copy of key made on insert */
  128493. int count; /* Number of entries in this table */
  128494. Fts3HashElem *first; /* The first element of the array */
  128495. int htsize; /* Number of buckets in the hash table */
  128496. struct _fts3ht { /* the hash table */
  128497. int count; /* Number of entries with this hash */
  128498. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  128499. } *ht;
  128500. };
  128501. /* Each element in the hash table is an instance of the following
  128502. ** structure. All elements are stored on a single doubly-linked list.
  128503. **
  128504. ** Again, this structure is intended to be opaque, but it can't really
  128505. ** be opaque because it is used by macros.
  128506. */
  128507. struct Fts3HashElem {
  128508. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  128509. void *data; /* Data associated with this element */
  128510. void *pKey; int nKey; /* Key associated with this element */
  128511. };
  128512. /*
  128513. ** There are 2 different modes of operation for a hash table:
  128514. **
  128515. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  128516. ** (including the null-terminator, if any). Case
  128517. ** is respected in comparisons.
  128518. **
  128519. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  128520. ** memcmp() is used to compare keys.
  128521. **
  128522. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  128523. */
  128524. #define FTS3_HASH_STRING 1
  128525. #define FTS3_HASH_BINARY 2
  128526. /*
  128527. ** Access routines. To delete, insert a NULL pointer.
  128528. */
  128529. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  128530. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  128531. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  128532. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  128533. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  128534. /*
  128535. ** Shorthand for the functions above
  128536. */
  128537. #define fts3HashInit sqlite3Fts3HashInit
  128538. #define fts3HashInsert sqlite3Fts3HashInsert
  128539. #define fts3HashFind sqlite3Fts3HashFind
  128540. #define fts3HashClear sqlite3Fts3HashClear
  128541. #define fts3HashFindElem sqlite3Fts3HashFindElem
  128542. /*
  128543. ** Macros for looping over all elements of a hash table. The idiom is
  128544. ** like this:
  128545. **
  128546. ** Fts3Hash h;
  128547. ** Fts3HashElem *p;
  128548. ** ...
  128549. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  128550. ** SomeStructure *pData = fts3HashData(p);
  128551. ** // do something with pData
  128552. ** }
  128553. */
  128554. #define fts3HashFirst(H) ((H)->first)
  128555. #define fts3HashNext(E) ((E)->next)
  128556. #define fts3HashData(E) ((E)->data)
  128557. #define fts3HashKey(E) ((E)->pKey)
  128558. #define fts3HashKeysize(E) ((E)->nKey)
  128559. /*
  128560. ** Number of entries in a hash table
  128561. */
  128562. #define fts3HashCount(H) ((H)->count)
  128563. #endif /* _FTS3_HASH_H_ */
  128564. /************** End of fts3_hash.h *******************************************/
  128565. /************** Continuing where we left off in fts3Int.h ********************/
  128566. /*
  128567. ** This constant determines the maximum depth of an FTS expression tree
  128568. ** that the library will create and use. FTS uses recursion to perform
  128569. ** various operations on the query tree, so the disadvantage of a large
  128570. ** limit is that it may allow very large queries to use large amounts
  128571. ** of stack space (perhaps causing a stack overflow).
  128572. */
  128573. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  128574. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  128575. #endif
  128576. /*
  128577. ** This constant controls how often segments are merged. Once there are
  128578. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  128579. ** segment of level N+1.
  128580. */
  128581. #define FTS3_MERGE_COUNT 16
  128582. /*
  128583. ** This is the maximum amount of data (in bytes) to store in the
  128584. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  128585. ** populated as documents are inserted/updated/deleted in a transaction
  128586. ** and used to create a new segment when the transaction is committed.
  128587. ** However if this limit is reached midway through a transaction, a new
  128588. ** segment is created and the hash table cleared immediately.
  128589. */
  128590. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  128591. /*
  128592. ** Macro to return the number of elements in an array. SQLite has a
  128593. ** similar macro called ArraySize(). Use a different name to avoid
  128594. ** a collision when building an amalgamation with built-in FTS3.
  128595. */
  128596. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  128597. #ifndef MIN
  128598. # define MIN(x,y) ((x)<(y)?(x):(y))
  128599. #endif
  128600. #ifndef MAX
  128601. # define MAX(x,y) ((x)>(y)?(x):(y))
  128602. #endif
  128603. /*
  128604. ** Maximum length of a varint encoded integer. The varint format is different
  128605. ** from that used by SQLite, so the maximum length is 10, not 9.
  128606. */
  128607. #define FTS3_VARINT_MAX 10
  128608. /*
  128609. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  128610. ** in the document set and zero or more prefix indexes. All indexes are stored
  128611. ** as one or more b+-trees in the %_segments and %_segdir tables.
  128612. **
  128613. ** It is possible to determine which index a b+-tree belongs to based on the
  128614. ** value stored in the "%_segdir.level" column. Given this value L, the index
  128615. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  128616. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  128617. ** between 1024 and 2047 to index 1, and so on.
  128618. **
  128619. ** It is considered impossible for an index to use more than 1024 levels. In
  128620. ** theory though this may happen, but only after at least
  128621. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  128622. */
  128623. #define FTS3_SEGDIR_MAXLEVEL 1024
  128624. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  128625. /*
  128626. ** The testcase() macro is only used by the amalgamation. If undefined,
  128627. ** make it a no-op.
  128628. */
  128629. #ifndef testcase
  128630. # define testcase(X)
  128631. #endif
  128632. /*
  128633. ** Terminator values for position-lists and column-lists.
  128634. */
  128635. #define POS_COLUMN (1) /* Column-list terminator */
  128636. #define POS_END (0) /* Position-list terminator */
  128637. /*
  128638. ** This section provides definitions to allow the
  128639. ** FTS3 extension to be compiled outside of the
  128640. ** amalgamation.
  128641. */
  128642. #ifndef SQLITE_AMALGAMATION
  128643. /*
  128644. ** Macros indicating that conditional expressions are always true or
  128645. ** false.
  128646. */
  128647. #ifdef SQLITE_COVERAGE_TEST
  128648. # define ALWAYS(x) (1)
  128649. # define NEVER(X) (0)
  128650. #elif defined(SQLITE_DEBUG)
  128651. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  128652. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  128653. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  128654. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  128655. #else
  128656. # define ALWAYS(x) (x)
  128657. # define NEVER(x) (x)
  128658. #endif
  128659. /*
  128660. ** Internal types used by SQLite.
  128661. */
  128662. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  128663. typedef short int i16; /* 2-byte (or larger) signed integer */
  128664. typedef unsigned int u32; /* 4-byte unsigned integer */
  128665. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  128666. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  128667. /*
  128668. ** Macro used to suppress compiler warnings for unused parameters.
  128669. */
  128670. #define UNUSED_PARAMETER(x) (void)(x)
  128671. /*
  128672. ** Activate assert() only if SQLITE_TEST is enabled.
  128673. */
  128674. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  128675. # define NDEBUG 1
  128676. #endif
  128677. /*
  128678. ** The TESTONLY macro is used to enclose variable declarations or
  128679. ** other bits of code that are needed to support the arguments
  128680. ** within testcase() and assert() macros.
  128681. */
  128682. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  128683. # define TESTONLY(X) X
  128684. #else
  128685. # define TESTONLY(X)
  128686. #endif
  128687. #endif /* SQLITE_AMALGAMATION */
  128688. #ifdef SQLITE_DEBUG
  128689. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  128690. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  128691. #else
  128692. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  128693. #endif
  128694. typedef struct Fts3Table Fts3Table;
  128695. typedef struct Fts3Cursor Fts3Cursor;
  128696. typedef struct Fts3Expr Fts3Expr;
  128697. typedef struct Fts3Phrase Fts3Phrase;
  128698. typedef struct Fts3PhraseToken Fts3PhraseToken;
  128699. typedef struct Fts3Doclist Fts3Doclist;
  128700. typedef struct Fts3SegFilter Fts3SegFilter;
  128701. typedef struct Fts3DeferredToken Fts3DeferredToken;
  128702. typedef struct Fts3SegReader Fts3SegReader;
  128703. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  128704. typedef struct MatchinfoBuffer MatchinfoBuffer;
  128705. /*
  128706. ** A connection to a fulltext index is an instance of the following
  128707. ** structure. The xCreate and xConnect methods create an instance
  128708. ** of this structure and xDestroy and xDisconnect free that instance.
  128709. ** All other methods receive a pointer to the structure as one of their
  128710. ** arguments.
  128711. */
  128712. struct Fts3Table {
  128713. sqlite3_vtab base; /* Base class used by SQLite core */
  128714. sqlite3 *db; /* The database connection */
  128715. const char *zDb; /* logical database name */
  128716. const char *zName; /* virtual table name */
  128717. int nColumn; /* number of named columns in virtual table */
  128718. char **azColumn; /* column names. malloced */
  128719. u8 *abNotindexed; /* True for 'notindexed' columns */
  128720. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  128721. char *zContentTbl; /* content=xxx option, or NULL */
  128722. char *zLanguageid; /* languageid=xxx option, or NULL */
  128723. int nAutoincrmerge; /* Value configured by 'automerge' */
  128724. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  128725. /* Precompiled statements used by the implementation. Each of these
  128726. ** statements is run and reset within a single virtual table API call.
  128727. */
  128728. sqlite3_stmt *aStmt[40];
  128729. char *zReadExprlist;
  128730. char *zWriteExprlist;
  128731. int nNodeSize; /* Soft limit for node size */
  128732. u8 bFts4; /* True for FTS4, false for FTS3 */
  128733. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  128734. u8 bHasDocsize; /* True if %_docsize table exists */
  128735. u8 bDescIdx; /* True if doclists are in reverse order */
  128736. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  128737. int nPgsz; /* Page size for host database */
  128738. char *zSegmentsTbl; /* Name of %_segments table */
  128739. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  128740. /*
  128741. ** The following array of hash tables is used to buffer pending index
  128742. ** updates during transactions. All pending updates buffered at any one
  128743. ** time must share a common language-id (see the FTS4 langid= feature).
  128744. ** The current language id is stored in variable iPrevLangid.
  128745. **
  128746. ** A single FTS4 table may have multiple full-text indexes. For each index
  128747. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  128748. ** terms that appear in the document set. Each subsequent index in aIndex[]
  128749. ** is an index of prefixes of a specific length.
  128750. **
  128751. ** Variable nPendingData contains an estimate the memory consumed by the
  128752. ** pending data structures, including hash table overhead, but not including
  128753. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  128754. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  128755. ** recently inserted record.
  128756. */
  128757. int nIndex; /* Size of aIndex[] */
  128758. struct Fts3Index {
  128759. int nPrefix; /* Prefix length (0 for main terms index) */
  128760. Fts3Hash hPending; /* Pending terms table for this index */
  128761. } *aIndex;
  128762. int nMaxPendingData; /* Max pending data before flush to disk */
  128763. int nPendingData; /* Current bytes of pending data */
  128764. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  128765. int iPrevLangid; /* Langid of recently inserted document */
  128766. int bPrevDelete; /* True if last operation was a delete */
  128767. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  128768. /* State variables used for validating that the transaction control
  128769. ** methods of the virtual table are called at appropriate times. These
  128770. ** values do not contribute to FTS functionality; they are used for
  128771. ** verifying the operation of the SQLite core.
  128772. */
  128773. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  128774. int mxSavepoint; /* Largest valid xSavepoint integer */
  128775. #endif
  128776. #ifdef SQLITE_TEST
  128777. /* True to disable the incremental doclist optimization. This is controled
  128778. ** by special insert command 'test-no-incr-doclist'. */
  128779. int bNoIncrDoclist;
  128780. #endif
  128781. };
  128782. /*
  128783. ** When the core wants to read from the virtual table, it creates a
  128784. ** virtual table cursor (an instance of the following structure) using
  128785. ** the xOpen method. Cursors are destroyed using the xClose method.
  128786. */
  128787. struct Fts3Cursor {
  128788. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  128789. i16 eSearch; /* Search strategy (see below) */
  128790. u8 isEof; /* True if at End Of Results */
  128791. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  128792. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  128793. Fts3Expr *pExpr; /* Parsed MATCH query string */
  128794. int iLangid; /* Language being queried for */
  128795. int nPhrase; /* Number of matchable phrases in query */
  128796. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  128797. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  128798. char *pNextId; /* Pointer into the body of aDoclist */
  128799. char *aDoclist; /* List of docids for full-text queries */
  128800. int nDoclist; /* Size of buffer at aDoclist */
  128801. u8 bDesc; /* True to sort in descending order */
  128802. int eEvalmode; /* An FTS3_EVAL_XX constant */
  128803. int nRowAvg; /* Average size of database rows, in pages */
  128804. sqlite3_int64 nDoc; /* Documents in table */
  128805. i64 iMinDocid; /* Minimum docid to return */
  128806. i64 iMaxDocid; /* Maximum docid to return */
  128807. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  128808. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  128809. };
  128810. #define FTS3_EVAL_FILTER 0
  128811. #define FTS3_EVAL_NEXT 1
  128812. #define FTS3_EVAL_MATCHINFO 2
  128813. /*
  128814. ** The Fts3Cursor.eSearch member is always set to one of the following.
  128815. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  128816. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  128817. ** of the column to be searched. For example, in
  128818. **
  128819. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  128820. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  128821. **
  128822. ** Because the LHS of the MATCH operator is 2nd column "b",
  128823. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  128824. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  128825. ** indicating that all columns should be searched,
  128826. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  128827. */
  128828. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  128829. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  128830. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  128831. /*
  128832. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  128833. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  128834. ** above. The upper 16-bits contain a combination of the following
  128835. ** bits, used to describe extra constraints on full-text searches.
  128836. */
  128837. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  128838. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  128839. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  128840. struct Fts3Doclist {
  128841. char *aAll; /* Array containing doclist (or NULL) */
  128842. int nAll; /* Size of a[] in bytes */
  128843. char *pNextDocid; /* Pointer to next docid */
  128844. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  128845. int bFreeList; /* True if pList should be sqlite3_free()d */
  128846. char *pList; /* Pointer to position list following iDocid */
  128847. int nList; /* Length of position list */
  128848. };
  128849. /*
  128850. ** A "phrase" is a sequence of one or more tokens that must match in
  128851. ** sequence. A single token is the base case and the most common case.
  128852. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  128853. ** nToken will be the number of tokens in the string.
  128854. */
  128855. struct Fts3PhraseToken {
  128856. char *z; /* Text of the token */
  128857. int n; /* Number of bytes in buffer z */
  128858. int isPrefix; /* True if token ends with a "*" character */
  128859. int bFirst; /* True if token must appear at position 0 */
  128860. /* Variables above this point are populated when the expression is
  128861. ** parsed (by code in fts3_expr.c). Below this point the variables are
  128862. ** used when evaluating the expression. */
  128863. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  128864. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  128865. };
  128866. struct Fts3Phrase {
  128867. /* Cache of doclist for this phrase. */
  128868. Fts3Doclist doclist;
  128869. int bIncr; /* True if doclist is loaded incrementally */
  128870. int iDoclistToken;
  128871. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  128872. ** OR condition. */
  128873. char *pOrPoslist;
  128874. i64 iOrDocid;
  128875. /* Variables below this point are populated by fts3_expr.c when parsing
  128876. ** a MATCH expression. Everything above is part of the evaluation phase.
  128877. */
  128878. int nToken; /* Number of tokens in the phrase */
  128879. int iColumn; /* Index of column this phrase must match */
  128880. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  128881. };
  128882. /*
  128883. ** A tree of these objects forms the RHS of a MATCH operator.
  128884. **
  128885. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  128886. ** points to a malloced buffer, size nDoclist bytes, containing the results
  128887. ** of this phrase query in FTS3 doclist format. As usual, the initial
  128888. ** "Length" field found in doclists stored on disk is omitted from this
  128889. ** buffer.
  128890. **
  128891. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  128892. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  128893. ** where nCol is the number of columns in the queried FTS table. The array
  128894. ** is populated as follows:
  128895. **
  128896. ** aMI[iCol*3 + 0] = Undefined
  128897. ** aMI[iCol*3 + 1] = Number of occurrences
  128898. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  128899. **
  128900. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  128901. ** when the expression node is.
  128902. */
  128903. struct Fts3Expr {
  128904. int eType; /* One of the FTSQUERY_XXX values defined below */
  128905. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  128906. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  128907. Fts3Expr *pLeft; /* Left operand */
  128908. Fts3Expr *pRight; /* Right operand */
  128909. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  128910. /* The following are used by the fts3_eval.c module. */
  128911. sqlite3_int64 iDocid; /* Current docid */
  128912. u8 bEof; /* True this expression is at EOF already */
  128913. u8 bStart; /* True if iDocid is valid */
  128914. u8 bDeferred; /* True if this expression is entirely deferred */
  128915. /* The following are used by the fts3_snippet.c module. */
  128916. int iPhrase; /* Index of this phrase in matchinfo() results */
  128917. u32 *aMI; /* See above */
  128918. };
  128919. /*
  128920. ** Candidate values for Fts3Query.eType. Note that the order of the first
  128921. ** four values is in order of precedence when parsing expressions. For
  128922. ** example, the following:
  128923. **
  128924. ** "a OR b AND c NOT d NEAR e"
  128925. **
  128926. ** is equivalent to:
  128927. **
  128928. ** "a OR (b AND (c NOT (d NEAR e)))"
  128929. */
  128930. #define FTSQUERY_NEAR 1
  128931. #define FTSQUERY_NOT 2
  128932. #define FTSQUERY_AND 3
  128933. #define FTSQUERY_OR 4
  128934. #define FTSQUERY_PHRASE 5
  128935. /* fts3_write.c */
  128936. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  128937. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  128938. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  128939. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  128940. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  128941. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  128942. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  128943. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  128944. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  128945. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  128946. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  128947. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  128948. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  128949. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  128950. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  128951. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  128952. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  128953. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  128954. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  128955. #else
  128956. # define sqlite3Fts3FreeDeferredTokens(x)
  128957. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  128958. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  128959. # define sqlite3Fts3FreeDeferredDoclists(x)
  128960. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  128961. #endif
  128962. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  128963. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  128964. /* Special values interpreted by sqlite3SegReaderCursor() */
  128965. #define FTS3_SEGCURSOR_PENDING -1
  128966. #define FTS3_SEGCURSOR_ALL -2
  128967. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  128968. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  128969. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  128970. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  128971. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  128972. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  128973. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  128974. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  128975. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  128976. #define FTS3_SEGMENT_PREFIX 0x00000008
  128977. #define FTS3_SEGMENT_SCAN 0x00000010
  128978. #define FTS3_SEGMENT_FIRST 0x00000020
  128979. /* Type passed as 4th argument to SegmentReaderIterate() */
  128980. struct Fts3SegFilter {
  128981. const char *zTerm;
  128982. int nTerm;
  128983. int iCol;
  128984. int flags;
  128985. };
  128986. struct Fts3MultiSegReader {
  128987. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  128988. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  128989. int nSegment; /* Size of apSegment array */
  128990. int nAdvance; /* How many seg-readers to advance */
  128991. Fts3SegFilter *pFilter; /* Pointer to filter object */
  128992. char *aBuffer; /* Buffer to merge doclists in */
  128993. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  128994. int iColFilter; /* If >=0, filter for this column */
  128995. int bRestart;
  128996. /* Used by fts3.c only. */
  128997. int nCost; /* Cost of running iterator */
  128998. int bLookup; /* True if a lookup of a single entry. */
  128999. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  129000. char *zTerm; /* Pointer to term buffer */
  129001. int nTerm; /* Size of zTerm in bytes */
  129002. char *aDoclist; /* Pointer to doclist buffer */
  129003. int nDoclist; /* Size of aDoclist[] in bytes */
  129004. };
  129005. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  129006. #define fts3GetVarint32(p, piVal) ( \
  129007. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  129008. )
  129009. /* fts3.c */
  129010. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  129011. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  129012. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  129013. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  129014. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  129015. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  129016. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  129017. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  129018. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  129019. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  129020. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  129021. /* fts3_tokenizer.c */
  129022. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  129023. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  129024. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  129025. sqlite3_tokenizer **, char **
  129026. );
  129027. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  129028. /* fts3_snippet.c */
  129029. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  129030. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  129031. const char *, const char *, int, int
  129032. );
  129033. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  129034. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  129035. /* fts3_expr.c */
  129036. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  129037. char **, int, int, int, const char *, int, Fts3Expr **, char **
  129038. );
  129039. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  129040. #ifdef SQLITE_TEST
  129041. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  129042. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  129043. #endif
  129044. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  129045. sqlite3_tokenizer_cursor **
  129046. );
  129047. /* fts3_aux.c */
  129048. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  129049. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  129050. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  129051. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  129052. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  129053. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  129054. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  129055. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  129056. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  129057. /* fts3_tokenize_vtab.c */
  129058. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  129059. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  129060. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  129061. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  129062. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  129063. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  129064. #endif
  129065. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  129066. #endif /* _FTSINT_H */
  129067. /************** End of fts3Int.h *********************************************/
  129068. /************** Continuing where we left off in fts3.c ***********************/
  129069. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  129070. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  129071. # define SQLITE_CORE 1
  129072. #endif
  129073. /* #include <assert.h> */
  129074. /* #include <stdlib.h> */
  129075. /* #include <stddef.h> */
  129076. /* #include <stdio.h> */
  129077. /* #include <string.h> */
  129078. /* #include <stdarg.h> */
  129079. /* #include "fts3.h" */
  129080. #ifndef SQLITE_CORE
  129081. /* # include "sqlite3ext.h" */
  129082. SQLITE_EXTENSION_INIT1
  129083. #endif
  129084. static int fts3EvalNext(Fts3Cursor *pCsr);
  129085. static int fts3EvalStart(Fts3Cursor *pCsr);
  129086. static int fts3TermSegReaderCursor(
  129087. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  129088. #ifndef SQLITE_AMALGAMATION
  129089. # if defined(SQLITE_DEBUG)
  129090. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  129091. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  129092. # endif
  129093. #endif
  129094. /*
  129095. ** Write a 64-bit variable-length integer to memory starting at p[0].
  129096. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  129097. ** The number of bytes written is returned.
  129098. */
  129099. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  129100. unsigned char *q = (unsigned char *) p;
  129101. sqlite_uint64 vu = v;
  129102. do{
  129103. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  129104. vu >>= 7;
  129105. }while( vu!=0 );
  129106. q[-1] &= 0x7f; /* turn off high bit in final byte */
  129107. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  129108. return (int) (q - (unsigned char *)p);
  129109. }
  129110. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  129111. v = (v & mask1) | ( (*ptr++) << shift ); \
  129112. if( (v & mask2)==0 ){ var = v; return ret; }
  129113. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  129114. v = (*ptr++); \
  129115. if( (v & mask2)==0 ){ var = v; return ret; }
  129116. /*
  129117. ** Read a 64-bit variable-length integer from memory starting at p[0].
  129118. ** Return the number of bytes read, or 0 on error.
  129119. ** The value is stored in *v.
  129120. */
  129121. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  129122. const char *pStart = p;
  129123. u32 a;
  129124. u64 b;
  129125. int shift;
  129126. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  129127. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  129128. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  129129. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  129130. b = (a & 0x0FFFFFFF );
  129131. for(shift=28; shift<=63; shift+=7){
  129132. u64 c = *p++;
  129133. b += (c&0x7F) << shift;
  129134. if( (c & 0x80)==0 ) break;
  129135. }
  129136. *v = b;
  129137. return (int)(p - pStart);
  129138. }
  129139. /*
  129140. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  129141. ** 32-bit integer before it is returned.
  129142. */
  129143. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  129144. u32 a;
  129145. #ifndef fts3GetVarint32
  129146. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  129147. #else
  129148. a = (*p++);
  129149. assert( a & 0x80 );
  129150. #endif
  129151. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  129152. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  129153. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  129154. a = (a & 0x0FFFFFFF );
  129155. *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
  129156. return 5;
  129157. }
  129158. /*
  129159. ** Return the number of bytes required to encode v as a varint
  129160. */
  129161. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  129162. int i = 0;
  129163. do{
  129164. i++;
  129165. v >>= 7;
  129166. }while( v!=0 );
  129167. return i;
  129168. }
  129169. /*
  129170. ** Convert an SQL-style quoted string into a normal string by removing
  129171. ** the quote characters. The conversion is done in-place. If the
  129172. ** input does not begin with a quote character, then this routine
  129173. ** is a no-op.
  129174. **
  129175. ** Examples:
  129176. **
  129177. ** "abc" becomes abc
  129178. ** 'xyz' becomes xyz
  129179. ** [pqr] becomes pqr
  129180. ** `mno` becomes mno
  129181. **
  129182. */
  129183. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  129184. char quote; /* Quote character (if any ) */
  129185. quote = z[0];
  129186. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  129187. int iIn = 1; /* Index of next byte to read from input */
  129188. int iOut = 0; /* Index of next byte to write to output */
  129189. /* If the first byte was a '[', then the close-quote character is a ']' */
  129190. if( quote=='[' ) quote = ']';
  129191. while( z[iIn] ){
  129192. if( z[iIn]==quote ){
  129193. if( z[iIn+1]!=quote ) break;
  129194. z[iOut++] = quote;
  129195. iIn += 2;
  129196. }else{
  129197. z[iOut++] = z[iIn++];
  129198. }
  129199. }
  129200. z[iOut] = '\0';
  129201. }
  129202. }
  129203. /*
  129204. ** Read a single varint from the doclist at *pp and advance *pp to point
  129205. ** to the first byte past the end of the varint. Add the value of the varint
  129206. ** to *pVal.
  129207. */
  129208. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  129209. sqlite3_int64 iVal;
  129210. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  129211. *pVal += iVal;
  129212. }
  129213. /*
  129214. ** When this function is called, *pp points to the first byte following a
  129215. ** varint that is part of a doclist (or position-list, or any other list
  129216. ** of varints). This function moves *pp to point to the start of that varint,
  129217. ** and sets *pVal by the varint value.
  129218. **
  129219. ** Argument pStart points to the first byte of the doclist that the
  129220. ** varint is part of.
  129221. */
  129222. static void fts3GetReverseVarint(
  129223. char **pp,
  129224. char *pStart,
  129225. sqlite3_int64 *pVal
  129226. ){
  129227. sqlite3_int64 iVal;
  129228. char *p;
  129229. /* Pointer p now points at the first byte past the varint we are
  129230. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  129231. ** clear on character p[-1]. */
  129232. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  129233. p++;
  129234. *pp = p;
  129235. sqlite3Fts3GetVarint(p, &iVal);
  129236. *pVal = iVal;
  129237. }
  129238. /*
  129239. ** The xDisconnect() virtual table method.
  129240. */
  129241. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  129242. Fts3Table *p = (Fts3Table *)pVtab;
  129243. int i;
  129244. assert( p->nPendingData==0 );
  129245. assert( p->pSegments==0 );
  129246. /* Free any prepared statements held */
  129247. for(i=0; i<SizeofArray(p->aStmt); i++){
  129248. sqlite3_finalize(p->aStmt[i]);
  129249. }
  129250. sqlite3_free(p->zSegmentsTbl);
  129251. sqlite3_free(p->zReadExprlist);
  129252. sqlite3_free(p->zWriteExprlist);
  129253. sqlite3_free(p->zContentTbl);
  129254. sqlite3_free(p->zLanguageid);
  129255. /* Invoke the tokenizer destructor to free the tokenizer. */
  129256. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  129257. sqlite3_free(p);
  129258. return SQLITE_OK;
  129259. }
  129260. /*
  129261. ** Write an error message into *pzErr
  129262. */
  129263. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  129264. va_list ap;
  129265. sqlite3_free(*pzErr);
  129266. va_start(ap, zFormat);
  129267. *pzErr = sqlite3_vmprintf(zFormat, ap);
  129268. va_end(ap);
  129269. }
  129270. /*
  129271. ** Construct one or more SQL statements from the format string given
  129272. ** and then evaluate those statements. The success code is written
  129273. ** into *pRc.
  129274. **
  129275. ** If *pRc is initially non-zero then this routine is a no-op.
  129276. */
  129277. static void fts3DbExec(
  129278. int *pRc, /* Success code */
  129279. sqlite3 *db, /* Database in which to run SQL */
  129280. const char *zFormat, /* Format string for SQL */
  129281. ... /* Arguments to the format string */
  129282. ){
  129283. va_list ap;
  129284. char *zSql;
  129285. if( *pRc ) return;
  129286. va_start(ap, zFormat);
  129287. zSql = sqlite3_vmprintf(zFormat, ap);
  129288. va_end(ap);
  129289. if( zSql==0 ){
  129290. *pRc = SQLITE_NOMEM;
  129291. }else{
  129292. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  129293. sqlite3_free(zSql);
  129294. }
  129295. }
  129296. /*
  129297. ** The xDestroy() virtual table method.
  129298. */
  129299. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  129300. Fts3Table *p = (Fts3Table *)pVtab;
  129301. int rc = SQLITE_OK; /* Return code */
  129302. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  129303. sqlite3 *db = p->db; /* Database handle */
  129304. /* Drop the shadow tables */
  129305. if( p->zContentTbl==0 ){
  129306. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  129307. }
  129308. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  129309. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  129310. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  129311. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  129312. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  129313. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  129314. ** Otherwise, return an SQLite error code.
  129315. */
  129316. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  129317. }
  129318. /*
  129319. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  129320. ** passed as the first argument. This is done as part of the xConnect()
  129321. ** and xCreate() methods.
  129322. **
  129323. ** If *pRc is non-zero when this function is called, it is a no-op.
  129324. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  129325. ** before returning.
  129326. */
  129327. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  129328. if( *pRc==SQLITE_OK ){
  129329. int i; /* Iterator variable */
  129330. int rc; /* Return code */
  129331. char *zSql; /* SQL statement passed to declare_vtab() */
  129332. char *zCols; /* List of user defined columns */
  129333. const char *zLanguageid;
  129334. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  129335. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  129336. /* Create a list of user columns for the virtual table */
  129337. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  129338. for(i=1; zCols && i<p->nColumn; i++){
  129339. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  129340. }
  129341. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  129342. zSql = sqlite3_mprintf(
  129343. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  129344. zCols, p->zName, zLanguageid
  129345. );
  129346. if( !zCols || !zSql ){
  129347. rc = SQLITE_NOMEM;
  129348. }else{
  129349. rc = sqlite3_declare_vtab(p->db, zSql);
  129350. }
  129351. sqlite3_free(zSql);
  129352. sqlite3_free(zCols);
  129353. *pRc = rc;
  129354. }
  129355. }
  129356. /*
  129357. ** Create the %_stat table if it does not already exist.
  129358. */
  129359. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  129360. fts3DbExec(pRc, p->db,
  129361. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  129362. "(id INTEGER PRIMARY KEY, value BLOB);",
  129363. p->zDb, p->zName
  129364. );
  129365. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  129366. }
  129367. /*
  129368. ** Create the backing store tables (%_content, %_segments and %_segdir)
  129369. ** required by the FTS3 table passed as the only argument. This is done
  129370. ** as part of the vtab xCreate() method.
  129371. **
  129372. ** If the p->bHasDocsize boolean is true (indicating that this is an
  129373. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  129374. ** %_stat tables required by FTS4.
  129375. */
  129376. static int fts3CreateTables(Fts3Table *p){
  129377. int rc = SQLITE_OK; /* Return code */
  129378. int i; /* Iterator variable */
  129379. sqlite3 *db = p->db; /* The database connection */
  129380. if( p->zContentTbl==0 ){
  129381. const char *zLanguageid = p->zLanguageid;
  129382. char *zContentCols; /* Columns of %_content table */
  129383. /* Create a list of user columns for the content table */
  129384. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  129385. for(i=0; zContentCols && i<p->nColumn; i++){
  129386. char *z = p->azColumn[i];
  129387. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  129388. }
  129389. if( zLanguageid && zContentCols ){
  129390. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  129391. }
  129392. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  129393. /* Create the content table */
  129394. fts3DbExec(&rc, db,
  129395. "CREATE TABLE %Q.'%q_content'(%s)",
  129396. p->zDb, p->zName, zContentCols
  129397. );
  129398. sqlite3_free(zContentCols);
  129399. }
  129400. /* Create other tables */
  129401. fts3DbExec(&rc, db,
  129402. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  129403. p->zDb, p->zName
  129404. );
  129405. fts3DbExec(&rc, db,
  129406. "CREATE TABLE %Q.'%q_segdir'("
  129407. "level INTEGER,"
  129408. "idx INTEGER,"
  129409. "start_block INTEGER,"
  129410. "leaves_end_block INTEGER,"
  129411. "end_block INTEGER,"
  129412. "root BLOB,"
  129413. "PRIMARY KEY(level, idx)"
  129414. ");",
  129415. p->zDb, p->zName
  129416. );
  129417. if( p->bHasDocsize ){
  129418. fts3DbExec(&rc, db,
  129419. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  129420. p->zDb, p->zName
  129421. );
  129422. }
  129423. assert( p->bHasStat==p->bFts4 );
  129424. if( p->bHasStat ){
  129425. sqlite3Fts3CreateStatTable(&rc, p);
  129426. }
  129427. return rc;
  129428. }
  129429. /*
  129430. ** Store the current database page-size in bytes in p->nPgsz.
  129431. **
  129432. ** If *pRc is non-zero when this function is called, it is a no-op.
  129433. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  129434. ** before returning.
  129435. */
  129436. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  129437. if( *pRc==SQLITE_OK ){
  129438. int rc; /* Return code */
  129439. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  129440. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  129441. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  129442. if( !zSql ){
  129443. rc = SQLITE_NOMEM;
  129444. }else{
  129445. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  129446. if( rc==SQLITE_OK ){
  129447. sqlite3_step(pStmt);
  129448. p->nPgsz = sqlite3_column_int(pStmt, 0);
  129449. rc = sqlite3_finalize(pStmt);
  129450. }else if( rc==SQLITE_AUTH ){
  129451. p->nPgsz = 1024;
  129452. rc = SQLITE_OK;
  129453. }
  129454. }
  129455. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  129456. sqlite3_free(zSql);
  129457. *pRc = rc;
  129458. }
  129459. }
  129460. /*
  129461. ** "Special" FTS4 arguments are column specifications of the following form:
  129462. **
  129463. ** <key> = <value>
  129464. **
  129465. ** There may not be whitespace surrounding the "=" character. The <value>
  129466. ** term may be quoted, but the <key> may not.
  129467. */
  129468. static int fts3IsSpecialColumn(
  129469. const char *z,
  129470. int *pnKey,
  129471. char **pzValue
  129472. ){
  129473. char *zValue;
  129474. const char *zCsr = z;
  129475. while( *zCsr!='=' ){
  129476. if( *zCsr=='\0' ) return 0;
  129477. zCsr++;
  129478. }
  129479. *pnKey = (int)(zCsr-z);
  129480. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  129481. if( zValue ){
  129482. sqlite3Fts3Dequote(zValue);
  129483. }
  129484. *pzValue = zValue;
  129485. return 1;
  129486. }
  129487. /*
  129488. ** Append the output of a printf() style formatting to an existing string.
  129489. */
  129490. static void fts3Appendf(
  129491. int *pRc, /* IN/OUT: Error code */
  129492. char **pz, /* IN/OUT: Pointer to string buffer */
  129493. const char *zFormat, /* Printf format string to append */
  129494. ... /* Arguments for printf format string */
  129495. ){
  129496. if( *pRc==SQLITE_OK ){
  129497. va_list ap;
  129498. char *z;
  129499. va_start(ap, zFormat);
  129500. z = sqlite3_vmprintf(zFormat, ap);
  129501. va_end(ap);
  129502. if( z && *pz ){
  129503. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  129504. sqlite3_free(z);
  129505. z = z2;
  129506. }
  129507. if( z==0 ) *pRc = SQLITE_NOMEM;
  129508. sqlite3_free(*pz);
  129509. *pz = z;
  129510. }
  129511. }
  129512. /*
  129513. ** Return a copy of input string zInput enclosed in double-quotes (") and
  129514. ** with all double quote characters escaped. For example:
  129515. **
  129516. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  129517. **
  129518. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  129519. ** is the callers responsibility to call sqlite3_free() to release this
  129520. ** memory.
  129521. */
  129522. static char *fts3QuoteId(char const *zInput){
  129523. int nRet;
  129524. char *zRet;
  129525. nRet = 2 + (int)strlen(zInput)*2 + 1;
  129526. zRet = sqlite3_malloc(nRet);
  129527. if( zRet ){
  129528. int i;
  129529. char *z = zRet;
  129530. *(z++) = '"';
  129531. for(i=0; zInput[i]; i++){
  129532. if( zInput[i]=='"' ) *(z++) = '"';
  129533. *(z++) = zInput[i];
  129534. }
  129535. *(z++) = '"';
  129536. *(z++) = '\0';
  129537. }
  129538. return zRet;
  129539. }
  129540. /*
  129541. ** Return a list of comma separated SQL expressions and a FROM clause that
  129542. ** could be used in a SELECT statement such as the following:
  129543. **
  129544. ** SELECT <list of expressions> FROM %_content AS x ...
  129545. **
  129546. ** to return the docid, followed by each column of text data in order
  129547. ** from left to write. If parameter zFunc is not NULL, then instead of
  129548. ** being returned directly each column of text data is passed to an SQL
  129549. ** function named zFunc first. For example, if zFunc is "unzip" and the
  129550. ** table has the three user-defined columns "a", "b", and "c", the following
  129551. ** string is returned:
  129552. **
  129553. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  129554. **
  129555. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  129556. ** is the responsibility of the caller to eventually free it.
  129557. **
  129558. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  129559. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  129560. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  129561. ** no error occurs, *pRc is left unmodified.
  129562. */
  129563. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  129564. char *zRet = 0;
  129565. char *zFree = 0;
  129566. char *zFunction;
  129567. int i;
  129568. if( p->zContentTbl==0 ){
  129569. if( !zFunc ){
  129570. zFunction = "";
  129571. }else{
  129572. zFree = zFunction = fts3QuoteId(zFunc);
  129573. }
  129574. fts3Appendf(pRc, &zRet, "docid");
  129575. for(i=0; i<p->nColumn; i++){
  129576. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  129577. }
  129578. if( p->zLanguageid ){
  129579. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  129580. }
  129581. sqlite3_free(zFree);
  129582. }else{
  129583. fts3Appendf(pRc, &zRet, "rowid");
  129584. for(i=0; i<p->nColumn; i++){
  129585. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  129586. }
  129587. if( p->zLanguageid ){
  129588. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  129589. }
  129590. }
  129591. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  129592. p->zDb,
  129593. (p->zContentTbl ? p->zContentTbl : p->zName),
  129594. (p->zContentTbl ? "" : "_content")
  129595. );
  129596. return zRet;
  129597. }
  129598. /*
  129599. ** Return a list of N comma separated question marks, where N is the number
  129600. ** of columns in the %_content table (one for the docid plus one for each
  129601. ** user-defined text column).
  129602. **
  129603. ** If argument zFunc is not NULL, then all but the first question mark
  129604. ** is preceded by zFunc and an open bracket, and followed by a closed
  129605. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  129606. ** user-defined text columns, the following string is returned:
  129607. **
  129608. ** "?, zip(?), zip(?), zip(?)"
  129609. **
  129610. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  129611. ** is the responsibility of the caller to eventually free it.
  129612. **
  129613. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  129614. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  129615. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  129616. ** no error occurs, *pRc is left unmodified.
  129617. */
  129618. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  129619. char *zRet = 0;
  129620. char *zFree = 0;
  129621. char *zFunction;
  129622. int i;
  129623. if( !zFunc ){
  129624. zFunction = "";
  129625. }else{
  129626. zFree = zFunction = fts3QuoteId(zFunc);
  129627. }
  129628. fts3Appendf(pRc, &zRet, "?");
  129629. for(i=0; i<p->nColumn; i++){
  129630. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  129631. }
  129632. if( p->zLanguageid ){
  129633. fts3Appendf(pRc, &zRet, ", ?");
  129634. }
  129635. sqlite3_free(zFree);
  129636. return zRet;
  129637. }
  129638. /*
  129639. ** This function interprets the string at (*pp) as a non-negative integer
  129640. ** value. It reads the integer and sets *pnOut to the value read, then
  129641. ** sets *pp to point to the byte immediately following the last byte of
  129642. ** the integer value.
  129643. **
  129644. ** Only decimal digits ('0'..'9') may be part of an integer value.
  129645. **
  129646. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  129647. ** the output value undefined. Otherwise SQLITE_OK is returned.
  129648. **
  129649. ** This function is used when parsing the "prefix=" FTS4 parameter.
  129650. */
  129651. static int fts3GobbleInt(const char **pp, int *pnOut){
  129652. const int MAX_NPREFIX = 10000000;
  129653. const char *p; /* Iterator pointer */
  129654. int nInt = 0; /* Output value */
  129655. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  129656. nInt = nInt * 10 + (p[0] - '0');
  129657. if( nInt>MAX_NPREFIX ){
  129658. nInt = 0;
  129659. break;
  129660. }
  129661. }
  129662. if( p==*pp ) return SQLITE_ERROR;
  129663. *pnOut = nInt;
  129664. *pp = p;
  129665. return SQLITE_OK;
  129666. }
  129667. /*
  129668. ** This function is called to allocate an array of Fts3Index structures
  129669. ** representing the indexes maintained by the current FTS table. FTS tables
  129670. ** always maintain the main "terms" index, but may also maintain one or
  129671. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  129672. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  129673. **
  129674. ** Argument zParam is passed the value of the "prefix=" option if one was
  129675. ** specified, or NULL otherwise.
  129676. **
  129677. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  129678. ** the allocated array. *pnIndex is set to the number of elements in the
  129679. ** array. If an error does occur, an SQLite error code is returned.
  129680. **
  129681. ** Regardless of whether or not an error is returned, it is the responsibility
  129682. ** of the caller to call sqlite3_free() on the output array to free it.
  129683. */
  129684. static int fts3PrefixParameter(
  129685. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  129686. int *pnIndex, /* OUT: size of *apIndex[] array */
  129687. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  129688. ){
  129689. struct Fts3Index *aIndex; /* Allocated array */
  129690. int nIndex = 1; /* Number of entries in array */
  129691. if( zParam && zParam[0] ){
  129692. const char *p;
  129693. nIndex++;
  129694. for(p=zParam; *p; p++){
  129695. if( *p==',' ) nIndex++;
  129696. }
  129697. }
  129698. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  129699. *apIndex = aIndex;
  129700. if( !aIndex ){
  129701. return SQLITE_NOMEM;
  129702. }
  129703. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  129704. if( zParam ){
  129705. const char *p = zParam;
  129706. int i;
  129707. for(i=1; i<nIndex; i++){
  129708. int nPrefix = 0;
  129709. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  129710. assert( nPrefix>=0 );
  129711. if( nPrefix==0 ){
  129712. nIndex--;
  129713. i--;
  129714. }else{
  129715. aIndex[i].nPrefix = nPrefix;
  129716. }
  129717. p++;
  129718. }
  129719. }
  129720. *pnIndex = nIndex;
  129721. return SQLITE_OK;
  129722. }
  129723. /*
  129724. ** This function is called when initializing an FTS4 table that uses the
  129725. ** content=xxx option. It determines the number of and names of the columns
  129726. ** of the new FTS4 table.
  129727. **
  129728. ** The third argument passed to this function is the value passed to the
  129729. ** config=xxx option (i.e. "xxx"). This function queries the database for
  129730. ** a table of that name. If found, the output variables are populated
  129731. ** as follows:
  129732. **
  129733. ** *pnCol: Set to the number of columns table xxx has,
  129734. **
  129735. ** *pnStr: Set to the total amount of space required to store a copy
  129736. ** of each columns name, including the nul-terminator.
  129737. **
  129738. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  129739. ** the name of the corresponding column in table xxx. The array
  129740. ** and its contents are allocated using a single allocation. It
  129741. ** is the responsibility of the caller to free this allocation
  129742. ** by eventually passing the *pazCol value to sqlite3_free().
  129743. **
  129744. ** If the table cannot be found, an error code is returned and the output
  129745. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  129746. ** returned (and the output variables are undefined).
  129747. */
  129748. static int fts3ContentColumns(
  129749. sqlite3 *db, /* Database handle */
  129750. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  129751. const char *zTbl, /* Name of content table */
  129752. const char ***pazCol, /* OUT: Malloc'd array of column names */
  129753. int *pnCol, /* OUT: Size of array *pazCol */
  129754. int *pnStr, /* OUT: Bytes of string content */
  129755. char **pzErr /* OUT: error message */
  129756. ){
  129757. int rc = SQLITE_OK; /* Return code */
  129758. char *zSql; /* "SELECT *" statement on zTbl */
  129759. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  129760. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  129761. if( !zSql ){
  129762. rc = SQLITE_NOMEM;
  129763. }else{
  129764. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  129765. if( rc!=SQLITE_OK ){
  129766. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  129767. }
  129768. }
  129769. sqlite3_free(zSql);
  129770. if( rc==SQLITE_OK ){
  129771. const char **azCol; /* Output array */
  129772. int nStr = 0; /* Size of all column names (incl. 0x00) */
  129773. int nCol; /* Number of table columns */
  129774. int i; /* Used to iterate through columns */
  129775. /* Loop through the returned columns. Set nStr to the number of bytes of
  129776. ** space required to store a copy of each column name, including the
  129777. ** nul-terminator byte. */
  129778. nCol = sqlite3_column_count(pStmt);
  129779. for(i=0; i<nCol; i++){
  129780. const char *zCol = sqlite3_column_name(pStmt, i);
  129781. nStr += (int)strlen(zCol) + 1;
  129782. }
  129783. /* Allocate and populate the array to return. */
  129784. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  129785. if( azCol==0 ){
  129786. rc = SQLITE_NOMEM;
  129787. }else{
  129788. char *p = (char *)&azCol[nCol];
  129789. for(i=0; i<nCol; i++){
  129790. const char *zCol = sqlite3_column_name(pStmt, i);
  129791. int n = (int)strlen(zCol)+1;
  129792. memcpy(p, zCol, n);
  129793. azCol[i] = p;
  129794. p += n;
  129795. }
  129796. }
  129797. sqlite3_finalize(pStmt);
  129798. /* Set the output variables. */
  129799. *pnCol = nCol;
  129800. *pnStr = nStr;
  129801. *pazCol = azCol;
  129802. }
  129803. return rc;
  129804. }
  129805. /*
  129806. ** This function is the implementation of both the xConnect and xCreate
  129807. ** methods of the FTS3 virtual table.
  129808. **
  129809. ** The argv[] array contains the following:
  129810. **
  129811. ** argv[0] -> module name ("fts3" or "fts4")
  129812. ** argv[1] -> database name
  129813. ** argv[2] -> table name
  129814. ** argv[...] -> "column name" and other module argument fields.
  129815. */
  129816. static int fts3InitVtab(
  129817. int isCreate, /* True for xCreate, false for xConnect */
  129818. sqlite3 *db, /* The SQLite database connection */
  129819. void *pAux, /* Hash table containing tokenizers */
  129820. int argc, /* Number of elements in argv array */
  129821. const char * const *argv, /* xCreate/xConnect argument array */
  129822. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  129823. char **pzErr /* Write any error message here */
  129824. ){
  129825. Fts3Hash *pHash = (Fts3Hash *)pAux;
  129826. Fts3Table *p = 0; /* Pointer to allocated vtab */
  129827. int rc = SQLITE_OK; /* Return code */
  129828. int i; /* Iterator variable */
  129829. int nByte; /* Size of allocation used for *p */
  129830. int iCol; /* Column index */
  129831. int nString = 0; /* Bytes required to hold all column names */
  129832. int nCol = 0; /* Number of columns in the FTS table */
  129833. char *zCsr; /* Space for holding column names */
  129834. int nDb; /* Bytes required to hold database name */
  129835. int nName; /* Bytes required to hold table name */
  129836. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  129837. const char **aCol; /* Array of column names */
  129838. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  129839. int nIndex = 0; /* Size of aIndex[] array */
  129840. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  129841. /* The results of parsing supported FTS4 key=value options: */
  129842. int bNoDocsize = 0; /* True to omit %_docsize table */
  129843. int bDescIdx = 0; /* True to store descending indexes */
  129844. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  129845. char *zCompress = 0; /* compress=? parameter (or NULL) */
  129846. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  129847. char *zContent = 0; /* content=? parameter (or NULL) */
  129848. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  129849. char **azNotindexed = 0; /* The set of notindexed= columns */
  129850. int nNotindexed = 0; /* Size of azNotindexed[] array */
  129851. assert( strlen(argv[0])==4 );
  129852. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  129853. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  129854. );
  129855. nDb = (int)strlen(argv[1]) + 1;
  129856. nName = (int)strlen(argv[2]) + 1;
  129857. nByte = sizeof(const char *) * (argc-2);
  129858. aCol = (const char **)sqlite3_malloc(nByte);
  129859. if( aCol ){
  129860. memset((void*)aCol, 0, nByte);
  129861. azNotindexed = (char **)sqlite3_malloc(nByte);
  129862. }
  129863. if( azNotindexed ){
  129864. memset(azNotindexed, 0, nByte);
  129865. }
  129866. if( !aCol || !azNotindexed ){
  129867. rc = SQLITE_NOMEM;
  129868. goto fts3_init_out;
  129869. }
  129870. /* Loop through all of the arguments passed by the user to the FTS3/4
  129871. ** module (i.e. all the column names and special arguments). This loop
  129872. ** does the following:
  129873. **
  129874. ** + Figures out the number of columns the FTSX table will have, and
  129875. ** the number of bytes of space that must be allocated to store copies
  129876. ** of the column names.
  129877. **
  129878. ** + If there is a tokenizer specification included in the arguments,
  129879. ** initializes the tokenizer pTokenizer.
  129880. */
  129881. for(i=3; rc==SQLITE_OK && i<argc; i++){
  129882. char const *z = argv[i];
  129883. int nKey;
  129884. char *zVal;
  129885. /* Check if this is a tokenizer specification */
  129886. if( !pTokenizer
  129887. && strlen(z)>8
  129888. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  129889. && 0==sqlite3Fts3IsIdChar(z[8])
  129890. ){
  129891. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  129892. }
  129893. /* Check if it is an FTS4 special argument. */
  129894. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  129895. struct Fts4Option {
  129896. const char *zOpt;
  129897. int nOpt;
  129898. } aFts4Opt[] = {
  129899. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  129900. { "prefix", 6 }, /* 1 -> PREFIX */
  129901. { "compress", 8 }, /* 2 -> COMPRESS */
  129902. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  129903. { "order", 5 }, /* 4 -> ORDER */
  129904. { "content", 7 }, /* 5 -> CONTENT */
  129905. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  129906. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  129907. };
  129908. int iOpt;
  129909. if( !zVal ){
  129910. rc = SQLITE_NOMEM;
  129911. }else{
  129912. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  129913. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  129914. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  129915. break;
  129916. }
  129917. }
  129918. if( iOpt==SizeofArray(aFts4Opt) ){
  129919. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  129920. rc = SQLITE_ERROR;
  129921. }else{
  129922. switch( iOpt ){
  129923. case 0: /* MATCHINFO */
  129924. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  129925. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  129926. rc = SQLITE_ERROR;
  129927. }
  129928. bNoDocsize = 1;
  129929. break;
  129930. case 1: /* PREFIX */
  129931. sqlite3_free(zPrefix);
  129932. zPrefix = zVal;
  129933. zVal = 0;
  129934. break;
  129935. case 2: /* COMPRESS */
  129936. sqlite3_free(zCompress);
  129937. zCompress = zVal;
  129938. zVal = 0;
  129939. break;
  129940. case 3: /* UNCOMPRESS */
  129941. sqlite3_free(zUncompress);
  129942. zUncompress = zVal;
  129943. zVal = 0;
  129944. break;
  129945. case 4: /* ORDER */
  129946. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  129947. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  129948. ){
  129949. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  129950. rc = SQLITE_ERROR;
  129951. }
  129952. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  129953. break;
  129954. case 5: /* CONTENT */
  129955. sqlite3_free(zContent);
  129956. zContent = zVal;
  129957. zVal = 0;
  129958. break;
  129959. case 6: /* LANGUAGEID */
  129960. assert( iOpt==6 );
  129961. sqlite3_free(zLanguageid);
  129962. zLanguageid = zVal;
  129963. zVal = 0;
  129964. break;
  129965. case 7: /* NOTINDEXED */
  129966. azNotindexed[nNotindexed++] = zVal;
  129967. zVal = 0;
  129968. break;
  129969. }
  129970. }
  129971. sqlite3_free(zVal);
  129972. }
  129973. }
  129974. /* Otherwise, the argument is a column name. */
  129975. else {
  129976. nString += (int)(strlen(z) + 1);
  129977. aCol[nCol++] = z;
  129978. }
  129979. }
  129980. /* If a content=xxx option was specified, the following:
  129981. **
  129982. ** 1. Ignore any compress= and uncompress= options.
  129983. **
  129984. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  129985. ** TABLE statement, use all columns from the content table.
  129986. */
  129987. if( rc==SQLITE_OK && zContent ){
  129988. sqlite3_free(zCompress);
  129989. sqlite3_free(zUncompress);
  129990. zCompress = 0;
  129991. zUncompress = 0;
  129992. if( nCol==0 ){
  129993. sqlite3_free((void*)aCol);
  129994. aCol = 0;
  129995. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  129996. /* If a languageid= option was specified, remove the language id
  129997. ** column from the aCol[] array. */
  129998. if( rc==SQLITE_OK && zLanguageid ){
  129999. int j;
  130000. for(j=0; j<nCol; j++){
  130001. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  130002. int k;
  130003. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  130004. nCol--;
  130005. break;
  130006. }
  130007. }
  130008. }
  130009. }
  130010. }
  130011. if( rc!=SQLITE_OK ) goto fts3_init_out;
  130012. if( nCol==0 ){
  130013. assert( nString==0 );
  130014. aCol[0] = "content";
  130015. nString = 8;
  130016. nCol = 1;
  130017. }
  130018. if( pTokenizer==0 ){
  130019. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  130020. if( rc!=SQLITE_OK ) goto fts3_init_out;
  130021. }
  130022. assert( pTokenizer );
  130023. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  130024. if( rc==SQLITE_ERROR ){
  130025. assert( zPrefix );
  130026. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  130027. }
  130028. if( rc!=SQLITE_OK ) goto fts3_init_out;
  130029. /* Allocate and populate the Fts3Table structure. */
  130030. nByte = sizeof(Fts3Table) + /* Fts3Table */
  130031. nCol * sizeof(char *) + /* azColumn */
  130032. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  130033. nCol * sizeof(u8) + /* abNotindexed */
  130034. nName + /* zName */
  130035. nDb + /* zDb */
  130036. nString; /* Space for azColumn strings */
  130037. p = (Fts3Table*)sqlite3_malloc(nByte);
  130038. if( p==0 ){
  130039. rc = SQLITE_NOMEM;
  130040. goto fts3_init_out;
  130041. }
  130042. memset(p, 0, nByte);
  130043. p->db = db;
  130044. p->nColumn = nCol;
  130045. p->nPendingData = 0;
  130046. p->azColumn = (char **)&p[1];
  130047. p->pTokenizer = pTokenizer;
  130048. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  130049. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  130050. p->bHasStat = isFts4;
  130051. p->bFts4 = isFts4;
  130052. p->bDescIdx = bDescIdx;
  130053. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  130054. p->zContentTbl = zContent;
  130055. p->zLanguageid = zLanguageid;
  130056. zContent = 0;
  130057. zLanguageid = 0;
  130058. TESTONLY( p->inTransaction = -1 );
  130059. TESTONLY( p->mxSavepoint = -1 );
  130060. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  130061. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  130062. p->nIndex = nIndex;
  130063. for(i=0; i<nIndex; i++){
  130064. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  130065. }
  130066. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  130067. /* Fill in the zName and zDb fields of the vtab structure. */
  130068. zCsr = (char *)&p->abNotindexed[nCol];
  130069. p->zName = zCsr;
  130070. memcpy(zCsr, argv[2], nName);
  130071. zCsr += nName;
  130072. p->zDb = zCsr;
  130073. memcpy(zCsr, argv[1], nDb);
  130074. zCsr += nDb;
  130075. /* Fill in the azColumn array */
  130076. for(iCol=0; iCol<nCol; iCol++){
  130077. char *z;
  130078. int n = 0;
  130079. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  130080. memcpy(zCsr, z, n);
  130081. zCsr[n] = '\0';
  130082. sqlite3Fts3Dequote(zCsr);
  130083. p->azColumn[iCol] = zCsr;
  130084. zCsr += n+1;
  130085. assert( zCsr <= &((char *)p)[nByte] );
  130086. }
  130087. /* Fill in the abNotindexed array */
  130088. for(iCol=0; iCol<nCol; iCol++){
  130089. int n = (int)strlen(p->azColumn[iCol]);
  130090. for(i=0; i<nNotindexed; i++){
  130091. char *zNot = azNotindexed[i];
  130092. if( zNot && n==(int)strlen(zNot)
  130093. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  130094. ){
  130095. p->abNotindexed[iCol] = 1;
  130096. sqlite3_free(zNot);
  130097. azNotindexed[i] = 0;
  130098. }
  130099. }
  130100. }
  130101. for(i=0; i<nNotindexed; i++){
  130102. if( azNotindexed[i] ){
  130103. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  130104. rc = SQLITE_ERROR;
  130105. }
  130106. }
  130107. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  130108. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  130109. rc = SQLITE_ERROR;
  130110. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  130111. }
  130112. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  130113. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  130114. if( rc!=SQLITE_OK ) goto fts3_init_out;
  130115. /* If this is an xCreate call, create the underlying tables in the
  130116. ** database. TODO: For xConnect(), it could verify that said tables exist.
  130117. */
  130118. if( isCreate ){
  130119. rc = fts3CreateTables(p);
  130120. }
  130121. /* Check to see if a legacy fts3 table has been "upgraded" by the
  130122. ** addition of a %_stat table so that it can use incremental merge.
  130123. */
  130124. if( !isFts4 && !isCreate ){
  130125. p->bHasStat = 2;
  130126. }
  130127. /* Figure out the page-size for the database. This is required in order to
  130128. ** estimate the cost of loading large doclists from the database. */
  130129. fts3DatabasePageSize(&rc, p);
  130130. p->nNodeSize = p->nPgsz-35;
  130131. /* Declare the table schema to SQLite. */
  130132. fts3DeclareVtab(&rc, p);
  130133. fts3_init_out:
  130134. sqlite3_free(zPrefix);
  130135. sqlite3_free(aIndex);
  130136. sqlite3_free(zCompress);
  130137. sqlite3_free(zUncompress);
  130138. sqlite3_free(zContent);
  130139. sqlite3_free(zLanguageid);
  130140. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  130141. sqlite3_free((void *)aCol);
  130142. sqlite3_free((void *)azNotindexed);
  130143. if( rc!=SQLITE_OK ){
  130144. if( p ){
  130145. fts3DisconnectMethod((sqlite3_vtab *)p);
  130146. }else if( pTokenizer ){
  130147. pTokenizer->pModule->xDestroy(pTokenizer);
  130148. }
  130149. }else{
  130150. assert( p->pSegments==0 );
  130151. *ppVTab = &p->base;
  130152. }
  130153. return rc;
  130154. }
  130155. /*
  130156. ** The xConnect() and xCreate() methods for the virtual table. All the
  130157. ** work is done in function fts3InitVtab().
  130158. */
  130159. static int fts3ConnectMethod(
  130160. sqlite3 *db, /* Database connection */
  130161. void *pAux, /* Pointer to tokenizer hash table */
  130162. int argc, /* Number of elements in argv array */
  130163. const char * const *argv, /* xCreate/xConnect argument array */
  130164. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  130165. char **pzErr /* OUT: sqlite3_malloc'd error message */
  130166. ){
  130167. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  130168. }
  130169. static int fts3CreateMethod(
  130170. sqlite3 *db, /* Database connection */
  130171. void *pAux, /* Pointer to tokenizer hash table */
  130172. int argc, /* Number of elements in argv array */
  130173. const char * const *argv, /* xCreate/xConnect argument array */
  130174. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  130175. char **pzErr /* OUT: sqlite3_malloc'd error message */
  130176. ){
  130177. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  130178. }
  130179. /*
  130180. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  130181. ** extension is currently being used by a version of SQLite too old to
  130182. ** support estimatedRows. In that case this function is a no-op.
  130183. */
  130184. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  130185. #if SQLITE_VERSION_NUMBER>=3008002
  130186. if( sqlite3_libversion_number()>=3008002 ){
  130187. pIdxInfo->estimatedRows = nRow;
  130188. }
  130189. #endif
  130190. }
  130191. /*
  130192. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  130193. ** extension is currently being used by a version of SQLite too old to
  130194. ** support index-info flags. In that case this function is a no-op.
  130195. */
  130196. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  130197. #if SQLITE_VERSION_NUMBER>=3008012
  130198. if( sqlite3_libversion_number()>=3008012 ){
  130199. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  130200. }
  130201. #endif
  130202. }
  130203. /*
  130204. ** Implementation of the xBestIndex method for FTS3 tables. There
  130205. ** are three possible strategies, in order of preference:
  130206. **
  130207. ** 1. Direct lookup by rowid or docid.
  130208. ** 2. Full-text search using a MATCH operator on a non-docid column.
  130209. ** 3. Linear scan of %_content table.
  130210. */
  130211. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  130212. Fts3Table *p = (Fts3Table *)pVTab;
  130213. int i; /* Iterator variable */
  130214. int iCons = -1; /* Index of constraint to use */
  130215. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  130216. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  130217. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  130218. int iIdx;
  130219. /* By default use a full table scan. This is an expensive option,
  130220. ** so search through the constraints to see if a more efficient
  130221. ** strategy is possible.
  130222. */
  130223. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  130224. pInfo->estimatedCost = 5000000;
  130225. for(i=0; i<pInfo->nConstraint; i++){
  130226. int bDocid; /* True if this constraint is on docid */
  130227. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  130228. if( pCons->usable==0 ){
  130229. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  130230. /* There exists an unusable MATCH constraint. This means that if
  130231. ** the planner does elect to use the results of this call as part
  130232. ** of the overall query plan the user will see an "unable to use
  130233. ** function MATCH in the requested context" error. To discourage
  130234. ** this, return a very high cost here. */
  130235. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  130236. pInfo->estimatedCost = 1e50;
  130237. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  130238. return SQLITE_OK;
  130239. }
  130240. continue;
  130241. }
  130242. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  130243. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  130244. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  130245. pInfo->idxNum = FTS3_DOCID_SEARCH;
  130246. pInfo->estimatedCost = 1.0;
  130247. iCons = i;
  130248. }
  130249. /* A MATCH constraint. Use a full-text search.
  130250. **
  130251. ** If there is more than one MATCH constraint available, use the first
  130252. ** one encountered. If there is both a MATCH constraint and a direct
  130253. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  130254. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  130255. ** it would lead to an "unable to use function MATCH in the requested
  130256. ** context" error.
  130257. */
  130258. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  130259. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  130260. ){
  130261. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  130262. pInfo->estimatedCost = 2.0;
  130263. iCons = i;
  130264. }
  130265. /* Equality constraint on the langid column */
  130266. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  130267. && pCons->iColumn==p->nColumn + 2
  130268. ){
  130269. iLangidCons = i;
  130270. }
  130271. if( bDocid ){
  130272. switch( pCons->op ){
  130273. case SQLITE_INDEX_CONSTRAINT_GE:
  130274. case SQLITE_INDEX_CONSTRAINT_GT:
  130275. iDocidGe = i;
  130276. break;
  130277. case SQLITE_INDEX_CONSTRAINT_LE:
  130278. case SQLITE_INDEX_CONSTRAINT_LT:
  130279. iDocidLe = i;
  130280. break;
  130281. }
  130282. }
  130283. }
  130284. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  130285. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  130286. iIdx = 1;
  130287. if( iCons>=0 ){
  130288. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  130289. pInfo->aConstraintUsage[iCons].omit = 1;
  130290. }
  130291. if( iLangidCons>=0 ){
  130292. pInfo->idxNum |= FTS3_HAVE_LANGID;
  130293. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  130294. }
  130295. if( iDocidGe>=0 ){
  130296. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  130297. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  130298. }
  130299. if( iDocidLe>=0 ){
  130300. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  130301. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  130302. }
  130303. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  130304. ** docid) order. Both ascending and descending are possible.
  130305. */
  130306. if( pInfo->nOrderBy==1 ){
  130307. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  130308. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  130309. if( pOrder->desc ){
  130310. pInfo->idxStr = "DESC";
  130311. }else{
  130312. pInfo->idxStr = "ASC";
  130313. }
  130314. pInfo->orderByConsumed = 1;
  130315. }
  130316. }
  130317. assert( p->pSegments==0 );
  130318. return SQLITE_OK;
  130319. }
  130320. /*
  130321. ** Implementation of xOpen method.
  130322. */
  130323. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  130324. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  130325. UNUSED_PARAMETER(pVTab);
  130326. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  130327. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  130328. ** if the allocation fails, return SQLITE_NOMEM.
  130329. */
  130330. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  130331. if( !pCsr ){
  130332. return SQLITE_NOMEM;
  130333. }
  130334. memset(pCsr, 0, sizeof(Fts3Cursor));
  130335. return SQLITE_OK;
  130336. }
  130337. /*
  130338. ** Close the cursor. For additional information see the documentation
  130339. ** on the xClose method of the virtual table interface.
  130340. */
  130341. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  130342. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  130343. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  130344. sqlite3_finalize(pCsr->pStmt);
  130345. sqlite3Fts3ExprFree(pCsr->pExpr);
  130346. sqlite3Fts3FreeDeferredTokens(pCsr);
  130347. sqlite3_free(pCsr->aDoclist);
  130348. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  130349. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  130350. sqlite3_free(pCsr);
  130351. return SQLITE_OK;
  130352. }
  130353. /*
  130354. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  130355. ** compose and prepare an SQL statement of the form:
  130356. **
  130357. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  130358. **
  130359. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  130360. ** it. If an error occurs, return an SQLite error code.
  130361. **
  130362. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  130363. */
  130364. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  130365. int rc = SQLITE_OK;
  130366. if( pCsr->pStmt==0 ){
  130367. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  130368. char *zSql;
  130369. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  130370. if( !zSql ) return SQLITE_NOMEM;
  130371. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  130372. sqlite3_free(zSql);
  130373. }
  130374. *ppStmt = pCsr->pStmt;
  130375. return rc;
  130376. }
  130377. /*
  130378. ** Position the pCsr->pStmt statement so that it is on the row
  130379. ** of the %_content table that contains the last match. Return
  130380. ** SQLITE_OK on success.
  130381. */
  130382. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  130383. int rc = SQLITE_OK;
  130384. if( pCsr->isRequireSeek ){
  130385. sqlite3_stmt *pStmt = 0;
  130386. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  130387. if( rc==SQLITE_OK ){
  130388. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  130389. pCsr->isRequireSeek = 0;
  130390. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  130391. return SQLITE_OK;
  130392. }else{
  130393. rc = sqlite3_reset(pCsr->pStmt);
  130394. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  130395. /* If no row was found and no error has occurred, then the %_content
  130396. ** table is missing a row that is present in the full-text index.
  130397. ** The data structures are corrupt. */
  130398. rc = FTS_CORRUPT_VTAB;
  130399. pCsr->isEof = 1;
  130400. }
  130401. }
  130402. }
  130403. }
  130404. if( rc!=SQLITE_OK && pContext ){
  130405. sqlite3_result_error_code(pContext, rc);
  130406. }
  130407. return rc;
  130408. }
  130409. /*
  130410. ** This function is used to process a single interior node when searching
  130411. ** a b-tree for a term or term prefix. The node data is passed to this
  130412. ** function via the zNode/nNode parameters. The term to search for is
  130413. ** passed in zTerm/nTerm.
  130414. **
  130415. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  130416. ** of the child node that heads the sub-tree that may contain the term.
  130417. **
  130418. ** If piLast is not NULL, then *piLast is set to the right-most child node
  130419. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  130420. ** a prefix.
  130421. **
  130422. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  130423. */
  130424. static int fts3ScanInteriorNode(
  130425. const char *zTerm, /* Term to select leaves for */
  130426. int nTerm, /* Size of term zTerm in bytes */
  130427. const char *zNode, /* Buffer containing segment interior node */
  130428. int nNode, /* Size of buffer at zNode */
  130429. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  130430. sqlite3_int64 *piLast /* OUT: Selected child node */
  130431. ){
  130432. int rc = SQLITE_OK; /* Return code */
  130433. const char *zCsr = zNode; /* Cursor to iterate through node */
  130434. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  130435. char *zBuffer = 0; /* Buffer to load terms into */
  130436. int nAlloc = 0; /* Size of allocated buffer */
  130437. int isFirstTerm = 1; /* True when processing first term on page */
  130438. sqlite3_int64 iChild; /* Block id of child node to descend to */
  130439. /* Skip over the 'height' varint that occurs at the start of every
  130440. ** interior node. Then load the blockid of the left-child of the b-tree
  130441. ** node into variable iChild.
  130442. **
  130443. ** Even if the data structure on disk is corrupted, this (reading two
  130444. ** varints from the buffer) does not risk an overread. If zNode is a
  130445. ** root node, then the buffer comes from a SELECT statement. SQLite does
  130446. ** not make this guarantee explicitly, but in practice there are always
  130447. ** either more than 20 bytes of allocated space following the nNode bytes of
  130448. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  130449. ** table, then there are always 20 bytes of zeroed padding following the
  130450. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  130451. */
  130452. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  130453. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  130454. if( zCsr>zEnd ){
  130455. return FTS_CORRUPT_VTAB;
  130456. }
  130457. while( zCsr<zEnd && (piFirst || piLast) ){
  130458. int cmp; /* memcmp() result */
  130459. int nSuffix; /* Size of term suffix */
  130460. int nPrefix = 0; /* Size of term prefix */
  130461. int nBuffer; /* Total term size */
  130462. /* Load the next term on the node into zBuffer. Use realloc() to expand
  130463. ** the size of zBuffer if required. */
  130464. if( !isFirstTerm ){
  130465. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  130466. }
  130467. isFirstTerm = 0;
  130468. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  130469. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  130470. rc = FTS_CORRUPT_VTAB;
  130471. goto finish_scan;
  130472. }
  130473. if( nPrefix+nSuffix>nAlloc ){
  130474. char *zNew;
  130475. nAlloc = (nPrefix+nSuffix) * 2;
  130476. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  130477. if( !zNew ){
  130478. rc = SQLITE_NOMEM;
  130479. goto finish_scan;
  130480. }
  130481. zBuffer = zNew;
  130482. }
  130483. assert( zBuffer );
  130484. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  130485. nBuffer = nPrefix + nSuffix;
  130486. zCsr += nSuffix;
  130487. /* Compare the term we are searching for with the term just loaded from
  130488. ** the interior node. If the specified term is greater than or equal
  130489. ** to the term from the interior node, then all terms on the sub-tree
  130490. ** headed by node iChild are smaller than zTerm. No need to search
  130491. ** iChild.
  130492. **
  130493. ** If the interior node term is larger than the specified term, then
  130494. ** the tree headed by iChild may contain the specified term.
  130495. */
  130496. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  130497. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  130498. *piFirst = iChild;
  130499. piFirst = 0;
  130500. }
  130501. if( piLast && cmp<0 ){
  130502. *piLast = iChild;
  130503. piLast = 0;
  130504. }
  130505. iChild++;
  130506. };
  130507. if( piFirst ) *piFirst = iChild;
  130508. if( piLast ) *piLast = iChild;
  130509. finish_scan:
  130510. sqlite3_free(zBuffer);
  130511. return rc;
  130512. }
  130513. /*
  130514. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  130515. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  130516. ** contains a term. This function searches the sub-tree headed by the zNode
  130517. ** node for the range of leaf nodes that may contain the specified term
  130518. ** or terms for which the specified term is a prefix.
  130519. **
  130520. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  130521. ** left-most leaf node in the tree that may contain the specified term.
  130522. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  130523. ** right-most leaf node that may contain a term for which the specified
  130524. ** term is a prefix.
  130525. **
  130526. ** It is possible that the range of returned leaf nodes does not contain
  130527. ** the specified term or any terms for which it is a prefix. However, if the
  130528. ** segment does contain any such terms, they are stored within the identified
  130529. ** range. Because this function only inspects interior segment nodes (and
  130530. ** never loads leaf nodes into memory), it is not possible to be sure.
  130531. **
  130532. ** If an error occurs, an error code other than SQLITE_OK is returned.
  130533. */
  130534. static int fts3SelectLeaf(
  130535. Fts3Table *p, /* Virtual table handle */
  130536. const char *zTerm, /* Term to select leaves for */
  130537. int nTerm, /* Size of term zTerm in bytes */
  130538. const char *zNode, /* Buffer containing segment interior node */
  130539. int nNode, /* Size of buffer at zNode */
  130540. sqlite3_int64 *piLeaf, /* Selected leaf node */
  130541. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  130542. ){
  130543. int rc = SQLITE_OK; /* Return code */
  130544. int iHeight; /* Height of this node in tree */
  130545. assert( piLeaf || piLeaf2 );
  130546. fts3GetVarint32(zNode, &iHeight);
  130547. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  130548. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  130549. if( rc==SQLITE_OK && iHeight>1 ){
  130550. char *zBlob = 0; /* Blob read from %_segments table */
  130551. int nBlob = 0; /* Size of zBlob in bytes */
  130552. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  130553. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  130554. if( rc==SQLITE_OK ){
  130555. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  130556. }
  130557. sqlite3_free(zBlob);
  130558. piLeaf = 0;
  130559. zBlob = 0;
  130560. }
  130561. if( rc==SQLITE_OK ){
  130562. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  130563. }
  130564. if( rc==SQLITE_OK ){
  130565. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  130566. }
  130567. sqlite3_free(zBlob);
  130568. }
  130569. return rc;
  130570. }
  130571. /*
  130572. ** This function is used to create delta-encoded serialized lists of FTS3
  130573. ** varints. Each call to this function appends a single varint to a list.
  130574. */
  130575. static void fts3PutDeltaVarint(
  130576. char **pp, /* IN/OUT: Output pointer */
  130577. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  130578. sqlite3_int64 iVal /* Write this value to the list */
  130579. ){
  130580. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  130581. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  130582. *piPrev = iVal;
  130583. }
  130584. /*
  130585. ** When this function is called, *ppPoslist is assumed to point to the
  130586. ** start of a position-list. After it returns, *ppPoslist points to the
  130587. ** first byte after the position-list.
  130588. **
  130589. ** A position list is list of positions (delta encoded) and columns for
  130590. ** a single document record of a doclist. So, in other words, this
  130591. ** routine advances *ppPoslist so that it points to the next docid in
  130592. ** the doclist, or to the first byte past the end of the doclist.
  130593. **
  130594. ** If pp is not NULL, then the contents of the position list are copied
  130595. ** to *pp. *pp is set to point to the first byte past the last byte copied
  130596. ** before this function returns.
  130597. */
  130598. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  130599. char *pEnd = *ppPoslist;
  130600. char c = 0;
  130601. /* The end of a position list is marked by a zero encoded as an FTS3
  130602. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  130603. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  130604. ** of some other, multi-byte, value.
  130605. **
  130606. ** The following while-loop moves pEnd to point to the first byte that is not
  130607. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  130608. ** pEnd once more so that it points to the byte immediately following the
  130609. ** last byte in the position-list.
  130610. */
  130611. while( *pEnd | c ){
  130612. c = *pEnd++ & 0x80;
  130613. testcase( c!=0 && (*pEnd)==0 );
  130614. }
  130615. pEnd++; /* Advance past the POS_END terminator byte */
  130616. if( pp ){
  130617. int n = (int)(pEnd - *ppPoslist);
  130618. char *p = *pp;
  130619. memcpy(p, *ppPoslist, n);
  130620. p += n;
  130621. *pp = p;
  130622. }
  130623. *ppPoslist = pEnd;
  130624. }
  130625. /*
  130626. ** When this function is called, *ppPoslist is assumed to point to the
  130627. ** start of a column-list. After it returns, *ppPoslist points to the
  130628. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  130629. **
  130630. ** A column-list is list of delta-encoded positions for a single column
  130631. ** within a single document within a doclist.
  130632. **
  130633. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  130634. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  130635. ** the POS_COLUMN or POS_END that terminates the column-list.
  130636. **
  130637. ** If pp is not NULL, then the contents of the column-list are copied
  130638. ** to *pp. *pp is set to point to the first byte past the last byte copied
  130639. ** before this function returns. The POS_COLUMN or POS_END terminator
  130640. ** is not copied into *pp.
  130641. */
  130642. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  130643. char *pEnd = *ppPoslist;
  130644. char c = 0;
  130645. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  130646. ** not part of a multi-byte varint.
  130647. */
  130648. while( 0xFE & (*pEnd | c) ){
  130649. c = *pEnd++ & 0x80;
  130650. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  130651. }
  130652. if( pp ){
  130653. int n = (int)(pEnd - *ppPoslist);
  130654. char *p = *pp;
  130655. memcpy(p, *ppPoslist, n);
  130656. p += n;
  130657. *pp = p;
  130658. }
  130659. *ppPoslist = pEnd;
  130660. }
  130661. /*
  130662. ** Value used to signify the end of an position-list. This is safe because
  130663. ** it is not possible to have a document with 2^31 terms.
  130664. */
  130665. #define POSITION_LIST_END 0x7fffffff
  130666. /*
  130667. ** This function is used to help parse position-lists. When this function is
  130668. ** called, *pp may point to the start of the next varint in the position-list
  130669. ** being parsed, or it may point to 1 byte past the end of the position-list
  130670. ** (in which case **pp will be a terminator bytes POS_END (0) or
  130671. ** (1)).
  130672. **
  130673. ** If *pp points past the end of the current position-list, set *pi to
  130674. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  130675. ** increment the current value of *pi by the value read, and set *pp to
  130676. ** point to the next value before returning.
  130677. **
  130678. ** Before calling this routine *pi must be initialized to the value of
  130679. ** the previous position, or zero if we are reading the first position
  130680. ** in the position-list. Because positions are delta-encoded, the value
  130681. ** of the previous position is needed in order to compute the value of
  130682. ** the next position.
  130683. */
  130684. static void fts3ReadNextPos(
  130685. char **pp, /* IN/OUT: Pointer into position-list buffer */
  130686. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  130687. ){
  130688. if( (**pp)&0xFE ){
  130689. fts3GetDeltaVarint(pp, pi);
  130690. *pi -= 2;
  130691. }else{
  130692. *pi = POSITION_LIST_END;
  130693. }
  130694. }
  130695. /*
  130696. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  130697. ** the value of iCol encoded as a varint to *pp. This will start a new
  130698. ** column list.
  130699. **
  130700. ** Set *pp to point to the byte just after the last byte written before
  130701. ** returning (do not modify it if iCol==0). Return the total number of bytes
  130702. ** written (0 if iCol==0).
  130703. */
  130704. static int fts3PutColNumber(char **pp, int iCol){
  130705. int n = 0; /* Number of bytes written */
  130706. if( iCol ){
  130707. char *p = *pp; /* Output pointer */
  130708. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  130709. *p = 0x01;
  130710. *pp = &p[n];
  130711. }
  130712. return n;
  130713. }
  130714. /*
  130715. ** Compute the union of two position lists. The output written
  130716. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  130717. ** order and with any duplicates removed. All pointers are
  130718. ** updated appropriately. The caller is responsible for insuring
  130719. ** that there is enough space in *pp to hold the complete output.
  130720. */
  130721. static void fts3PoslistMerge(
  130722. char **pp, /* Output buffer */
  130723. char **pp1, /* Left input list */
  130724. char **pp2 /* Right input list */
  130725. ){
  130726. char *p = *pp;
  130727. char *p1 = *pp1;
  130728. char *p2 = *pp2;
  130729. while( *p1 || *p2 ){
  130730. int iCol1; /* The current column index in pp1 */
  130731. int iCol2; /* The current column index in pp2 */
  130732. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  130733. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  130734. else iCol1 = 0;
  130735. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  130736. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  130737. else iCol2 = 0;
  130738. if( iCol1==iCol2 ){
  130739. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  130740. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  130741. sqlite3_int64 iPrev = 0;
  130742. int n = fts3PutColNumber(&p, iCol1);
  130743. p1 += n;
  130744. p2 += n;
  130745. /* At this point, both p1 and p2 point to the start of column-lists
  130746. ** for the same column (the column with index iCol1 and iCol2).
  130747. ** A column-list is a list of non-negative delta-encoded varints, each
  130748. ** incremented by 2 before being stored. Each list is terminated by a
  130749. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  130750. ** and writes the results to buffer p. p is left pointing to the byte
  130751. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  130752. ** written to the output.
  130753. */
  130754. fts3GetDeltaVarint(&p1, &i1);
  130755. fts3GetDeltaVarint(&p2, &i2);
  130756. do {
  130757. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  130758. iPrev -= 2;
  130759. if( i1==i2 ){
  130760. fts3ReadNextPos(&p1, &i1);
  130761. fts3ReadNextPos(&p2, &i2);
  130762. }else if( i1<i2 ){
  130763. fts3ReadNextPos(&p1, &i1);
  130764. }else{
  130765. fts3ReadNextPos(&p2, &i2);
  130766. }
  130767. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  130768. }else if( iCol1<iCol2 ){
  130769. p1 += fts3PutColNumber(&p, iCol1);
  130770. fts3ColumnlistCopy(&p, &p1);
  130771. }else{
  130772. p2 += fts3PutColNumber(&p, iCol2);
  130773. fts3ColumnlistCopy(&p, &p2);
  130774. }
  130775. }
  130776. *p++ = POS_END;
  130777. *pp = p;
  130778. *pp1 = p1 + 1;
  130779. *pp2 = p2 + 1;
  130780. }
  130781. /*
  130782. ** This function is used to merge two position lists into one. When it is
  130783. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  130784. ** the part of a doclist that follows each document id. For example, if a row
  130785. ** contains:
  130786. **
  130787. ** 'a b c'|'x y z'|'a b b a'
  130788. **
  130789. ** Then the position list for this row for token 'b' would consist of:
  130790. **
  130791. ** 0x02 0x01 0x02 0x03 0x03 0x00
  130792. **
  130793. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  130794. ** byte following the 0x00 terminator of their respective position lists.
  130795. **
  130796. ** If isSaveLeft is 0, an entry is added to the output position list for
  130797. ** each position in *pp2 for which there exists one or more positions in
  130798. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  130799. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  130800. ** slots before it.
  130801. **
  130802. ** e.g. nToken==1 searches for adjacent positions.
  130803. */
  130804. static int fts3PoslistPhraseMerge(
  130805. char **pp, /* IN/OUT: Preallocated output buffer */
  130806. int nToken, /* Maximum difference in token positions */
  130807. int isSaveLeft, /* Save the left position */
  130808. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  130809. char **pp1, /* IN/OUT: Left input list */
  130810. char **pp2 /* IN/OUT: Right input list */
  130811. ){
  130812. char *p = *pp;
  130813. char *p1 = *pp1;
  130814. char *p2 = *pp2;
  130815. int iCol1 = 0;
  130816. int iCol2 = 0;
  130817. /* Never set both isSaveLeft and isExact for the same invocation. */
  130818. assert( isSaveLeft==0 || isExact==0 );
  130819. assert( p!=0 && *p1!=0 && *p2!=0 );
  130820. if( *p1==POS_COLUMN ){
  130821. p1++;
  130822. p1 += fts3GetVarint32(p1, &iCol1);
  130823. }
  130824. if( *p2==POS_COLUMN ){
  130825. p2++;
  130826. p2 += fts3GetVarint32(p2, &iCol2);
  130827. }
  130828. while( 1 ){
  130829. if( iCol1==iCol2 ){
  130830. char *pSave = p;
  130831. sqlite3_int64 iPrev = 0;
  130832. sqlite3_int64 iPos1 = 0;
  130833. sqlite3_int64 iPos2 = 0;
  130834. if( iCol1 ){
  130835. *p++ = POS_COLUMN;
  130836. p += sqlite3Fts3PutVarint(p, iCol1);
  130837. }
  130838. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  130839. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  130840. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  130841. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  130842. while( 1 ){
  130843. if( iPos2==iPos1+nToken
  130844. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  130845. ){
  130846. sqlite3_int64 iSave;
  130847. iSave = isSaveLeft ? iPos1 : iPos2;
  130848. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  130849. pSave = 0;
  130850. assert( p );
  130851. }
  130852. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  130853. if( (*p2&0xFE)==0 ) break;
  130854. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  130855. }else{
  130856. if( (*p1&0xFE)==0 ) break;
  130857. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  130858. }
  130859. }
  130860. if( pSave ){
  130861. assert( pp && p );
  130862. p = pSave;
  130863. }
  130864. fts3ColumnlistCopy(0, &p1);
  130865. fts3ColumnlistCopy(0, &p2);
  130866. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  130867. if( 0==*p1 || 0==*p2 ) break;
  130868. p1++;
  130869. p1 += fts3GetVarint32(p1, &iCol1);
  130870. p2++;
  130871. p2 += fts3GetVarint32(p2, &iCol2);
  130872. }
  130873. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  130874. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  130875. ** end of the position list, or the 0x01 that precedes the next
  130876. ** column-number in the position list.
  130877. */
  130878. else if( iCol1<iCol2 ){
  130879. fts3ColumnlistCopy(0, &p1);
  130880. if( 0==*p1 ) break;
  130881. p1++;
  130882. p1 += fts3GetVarint32(p1, &iCol1);
  130883. }else{
  130884. fts3ColumnlistCopy(0, &p2);
  130885. if( 0==*p2 ) break;
  130886. p2++;
  130887. p2 += fts3GetVarint32(p2, &iCol2);
  130888. }
  130889. }
  130890. fts3PoslistCopy(0, &p2);
  130891. fts3PoslistCopy(0, &p1);
  130892. *pp1 = p1;
  130893. *pp2 = p2;
  130894. if( *pp==p ){
  130895. return 0;
  130896. }
  130897. *p++ = 0x00;
  130898. *pp = p;
  130899. return 1;
  130900. }
  130901. /*
  130902. ** Merge two position-lists as required by the NEAR operator. The argument
  130903. ** position lists correspond to the left and right phrases of an expression
  130904. ** like:
  130905. **
  130906. ** "phrase 1" NEAR "phrase number 2"
  130907. **
  130908. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  130909. ** expression and *pp2 to the right. As usual, the indexes in the position
  130910. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  130911. ** in the example above).
  130912. **
  130913. ** The output position list - written to *pp - is a copy of *pp2 with those
  130914. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  130915. */
  130916. static int fts3PoslistNearMerge(
  130917. char **pp, /* Output buffer */
  130918. char *aTmp, /* Temporary buffer space */
  130919. int nRight, /* Maximum difference in token positions */
  130920. int nLeft, /* Maximum difference in token positions */
  130921. char **pp1, /* IN/OUT: Left input list */
  130922. char **pp2 /* IN/OUT: Right input list */
  130923. ){
  130924. char *p1 = *pp1;
  130925. char *p2 = *pp2;
  130926. char *pTmp1 = aTmp;
  130927. char *pTmp2;
  130928. char *aTmp2;
  130929. int res = 1;
  130930. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  130931. aTmp2 = pTmp2 = pTmp1;
  130932. *pp1 = p1;
  130933. *pp2 = p2;
  130934. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  130935. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  130936. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  130937. }else if( pTmp1!=aTmp ){
  130938. fts3PoslistCopy(pp, &aTmp);
  130939. }else if( pTmp2!=aTmp2 ){
  130940. fts3PoslistCopy(pp, &aTmp2);
  130941. }else{
  130942. res = 0;
  130943. }
  130944. return res;
  130945. }
  130946. /*
  130947. ** An instance of this function is used to merge together the (potentially
  130948. ** large number of) doclists for each term that matches a prefix query.
  130949. ** See function fts3TermSelectMerge() for details.
  130950. */
  130951. typedef struct TermSelect TermSelect;
  130952. struct TermSelect {
  130953. char *aaOutput[16]; /* Malloc'd output buffers */
  130954. int anOutput[16]; /* Size each output buffer in bytes */
  130955. };
  130956. /*
  130957. ** This function is used to read a single varint from a buffer. Parameter
  130958. ** pEnd points 1 byte past the end of the buffer. When this function is
  130959. ** called, if *pp points to pEnd or greater, then the end of the buffer
  130960. ** has been reached. In this case *pp is set to 0 and the function returns.
  130961. **
  130962. ** If *pp does not point to or past pEnd, then a single varint is read
  130963. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  130964. **
  130965. ** If bDescIdx is false, the value read is added to *pVal before returning.
  130966. ** If it is true, the value read is subtracted from *pVal before this
  130967. ** function returns.
  130968. */
  130969. static void fts3GetDeltaVarint3(
  130970. char **pp, /* IN/OUT: Point to read varint from */
  130971. char *pEnd, /* End of buffer */
  130972. int bDescIdx, /* True if docids are descending */
  130973. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  130974. ){
  130975. if( *pp>=pEnd ){
  130976. *pp = 0;
  130977. }else{
  130978. sqlite3_int64 iVal;
  130979. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  130980. if( bDescIdx ){
  130981. *pVal -= iVal;
  130982. }else{
  130983. *pVal += iVal;
  130984. }
  130985. }
  130986. }
  130987. /*
  130988. ** This function is used to write a single varint to a buffer. The varint
  130989. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  130990. ** end of the value written.
  130991. **
  130992. ** If *pbFirst is zero when this function is called, the value written to
  130993. ** the buffer is that of parameter iVal.
  130994. **
  130995. ** If *pbFirst is non-zero when this function is called, then the value
  130996. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  130997. ** (if bDescIdx is non-zero).
  130998. **
  130999. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  131000. ** to the value of parameter iVal.
  131001. */
  131002. static void fts3PutDeltaVarint3(
  131003. char **pp, /* IN/OUT: Output pointer */
  131004. int bDescIdx, /* True for descending docids */
  131005. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  131006. int *pbFirst, /* IN/OUT: True after first int written */
  131007. sqlite3_int64 iVal /* Write this value to the list */
  131008. ){
  131009. sqlite3_int64 iWrite;
  131010. if( bDescIdx==0 || *pbFirst==0 ){
  131011. iWrite = iVal - *piPrev;
  131012. }else{
  131013. iWrite = *piPrev - iVal;
  131014. }
  131015. assert( *pbFirst || *piPrev==0 );
  131016. assert( *pbFirst==0 || iWrite>0 );
  131017. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  131018. *piPrev = iVal;
  131019. *pbFirst = 1;
  131020. }
  131021. /*
  131022. ** This macro is used by various functions that merge doclists. The two
  131023. ** arguments are 64-bit docid values. If the value of the stack variable
  131024. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  131025. ** Otherwise, (i2-i1).
  131026. **
  131027. ** Using this makes it easier to write code that can merge doclists that are
  131028. ** sorted in either ascending or descending order.
  131029. */
  131030. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  131031. /*
  131032. ** This function does an "OR" merge of two doclists (output contains all
  131033. ** positions contained in either argument doclist). If the docids in the
  131034. ** input doclists are sorted in ascending order, parameter bDescDoclist
  131035. ** should be false. If they are sorted in ascending order, it should be
  131036. ** passed a non-zero value.
  131037. **
  131038. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  131039. ** containing the output doclist and SQLITE_OK is returned. In this case
  131040. ** *pnOut is set to the number of bytes in the output doclist.
  131041. **
  131042. ** If an error occurs, an SQLite error code is returned. The output values
  131043. ** are undefined in this case.
  131044. */
  131045. static int fts3DoclistOrMerge(
  131046. int bDescDoclist, /* True if arguments are desc */
  131047. char *a1, int n1, /* First doclist */
  131048. char *a2, int n2, /* Second doclist */
  131049. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  131050. ){
  131051. sqlite3_int64 i1 = 0;
  131052. sqlite3_int64 i2 = 0;
  131053. sqlite3_int64 iPrev = 0;
  131054. char *pEnd1 = &a1[n1];
  131055. char *pEnd2 = &a2[n2];
  131056. char *p1 = a1;
  131057. char *p2 = a2;
  131058. char *p;
  131059. char *aOut;
  131060. int bFirstOut = 0;
  131061. *paOut = 0;
  131062. *pnOut = 0;
  131063. /* Allocate space for the output. Both the input and output doclists
  131064. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  131065. ** then the first docid in each list is simply encoded as a varint. For
  131066. ** each subsequent docid, the varint stored is the difference between the
  131067. ** current and previous docid (a positive number - since the list is in
  131068. ** ascending order).
  131069. **
  131070. ** The first docid written to the output is therefore encoded using the
  131071. ** same number of bytes as it is in whichever of the input lists it is
  131072. ** read from. And each subsequent docid read from the same input list
  131073. ** consumes either the same or less bytes as it did in the input (since
  131074. ** the difference between it and the previous value in the output must
  131075. ** be a positive value less than or equal to the delta value read from
  131076. ** the input list). The same argument applies to all but the first docid
  131077. ** read from the 'other' list. And to the contents of all position lists
  131078. ** that will be copied and merged from the input to the output.
  131079. **
  131080. ** However, if the first docid copied to the output is a negative number,
  131081. ** then the encoding of the first docid from the 'other' input list may
  131082. ** be larger in the output than it was in the input (since the delta value
  131083. ** may be a larger positive integer than the actual docid).
  131084. **
  131085. ** The space required to store the output is therefore the sum of the
  131086. ** sizes of the two inputs, plus enough space for exactly one of the input
  131087. ** docids to grow.
  131088. **
  131089. ** A symetric argument may be made if the doclists are in descending
  131090. ** order.
  131091. */
  131092. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  131093. if( !aOut ) return SQLITE_NOMEM;
  131094. p = aOut;
  131095. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  131096. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  131097. while( p1 || p2 ){
  131098. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  131099. if( p2 && p1 && iDiff==0 ){
  131100. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  131101. fts3PoslistMerge(&p, &p1, &p2);
  131102. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  131103. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  131104. }else if( !p2 || (p1 && iDiff<0) ){
  131105. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  131106. fts3PoslistCopy(&p, &p1);
  131107. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  131108. }else{
  131109. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  131110. fts3PoslistCopy(&p, &p2);
  131111. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  131112. }
  131113. }
  131114. *paOut = aOut;
  131115. *pnOut = (int)(p-aOut);
  131116. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  131117. return SQLITE_OK;
  131118. }
  131119. /*
  131120. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  131121. ** the output contains a copy of each position from the right-hand input
  131122. ** doclist for which there is a position in the left-hand input doclist
  131123. ** exactly nDist tokens before it.
  131124. **
  131125. ** If the docids in the input doclists are sorted in ascending order,
  131126. ** parameter bDescDoclist should be false. If they are sorted in ascending
  131127. ** order, it should be passed a non-zero value.
  131128. **
  131129. ** The right-hand input doclist is overwritten by this function.
  131130. */
  131131. static int fts3DoclistPhraseMerge(
  131132. int bDescDoclist, /* True if arguments are desc */
  131133. int nDist, /* Distance from left to right (1=adjacent) */
  131134. char *aLeft, int nLeft, /* Left doclist */
  131135. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  131136. ){
  131137. sqlite3_int64 i1 = 0;
  131138. sqlite3_int64 i2 = 0;
  131139. sqlite3_int64 iPrev = 0;
  131140. char *aRight = *paRight;
  131141. char *pEnd1 = &aLeft[nLeft];
  131142. char *pEnd2 = &aRight[*pnRight];
  131143. char *p1 = aLeft;
  131144. char *p2 = aRight;
  131145. char *p;
  131146. int bFirstOut = 0;
  131147. char *aOut;
  131148. assert( nDist>0 );
  131149. if( bDescDoclist ){
  131150. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  131151. if( aOut==0 ) return SQLITE_NOMEM;
  131152. }else{
  131153. aOut = aRight;
  131154. }
  131155. p = aOut;
  131156. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  131157. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  131158. while( p1 && p2 ){
  131159. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  131160. if( iDiff==0 ){
  131161. char *pSave = p;
  131162. sqlite3_int64 iPrevSave = iPrev;
  131163. int bFirstOutSave = bFirstOut;
  131164. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  131165. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  131166. p = pSave;
  131167. iPrev = iPrevSave;
  131168. bFirstOut = bFirstOutSave;
  131169. }
  131170. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  131171. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  131172. }else if( iDiff<0 ){
  131173. fts3PoslistCopy(0, &p1);
  131174. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  131175. }else{
  131176. fts3PoslistCopy(0, &p2);
  131177. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  131178. }
  131179. }
  131180. *pnRight = (int)(p - aOut);
  131181. if( bDescDoclist ){
  131182. sqlite3_free(aRight);
  131183. *paRight = aOut;
  131184. }
  131185. return SQLITE_OK;
  131186. }
  131187. /*
  131188. ** Argument pList points to a position list nList bytes in size. This
  131189. ** function checks to see if the position list contains any entries for
  131190. ** a token in position 0 (of any column). If so, it writes argument iDelta
  131191. ** to the output buffer pOut, followed by a position list consisting only
  131192. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  131193. ** The value returned is the number of bytes written to pOut (if any).
  131194. */
  131195. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  131196. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  131197. char *pList, /* Position list (no 0x00 term) */
  131198. int nList, /* Size of pList in bytes */
  131199. char *pOut /* Write output here */
  131200. ){
  131201. int nOut = 0;
  131202. int bWritten = 0; /* True once iDelta has been written */
  131203. char *p = pList;
  131204. char *pEnd = &pList[nList];
  131205. if( *p!=0x01 ){
  131206. if( *p==0x02 ){
  131207. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  131208. pOut[nOut++] = 0x02;
  131209. bWritten = 1;
  131210. }
  131211. fts3ColumnlistCopy(0, &p);
  131212. }
  131213. while( p<pEnd && *p==0x01 ){
  131214. sqlite3_int64 iCol;
  131215. p++;
  131216. p += sqlite3Fts3GetVarint(p, &iCol);
  131217. if( *p==0x02 ){
  131218. if( bWritten==0 ){
  131219. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  131220. bWritten = 1;
  131221. }
  131222. pOut[nOut++] = 0x01;
  131223. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  131224. pOut[nOut++] = 0x02;
  131225. }
  131226. fts3ColumnlistCopy(0, &p);
  131227. }
  131228. if( bWritten ){
  131229. pOut[nOut++] = 0x00;
  131230. }
  131231. return nOut;
  131232. }
  131233. /*
  131234. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  131235. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  131236. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  131237. **
  131238. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  131239. ** the responsibility of the caller to free any doclists left in the
  131240. ** TermSelect.aaOutput[] array.
  131241. */
  131242. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  131243. char *aOut = 0;
  131244. int nOut = 0;
  131245. int i;
  131246. /* Loop through the doclists in the aaOutput[] array. Merge them all
  131247. ** into a single doclist.
  131248. */
  131249. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  131250. if( pTS->aaOutput[i] ){
  131251. if( !aOut ){
  131252. aOut = pTS->aaOutput[i];
  131253. nOut = pTS->anOutput[i];
  131254. pTS->aaOutput[i] = 0;
  131255. }else{
  131256. int nNew;
  131257. char *aNew;
  131258. int rc = fts3DoclistOrMerge(p->bDescIdx,
  131259. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  131260. );
  131261. if( rc!=SQLITE_OK ){
  131262. sqlite3_free(aOut);
  131263. return rc;
  131264. }
  131265. sqlite3_free(pTS->aaOutput[i]);
  131266. sqlite3_free(aOut);
  131267. pTS->aaOutput[i] = 0;
  131268. aOut = aNew;
  131269. nOut = nNew;
  131270. }
  131271. }
  131272. }
  131273. pTS->aaOutput[0] = aOut;
  131274. pTS->anOutput[0] = nOut;
  131275. return SQLITE_OK;
  131276. }
  131277. /*
  131278. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  131279. ** as the first argument. The merge is an "OR" merge (see function
  131280. ** fts3DoclistOrMerge() for details).
  131281. **
  131282. ** This function is called with the doclist for each term that matches
  131283. ** a queried prefix. It merges all these doclists into one, the doclist
  131284. ** for the specified prefix. Since there can be a very large number of
  131285. ** doclists to merge, the merging is done pair-wise using the TermSelect
  131286. ** object.
  131287. **
  131288. ** This function returns SQLITE_OK if the merge is successful, or an
  131289. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  131290. */
  131291. static int fts3TermSelectMerge(
  131292. Fts3Table *p, /* FTS table handle */
  131293. TermSelect *pTS, /* TermSelect object to merge into */
  131294. char *aDoclist, /* Pointer to doclist */
  131295. int nDoclist /* Size of aDoclist in bytes */
  131296. ){
  131297. if( pTS->aaOutput[0]==0 ){
  131298. /* If this is the first term selected, copy the doclist to the output
  131299. ** buffer using memcpy().
  131300. **
  131301. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  131302. ** allocation. This is so as to ensure that the buffer is big enough
  131303. ** to hold the current doclist AND'd with any other doclist. If the
  131304. ** doclists are stored in order=ASC order, this padding would not be
  131305. ** required (since the size of [doclistA AND doclistB] is always less
  131306. ** than or equal to the size of [doclistA] in that case). But this is
  131307. ** not true for order=DESC. For example, a doclist containing (1, -1)
  131308. ** may be smaller than (-1), as in the first example the -1 may be stored
  131309. ** as a single-byte delta, whereas in the second it must be stored as a
  131310. ** FTS3_VARINT_MAX byte varint.
  131311. **
  131312. ** Similar padding is added in the fts3DoclistOrMerge() function.
  131313. */
  131314. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  131315. pTS->anOutput[0] = nDoclist;
  131316. if( pTS->aaOutput[0] ){
  131317. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  131318. }else{
  131319. return SQLITE_NOMEM;
  131320. }
  131321. }else{
  131322. char *aMerge = aDoclist;
  131323. int nMerge = nDoclist;
  131324. int iOut;
  131325. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  131326. if( pTS->aaOutput[iOut]==0 ){
  131327. assert( iOut>0 );
  131328. pTS->aaOutput[iOut] = aMerge;
  131329. pTS->anOutput[iOut] = nMerge;
  131330. break;
  131331. }else{
  131332. char *aNew;
  131333. int nNew;
  131334. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  131335. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  131336. );
  131337. if( rc!=SQLITE_OK ){
  131338. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  131339. return rc;
  131340. }
  131341. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  131342. sqlite3_free(pTS->aaOutput[iOut]);
  131343. pTS->aaOutput[iOut] = 0;
  131344. aMerge = aNew;
  131345. nMerge = nNew;
  131346. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  131347. pTS->aaOutput[iOut] = aMerge;
  131348. pTS->anOutput[iOut] = nMerge;
  131349. }
  131350. }
  131351. }
  131352. }
  131353. return SQLITE_OK;
  131354. }
  131355. /*
  131356. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  131357. */
  131358. static int fts3SegReaderCursorAppend(
  131359. Fts3MultiSegReader *pCsr,
  131360. Fts3SegReader *pNew
  131361. ){
  131362. if( (pCsr->nSegment%16)==0 ){
  131363. Fts3SegReader **apNew;
  131364. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  131365. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  131366. if( !apNew ){
  131367. sqlite3Fts3SegReaderFree(pNew);
  131368. return SQLITE_NOMEM;
  131369. }
  131370. pCsr->apSegment = apNew;
  131371. }
  131372. pCsr->apSegment[pCsr->nSegment++] = pNew;
  131373. return SQLITE_OK;
  131374. }
  131375. /*
  131376. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  131377. ** 8th argument.
  131378. **
  131379. ** This function returns SQLITE_OK if successful, or an SQLite error code
  131380. ** otherwise.
  131381. */
  131382. static int fts3SegReaderCursor(
  131383. Fts3Table *p, /* FTS3 table handle */
  131384. int iLangid, /* Language id */
  131385. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  131386. int iLevel, /* Level of segments to scan */
  131387. const char *zTerm, /* Term to query for */
  131388. int nTerm, /* Size of zTerm in bytes */
  131389. int isPrefix, /* True for a prefix search */
  131390. int isScan, /* True to scan from zTerm to EOF */
  131391. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  131392. ){
  131393. int rc = SQLITE_OK; /* Error code */
  131394. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  131395. int rc2; /* Result of sqlite3_reset() */
  131396. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  131397. ** for the pending-terms. If this is a scan, then this call must be being
  131398. ** made by an fts4aux module, not an FTS table. In this case calling
  131399. ** Fts3SegReaderPending might segfault, as the data structures used by
  131400. ** fts4aux are not completely populated. So it's easiest to filter these
  131401. ** calls out here. */
  131402. if( iLevel<0 && p->aIndex ){
  131403. Fts3SegReader *pSeg = 0;
  131404. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  131405. if( rc==SQLITE_OK && pSeg ){
  131406. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  131407. }
  131408. }
  131409. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  131410. if( rc==SQLITE_OK ){
  131411. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  131412. }
  131413. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  131414. Fts3SegReader *pSeg = 0;
  131415. /* Read the values returned by the SELECT into local variables. */
  131416. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  131417. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  131418. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  131419. int nRoot = sqlite3_column_bytes(pStmt, 4);
  131420. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  131421. /* If zTerm is not NULL, and this segment is not stored entirely on its
  131422. ** root node, the range of leaves scanned can be reduced. Do this. */
  131423. if( iStartBlock && zTerm ){
  131424. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  131425. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  131426. if( rc!=SQLITE_OK ) goto finished;
  131427. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  131428. }
  131429. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  131430. (isPrefix==0 && isScan==0),
  131431. iStartBlock, iLeavesEndBlock,
  131432. iEndBlock, zRoot, nRoot, &pSeg
  131433. );
  131434. if( rc!=SQLITE_OK ) goto finished;
  131435. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  131436. }
  131437. }
  131438. finished:
  131439. rc2 = sqlite3_reset(pStmt);
  131440. if( rc==SQLITE_DONE ) rc = rc2;
  131441. return rc;
  131442. }
  131443. /*
  131444. ** Set up a cursor object for iterating through a full-text index or a
  131445. ** single level therein.
  131446. */
  131447. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  131448. Fts3Table *p, /* FTS3 table handle */
  131449. int iLangid, /* Language-id to search */
  131450. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  131451. int iLevel, /* Level of segments to scan */
  131452. const char *zTerm, /* Term to query for */
  131453. int nTerm, /* Size of zTerm in bytes */
  131454. int isPrefix, /* True for a prefix search */
  131455. int isScan, /* True to scan from zTerm to EOF */
  131456. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  131457. ){
  131458. assert( iIndex>=0 && iIndex<p->nIndex );
  131459. assert( iLevel==FTS3_SEGCURSOR_ALL
  131460. || iLevel==FTS3_SEGCURSOR_PENDING
  131461. || iLevel>=0
  131462. );
  131463. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  131464. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  131465. assert( isPrefix==0 || isScan==0 );
  131466. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  131467. return fts3SegReaderCursor(
  131468. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  131469. );
  131470. }
  131471. /*
  131472. ** In addition to its current configuration, have the Fts3MultiSegReader
  131473. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  131474. **
  131475. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  131476. */
  131477. static int fts3SegReaderCursorAddZero(
  131478. Fts3Table *p, /* FTS virtual table handle */
  131479. int iLangid,
  131480. const char *zTerm, /* Term to scan doclist of */
  131481. int nTerm, /* Number of bytes in zTerm */
  131482. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  131483. ){
  131484. return fts3SegReaderCursor(p,
  131485. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  131486. );
  131487. }
  131488. /*
  131489. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  131490. ** if isPrefix is true, to scan the doclist for all terms for which
  131491. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  131492. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  131493. ** an SQLite error code.
  131494. **
  131495. ** It is the responsibility of the caller to free this object by eventually
  131496. ** passing it to fts3SegReaderCursorFree()
  131497. **
  131498. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  131499. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  131500. */
  131501. static int fts3TermSegReaderCursor(
  131502. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  131503. const char *zTerm, /* Term to query for */
  131504. int nTerm, /* Size of zTerm in bytes */
  131505. int isPrefix, /* True for a prefix search */
  131506. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  131507. ){
  131508. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  131509. int rc = SQLITE_NOMEM; /* Return code */
  131510. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  131511. if( pSegcsr ){
  131512. int i;
  131513. int bFound = 0; /* True once an index has been found */
  131514. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  131515. if( isPrefix ){
  131516. for(i=1; bFound==0 && i<p->nIndex; i++){
  131517. if( p->aIndex[i].nPrefix==nTerm ){
  131518. bFound = 1;
  131519. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  131520. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  131521. );
  131522. pSegcsr->bLookup = 1;
  131523. }
  131524. }
  131525. for(i=1; bFound==0 && i<p->nIndex; i++){
  131526. if( p->aIndex[i].nPrefix==nTerm+1 ){
  131527. bFound = 1;
  131528. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  131529. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  131530. );
  131531. if( rc==SQLITE_OK ){
  131532. rc = fts3SegReaderCursorAddZero(
  131533. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  131534. );
  131535. }
  131536. }
  131537. }
  131538. }
  131539. if( bFound==0 ){
  131540. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  131541. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  131542. );
  131543. pSegcsr->bLookup = !isPrefix;
  131544. }
  131545. }
  131546. *ppSegcsr = pSegcsr;
  131547. return rc;
  131548. }
  131549. /*
  131550. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  131551. */
  131552. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  131553. sqlite3Fts3SegReaderFinish(pSegcsr);
  131554. sqlite3_free(pSegcsr);
  131555. }
  131556. /*
  131557. ** This function retrieves the doclist for the specified term (or term
  131558. ** prefix) from the database.
  131559. */
  131560. static int fts3TermSelect(
  131561. Fts3Table *p, /* Virtual table handle */
  131562. Fts3PhraseToken *pTok, /* Token to query for */
  131563. int iColumn, /* Column to query (or -ve for all columns) */
  131564. int *pnOut, /* OUT: Size of buffer at *ppOut */
  131565. char **ppOut /* OUT: Malloced result buffer */
  131566. ){
  131567. int rc; /* Return code */
  131568. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  131569. TermSelect tsc; /* Object for pair-wise doclist merging */
  131570. Fts3SegFilter filter; /* Segment term filter configuration */
  131571. pSegcsr = pTok->pSegcsr;
  131572. memset(&tsc, 0, sizeof(TermSelect));
  131573. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  131574. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  131575. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  131576. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  131577. filter.iCol = iColumn;
  131578. filter.zTerm = pTok->z;
  131579. filter.nTerm = pTok->n;
  131580. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  131581. while( SQLITE_OK==rc
  131582. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  131583. ){
  131584. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  131585. }
  131586. if( rc==SQLITE_OK ){
  131587. rc = fts3TermSelectFinishMerge(p, &tsc);
  131588. }
  131589. if( rc==SQLITE_OK ){
  131590. *ppOut = tsc.aaOutput[0];
  131591. *pnOut = tsc.anOutput[0];
  131592. }else{
  131593. int i;
  131594. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  131595. sqlite3_free(tsc.aaOutput[i]);
  131596. }
  131597. }
  131598. fts3SegReaderCursorFree(pSegcsr);
  131599. pTok->pSegcsr = 0;
  131600. return rc;
  131601. }
  131602. /*
  131603. ** This function counts the total number of docids in the doclist stored
  131604. ** in buffer aList[], size nList bytes.
  131605. **
  131606. ** If the isPoslist argument is true, then it is assumed that the doclist
  131607. ** contains a position-list following each docid. Otherwise, it is assumed
  131608. ** that the doclist is simply a list of docids stored as delta encoded
  131609. ** varints.
  131610. */
  131611. static int fts3DoclistCountDocids(char *aList, int nList){
  131612. int nDoc = 0; /* Return value */
  131613. if( aList ){
  131614. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  131615. char *p = aList; /* Cursor */
  131616. while( p<aEnd ){
  131617. nDoc++;
  131618. while( (*p++)&0x80 ); /* Skip docid varint */
  131619. fts3PoslistCopy(0, &p); /* Skip over position list */
  131620. }
  131621. }
  131622. return nDoc;
  131623. }
  131624. /*
  131625. ** Advance the cursor to the next row in the %_content table that
  131626. ** matches the search criteria. For a MATCH search, this will be
  131627. ** the next row that matches. For a full-table scan, this will be
  131628. ** simply the next row in the %_content table. For a docid lookup,
  131629. ** this routine simply sets the EOF flag.
  131630. **
  131631. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  131632. ** even if we reach end-of-file. The fts3EofMethod() will be called
  131633. ** subsequently to determine whether or not an EOF was hit.
  131634. */
  131635. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  131636. int rc;
  131637. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  131638. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  131639. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  131640. pCsr->isEof = 1;
  131641. rc = sqlite3_reset(pCsr->pStmt);
  131642. }else{
  131643. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  131644. rc = SQLITE_OK;
  131645. }
  131646. }else{
  131647. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  131648. }
  131649. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  131650. return rc;
  131651. }
  131652. /*
  131653. ** The following are copied from sqliteInt.h.
  131654. **
  131655. ** Constants for the largest and smallest possible 64-bit signed integers.
  131656. ** These macros are designed to work correctly on both 32-bit and 64-bit
  131657. ** compilers.
  131658. */
  131659. #ifndef SQLITE_AMALGAMATION
  131660. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  131661. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  131662. #endif
  131663. /*
  131664. ** If the numeric type of argument pVal is "integer", then return it
  131665. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  131666. ** the second parameter, iDefault.
  131667. */
  131668. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  131669. if( pVal ){
  131670. int eType = sqlite3_value_numeric_type(pVal);
  131671. if( eType==SQLITE_INTEGER ){
  131672. return sqlite3_value_int64(pVal);
  131673. }
  131674. }
  131675. return iDefault;
  131676. }
  131677. /*
  131678. ** This is the xFilter interface for the virtual table. See
  131679. ** the virtual table xFilter method documentation for additional
  131680. ** information.
  131681. **
  131682. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  131683. ** the %_content table.
  131684. **
  131685. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  131686. ** in the %_content table.
  131687. **
  131688. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  131689. ** column on the left-hand side of the MATCH operator is column
  131690. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  131691. ** side of the MATCH operator.
  131692. */
  131693. static int fts3FilterMethod(
  131694. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  131695. int idxNum, /* Strategy index */
  131696. const char *idxStr, /* Unused */
  131697. int nVal, /* Number of elements in apVal */
  131698. sqlite3_value **apVal /* Arguments for the indexing scheme */
  131699. ){
  131700. int rc = SQLITE_OK;
  131701. char *zSql; /* SQL statement used to access %_content */
  131702. int eSearch;
  131703. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  131704. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  131705. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  131706. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  131707. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  131708. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  131709. int iIdx;
  131710. UNUSED_PARAMETER(idxStr);
  131711. UNUSED_PARAMETER(nVal);
  131712. eSearch = (idxNum & 0x0000FFFF);
  131713. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  131714. assert( p->pSegments==0 );
  131715. /* Collect arguments into local variables */
  131716. iIdx = 0;
  131717. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  131718. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  131719. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  131720. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  131721. assert( iIdx==nVal );
  131722. /* In case the cursor has been used before, clear it now. */
  131723. sqlite3_finalize(pCsr->pStmt);
  131724. sqlite3_free(pCsr->aDoclist);
  131725. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  131726. sqlite3Fts3ExprFree(pCsr->pExpr);
  131727. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  131728. /* Set the lower and upper bounds on docids to return */
  131729. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  131730. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  131731. if( idxStr ){
  131732. pCsr->bDesc = (idxStr[0]=='D');
  131733. }else{
  131734. pCsr->bDesc = p->bDescIdx;
  131735. }
  131736. pCsr->eSearch = (i16)eSearch;
  131737. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  131738. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  131739. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  131740. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  131741. return SQLITE_NOMEM;
  131742. }
  131743. pCsr->iLangid = 0;
  131744. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  131745. assert( p->base.zErrMsg==0 );
  131746. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  131747. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  131748. &p->base.zErrMsg
  131749. );
  131750. if( rc!=SQLITE_OK ){
  131751. return rc;
  131752. }
  131753. rc = fts3EvalStart(pCsr);
  131754. sqlite3Fts3SegmentsClose(p);
  131755. if( rc!=SQLITE_OK ) return rc;
  131756. pCsr->pNextId = pCsr->aDoclist;
  131757. pCsr->iPrevId = 0;
  131758. }
  131759. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  131760. ** statement loops through all rows of the %_content table. For a
  131761. ** full-text query or docid lookup, the statement retrieves a single
  131762. ** row by docid.
  131763. */
  131764. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  131765. if( pDocidGe || pDocidLe ){
  131766. zSql = sqlite3_mprintf(
  131767. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  131768. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  131769. (pCsr->bDesc ? "DESC" : "ASC")
  131770. );
  131771. }else{
  131772. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  131773. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  131774. );
  131775. }
  131776. if( zSql ){
  131777. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  131778. sqlite3_free(zSql);
  131779. }else{
  131780. rc = SQLITE_NOMEM;
  131781. }
  131782. }else if( eSearch==FTS3_DOCID_SEARCH ){
  131783. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  131784. if( rc==SQLITE_OK ){
  131785. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  131786. }
  131787. }
  131788. if( rc!=SQLITE_OK ) return rc;
  131789. return fts3NextMethod(pCursor);
  131790. }
  131791. /*
  131792. ** This is the xEof method of the virtual table. SQLite calls this
  131793. ** routine to find out if it has reached the end of a result set.
  131794. */
  131795. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  131796. return ((Fts3Cursor *)pCursor)->isEof;
  131797. }
  131798. /*
  131799. ** This is the xRowid method. The SQLite core calls this routine to
  131800. ** retrieve the rowid for the current row of the result set. fts3
  131801. ** exposes %_content.docid as the rowid for the virtual table. The
  131802. ** rowid should be written to *pRowid.
  131803. */
  131804. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  131805. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  131806. *pRowid = pCsr->iPrevId;
  131807. return SQLITE_OK;
  131808. }
  131809. /*
  131810. ** This is the xColumn method, called by SQLite to request a value from
  131811. ** the row that the supplied cursor currently points to.
  131812. **
  131813. ** If:
  131814. **
  131815. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  131816. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  131817. ** (iCol == p->nColumn+1) -> Docid column
  131818. ** (iCol == p->nColumn+2) -> Langid column
  131819. */
  131820. static int fts3ColumnMethod(
  131821. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  131822. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  131823. int iCol /* Index of column to read value from */
  131824. ){
  131825. int rc = SQLITE_OK; /* Return Code */
  131826. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  131827. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  131828. /* The column value supplied by SQLite must be in range. */
  131829. assert( iCol>=0 && iCol<=p->nColumn+2 );
  131830. if( iCol==p->nColumn+1 ){
  131831. /* This call is a request for the "docid" column. Since "docid" is an
  131832. ** alias for "rowid", use the xRowid() method to obtain the value.
  131833. */
  131834. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  131835. }else if( iCol==p->nColumn ){
  131836. /* The extra column whose name is the same as the table.
  131837. ** Return a blob which is a pointer to the cursor. */
  131838. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  131839. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  131840. sqlite3_result_int64(pCtx, pCsr->iLangid);
  131841. }else{
  131842. /* The requested column is either a user column (one that contains
  131843. ** indexed data), or the language-id column. */
  131844. rc = fts3CursorSeek(0, pCsr);
  131845. if( rc==SQLITE_OK ){
  131846. if( iCol==p->nColumn+2 ){
  131847. int iLangid = 0;
  131848. if( p->zLanguageid ){
  131849. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  131850. }
  131851. sqlite3_result_int(pCtx, iLangid);
  131852. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  131853. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  131854. }
  131855. }
  131856. }
  131857. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  131858. return rc;
  131859. }
  131860. /*
  131861. ** This function is the implementation of the xUpdate callback used by
  131862. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  131863. ** inserted, updated or deleted.
  131864. */
  131865. static int fts3UpdateMethod(
  131866. sqlite3_vtab *pVtab, /* Virtual table handle */
  131867. int nArg, /* Size of argument array */
  131868. sqlite3_value **apVal, /* Array of arguments */
  131869. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  131870. ){
  131871. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  131872. }
  131873. /*
  131874. ** Implementation of xSync() method. Flush the contents of the pending-terms
  131875. ** hash-table to the database.
  131876. */
  131877. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  131878. /* Following an incremental-merge operation, assuming that the input
  131879. ** segments are not completely consumed (the usual case), they are updated
  131880. ** in place to remove the entries that have already been merged. This
  131881. ** involves updating the leaf block that contains the smallest unmerged
  131882. ** entry and each block (if any) between the leaf and the root node. So
  131883. ** if the height of the input segment b-trees is N, and input segments
  131884. ** are merged eight at a time, updating the input segments at the end
  131885. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  131886. ** small - often between 0 and 2. So the overhead of the incremental
  131887. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  131888. ** dwarfing the actual productive work accomplished, the incremental merge
  131889. ** is only attempted if it will write at least 64 leaf blocks. Hence
  131890. ** nMinMerge.
  131891. **
  131892. ** Of course, updating the input segments also involves deleting a bunch
  131893. ** of blocks from the segments table. But this is not considered overhead
  131894. ** as it would also be required by a crisis-merge that used the same input
  131895. ** segments.
  131896. */
  131897. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  131898. Fts3Table *p = (Fts3Table*)pVtab;
  131899. int rc = sqlite3Fts3PendingTermsFlush(p);
  131900. if( rc==SQLITE_OK
  131901. && p->nLeafAdd>(nMinMerge/16)
  131902. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  131903. ){
  131904. int mxLevel = 0; /* Maximum relative level value in db */
  131905. int A; /* Incr-merge parameter A */
  131906. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  131907. assert( rc==SQLITE_OK || mxLevel==0 );
  131908. A = p->nLeafAdd * mxLevel;
  131909. A += (A/2);
  131910. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  131911. }
  131912. sqlite3Fts3SegmentsClose(p);
  131913. return rc;
  131914. }
  131915. /*
  131916. ** If it is currently unknown whether or not the FTS table has an %_stat
  131917. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  131918. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  131919. ** if an error occurs.
  131920. */
  131921. static int fts3SetHasStat(Fts3Table *p){
  131922. int rc = SQLITE_OK;
  131923. if( p->bHasStat==2 ){
  131924. const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
  131925. char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
  131926. if( zSql ){
  131927. sqlite3_stmt *pStmt = 0;
  131928. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  131929. if( rc==SQLITE_OK ){
  131930. int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
  131931. rc = sqlite3_finalize(pStmt);
  131932. if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
  131933. }
  131934. sqlite3_free(zSql);
  131935. }else{
  131936. rc = SQLITE_NOMEM;
  131937. }
  131938. }
  131939. return rc;
  131940. }
  131941. /*
  131942. ** Implementation of xBegin() method.
  131943. */
  131944. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  131945. Fts3Table *p = (Fts3Table*)pVtab;
  131946. UNUSED_PARAMETER(pVtab);
  131947. assert( p->pSegments==0 );
  131948. assert( p->nPendingData==0 );
  131949. assert( p->inTransaction!=1 );
  131950. TESTONLY( p->inTransaction = 1 );
  131951. TESTONLY( p->mxSavepoint = -1; );
  131952. p->nLeafAdd = 0;
  131953. return fts3SetHasStat(p);
  131954. }
  131955. /*
  131956. ** Implementation of xCommit() method. This is a no-op. The contents of
  131957. ** the pending-terms hash-table have already been flushed into the database
  131958. ** by fts3SyncMethod().
  131959. */
  131960. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  131961. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  131962. UNUSED_PARAMETER(pVtab);
  131963. assert( p->nPendingData==0 );
  131964. assert( p->inTransaction!=0 );
  131965. assert( p->pSegments==0 );
  131966. TESTONLY( p->inTransaction = 0 );
  131967. TESTONLY( p->mxSavepoint = -1; );
  131968. return SQLITE_OK;
  131969. }
  131970. /*
  131971. ** Implementation of xRollback(). Discard the contents of the pending-terms
  131972. ** hash-table. Any changes made to the database are reverted by SQLite.
  131973. */
  131974. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  131975. Fts3Table *p = (Fts3Table*)pVtab;
  131976. sqlite3Fts3PendingTermsClear(p);
  131977. assert( p->inTransaction!=0 );
  131978. TESTONLY( p->inTransaction = 0 );
  131979. TESTONLY( p->mxSavepoint = -1; );
  131980. return SQLITE_OK;
  131981. }
  131982. /*
  131983. ** When called, *ppPoslist must point to the byte immediately following the
  131984. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  131985. ** moves *ppPoslist so that it instead points to the first byte of the
  131986. ** same position list.
  131987. */
  131988. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  131989. char *p = &(*ppPoslist)[-2];
  131990. char c = 0;
  131991. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  131992. while( p>pStart && (c=*p--)==0 );
  131993. /* Search backwards for a varint with value zero (the end of the previous
  131994. ** poslist). This is an 0x00 byte preceded by some byte that does not
  131995. ** have the 0x80 bit set. */
  131996. while( p>pStart && (*p & 0x80) | c ){
  131997. c = *p--;
  131998. }
  131999. assert( p==pStart || c==0 );
  132000. /* At this point p points to that preceding byte without the 0x80 bit
  132001. ** set. So to find the start of the poslist, skip forward 2 bytes then
  132002. ** over a varint.
  132003. **
  132004. ** Normally. The other case is that p==pStart and the poslist to return
  132005. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  132006. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  132007. ** is required for cases where the first byte of a doclist and the
  132008. ** doclist is empty. For example, if the first docid is 10, a doclist
  132009. ** that begins with:
  132010. **
  132011. ** 0x0A 0x00 <next docid delta varint>
  132012. */
  132013. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  132014. while( *p++&0x80 );
  132015. *ppPoslist = p;
  132016. }
  132017. /*
  132018. ** Helper function used by the implementation of the overloaded snippet(),
  132019. ** offsets() and optimize() SQL functions.
  132020. **
  132021. ** If the value passed as the third argument is a blob of size
  132022. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  132023. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  132024. ** message is written to context pContext and SQLITE_ERROR returned. The
  132025. ** string passed via zFunc is used as part of the error message.
  132026. */
  132027. static int fts3FunctionArg(
  132028. sqlite3_context *pContext, /* SQL function call context */
  132029. const char *zFunc, /* Function name */
  132030. sqlite3_value *pVal, /* argv[0] passed to function */
  132031. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  132032. ){
  132033. Fts3Cursor *pRet;
  132034. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  132035. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  132036. ){
  132037. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  132038. sqlite3_result_error(pContext, zErr, -1);
  132039. sqlite3_free(zErr);
  132040. return SQLITE_ERROR;
  132041. }
  132042. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  132043. *ppCsr = pRet;
  132044. return SQLITE_OK;
  132045. }
  132046. /*
  132047. ** Implementation of the snippet() function for FTS3
  132048. */
  132049. static void fts3SnippetFunc(
  132050. sqlite3_context *pContext, /* SQLite function call context */
  132051. int nVal, /* Size of apVal[] array */
  132052. sqlite3_value **apVal /* Array of arguments */
  132053. ){
  132054. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  132055. const char *zStart = "<b>";
  132056. const char *zEnd = "</b>";
  132057. const char *zEllipsis = "<b>...</b>";
  132058. int iCol = -1;
  132059. int nToken = 15; /* Default number of tokens in snippet */
  132060. /* There must be at least one argument passed to this function (otherwise
  132061. ** the non-overloaded version would have been called instead of this one).
  132062. */
  132063. assert( nVal>=1 );
  132064. if( nVal>6 ){
  132065. sqlite3_result_error(pContext,
  132066. "wrong number of arguments to function snippet()", -1);
  132067. return;
  132068. }
  132069. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  132070. switch( nVal ){
  132071. case 6: nToken = sqlite3_value_int(apVal[5]);
  132072. case 5: iCol = sqlite3_value_int(apVal[4]);
  132073. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  132074. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  132075. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  132076. }
  132077. if( !zEllipsis || !zEnd || !zStart ){
  132078. sqlite3_result_error_nomem(pContext);
  132079. }else if( nToken==0 ){
  132080. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  132081. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  132082. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  132083. }
  132084. }
  132085. /*
  132086. ** Implementation of the offsets() function for FTS3
  132087. */
  132088. static void fts3OffsetsFunc(
  132089. sqlite3_context *pContext, /* SQLite function call context */
  132090. int nVal, /* Size of argument array */
  132091. sqlite3_value **apVal /* Array of arguments */
  132092. ){
  132093. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  132094. UNUSED_PARAMETER(nVal);
  132095. assert( nVal==1 );
  132096. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  132097. assert( pCsr );
  132098. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  132099. sqlite3Fts3Offsets(pContext, pCsr);
  132100. }
  132101. }
  132102. /*
  132103. ** Implementation of the special optimize() function for FTS3. This
  132104. ** function merges all segments in the database to a single segment.
  132105. ** Example usage is:
  132106. **
  132107. ** SELECT optimize(t) FROM t LIMIT 1;
  132108. **
  132109. ** where 't' is the name of an FTS3 table.
  132110. */
  132111. static void fts3OptimizeFunc(
  132112. sqlite3_context *pContext, /* SQLite function call context */
  132113. int nVal, /* Size of argument array */
  132114. sqlite3_value **apVal /* Array of arguments */
  132115. ){
  132116. int rc; /* Return code */
  132117. Fts3Table *p; /* Virtual table handle */
  132118. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  132119. UNUSED_PARAMETER(nVal);
  132120. assert( nVal==1 );
  132121. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  132122. p = (Fts3Table *)pCursor->base.pVtab;
  132123. assert( p );
  132124. rc = sqlite3Fts3Optimize(p);
  132125. switch( rc ){
  132126. case SQLITE_OK:
  132127. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  132128. break;
  132129. case SQLITE_DONE:
  132130. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  132131. break;
  132132. default:
  132133. sqlite3_result_error_code(pContext, rc);
  132134. break;
  132135. }
  132136. }
  132137. /*
  132138. ** Implementation of the matchinfo() function for FTS3
  132139. */
  132140. static void fts3MatchinfoFunc(
  132141. sqlite3_context *pContext, /* SQLite function call context */
  132142. int nVal, /* Size of argument array */
  132143. sqlite3_value **apVal /* Array of arguments */
  132144. ){
  132145. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  132146. assert( nVal==1 || nVal==2 );
  132147. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  132148. const char *zArg = 0;
  132149. if( nVal>1 ){
  132150. zArg = (const char *)sqlite3_value_text(apVal[1]);
  132151. }
  132152. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  132153. }
  132154. }
  132155. /*
  132156. ** This routine implements the xFindFunction method for the FTS3
  132157. ** virtual table.
  132158. */
  132159. static int fts3FindFunctionMethod(
  132160. sqlite3_vtab *pVtab, /* Virtual table handle */
  132161. int nArg, /* Number of SQL function arguments */
  132162. const char *zName, /* Name of SQL function */
  132163. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  132164. void **ppArg /* Unused */
  132165. ){
  132166. struct Overloaded {
  132167. const char *zName;
  132168. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  132169. } aOverload[] = {
  132170. { "snippet", fts3SnippetFunc },
  132171. { "offsets", fts3OffsetsFunc },
  132172. { "optimize", fts3OptimizeFunc },
  132173. { "matchinfo", fts3MatchinfoFunc },
  132174. };
  132175. int i; /* Iterator variable */
  132176. UNUSED_PARAMETER(pVtab);
  132177. UNUSED_PARAMETER(nArg);
  132178. UNUSED_PARAMETER(ppArg);
  132179. for(i=0; i<SizeofArray(aOverload); i++){
  132180. if( strcmp(zName, aOverload[i].zName)==0 ){
  132181. *pxFunc = aOverload[i].xFunc;
  132182. return 1;
  132183. }
  132184. }
  132185. /* No function of the specified name was found. Return 0. */
  132186. return 0;
  132187. }
  132188. /*
  132189. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  132190. */
  132191. static int fts3RenameMethod(
  132192. sqlite3_vtab *pVtab, /* Virtual table handle */
  132193. const char *zName /* New name of table */
  132194. ){
  132195. Fts3Table *p = (Fts3Table *)pVtab;
  132196. sqlite3 *db = p->db; /* Database connection */
  132197. int rc; /* Return Code */
  132198. /* At this point it must be known if the %_stat table exists or not.
  132199. ** So bHasStat may not be 2. */
  132200. rc = fts3SetHasStat(p);
  132201. /* As it happens, the pending terms table is always empty here. This is
  132202. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  132203. ** always opens a savepoint transaction. And the xSavepoint() method
  132204. ** flushes the pending terms table. But leave the (no-op) call to
  132205. ** PendingTermsFlush() in in case that changes.
  132206. */
  132207. assert( p->nPendingData==0 );
  132208. if( rc==SQLITE_OK ){
  132209. rc = sqlite3Fts3PendingTermsFlush(p);
  132210. }
  132211. if( p->zContentTbl==0 ){
  132212. fts3DbExec(&rc, db,
  132213. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  132214. p->zDb, p->zName, zName
  132215. );
  132216. }
  132217. if( p->bHasDocsize ){
  132218. fts3DbExec(&rc, db,
  132219. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  132220. p->zDb, p->zName, zName
  132221. );
  132222. }
  132223. if( p->bHasStat ){
  132224. fts3DbExec(&rc, db,
  132225. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  132226. p->zDb, p->zName, zName
  132227. );
  132228. }
  132229. fts3DbExec(&rc, db,
  132230. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  132231. p->zDb, p->zName, zName
  132232. );
  132233. fts3DbExec(&rc, db,
  132234. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  132235. p->zDb, p->zName, zName
  132236. );
  132237. return rc;
  132238. }
  132239. /*
  132240. ** The xSavepoint() method.
  132241. **
  132242. ** Flush the contents of the pending-terms table to disk.
  132243. */
  132244. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  132245. int rc = SQLITE_OK;
  132246. UNUSED_PARAMETER(iSavepoint);
  132247. assert( ((Fts3Table *)pVtab)->inTransaction );
  132248. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  132249. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  132250. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  132251. rc = fts3SyncMethod(pVtab);
  132252. }
  132253. return rc;
  132254. }
  132255. /*
  132256. ** The xRelease() method.
  132257. **
  132258. ** This is a no-op.
  132259. */
  132260. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  132261. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  132262. UNUSED_PARAMETER(iSavepoint);
  132263. UNUSED_PARAMETER(pVtab);
  132264. assert( p->inTransaction );
  132265. assert( p->mxSavepoint >= iSavepoint );
  132266. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  132267. return SQLITE_OK;
  132268. }
  132269. /*
  132270. ** The xRollbackTo() method.
  132271. **
  132272. ** Discard the contents of the pending terms table.
  132273. */
  132274. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  132275. Fts3Table *p = (Fts3Table*)pVtab;
  132276. UNUSED_PARAMETER(iSavepoint);
  132277. assert( p->inTransaction );
  132278. assert( p->mxSavepoint >= iSavepoint );
  132279. TESTONLY( p->mxSavepoint = iSavepoint );
  132280. sqlite3Fts3PendingTermsClear(p);
  132281. return SQLITE_OK;
  132282. }
  132283. static const sqlite3_module fts3Module = {
  132284. /* iVersion */ 2,
  132285. /* xCreate */ fts3CreateMethod,
  132286. /* xConnect */ fts3ConnectMethod,
  132287. /* xBestIndex */ fts3BestIndexMethod,
  132288. /* xDisconnect */ fts3DisconnectMethod,
  132289. /* xDestroy */ fts3DestroyMethod,
  132290. /* xOpen */ fts3OpenMethod,
  132291. /* xClose */ fts3CloseMethod,
  132292. /* xFilter */ fts3FilterMethod,
  132293. /* xNext */ fts3NextMethod,
  132294. /* xEof */ fts3EofMethod,
  132295. /* xColumn */ fts3ColumnMethod,
  132296. /* xRowid */ fts3RowidMethod,
  132297. /* xUpdate */ fts3UpdateMethod,
  132298. /* xBegin */ fts3BeginMethod,
  132299. /* xSync */ fts3SyncMethod,
  132300. /* xCommit */ fts3CommitMethod,
  132301. /* xRollback */ fts3RollbackMethod,
  132302. /* xFindFunction */ fts3FindFunctionMethod,
  132303. /* xRename */ fts3RenameMethod,
  132304. /* xSavepoint */ fts3SavepointMethod,
  132305. /* xRelease */ fts3ReleaseMethod,
  132306. /* xRollbackTo */ fts3RollbackToMethod,
  132307. };
  132308. /*
  132309. ** This function is registered as the module destructor (called when an
  132310. ** FTS3 enabled database connection is closed). It frees the memory
  132311. ** allocated for the tokenizer hash table.
  132312. */
  132313. static void hashDestroy(void *p){
  132314. Fts3Hash *pHash = (Fts3Hash *)p;
  132315. sqlite3Fts3HashClear(pHash);
  132316. sqlite3_free(pHash);
  132317. }
  132318. /*
  132319. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  132320. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  132321. ** respectively. The following three forward declarations are for functions
  132322. ** declared in these files used to retrieve the respective implementations.
  132323. **
  132324. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  132325. ** to by the argument to point to the "simple" tokenizer implementation.
  132326. ** And so on.
  132327. */
  132328. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  132329. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  132330. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  132331. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  132332. #endif
  132333. #ifdef SQLITE_ENABLE_ICU
  132334. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  132335. #endif
  132336. /*
  132337. ** Initialize the fts3 extension. If this extension is built as part
  132338. ** of the sqlite library, then this function is called directly by
  132339. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  132340. ** function is called by the sqlite3_extension_init() entry point.
  132341. */
  132342. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  132343. int rc = SQLITE_OK;
  132344. Fts3Hash *pHash = 0;
  132345. const sqlite3_tokenizer_module *pSimple = 0;
  132346. const sqlite3_tokenizer_module *pPorter = 0;
  132347. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  132348. const sqlite3_tokenizer_module *pUnicode = 0;
  132349. #endif
  132350. #ifdef SQLITE_ENABLE_ICU
  132351. const sqlite3_tokenizer_module *pIcu = 0;
  132352. sqlite3Fts3IcuTokenizerModule(&pIcu);
  132353. #endif
  132354. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  132355. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  132356. #endif
  132357. #ifdef SQLITE_TEST
  132358. rc = sqlite3Fts3InitTerm(db);
  132359. if( rc!=SQLITE_OK ) return rc;
  132360. #endif
  132361. rc = sqlite3Fts3InitAux(db);
  132362. if( rc!=SQLITE_OK ) return rc;
  132363. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  132364. sqlite3Fts3PorterTokenizerModule(&pPorter);
  132365. /* Allocate and initialize the hash-table used to store tokenizers. */
  132366. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  132367. if( !pHash ){
  132368. rc = SQLITE_NOMEM;
  132369. }else{
  132370. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  132371. }
  132372. /* Load the built-in tokenizers into the hash table */
  132373. if( rc==SQLITE_OK ){
  132374. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  132375. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  132376. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  132377. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  132378. #endif
  132379. #ifdef SQLITE_ENABLE_ICU
  132380. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  132381. #endif
  132382. ){
  132383. rc = SQLITE_NOMEM;
  132384. }
  132385. }
  132386. #ifdef SQLITE_TEST
  132387. if( rc==SQLITE_OK ){
  132388. rc = sqlite3Fts3ExprInitTestInterface(db);
  132389. }
  132390. #endif
  132391. /* Create the virtual table wrapper around the hash-table and overload
  132392. ** the two scalar functions. If this is successful, register the
  132393. ** module with sqlite.
  132394. */
  132395. if( SQLITE_OK==rc
  132396. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  132397. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  132398. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  132399. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  132400. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  132401. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  132402. ){
  132403. rc = sqlite3_create_module_v2(
  132404. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  132405. );
  132406. if( rc==SQLITE_OK ){
  132407. rc = sqlite3_create_module_v2(
  132408. db, "fts4", &fts3Module, (void *)pHash, 0
  132409. );
  132410. }
  132411. if( rc==SQLITE_OK ){
  132412. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  132413. }
  132414. return rc;
  132415. }
  132416. /* An error has occurred. Delete the hash table and return the error code. */
  132417. assert( rc!=SQLITE_OK );
  132418. if( pHash ){
  132419. sqlite3Fts3HashClear(pHash);
  132420. sqlite3_free(pHash);
  132421. }
  132422. return rc;
  132423. }
  132424. /*
  132425. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  132426. ** by pExpr.
  132427. **
  132428. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  132429. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  132430. ** Fts3SegReader objects internally to provide an interface to seek or scan
  132431. ** within the union of all segments of a b-tree. Hence the name.
  132432. **
  132433. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  132434. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  132435. ** there exists prefix b-tree of the right length) then it may be traversed
  132436. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  132437. ** doclist and then traversed.
  132438. */
  132439. static void fts3EvalAllocateReaders(
  132440. Fts3Cursor *pCsr, /* FTS cursor handle */
  132441. Fts3Expr *pExpr, /* Allocate readers for this expression */
  132442. int *pnToken, /* OUT: Total number of tokens in phrase. */
  132443. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  132444. int *pRc /* IN/OUT: Error code */
  132445. ){
  132446. if( pExpr && SQLITE_OK==*pRc ){
  132447. if( pExpr->eType==FTSQUERY_PHRASE ){
  132448. int i;
  132449. int nToken = pExpr->pPhrase->nToken;
  132450. *pnToken += nToken;
  132451. for(i=0; i<nToken; i++){
  132452. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  132453. int rc = fts3TermSegReaderCursor(pCsr,
  132454. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  132455. );
  132456. if( rc!=SQLITE_OK ){
  132457. *pRc = rc;
  132458. return;
  132459. }
  132460. }
  132461. assert( pExpr->pPhrase->iDoclistToken==0 );
  132462. pExpr->pPhrase->iDoclistToken = -1;
  132463. }else{
  132464. *pnOr += (pExpr->eType==FTSQUERY_OR);
  132465. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  132466. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  132467. }
  132468. }
  132469. }
  132470. /*
  132471. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  132472. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  132473. **
  132474. ** This function assumes that pList points to a buffer allocated using
  132475. ** sqlite3_malloc(). This function takes responsibility for eventually
  132476. ** freeing the buffer.
  132477. **
  132478. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  132479. */
  132480. static int fts3EvalPhraseMergeToken(
  132481. Fts3Table *pTab, /* FTS Table pointer */
  132482. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  132483. int iToken, /* Token pList/nList corresponds to */
  132484. char *pList, /* Pointer to doclist */
  132485. int nList /* Number of bytes in pList */
  132486. ){
  132487. int rc = SQLITE_OK;
  132488. assert( iToken!=p->iDoclistToken );
  132489. if( pList==0 ){
  132490. sqlite3_free(p->doclist.aAll);
  132491. p->doclist.aAll = 0;
  132492. p->doclist.nAll = 0;
  132493. }
  132494. else if( p->iDoclistToken<0 ){
  132495. p->doclist.aAll = pList;
  132496. p->doclist.nAll = nList;
  132497. }
  132498. else if( p->doclist.aAll==0 ){
  132499. sqlite3_free(pList);
  132500. }
  132501. else {
  132502. char *pLeft;
  132503. char *pRight;
  132504. int nLeft;
  132505. int nRight;
  132506. int nDiff;
  132507. if( p->iDoclistToken<iToken ){
  132508. pLeft = p->doclist.aAll;
  132509. nLeft = p->doclist.nAll;
  132510. pRight = pList;
  132511. nRight = nList;
  132512. nDiff = iToken - p->iDoclistToken;
  132513. }else{
  132514. pRight = p->doclist.aAll;
  132515. nRight = p->doclist.nAll;
  132516. pLeft = pList;
  132517. nLeft = nList;
  132518. nDiff = p->iDoclistToken - iToken;
  132519. }
  132520. rc = fts3DoclistPhraseMerge(
  132521. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  132522. );
  132523. sqlite3_free(pLeft);
  132524. p->doclist.aAll = pRight;
  132525. p->doclist.nAll = nRight;
  132526. }
  132527. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  132528. return rc;
  132529. }
  132530. /*
  132531. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  132532. ** does not take deferred tokens into account.
  132533. **
  132534. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  132535. */
  132536. static int fts3EvalPhraseLoad(
  132537. Fts3Cursor *pCsr, /* FTS Cursor handle */
  132538. Fts3Phrase *p /* Phrase object */
  132539. ){
  132540. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132541. int iToken;
  132542. int rc = SQLITE_OK;
  132543. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  132544. Fts3PhraseToken *pToken = &p->aToken[iToken];
  132545. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  132546. if( pToken->pSegcsr ){
  132547. int nThis = 0;
  132548. char *pThis = 0;
  132549. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  132550. if( rc==SQLITE_OK ){
  132551. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  132552. }
  132553. }
  132554. assert( pToken->pSegcsr==0 );
  132555. }
  132556. return rc;
  132557. }
  132558. /*
  132559. ** This function is called on each phrase after the position lists for
  132560. ** any deferred tokens have been loaded into memory. It updates the phrases
  132561. ** current position list to include only those positions that are really
  132562. ** instances of the phrase (after considering deferred tokens). If this
  132563. ** means that the phrase does not appear in the current row, doclist.pList
  132564. ** and doclist.nList are both zeroed.
  132565. **
  132566. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  132567. */
  132568. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  132569. int iToken; /* Used to iterate through phrase tokens */
  132570. char *aPoslist = 0; /* Position list for deferred tokens */
  132571. int nPoslist = 0; /* Number of bytes in aPoslist */
  132572. int iPrev = -1; /* Token number of previous deferred token */
  132573. assert( pPhrase->doclist.bFreeList==0 );
  132574. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  132575. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  132576. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  132577. if( pDeferred ){
  132578. char *pList;
  132579. int nList;
  132580. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  132581. if( rc!=SQLITE_OK ) return rc;
  132582. if( pList==0 ){
  132583. sqlite3_free(aPoslist);
  132584. pPhrase->doclist.pList = 0;
  132585. pPhrase->doclist.nList = 0;
  132586. return SQLITE_OK;
  132587. }else if( aPoslist==0 ){
  132588. aPoslist = pList;
  132589. nPoslist = nList;
  132590. }else{
  132591. char *aOut = pList;
  132592. char *p1 = aPoslist;
  132593. char *p2 = aOut;
  132594. assert( iPrev>=0 );
  132595. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  132596. sqlite3_free(aPoslist);
  132597. aPoslist = pList;
  132598. nPoslist = (int)(aOut - aPoslist);
  132599. if( nPoslist==0 ){
  132600. sqlite3_free(aPoslist);
  132601. pPhrase->doclist.pList = 0;
  132602. pPhrase->doclist.nList = 0;
  132603. return SQLITE_OK;
  132604. }
  132605. }
  132606. iPrev = iToken;
  132607. }
  132608. }
  132609. if( iPrev>=0 ){
  132610. int nMaxUndeferred = pPhrase->iDoclistToken;
  132611. if( nMaxUndeferred<0 ){
  132612. pPhrase->doclist.pList = aPoslist;
  132613. pPhrase->doclist.nList = nPoslist;
  132614. pPhrase->doclist.iDocid = pCsr->iPrevId;
  132615. pPhrase->doclist.bFreeList = 1;
  132616. }else{
  132617. int nDistance;
  132618. char *p1;
  132619. char *p2;
  132620. char *aOut;
  132621. if( nMaxUndeferred>iPrev ){
  132622. p1 = aPoslist;
  132623. p2 = pPhrase->doclist.pList;
  132624. nDistance = nMaxUndeferred - iPrev;
  132625. }else{
  132626. p1 = pPhrase->doclist.pList;
  132627. p2 = aPoslist;
  132628. nDistance = iPrev - nMaxUndeferred;
  132629. }
  132630. aOut = (char *)sqlite3_malloc(nPoslist+8);
  132631. if( !aOut ){
  132632. sqlite3_free(aPoslist);
  132633. return SQLITE_NOMEM;
  132634. }
  132635. pPhrase->doclist.pList = aOut;
  132636. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  132637. pPhrase->doclist.bFreeList = 1;
  132638. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  132639. }else{
  132640. sqlite3_free(aOut);
  132641. pPhrase->doclist.pList = 0;
  132642. pPhrase->doclist.nList = 0;
  132643. }
  132644. sqlite3_free(aPoslist);
  132645. }
  132646. }
  132647. return SQLITE_OK;
  132648. }
  132649. /*
  132650. ** Maximum number of tokens a phrase may have to be considered for the
  132651. ** incremental doclists strategy.
  132652. */
  132653. #define MAX_INCR_PHRASE_TOKENS 4
  132654. /*
  132655. ** This function is called for each Fts3Phrase in a full-text query
  132656. ** expression to initialize the mechanism for returning rows. Once this
  132657. ** function has been called successfully on an Fts3Phrase, it may be
  132658. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  132659. **
  132660. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  132661. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  132662. ** memory within this call.
  132663. **
  132664. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  132665. */
  132666. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  132667. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132668. int rc = SQLITE_OK; /* Error code */
  132669. int i;
  132670. /* Determine if doclists may be loaded from disk incrementally. This is
  132671. ** possible if the bOptOk argument is true, the FTS doclists will be
  132672. ** scanned in forward order, and the phrase consists of
  132673. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  132674. ** tokens or prefix tokens that cannot use a prefix-index. */
  132675. int bHaveIncr = 0;
  132676. int bIncrOk = (bOptOk
  132677. && pCsr->bDesc==pTab->bDescIdx
  132678. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  132679. #ifdef SQLITE_TEST
  132680. && pTab->bNoIncrDoclist==0
  132681. #endif
  132682. );
  132683. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  132684. Fts3PhraseToken *pToken = &p->aToken[i];
  132685. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  132686. bIncrOk = 0;
  132687. }
  132688. if( pToken->pSegcsr ) bHaveIncr = 1;
  132689. }
  132690. if( bIncrOk && bHaveIncr ){
  132691. /* Use the incremental approach. */
  132692. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  132693. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  132694. Fts3PhraseToken *pToken = &p->aToken[i];
  132695. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  132696. if( pSegcsr ){
  132697. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  132698. }
  132699. }
  132700. p->bIncr = 1;
  132701. }else{
  132702. /* Load the full doclist for the phrase into memory. */
  132703. rc = fts3EvalPhraseLoad(pCsr, p);
  132704. p->bIncr = 0;
  132705. }
  132706. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  132707. return rc;
  132708. }
  132709. /*
  132710. ** This function is used to iterate backwards (from the end to start)
  132711. ** through doclists. It is used by this module to iterate through phrase
  132712. ** doclists in reverse and by the fts3_write.c module to iterate through
  132713. ** pending-terms lists when writing to databases with "order=desc".
  132714. **
  132715. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  132716. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  132717. ** function iterates from the end of the doclist to the beginning.
  132718. */
  132719. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  132720. int bDescIdx, /* True if the doclist is desc */
  132721. char *aDoclist, /* Pointer to entire doclist */
  132722. int nDoclist, /* Length of aDoclist in bytes */
  132723. char **ppIter, /* IN/OUT: Iterator pointer */
  132724. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  132725. int *pnList, /* OUT: List length pointer */
  132726. u8 *pbEof /* OUT: End-of-file flag */
  132727. ){
  132728. char *p = *ppIter;
  132729. assert( nDoclist>0 );
  132730. assert( *pbEof==0 );
  132731. assert( p || *piDocid==0 );
  132732. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  132733. if( p==0 ){
  132734. sqlite3_int64 iDocid = 0;
  132735. char *pNext = 0;
  132736. char *pDocid = aDoclist;
  132737. char *pEnd = &aDoclist[nDoclist];
  132738. int iMul = 1;
  132739. while( pDocid<pEnd ){
  132740. sqlite3_int64 iDelta;
  132741. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  132742. iDocid += (iMul * iDelta);
  132743. pNext = pDocid;
  132744. fts3PoslistCopy(0, &pDocid);
  132745. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  132746. iMul = (bDescIdx ? -1 : 1);
  132747. }
  132748. *pnList = (int)(pEnd - pNext);
  132749. *ppIter = pNext;
  132750. *piDocid = iDocid;
  132751. }else{
  132752. int iMul = (bDescIdx ? -1 : 1);
  132753. sqlite3_int64 iDelta;
  132754. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  132755. *piDocid -= (iMul * iDelta);
  132756. if( p==aDoclist ){
  132757. *pbEof = 1;
  132758. }else{
  132759. char *pSave = p;
  132760. fts3ReversePoslist(aDoclist, &p);
  132761. *pnList = (int)(pSave - p);
  132762. }
  132763. *ppIter = p;
  132764. }
  132765. }
  132766. /*
  132767. ** Iterate forwards through a doclist.
  132768. */
  132769. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  132770. int bDescIdx, /* True if the doclist is desc */
  132771. char *aDoclist, /* Pointer to entire doclist */
  132772. int nDoclist, /* Length of aDoclist in bytes */
  132773. char **ppIter, /* IN/OUT: Iterator pointer */
  132774. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  132775. u8 *pbEof /* OUT: End-of-file flag */
  132776. ){
  132777. char *p = *ppIter;
  132778. assert( nDoclist>0 );
  132779. assert( *pbEof==0 );
  132780. assert( p || *piDocid==0 );
  132781. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  132782. if( p==0 ){
  132783. p = aDoclist;
  132784. p += sqlite3Fts3GetVarint(p, piDocid);
  132785. }else{
  132786. fts3PoslistCopy(0, &p);
  132787. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  132788. if( p>=&aDoclist[nDoclist] ){
  132789. *pbEof = 1;
  132790. }else{
  132791. sqlite3_int64 iVar;
  132792. p += sqlite3Fts3GetVarint(p, &iVar);
  132793. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  132794. }
  132795. }
  132796. *ppIter = p;
  132797. }
  132798. /*
  132799. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  132800. ** to true if EOF is reached.
  132801. */
  132802. static void fts3EvalDlPhraseNext(
  132803. Fts3Table *pTab,
  132804. Fts3Doclist *pDL,
  132805. u8 *pbEof
  132806. ){
  132807. char *pIter; /* Used to iterate through aAll */
  132808. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  132809. if( pDL->pNextDocid ){
  132810. pIter = pDL->pNextDocid;
  132811. }else{
  132812. pIter = pDL->aAll;
  132813. }
  132814. if( pIter>=pEnd ){
  132815. /* We have already reached the end of this doclist. EOF. */
  132816. *pbEof = 1;
  132817. }else{
  132818. sqlite3_int64 iDelta;
  132819. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  132820. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  132821. pDL->iDocid += iDelta;
  132822. }else{
  132823. pDL->iDocid -= iDelta;
  132824. }
  132825. pDL->pList = pIter;
  132826. fts3PoslistCopy(0, &pIter);
  132827. pDL->nList = (int)(pIter - pDL->pList);
  132828. /* pIter now points just past the 0x00 that terminates the position-
  132829. ** list for document pDL->iDocid. However, if this position-list was
  132830. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  132831. ** point to the start of the next docid value. The following line deals
  132832. ** with this case by advancing pIter past the zero-padding added by
  132833. ** fts3EvalNearTrim(). */
  132834. while( pIter<pEnd && *pIter==0 ) pIter++;
  132835. pDL->pNextDocid = pIter;
  132836. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  132837. *pbEof = 0;
  132838. }
  132839. }
  132840. /*
  132841. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  132842. */
  132843. typedef struct TokenDoclist TokenDoclist;
  132844. struct TokenDoclist {
  132845. int bIgnore;
  132846. sqlite3_int64 iDocid;
  132847. char *pList;
  132848. int nList;
  132849. };
  132850. /*
  132851. ** Token pToken is an incrementally loaded token that is part of a
  132852. ** multi-token phrase. Advance it to the next matching document in the
  132853. ** database and populate output variable *p with the details of the new
  132854. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  132855. **
  132856. ** If an error occurs, return an SQLite error code. Otherwise, return
  132857. ** SQLITE_OK.
  132858. */
  132859. static int incrPhraseTokenNext(
  132860. Fts3Table *pTab, /* Virtual table handle */
  132861. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  132862. int iToken, /* Specific token to advance */
  132863. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  132864. u8 *pbEof /* OUT: True if iterator is at EOF */
  132865. ){
  132866. int rc = SQLITE_OK;
  132867. if( pPhrase->iDoclistToken==iToken ){
  132868. assert( p->bIgnore==0 );
  132869. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  132870. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  132871. p->pList = pPhrase->doclist.pList;
  132872. p->nList = pPhrase->doclist.nList;
  132873. p->iDocid = pPhrase->doclist.iDocid;
  132874. }else{
  132875. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  132876. assert( pToken->pDeferred==0 );
  132877. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  132878. if( pToken->pSegcsr ){
  132879. assert( p->bIgnore==0 );
  132880. rc = sqlite3Fts3MsrIncrNext(
  132881. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  132882. );
  132883. if( p->pList==0 ) *pbEof = 1;
  132884. }else{
  132885. p->bIgnore = 1;
  132886. }
  132887. }
  132888. return rc;
  132889. }
  132890. /*
  132891. ** The phrase iterator passed as the second argument:
  132892. **
  132893. ** * features at least one token that uses an incremental doclist, and
  132894. **
  132895. ** * does not contain any deferred tokens.
  132896. **
  132897. ** Advance it to the next matching documnent in the database and populate
  132898. ** the Fts3Doclist.pList and nList fields.
  132899. **
  132900. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  132901. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  132902. ** successfully advanced, *pbEof is set to 0.
  132903. **
  132904. ** If an error occurs, return an SQLite error code. Otherwise, return
  132905. ** SQLITE_OK.
  132906. */
  132907. static int fts3EvalIncrPhraseNext(
  132908. Fts3Cursor *pCsr, /* FTS Cursor handle */
  132909. Fts3Phrase *p, /* Phrase object to advance to next docid */
  132910. u8 *pbEof /* OUT: Set to 1 if EOF */
  132911. ){
  132912. int rc = SQLITE_OK;
  132913. Fts3Doclist *pDL = &p->doclist;
  132914. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132915. u8 bEof = 0;
  132916. /* This is only called if it is guaranteed that the phrase has at least
  132917. ** one incremental token. In which case the bIncr flag is set. */
  132918. assert( p->bIncr==1 );
  132919. if( p->nToken==1 && p->bIncr ){
  132920. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  132921. &pDL->iDocid, &pDL->pList, &pDL->nList
  132922. );
  132923. if( pDL->pList==0 ) bEof = 1;
  132924. }else{
  132925. int bDescDoclist = pCsr->bDesc;
  132926. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  132927. memset(a, 0, sizeof(a));
  132928. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  132929. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  132930. while( bEof==0 ){
  132931. int bMaxSet = 0;
  132932. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  132933. int i; /* Used to iterate through tokens */
  132934. /* Advance the iterator for each token in the phrase once. */
  132935. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  132936. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  132937. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  132938. iMax = a[i].iDocid;
  132939. bMaxSet = 1;
  132940. }
  132941. }
  132942. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  132943. assert( rc!=SQLITE_OK || bMaxSet );
  132944. /* Keep advancing iterators until they all point to the same document */
  132945. for(i=0; i<p->nToken; i++){
  132946. while( rc==SQLITE_OK && bEof==0
  132947. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  132948. ){
  132949. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  132950. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  132951. iMax = a[i].iDocid;
  132952. i = 0;
  132953. }
  132954. }
  132955. }
  132956. /* Check if the current entries really are a phrase match */
  132957. if( bEof==0 ){
  132958. int nList = 0;
  132959. int nByte = a[p->nToken-1].nList;
  132960. char *aDoclist = sqlite3_malloc(nByte+1);
  132961. if( !aDoclist ) return SQLITE_NOMEM;
  132962. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  132963. for(i=0; i<(p->nToken-1); i++){
  132964. if( a[i].bIgnore==0 ){
  132965. char *pL = a[i].pList;
  132966. char *pR = aDoclist;
  132967. char *pOut = aDoclist;
  132968. int nDist = p->nToken-1-i;
  132969. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  132970. if( res==0 ) break;
  132971. nList = (int)(pOut - aDoclist);
  132972. }
  132973. }
  132974. if( i==(p->nToken-1) ){
  132975. pDL->iDocid = iMax;
  132976. pDL->pList = aDoclist;
  132977. pDL->nList = nList;
  132978. pDL->bFreeList = 1;
  132979. break;
  132980. }
  132981. sqlite3_free(aDoclist);
  132982. }
  132983. }
  132984. }
  132985. *pbEof = bEof;
  132986. return rc;
  132987. }
  132988. /*
  132989. ** Attempt to move the phrase iterator to point to the next matching docid.
  132990. ** If an error occurs, return an SQLite error code. Otherwise, return
  132991. ** SQLITE_OK.
  132992. **
  132993. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  132994. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  132995. ** successfully advanced, *pbEof is set to 0.
  132996. */
  132997. static int fts3EvalPhraseNext(
  132998. Fts3Cursor *pCsr, /* FTS Cursor handle */
  132999. Fts3Phrase *p, /* Phrase object to advance to next docid */
  133000. u8 *pbEof /* OUT: Set to 1 if EOF */
  133001. ){
  133002. int rc = SQLITE_OK;
  133003. Fts3Doclist *pDL = &p->doclist;
  133004. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  133005. if( p->bIncr ){
  133006. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  133007. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  133008. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  133009. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  133010. );
  133011. pDL->pList = pDL->pNextDocid;
  133012. }else{
  133013. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  133014. }
  133015. return rc;
  133016. }
  133017. /*
  133018. **
  133019. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  133020. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  133021. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  133022. ** expressions for which all descendent tokens are deferred.
  133023. **
  133024. ** If parameter bOptOk is zero, then it is guaranteed that the
  133025. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  133026. ** each phrase in the expression (subject to deferred token processing).
  133027. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  133028. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  133029. **
  133030. ** If an error occurs within this function, *pRc is set to an SQLite error
  133031. ** code before returning.
  133032. */
  133033. static void fts3EvalStartReaders(
  133034. Fts3Cursor *pCsr, /* FTS Cursor handle */
  133035. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  133036. int *pRc /* IN/OUT: Error code */
  133037. ){
  133038. if( pExpr && SQLITE_OK==*pRc ){
  133039. if( pExpr->eType==FTSQUERY_PHRASE ){
  133040. int nToken = pExpr->pPhrase->nToken;
  133041. if( nToken ){
  133042. int i;
  133043. for(i=0; i<nToken; i++){
  133044. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  133045. }
  133046. pExpr->bDeferred = (i==nToken);
  133047. }
  133048. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  133049. }else{
  133050. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  133051. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  133052. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  133053. }
  133054. }
  133055. }
  133056. /*
  133057. ** An array of the following structures is assembled as part of the process
  133058. ** of selecting tokens to defer before the query starts executing (as part
  133059. ** of the xFilter() method). There is one element in the array for each
  133060. ** token in the FTS expression.
  133061. **
  133062. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  133063. ** to phrases that are connected only by AND and NEAR operators (not OR or
  133064. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  133065. ** separately. The root of a tokens AND/NEAR cluster is stored in
  133066. ** Fts3TokenAndCost.pRoot.
  133067. */
  133068. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  133069. struct Fts3TokenAndCost {
  133070. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  133071. int iToken; /* Position of token in phrase */
  133072. Fts3PhraseToken *pToken; /* The token itself */
  133073. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  133074. int nOvfl; /* Number of overflow pages to load doclist */
  133075. int iCol; /* The column the token must match */
  133076. };
  133077. /*
  133078. ** This function is used to populate an allocated Fts3TokenAndCost array.
  133079. **
  133080. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  133081. ** Otherwise, if an error occurs during execution, *pRc is set to an
  133082. ** SQLite error code.
  133083. */
  133084. static void fts3EvalTokenCosts(
  133085. Fts3Cursor *pCsr, /* FTS Cursor handle */
  133086. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  133087. Fts3Expr *pExpr, /* Expression to consider */
  133088. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  133089. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  133090. int *pRc /* IN/OUT: Error code */
  133091. ){
  133092. if( *pRc==SQLITE_OK ){
  133093. if( pExpr->eType==FTSQUERY_PHRASE ){
  133094. Fts3Phrase *pPhrase = pExpr->pPhrase;
  133095. int i;
  133096. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  133097. Fts3TokenAndCost *pTC = (*ppTC)++;
  133098. pTC->pPhrase = pPhrase;
  133099. pTC->iToken = i;
  133100. pTC->pRoot = pRoot;
  133101. pTC->pToken = &pPhrase->aToken[i];
  133102. pTC->iCol = pPhrase->iColumn;
  133103. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  133104. }
  133105. }else if( pExpr->eType!=FTSQUERY_NOT ){
  133106. assert( pExpr->eType==FTSQUERY_OR
  133107. || pExpr->eType==FTSQUERY_AND
  133108. || pExpr->eType==FTSQUERY_NEAR
  133109. );
  133110. assert( pExpr->pLeft && pExpr->pRight );
  133111. if( pExpr->eType==FTSQUERY_OR ){
  133112. pRoot = pExpr->pLeft;
  133113. **ppOr = pRoot;
  133114. (*ppOr)++;
  133115. }
  133116. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  133117. if( pExpr->eType==FTSQUERY_OR ){
  133118. pRoot = pExpr->pRight;
  133119. **ppOr = pRoot;
  133120. (*ppOr)++;
  133121. }
  133122. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  133123. }
  133124. }
  133125. }
  133126. /*
  133127. ** Determine the average document (row) size in pages. If successful,
  133128. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  133129. ** an SQLite error code.
  133130. **
  133131. ** The average document size in pages is calculated by first calculating
  133132. ** determining the average size in bytes, B. If B is less than the amount
  133133. ** of data that will fit on a single leaf page of an intkey table in
  133134. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  133135. ** the number of overflow pages consumed by a record B bytes in size.
  133136. */
  133137. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  133138. if( pCsr->nRowAvg==0 ){
  133139. /* The average document size, which is required to calculate the cost
  133140. ** of each doclist, has not yet been determined. Read the required
  133141. ** data from the %_stat table to calculate it.
  133142. **
  133143. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  133144. ** varints, where nCol is the number of columns in the FTS3 table.
  133145. ** The first varint is the number of documents currently stored in
  133146. ** the table. The following nCol varints contain the total amount of
  133147. ** data stored in all rows of each column of the table, from left
  133148. ** to right.
  133149. */
  133150. int rc;
  133151. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  133152. sqlite3_stmt *pStmt;
  133153. sqlite3_int64 nDoc = 0;
  133154. sqlite3_int64 nByte = 0;
  133155. const char *pEnd;
  133156. const char *a;
  133157. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  133158. if( rc!=SQLITE_OK ) return rc;
  133159. a = sqlite3_column_blob(pStmt, 0);
  133160. assert( a );
  133161. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  133162. a += sqlite3Fts3GetVarint(a, &nDoc);
  133163. while( a<pEnd ){
  133164. a += sqlite3Fts3GetVarint(a, &nByte);
  133165. }
  133166. if( nDoc==0 || nByte==0 ){
  133167. sqlite3_reset(pStmt);
  133168. return FTS_CORRUPT_VTAB;
  133169. }
  133170. pCsr->nDoc = nDoc;
  133171. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  133172. assert( pCsr->nRowAvg>0 );
  133173. rc = sqlite3_reset(pStmt);
  133174. if( rc!=SQLITE_OK ) return rc;
  133175. }
  133176. *pnPage = pCsr->nRowAvg;
  133177. return SQLITE_OK;
  133178. }
  133179. /*
  133180. ** This function is called to select the tokens (if any) that will be
  133181. ** deferred. The array aTC[] has already been populated when this is
  133182. ** called.
  133183. **
  133184. ** This function is called once for each AND/NEAR cluster in the
  133185. ** expression. Each invocation determines which tokens to defer within
  133186. ** the cluster with root node pRoot. See comments above the definition
  133187. ** of struct Fts3TokenAndCost for more details.
  133188. **
  133189. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  133190. ** called on each token to defer. Otherwise, an SQLite error code is
  133191. ** returned.
  133192. */
  133193. static int fts3EvalSelectDeferred(
  133194. Fts3Cursor *pCsr, /* FTS Cursor handle */
  133195. Fts3Expr *pRoot, /* Consider tokens with this root node */
  133196. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  133197. int nTC /* Number of entries in aTC[] */
  133198. ){
  133199. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  133200. int nDocSize = 0; /* Number of pages per doc loaded */
  133201. int rc = SQLITE_OK; /* Return code */
  133202. int ii; /* Iterator variable for various purposes */
  133203. int nOvfl = 0; /* Total overflow pages used by doclists */
  133204. int nToken = 0; /* Total number of tokens in cluster */
  133205. int nMinEst = 0; /* The minimum count for any phrase so far. */
  133206. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  133207. /* Tokens are never deferred for FTS tables created using the content=xxx
  133208. ** option. The reason being that it is not guaranteed that the content
  133209. ** table actually contains the same data as the index. To prevent this from
  133210. ** causing any problems, the deferred token optimization is completely
  133211. ** disabled for content=xxx tables. */
  133212. if( pTab->zContentTbl ){
  133213. return SQLITE_OK;
  133214. }
  133215. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  133216. ** associated with the tokens spill onto overflow pages, or if there is
  133217. ** only 1 token, exit early. No tokens to defer in this case. */
  133218. for(ii=0; ii<nTC; ii++){
  133219. if( aTC[ii].pRoot==pRoot ){
  133220. nOvfl += aTC[ii].nOvfl;
  133221. nToken++;
  133222. }
  133223. }
  133224. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  133225. /* Obtain the average docsize (in pages). */
  133226. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  133227. assert( rc!=SQLITE_OK || nDocSize>0 );
  133228. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  133229. ** of the number of overflow pages that will be loaded by the pager layer
  133230. ** to retrieve the entire doclist for the token from the full-text index.
  133231. ** Load the doclists for tokens that are either:
  133232. **
  133233. ** a. The cheapest token in the entire query (i.e. the one visited by the
  133234. ** first iteration of this loop), or
  133235. **
  133236. ** b. Part of a multi-token phrase.
  133237. **
  133238. ** After each token doclist is loaded, merge it with the others from the
  133239. ** same phrase and count the number of documents that the merged doclist
  133240. ** contains. Set variable "nMinEst" to the smallest number of documents in
  133241. ** any phrase doclist for which 1 or more token doclists have been loaded.
  133242. ** Let nOther be the number of other phrases for which it is certain that
  133243. ** one or more tokens will not be deferred.
  133244. **
  133245. ** Then, for each token, defer it if loading the doclist would result in
  133246. ** loading N or more overflow pages into memory, where N is computed as:
  133247. **
  133248. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  133249. */
  133250. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  133251. int iTC; /* Used to iterate through aTC[] array. */
  133252. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  133253. /* Set pTC to point to the cheapest remaining token. */
  133254. for(iTC=0; iTC<nTC; iTC++){
  133255. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  133256. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  133257. ){
  133258. pTC = &aTC[iTC];
  133259. }
  133260. }
  133261. assert( pTC );
  133262. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  133263. /* The number of overflow pages to load for this (and therefore all
  133264. ** subsequent) tokens is greater than the estimated number of pages
  133265. ** that will be loaded if all subsequent tokens are deferred.
  133266. */
  133267. Fts3PhraseToken *pToken = pTC->pToken;
  133268. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  133269. fts3SegReaderCursorFree(pToken->pSegcsr);
  133270. pToken->pSegcsr = 0;
  133271. }else{
  133272. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  133273. ** for-loop. Except, limit the value to 2^24 to prevent it from
  133274. ** overflowing the 32-bit integer it is stored in. */
  133275. if( ii<12 ) nLoad4 = nLoad4*4;
  133276. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  133277. /* Either this is the cheapest token in the entire query, or it is
  133278. ** part of a multi-token phrase. Either way, the entire doclist will
  133279. ** (eventually) be loaded into memory. It may as well be now. */
  133280. Fts3PhraseToken *pToken = pTC->pToken;
  133281. int nList = 0;
  133282. char *pList = 0;
  133283. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  133284. assert( rc==SQLITE_OK || pList==0 );
  133285. if( rc==SQLITE_OK ){
  133286. rc = fts3EvalPhraseMergeToken(
  133287. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  133288. );
  133289. }
  133290. if( rc==SQLITE_OK ){
  133291. int nCount;
  133292. nCount = fts3DoclistCountDocids(
  133293. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  133294. );
  133295. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  133296. }
  133297. }
  133298. }
  133299. pTC->pToken = 0;
  133300. }
  133301. return rc;
  133302. }
  133303. /*
  133304. ** This function is called from within the xFilter method. It initializes
  133305. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  133306. ** the results of a query, the caller does:
  133307. **
  133308. ** fts3EvalStart(pCsr);
  133309. ** while( 1 ){
  133310. ** fts3EvalNext(pCsr);
  133311. ** if( pCsr->bEof ) break;
  133312. ** ... return row pCsr->iPrevId to the caller ...
  133313. ** }
  133314. */
  133315. static int fts3EvalStart(Fts3Cursor *pCsr){
  133316. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  133317. int rc = SQLITE_OK;
  133318. int nToken = 0;
  133319. int nOr = 0;
  133320. /* Allocate a MultiSegReader for each token in the expression. */
  133321. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  133322. /* Determine which, if any, tokens in the expression should be deferred. */
  133323. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  133324. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  133325. Fts3TokenAndCost *aTC;
  133326. Fts3Expr **apOr;
  133327. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  133328. sizeof(Fts3TokenAndCost) * nToken
  133329. + sizeof(Fts3Expr *) * nOr * 2
  133330. );
  133331. apOr = (Fts3Expr **)&aTC[nToken];
  133332. if( !aTC ){
  133333. rc = SQLITE_NOMEM;
  133334. }else{
  133335. int ii;
  133336. Fts3TokenAndCost *pTC = aTC;
  133337. Fts3Expr **ppOr = apOr;
  133338. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  133339. nToken = (int)(pTC-aTC);
  133340. nOr = (int)(ppOr-apOr);
  133341. if( rc==SQLITE_OK ){
  133342. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  133343. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  133344. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  133345. }
  133346. }
  133347. sqlite3_free(aTC);
  133348. }
  133349. }
  133350. #endif
  133351. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  133352. return rc;
  133353. }
  133354. /*
  133355. ** Invalidate the current position list for phrase pPhrase.
  133356. */
  133357. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  133358. if( pPhrase->doclist.bFreeList ){
  133359. sqlite3_free(pPhrase->doclist.pList);
  133360. }
  133361. pPhrase->doclist.pList = 0;
  133362. pPhrase->doclist.nList = 0;
  133363. pPhrase->doclist.bFreeList = 0;
  133364. }
  133365. /*
  133366. ** This function is called to edit the position list associated with
  133367. ** the phrase object passed as the fifth argument according to a NEAR
  133368. ** condition. For example:
  133369. **
  133370. ** abc NEAR/5 "def ghi"
  133371. **
  133372. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  133373. ** the example above). When this function is called, *paPoslist points to
  133374. ** the position list, and *pnToken is the number of phrase tokens in, the
  133375. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  133376. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  133377. ** the position list associated with phrase "abc".
  133378. **
  133379. ** All positions in the pPhrase position list that are not sufficiently
  133380. ** close to a position in the *paPoslist position list are removed. If this
  133381. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  133382. **
  133383. ** Before returning, *paPoslist is set to point to the position lsit
  133384. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  133385. ** pPhrase.
  133386. */
  133387. static int fts3EvalNearTrim(
  133388. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  133389. char *aTmp, /* Temporary space to use */
  133390. char **paPoslist, /* IN/OUT: Position list */
  133391. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  133392. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  133393. ){
  133394. int nParam1 = nNear + pPhrase->nToken;
  133395. int nParam2 = nNear + *pnToken;
  133396. int nNew;
  133397. char *p2;
  133398. char *pOut;
  133399. int res;
  133400. assert( pPhrase->doclist.pList );
  133401. p2 = pOut = pPhrase->doclist.pList;
  133402. res = fts3PoslistNearMerge(
  133403. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  133404. );
  133405. if( res ){
  133406. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  133407. assert( pPhrase->doclist.pList[nNew]=='\0' );
  133408. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  133409. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  133410. pPhrase->doclist.nList = nNew;
  133411. *paPoslist = pPhrase->doclist.pList;
  133412. *pnToken = pPhrase->nToken;
  133413. }
  133414. return res;
  133415. }
  133416. /*
  133417. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  133418. ** Otherwise, it advances the expression passed as the second argument to
  133419. ** point to the next matching row in the database. Expressions iterate through
  133420. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  133421. ** or descending if it is non-zero.
  133422. **
  133423. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  133424. ** successful, the following variables in pExpr are set:
  133425. **
  133426. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  133427. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  133428. **
  133429. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  133430. ** at EOF, then the following variables are populated with the position list
  133431. ** for the phrase for the visited row:
  133432. **
  133433. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  133434. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  133435. **
  133436. ** It says above that this function advances the expression to the next
  133437. ** matching row. This is usually true, but there are the following exceptions:
  133438. **
  133439. ** 1. Deferred tokens are not taken into account. If a phrase consists
  133440. ** entirely of deferred tokens, it is assumed to match every row in
  133441. ** the db. In this case the position-list is not populated at all.
  133442. **
  133443. ** Or, if a phrase contains one or more deferred tokens and one or
  133444. ** more non-deferred tokens, then the expression is advanced to the
  133445. ** next possible match, considering only non-deferred tokens. In other
  133446. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  133447. ** is advanced to the next row that contains an instance of "A * C",
  133448. ** where "*" may match any single token. The position list in this case
  133449. ** is populated as for "A * C" before returning.
  133450. **
  133451. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  133452. ** advanced to point to the next row that matches "x AND y".
  133453. **
  133454. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  133455. ** really a match, taking into account deferred tokens and NEAR operators.
  133456. */
  133457. static void fts3EvalNextRow(
  133458. Fts3Cursor *pCsr, /* FTS Cursor handle */
  133459. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  133460. int *pRc /* IN/OUT: Error code */
  133461. ){
  133462. if( *pRc==SQLITE_OK ){
  133463. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  133464. assert( pExpr->bEof==0 );
  133465. pExpr->bStart = 1;
  133466. switch( pExpr->eType ){
  133467. case FTSQUERY_NEAR:
  133468. case FTSQUERY_AND: {
  133469. Fts3Expr *pLeft = pExpr->pLeft;
  133470. Fts3Expr *pRight = pExpr->pRight;
  133471. assert( !pLeft->bDeferred || !pRight->bDeferred );
  133472. if( pLeft->bDeferred ){
  133473. /* LHS is entirely deferred. So we assume it matches every row.
  133474. ** Advance the RHS iterator to find the next row visited. */
  133475. fts3EvalNextRow(pCsr, pRight, pRc);
  133476. pExpr->iDocid = pRight->iDocid;
  133477. pExpr->bEof = pRight->bEof;
  133478. }else if( pRight->bDeferred ){
  133479. /* RHS is entirely deferred. So we assume it matches every row.
  133480. ** Advance the LHS iterator to find the next row visited. */
  133481. fts3EvalNextRow(pCsr, pLeft, pRc);
  133482. pExpr->iDocid = pLeft->iDocid;
  133483. pExpr->bEof = pLeft->bEof;
  133484. }else{
  133485. /* Neither the RHS or LHS are deferred. */
  133486. fts3EvalNextRow(pCsr, pLeft, pRc);
  133487. fts3EvalNextRow(pCsr, pRight, pRc);
  133488. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  133489. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  133490. if( iDiff==0 ) break;
  133491. if( iDiff<0 ){
  133492. fts3EvalNextRow(pCsr, pLeft, pRc);
  133493. }else{
  133494. fts3EvalNextRow(pCsr, pRight, pRc);
  133495. }
  133496. }
  133497. pExpr->iDocid = pLeft->iDocid;
  133498. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  133499. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  133500. if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
  133501. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  133502. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  133503. memset(pDl->pList, 0, pDl->nList);
  133504. fts3EvalNextRow(pCsr, pRight, pRc);
  133505. }
  133506. }
  133507. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  133508. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  133509. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  133510. memset(pDl->pList, 0, pDl->nList);
  133511. fts3EvalNextRow(pCsr, pLeft, pRc);
  133512. }
  133513. }
  133514. }
  133515. }
  133516. break;
  133517. }
  133518. case FTSQUERY_OR: {
  133519. Fts3Expr *pLeft = pExpr->pLeft;
  133520. Fts3Expr *pRight = pExpr->pRight;
  133521. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  133522. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  133523. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  133524. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  133525. fts3EvalNextRow(pCsr, pLeft, pRc);
  133526. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  133527. fts3EvalNextRow(pCsr, pRight, pRc);
  133528. }else{
  133529. fts3EvalNextRow(pCsr, pLeft, pRc);
  133530. fts3EvalNextRow(pCsr, pRight, pRc);
  133531. }
  133532. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  133533. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  133534. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  133535. pExpr->iDocid = pLeft->iDocid;
  133536. }else{
  133537. pExpr->iDocid = pRight->iDocid;
  133538. }
  133539. break;
  133540. }
  133541. case FTSQUERY_NOT: {
  133542. Fts3Expr *pLeft = pExpr->pLeft;
  133543. Fts3Expr *pRight = pExpr->pRight;
  133544. if( pRight->bStart==0 ){
  133545. fts3EvalNextRow(pCsr, pRight, pRc);
  133546. assert( *pRc!=SQLITE_OK || pRight->bStart );
  133547. }
  133548. fts3EvalNextRow(pCsr, pLeft, pRc);
  133549. if( pLeft->bEof==0 ){
  133550. while( !*pRc
  133551. && !pRight->bEof
  133552. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  133553. ){
  133554. fts3EvalNextRow(pCsr, pRight, pRc);
  133555. }
  133556. }
  133557. pExpr->iDocid = pLeft->iDocid;
  133558. pExpr->bEof = pLeft->bEof;
  133559. break;
  133560. }
  133561. default: {
  133562. Fts3Phrase *pPhrase = pExpr->pPhrase;
  133563. fts3EvalInvalidatePoslist(pPhrase);
  133564. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  133565. pExpr->iDocid = pPhrase->doclist.iDocid;
  133566. break;
  133567. }
  133568. }
  133569. }
  133570. }
  133571. /*
  133572. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  133573. ** cluster, then this function returns 1 immediately.
  133574. **
  133575. ** Otherwise, it checks if the current row really does match the NEAR
  133576. ** expression, using the data currently stored in the position lists
  133577. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  133578. **
  133579. ** If the current row is a match, the position list associated with each
  133580. ** phrase in the NEAR expression is edited in place to contain only those
  133581. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  133582. ** constraints. In this case it returns 1. If the NEAR expression does not
  133583. ** match the current row, 0 is returned. The position lists may or may not
  133584. ** be edited if 0 is returned.
  133585. */
  133586. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  133587. int res = 1;
  133588. /* The following block runs if pExpr is the root of a NEAR query.
  133589. ** For example, the query:
  133590. **
  133591. ** "w" NEAR "x" NEAR "y" NEAR "z"
  133592. **
  133593. ** which is represented in tree form as:
  133594. **
  133595. ** |
  133596. ** +--NEAR--+ <-- root of NEAR query
  133597. ** | |
  133598. ** +--NEAR--+ "z"
  133599. ** | |
  133600. ** +--NEAR--+ "y"
  133601. ** | |
  133602. ** "w" "x"
  133603. **
  133604. ** The right-hand child of a NEAR node is always a phrase. The
  133605. ** left-hand child may be either a phrase or a NEAR node. There are
  133606. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  133607. */
  133608. if( *pRc==SQLITE_OK
  133609. && pExpr->eType==FTSQUERY_NEAR
  133610. && pExpr->bEof==0
  133611. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  133612. ){
  133613. Fts3Expr *p;
  133614. int nTmp = 0; /* Bytes of temp space */
  133615. char *aTmp; /* Temp space for PoslistNearMerge() */
  133616. /* Allocate temporary working space. */
  133617. for(p=pExpr; p->pLeft; p=p->pLeft){
  133618. nTmp += p->pRight->pPhrase->doclist.nList;
  133619. }
  133620. nTmp += p->pPhrase->doclist.nList;
  133621. if( nTmp==0 ){
  133622. res = 0;
  133623. }else{
  133624. aTmp = sqlite3_malloc(nTmp*2);
  133625. if( !aTmp ){
  133626. *pRc = SQLITE_NOMEM;
  133627. res = 0;
  133628. }else{
  133629. char *aPoslist = p->pPhrase->doclist.pList;
  133630. int nToken = p->pPhrase->nToken;
  133631. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  133632. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  133633. int nNear = p->nNear;
  133634. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  133635. }
  133636. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  133637. nToken = pExpr->pRight->pPhrase->nToken;
  133638. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  133639. int nNear;
  133640. Fts3Phrase *pPhrase;
  133641. assert( p->pParent && p->pParent->pLeft==p );
  133642. nNear = p->pParent->nNear;
  133643. pPhrase = (
  133644. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  133645. );
  133646. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  133647. }
  133648. }
  133649. sqlite3_free(aTmp);
  133650. }
  133651. }
  133652. return res;
  133653. }
  133654. /*
  133655. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  133656. ** Assuming no error occurs or has occurred, It returns non-zero if the
  133657. ** expression passed as the second argument matches the row that pCsr
  133658. ** currently points to, or zero if it does not.
  133659. **
  133660. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  133661. ** If an error occurs during execution of this function, *pRc is set to
  133662. ** the appropriate SQLite error code. In this case the returned value is
  133663. ** undefined.
  133664. */
  133665. static int fts3EvalTestExpr(
  133666. Fts3Cursor *pCsr, /* FTS cursor handle */
  133667. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  133668. int *pRc /* IN/OUT: Error code */
  133669. ){
  133670. int bHit = 1; /* Return value */
  133671. if( *pRc==SQLITE_OK ){
  133672. switch( pExpr->eType ){
  133673. case FTSQUERY_NEAR:
  133674. case FTSQUERY_AND:
  133675. bHit = (
  133676. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  133677. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  133678. && fts3EvalNearTest(pExpr, pRc)
  133679. );
  133680. /* If the NEAR expression does not match any rows, zero the doclist for
  133681. ** all phrases involved in the NEAR. This is because the snippet(),
  133682. ** offsets() and matchinfo() functions are not supposed to recognize
  133683. ** any instances of phrases that are part of unmatched NEAR queries.
  133684. ** For example if this expression:
  133685. **
  133686. ** ... MATCH 'a OR (b NEAR c)'
  133687. **
  133688. ** is matched against a row containing:
  133689. **
  133690. ** 'a b d e'
  133691. **
  133692. ** then any snippet() should ony highlight the "a" term, not the "b"
  133693. ** (as "b" is part of a non-matching NEAR clause).
  133694. */
  133695. if( bHit==0
  133696. && pExpr->eType==FTSQUERY_NEAR
  133697. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  133698. ){
  133699. Fts3Expr *p;
  133700. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  133701. if( p->pRight->iDocid==pCsr->iPrevId ){
  133702. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  133703. }
  133704. }
  133705. if( p->iDocid==pCsr->iPrevId ){
  133706. fts3EvalInvalidatePoslist(p->pPhrase);
  133707. }
  133708. }
  133709. break;
  133710. case FTSQUERY_OR: {
  133711. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  133712. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  133713. bHit = bHit1 || bHit2;
  133714. break;
  133715. }
  133716. case FTSQUERY_NOT:
  133717. bHit = (
  133718. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  133719. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  133720. );
  133721. break;
  133722. default: {
  133723. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  133724. if( pCsr->pDeferred
  133725. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  133726. ){
  133727. Fts3Phrase *pPhrase = pExpr->pPhrase;
  133728. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  133729. if( pExpr->bDeferred ){
  133730. fts3EvalInvalidatePoslist(pPhrase);
  133731. }
  133732. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  133733. bHit = (pPhrase->doclist.pList!=0);
  133734. pExpr->iDocid = pCsr->iPrevId;
  133735. }else
  133736. #endif
  133737. {
  133738. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  133739. }
  133740. break;
  133741. }
  133742. }
  133743. }
  133744. return bHit;
  133745. }
  133746. /*
  133747. ** This function is called as the second part of each xNext operation when
  133748. ** iterating through the results of a full-text query. At this point the
  133749. ** cursor points to a row that matches the query expression, with the
  133750. ** following caveats:
  133751. **
  133752. ** * Up until this point, "NEAR" operators in the expression have been
  133753. ** treated as "AND".
  133754. **
  133755. ** * Deferred tokens have not yet been considered.
  133756. **
  133757. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  133758. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  133759. ** operators and deferred tokens the current row is still a match for the
  133760. ** expression. It returns 1 if both of the following are true:
  133761. **
  133762. ** 1. *pRc is SQLITE_OK when this function returns, and
  133763. **
  133764. ** 2. After scanning the current FTS table row for the deferred tokens,
  133765. ** it is determined that the row does *not* match the query.
  133766. **
  133767. ** Or, if no error occurs and it seems the current row does match the FTS
  133768. ** query, return 0.
  133769. */
  133770. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  133771. int rc = *pRc;
  133772. int bMiss = 0;
  133773. if( rc==SQLITE_OK ){
  133774. /* If there are one or more deferred tokens, load the current row into
  133775. ** memory and scan it to determine the position list for each deferred
  133776. ** token. Then, see if this row is really a match, considering deferred
  133777. ** tokens and NEAR operators (neither of which were taken into account
  133778. ** earlier, by fts3EvalNextRow()).
  133779. */
  133780. if( pCsr->pDeferred ){
  133781. rc = fts3CursorSeek(0, pCsr);
  133782. if( rc==SQLITE_OK ){
  133783. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  133784. }
  133785. }
  133786. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  133787. /* Free the position-lists accumulated for each deferred token above. */
  133788. sqlite3Fts3FreeDeferredDoclists(pCsr);
  133789. *pRc = rc;
  133790. }
  133791. return (rc==SQLITE_OK && bMiss);
  133792. }
  133793. /*
  133794. ** Advance to the next document that matches the FTS expression in
  133795. ** Fts3Cursor.pExpr.
  133796. */
  133797. static int fts3EvalNext(Fts3Cursor *pCsr){
  133798. int rc = SQLITE_OK; /* Return Code */
  133799. Fts3Expr *pExpr = pCsr->pExpr;
  133800. assert( pCsr->isEof==0 );
  133801. if( pExpr==0 ){
  133802. pCsr->isEof = 1;
  133803. }else{
  133804. do {
  133805. if( pCsr->isRequireSeek==0 ){
  133806. sqlite3_reset(pCsr->pStmt);
  133807. }
  133808. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  133809. fts3EvalNextRow(pCsr, pExpr, &rc);
  133810. pCsr->isEof = pExpr->bEof;
  133811. pCsr->isRequireSeek = 1;
  133812. pCsr->isMatchinfoNeeded = 1;
  133813. pCsr->iPrevId = pExpr->iDocid;
  133814. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  133815. }
  133816. /* Check if the cursor is past the end of the docid range specified
  133817. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  133818. if( rc==SQLITE_OK && (
  133819. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  133820. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  133821. )){
  133822. pCsr->isEof = 1;
  133823. }
  133824. return rc;
  133825. }
  133826. /*
  133827. ** Restart interation for expression pExpr so that the next call to
  133828. ** fts3EvalNext() visits the first row. Do not allow incremental
  133829. ** loading or merging of phrase doclists for this iteration.
  133830. **
  133831. ** If *pRc is other than SQLITE_OK when this function is called, it is
  133832. ** a no-op. If an error occurs within this function, *pRc is set to an
  133833. ** SQLite error code before returning.
  133834. */
  133835. static void fts3EvalRestart(
  133836. Fts3Cursor *pCsr,
  133837. Fts3Expr *pExpr,
  133838. int *pRc
  133839. ){
  133840. if( pExpr && *pRc==SQLITE_OK ){
  133841. Fts3Phrase *pPhrase = pExpr->pPhrase;
  133842. if( pPhrase ){
  133843. fts3EvalInvalidatePoslist(pPhrase);
  133844. if( pPhrase->bIncr ){
  133845. int i;
  133846. for(i=0; i<pPhrase->nToken; i++){
  133847. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  133848. assert( pToken->pDeferred==0 );
  133849. if( pToken->pSegcsr ){
  133850. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  133851. }
  133852. }
  133853. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  133854. }
  133855. pPhrase->doclist.pNextDocid = 0;
  133856. pPhrase->doclist.iDocid = 0;
  133857. pPhrase->pOrPoslist = 0;
  133858. }
  133859. pExpr->iDocid = 0;
  133860. pExpr->bEof = 0;
  133861. pExpr->bStart = 0;
  133862. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  133863. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  133864. }
  133865. }
  133866. /*
  133867. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  133868. ** expression rooted at pExpr, the cursor iterates through all rows matched
  133869. ** by pExpr, calling this function for each row. This function increments
  133870. ** the values in Fts3Expr.aMI[] according to the position-list currently
  133871. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  133872. ** expression nodes.
  133873. */
  133874. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  133875. if( pExpr ){
  133876. Fts3Phrase *pPhrase = pExpr->pPhrase;
  133877. if( pPhrase && pPhrase->doclist.pList ){
  133878. int iCol = 0;
  133879. char *p = pPhrase->doclist.pList;
  133880. assert( *p );
  133881. while( 1 ){
  133882. u8 c = 0;
  133883. int iCnt = 0;
  133884. while( 0xFE & (*p | c) ){
  133885. if( (c&0x80)==0 ) iCnt++;
  133886. c = *p++ & 0x80;
  133887. }
  133888. /* aMI[iCol*3 + 1] = Number of occurrences
  133889. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  133890. */
  133891. pExpr->aMI[iCol*3 + 1] += iCnt;
  133892. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  133893. if( *p==0x00 ) break;
  133894. p++;
  133895. p += fts3GetVarint32(p, &iCol);
  133896. }
  133897. }
  133898. fts3EvalUpdateCounts(pExpr->pLeft);
  133899. fts3EvalUpdateCounts(pExpr->pRight);
  133900. }
  133901. }
  133902. /*
  133903. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  133904. **
  133905. ** If it is not already allocated and populated, this function allocates and
  133906. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  133907. ** of a NEAR expression, then it also allocates and populates the same array
  133908. ** for all other phrases that are part of the NEAR expression.
  133909. **
  133910. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  133911. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  133912. */
  133913. static int fts3EvalGatherStats(
  133914. Fts3Cursor *pCsr, /* Cursor object */
  133915. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  133916. ){
  133917. int rc = SQLITE_OK; /* Return code */
  133918. assert( pExpr->eType==FTSQUERY_PHRASE );
  133919. if( pExpr->aMI==0 ){
  133920. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  133921. Fts3Expr *pRoot; /* Root of NEAR expression */
  133922. Fts3Expr *p; /* Iterator used for several purposes */
  133923. sqlite3_int64 iPrevId = pCsr->iPrevId;
  133924. sqlite3_int64 iDocid;
  133925. u8 bEof;
  133926. /* Find the root of the NEAR expression */
  133927. pRoot = pExpr;
  133928. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  133929. pRoot = pRoot->pParent;
  133930. }
  133931. iDocid = pRoot->iDocid;
  133932. bEof = pRoot->bEof;
  133933. assert( pRoot->bStart );
  133934. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  133935. for(p=pRoot; p; p=p->pLeft){
  133936. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  133937. assert( pE->aMI==0 );
  133938. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  133939. if( !pE->aMI ) return SQLITE_NOMEM;
  133940. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  133941. }
  133942. fts3EvalRestart(pCsr, pRoot, &rc);
  133943. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  133944. do {
  133945. /* Ensure the %_content statement is reset. */
  133946. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  133947. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  133948. /* Advance to the next document */
  133949. fts3EvalNextRow(pCsr, pRoot, &rc);
  133950. pCsr->isEof = pRoot->bEof;
  133951. pCsr->isRequireSeek = 1;
  133952. pCsr->isMatchinfoNeeded = 1;
  133953. pCsr->iPrevId = pRoot->iDocid;
  133954. }while( pCsr->isEof==0
  133955. && pRoot->eType==FTSQUERY_NEAR
  133956. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  133957. );
  133958. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  133959. fts3EvalUpdateCounts(pRoot);
  133960. }
  133961. }
  133962. pCsr->isEof = 0;
  133963. pCsr->iPrevId = iPrevId;
  133964. if( bEof ){
  133965. pRoot->bEof = bEof;
  133966. }else{
  133967. /* Caution: pRoot may iterate through docids in ascending or descending
  133968. ** order. For this reason, even though it seems more defensive, the
  133969. ** do loop can not be written:
  133970. **
  133971. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  133972. */
  133973. fts3EvalRestart(pCsr, pRoot, &rc);
  133974. do {
  133975. fts3EvalNextRow(pCsr, pRoot, &rc);
  133976. assert( pRoot->bEof==0 );
  133977. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  133978. }
  133979. }
  133980. return rc;
  133981. }
  133982. /*
  133983. ** This function is used by the matchinfo() module to query a phrase
  133984. ** expression node for the following information:
  133985. **
  133986. ** 1. The total number of occurrences of the phrase in each column of
  133987. ** the FTS table (considering all rows), and
  133988. **
  133989. ** 2. For each column, the number of rows in the table for which the
  133990. ** column contains at least one instance of the phrase.
  133991. **
  133992. ** If no error occurs, SQLITE_OK is returned and the values for each column
  133993. ** written into the array aiOut as follows:
  133994. **
  133995. ** aiOut[iCol*3 + 1] = Number of occurrences
  133996. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  133997. **
  133998. ** Caveats:
  133999. **
  134000. ** * If a phrase consists entirely of deferred tokens, then all output
  134001. ** values are set to the number of documents in the table. In other
  134002. ** words we assume that very common tokens occur exactly once in each
  134003. ** column of each row of the table.
  134004. **
  134005. ** * If a phrase contains some deferred tokens (and some non-deferred
  134006. ** tokens), count the potential occurrence identified by considering
  134007. ** the non-deferred tokens instead of actual phrase occurrences.
  134008. **
  134009. ** * If the phrase is part of a NEAR expression, then only phrase instances
  134010. ** that meet the NEAR constraint are included in the counts.
  134011. */
  134012. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  134013. Fts3Cursor *pCsr, /* FTS cursor handle */
  134014. Fts3Expr *pExpr, /* Phrase expression */
  134015. u32 *aiOut /* Array to write results into (see above) */
  134016. ){
  134017. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  134018. int rc = SQLITE_OK;
  134019. int iCol;
  134020. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  134021. assert( pCsr->nDoc>0 );
  134022. for(iCol=0; iCol<pTab->nColumn; iCol++){
  134023. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  134024. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  134025. }
  134026. }else{
  134027. rc = fts3EvalGatherStats(pCsr, pExpr);
  134028. if( rc==SQLITE_OK ){
  134029. assert( pExpr->aMI );
  134030. for(iCol=0; iCol<pTab->nColumn; iCol++){
  134031. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  134032. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  134033. }
  134034. }
  134035. }
  134036. return rc;
  134037. }
  134038. /*
  134039. ** The expression pExpr passed as the second argument to this function
  134040. ** must be of type FTSQUERY_PHRASE.
  134041. **
  134042. ** The returned value is either NULL or a pointer to a buffer containing
  134043. ** a position-list indicating the occurrences of the phrase in column iCol
  134044. ** of the current row.
  134045. **
  134046. ** More specifically, the returned buffer contains 1 varint for each
  134047. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  134048. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  134049. ** if the requested column contains "a b X c d X X" and the position-list
  134050. ** for 'X' is requested, the buffer returned may contain:
  134051. **
  134052. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  134053. **
  134054. ** This function works regardless of whether or not the phrase is deferred,
  134055. ** incremental, or neither.
  134056. */
  134057. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  134058. Fts3Cursor *pCsr, /* FTS3 cursor object */
  134059. Fts3Expr *pExpr, /* Phrase to return doclist for */
  134060. int iCol, /* Column to return position list for */
  134061. char **ppOut /* OUT: Pointer to position list */
  134062. ){
  134063. Fts3Phrase *pPhrase = pExpr->pPhrase;
  134064. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  134065. char *pIter;
  134066. int iThis;
  134067. sqlite3_int64 iDocid;
  134068. /* If this phrase is applies specifically to some column other than
  134069. ** column iCol, return a NULL pointer. */
  134070. *ppOut = 0;
  134071. assert( iCol>=0 && iCol<pTab->nColumn );
  134072. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  134073. return SQLITE_OK;
  134074. }
  134075. iDocid = pExpr->iDocid;
  134076. pIter = pPhrase->doclist.pList;
  134077. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  134078. int rc = SQLITE_OK;
  134079. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  134080. int bOr = 0;
  134081. u8 bTreeEof = 0;
  134082. Fts3Expr *p; /* Used to iterate from pExpr to root */
  134083. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  134084. int bMatch;
  134085. /* Check if this phrase descends from an OR expression node. If not,
  134086. ** return NULL. Otherwise, the entry that corresponds to docid
  134087. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  134088. ** tree that the node is part of has been marked as EOF, but the node
  134089. ** itself is not EOF, then it may point to an earlier entry. */
  134090. pNear = pExpr;
  134091. for(p=pExpr->pParent; p; p=p->pParent){
  134092. if( p->eType==FTSQUERY_OR ) bOr = 1;
  134093. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  134094. if( p->bEof ) bTreeEof = 1;
  134095. }
  134096. if( bOr==0 ) return SQLITE_OK;
  134097. /* This is the descendent of an OR node. In this case we cannot use
  134098. ** an incremental phrase. Load the entire doclist for the phrase
  134099. ** into memory in this case. */
  134100. if( pPhrase->bIncr ){
  134101. int bEofSave = pNear->bEof;
  134102. fts3EvalRestart(pCsr, pNear, &rc);
  134103. while( rc==SQLITE_OK && !pNear->bEof ){
  134104. fts3EvalNextRow(pCsr, pNear, &rc);
  134105. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  134106. }
  134107. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  134108. }
  134109. if( bTreeEof ){
  134110. while( rc==SQLITE_OK && !pNear->bEof ){
  134111. fts3EvalNextRow(pCsr, pNear, &rc);
  134112. }
  134113. }
  134114. if( rc!=SQLITE_OK ) return rc;
  134115. bMatch = 1;
  134116. for(p=pNear; p; p=p->pLeft){
  134117. u8 bEof = 0;
  134118. Fts3Expr *pTest = p;
  134119. Fts3Phrase *pPh;
  134120. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  134121. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  134122. assert( pTest->eType==FTSQUERY_PHRASE );
  134123. pPh = pTest->pPhrase;
  134124. pIter = pPh->pOrPoslist;
  134125. iDocid = pPh->iOrDocid;
  134126. if( pCsr->bDesc==bDescDoclist ){
  134127. bEof = !pPh->doclist.nAll ||
  134128. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  134129. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  134130. sqlite3Fts3DoclistNext(
  134131. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  134132. &pIter, &iDocid, &bEof
  134133. );
  134134. }
  134135. }else{
  134136. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  134137. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  134138. int dummy;
  134139. sqlite3Fts3DoclistPrev(
  134140. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  134141. &pIter, &iDocid, &dummy, &bEof
  134142. );
  134143. }
  134144. }
  134145. pPh->pOrPoslist = pIter;
  134146. pPh->iOrDocid = iDocid;
  134147. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  134148. }
  134149. if( bMatch ){
  134150. pIter = pPhrase->pOrPoslist;
  134151. }else{
  134152. pIter = 0;
  134153. }
  134154. }
  134155. if( pIter==0 ) return SQLITE_OK;
  134156. if( *pIter==0x01 ){
  134157. pIter++;
  134158. pIter += fts3GetVarint32(pIter, &iThis);
  134159. }else{
  134160. iThis = 0;
  134161. }
  134162. while( iThis<iCol ){
  134163. fts3ColumnlistCopy(0, &pIter);
  134164. if( *pIter==0x00 ) return SQLITE_OK;
  134165. pIter++;
  134166. pIter += fts3GetVarint32(pIter, &iThis);
  134167. }
  134168. if( *pIter==0x00 ){
  134169. pIter = 0;
  134170. }
  134171. *ppOut = ((iCol==iThis)?pIter:0);
  134172. return SQLITE_OK;
  134173. }
  134174. /*
  134175. ** Free all components of the Fts3Phrase structure that were allocated by
  134176. ** the eval module. Specifically, this means to free:
  134177. **
  134178. ** * the contents of pPhrase->doclist, and
  134179. ** * any Fts3MultiSegReader objects held by phrase tokens.
  134180. */
  134181. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  134182. if( pPhrase ){
  134183. int i;
  134184. sqlite3_free(pPhrase->doclist.aAll);
  134185. fts3EvalInvalidatePoslist(pPhrase);
  134186. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  134187. for(i=0; i<pPhrase->nToken; i++){
  134188. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  134189. pPhrase->aToken[i].pSegcsr = 0;
  134190. }
  134191. }
  134192. }
  134193. /*
  134194. ** Return SQLITE_CORRUPT_VTAB.
  134195. */
  134196. #ifdef SQLITE_DEBUG
  134197. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  134198. return SQLITE_CORRUPT_VTAB;
  134199. }
  134200. #endif
  134201. #if !SQLITE_CORE
  134202. /*
  134203. ** Initialize API pointer table, if required.
  134204. */
  134205. #ifdef _WIN32
  134206. __declspec(dllexport)
  134207. #endif
  134208. SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
  134209. sqlite3 *db,
  134210. char **pzErrMsg,
  134211. const sqlite3_api_routines *pApi
  134212. ){
  134213. SQLITE_EXTENSION_INIT2(pApi)
  134214. return sqlite3Fts3Init(db);
  134215. }
  134216. #endif
  134217. #endif
  134218. /************** End of fts3.c ************************************************/
  134219. /************** Begin file fts3_aux.c ****************************************/
  134220. /*
  134221. ** 2011 Jan 27
  134222. **
  134223. ** The author disclaims copyright to this source code. In place of
  134224. ** a legal notice, here is a blessing:
  134225. **
  134226. ** May you do good and not evil.
  134227. ** May you find forgiveness for yourself and forgive others.
  134228. ** May you share freely, never taking more than you give.
  134229. **
  134230. ******************************************************************************
  134231. **
  134232. */
  134233. /* #include "fts3Int.h" */
  134234. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  134235. /* #include <string.h> */
  134236. /* #include <assert.h> */
  134237. typedef struct Fts3auxTable Fts3auxTable;
  134238. typedef struct Fts3auxCursor Fts3auxCursor;
  134239. struct Fts3auxTable {
  134240. sqlite3_vtab base; /* Base class used by SQLite core */
  134241. Fts3Table *pFts3Tab;
  134242. };
  134243. struct Fts3auxCursor {
  134244. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  134245. Fts3MultiSegReader csr; /* Must be right after "base" */
  134246. Fts3SegFilter filter;
  134247. char *zStop;
  134248. int nStop; /* Byte-length of string zStop */
  134249. int iLangid; /* Language id to query */
  134250. int isEof; /* True if cursor is at EOF */
  134251. sqlite3_int64 iRowid; /* Current rowid */
  134252. int iCol; /* Current value of 'col' column */
  134253. int nStat; /* Size of aStat[] array */
  134254. struct Fts3auxColstats {
  134255. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  134256. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  134257. } *aStat;
  134258. };
  134259. /*
  134260. ** Schema of the terms table.
  134261. */
  134262. #define FTS3_AUX_SCHEMA \
  134263. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  134264. /*
  134265. ** This function does all the work for both the xConnect and xCreate methods.
  134266. ** These tables have no persistent representation of their own, so xConnect
  134267. ** and xCreate are identical operations.
  134268. */
  134269. static int fts3auxConnectMethod(
  134270. sqlite3 *db, /* Database connection */
  134271. void *pUnused, /* Unused */
  134272. int argc, /* Number of elements in argv array */
  134273. const char * const *argv, /* xCreate/xConnect argument array */
  134274. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  134275. char **pzErr /* OUT: sqlite3_malloc'd error message */
  134276. ){
  134277. char const *zDb; /* Name of database (e.g. "main") */
  134278. char const *zFts3; /* Name of fts3 table */
  134279. int nDb; /* Result of strlen(zDb) */
  134280. int nFts3; /* Result of strlen(zFts3) */
  134281. int nByte; /* Bytes of space to allocate here */
  134282. int rc; /* value returned by declare_vtab() */
  134283. Fts3auxTable *p; /* Virtual table object to return */
  134284. UNUSED_PARAMETER(pUnused);
  134285. /* The user should invoke this in one of two forms:
  134286. **
  134287. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  134288. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  134289. */
  134290. if( argc!=4 && argc!=5 ) goto bad_args;
  134291. zDb = argv[1];
  134292. nDb = (int)strlen(zDb);
  134293. if( argc==5 ){
  134294. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  134295. zDb = argv[3];
  134296. nDb = (int)strlen(zDb);
  134297. zFts3 = argv[4];
  134298. }else{
  134299. goto bad_args;
  134300. }
  134301. }else{
  134302. zFts3 = argv[3];
  134303. }
  134304. nFts3 = (int)strlen(zFts3);
  134305. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  134306. if( rc!=SQLITE_OK ) return rc;
  134307. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  134308. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  134309. if( !p ) return SQLITE_NOMEM;
  134310. memset(p, 0, nByte);
  134311. p->pFts3Tab = (Fts3Table *)&p[1];
  134312. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  134313. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  134314. p->pFts3Tab->db = db;
  134315. p->pFts3Tab->nIndex = 1;
  134316. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  134317. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  134318. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  134319. *ppVtab = (sqlite3_vtab *)p;
  134320. return SQLITE_OK;
  134321. bad_args:
  134322. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  134323. return SQLITE_ERROR;
  134324. }
  134325. /*
  134326. ** This function does the work for both the xDisconnect and xDestroy methods.
  134327. ** These tables have no persistent representation of their own, so xDisconnect
  134328. ** and xDestroy are identical operations.
  134329. */
  134330. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  134331. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  134332. Fts3Table *pFts3 = p->pFts3Tab;
  134333. int i;
  134334. /* Free any prepared statements held */
  134335. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  134336. sqlite3_finalize(pFts3->aStmt[i]);
  134337. }
  134338. sqlite3_free(pFts3->zSegmentsTbl);
  134339. sqlite3_free(p);
  134340. return SQLITE_OK;
  134341. }
  134342. #define FTS4AUX_EQ_CONSTRAINT 1
  134343. #define FTS4AUX_GE_CONSTRAINT 2
  134344. #define FTS4AUX_LE_CONSTRAINT 4
  134345. /*
  134346. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  134347. */
  134348. static int fts3auxBestIndexMethod(
  134349. sqlite3_vtab *pVTab,
  134350. sqlite3_index_info *pInfo
  134351. ){
  134352. int i;
  134353. int iEq = -1;
  134354. int iGe = -1;
  134355. int iLe = -1;
  134356. int iLangid = -1;
  134357. int iNext = 1; /* Next free argvIndex value */
  134358. UNUSED_PARAMETER(pVTab);
  134359. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  134360. if( pInfo->nOrderBy==1
  134361. && pInfo->aOrderBy[0].iColumn==0
  134362. && pInfo->aOrderBy[0].desc==0
  134363. ){
  134364. pInfo->orderByConsumed = 1;
  134365. }
  134366. /* Search for equality and range constraints on the "term" column.
  134367. ** And equality constraints on the hidden "languageid" column. */
  134368. for(i=0; i<pInfo->nConstraint; i++){
  134369. if( pInfo->aConstraint[i].usable ){
  134370. int op = pInfo->aConstraint[i].op;
  134371. int iCol = pInfo->aConstraint[i].iColumn;
  134372. if( iCol==0 ){
  134373. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  134374. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  134375. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  134376. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  134377. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  134378. }
  134379. if( iCol==4 ){
  134380. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  134381. }
  134382. }
  134383. }
  134384. if( iEq>=0 ){
  134385. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  134386. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  134387. pInfo->estimatedCost = 5;
  134388. }else{
  134389. pInfo->idxNum = 0;
  134390. pInfo->estimatedCost = 20000;
  134391. if( iGe>=0 ){
  134392. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  134393. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  134394. pInfo->estimatedCost /= 2;
  134395. }
  134396. if( iLe>=0 ){
  134397. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  134398. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  134399. pInfo->estimatedCost /= 2;
  134400. }
  134401. }
  134402. if( iLangid>=0 ){
  134403. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  134404. pInfo->estimatedCost--;
  134405. }
  134406. return SQLITE_OK;
  134407. }
  134408. /*
  134409. ** xOpen - Open a cursor.
  134410. */
  134411. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  134412. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  134413. UNUSED_PARAMETER(pVTab);
  134414. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  134415. if( !pCsr ) return SQLITE_NOMEM;
  134416. memset(pCsr, 0, sizeof(Fts3auxCursor));
  134417. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  134418. return SQLITE_OK;
  134419. }
  134420. /*
  134421. ** xClose - Close a cursor.
  134422. */
  134423. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  134424. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  134425. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  134426. sqlite3Fts3SegmentsClose(pFts3);
  134427. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  134428. sqlite3_free((void *)pCsr->filter.zTerm);
  134429. sqlite3_free(pCsr->zStop);
  134430. sqlite3_free(pCsr->aStat);
  134431. sqlite3_free(pCsr);
  134432. return SQLITE_OK;
  134433. }
  134434. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  134435. if( nSize>pCsr->nStat ){
  134436. struct Fts3auxColstats *aNew;
  134437. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  134438. sizeof(struct Fts3auxColstats) * nSize
  134439. );
  134440. if( aNew==0 ) return SQLITE_NOMEM;
  134441. memset(&aNew[pCsr->nStat], 0,
  134442. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  134443. );
  134444. pCsr->aStat = aNew;
  134445. pCsr->nStat = nSize;
  134446. }
  134447. return SQLITE_OK;
  134448. }
  134449. /*
  134450. ** xNext - Advance the cursor to the next row, if any.
  134451. */
  134452. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  134453. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  134454. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  134455. int rc;
  134456. /* Increment our pretend rowid value. */
  134457. pCsr->iRowid++;
  134458. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  134459. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  134460. }
  134461. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  134462. if( rc==SQLITE_ROW ){
  134463. int i = 0;
  134464. int nDoclist = pCsr->csr.nDoclist;
  134465. char *aDoclist = pCsr->csr.aDoclist;
  134466. int iCol;
  134467. int eState = 0;
  134468. if( pCsr->zStop ){
  134469. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  134470. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  134471. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  134472. pCsr->isEof = 1;
  134473. return SQLITE_OK;
  134474. }
  134475. }
  134476. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  134477. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  134478. iCol = 0;
  134479. while( i<nDoclist ){
  134480. sqlite3_int64 v = 0;
  134481. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  134482. switch( eState ){
  134483. /* State 0. In this state the integer just read was a docid. */
  134484. case 0:
  134485. pCsr->aStat[0].nDoc++;
  134486. eState = 1;
  134487. iCol = 0;
  134488. break;
  134489. /* State 1. In this state we are expecting either a 1, indicating
  134490. ** that the following integer will be a column number, or the
  134491. ** start of a position list for column 0.
  134492. **
  134493. ** The only difference between state 1 and state 2 is that if the
  134494. ** integer encountered in state 1 is not 0 or 1, then we need to
  134495. ** increment the column 0 "nDoc" count for this term.
  134496. */
  134497. case 1:
  134498. assert( iCol==0 );
  134499. if( v>1 ){
  134500. pCsr->aStat[1].nDoc++;
  134501. }
  134502. eState = 2;
  134503. /* fall through */
  134504. case 2:
  134505. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  134506. eState = 0;
  134507. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  134508. eState = 3;
  134509. }else{ /* 2 or greater. A position. */
  134510. pCsr->aStat[iCol+1].nOcc++;
  134511. pCsr->aStat[0].nOcc++;
  134512. }
  134513. break;
  134514. /* State 3. The integer just read is a column number. */
  134515. default: assert( eState==3 );
  134516. iCol = (int)v;
  134517. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  134518. pCsr->aStat[iCol+1].nDoc++;
  134519. eState = 2;
  134520. break;
  134521. }
  134522. }
  134523. pCsr->iCol = 0;
  134524. rc = SQLITE_OK;
  134525. }else{
  134526. pCsr->isEof = 1;
  134527. }
  134528. return rc;
  134529. }
  134530. /*
  134531. ** xFilter - Initialize a cursor to point at the start of its data.
  134532. */
  134533. static int fts3auxFilterMethod(
  134534. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  134535. int idxNum, /* Strategy index */
  134536. const char *idxStr, /* Unused */
  134537. int nVal, /* Number of elements in apVal */
  134538. sqlite3_value **apVal /* Arguments for the indexing scheme */
  134539. ){
  134540. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  134541. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  134542. int rc;
  134543. int isScan = 0;
  134544. int iLangVal = 0; /* Language id to query */
  134545. int iEq = -1; /* Index of term=? value in apVal */
  134546. int iGe = -1; /* Index of term>=? value in apVal */
  134547. int iLe = -1; /* Index of term<=? value in apVal */
  134548. int iLangid = -1; /* Index of languageid=? value in apVal */
  134549. int iNext = 0;
  134550. UNUSED_PARAMETER(nVal);
  134551. UNUSED_PARAMETER(idxStr);
  134552. assert( idxStr==0 );
  134553. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  134554. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  134555. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  134556. );
  134557. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  134558. iEq = iNext++;
  134559. }else{
  134560. isScan = 1;
  134561. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  134562. iGe = iNext++;
  134563. }
  134564. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  134565. iLe = iNext++;
  134566. }
  134567. }
  134568. if( iNext<nVal ){
  134569. iLangid = iNext++;
  134570. }
  134571. /* In case this cursor is being reused, close and zero it. */
  134572. testcase(pCsr->filter.zTerm);
  134573. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  134574. sqlite3_free((void *)pCsr->filter.zTerm);
  134575. sqlite3_free(pCsr->aStat);
  134576. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  134577. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  134578. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  134579. if( iEq>=0 || iGe>=0 ){
  134580. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  134581. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  134582. if( zStr ){
  134583. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  134584. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  134585. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  134586. }
  134587. }
  134588. if( iLe>=0 ){
  134589. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  134590. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  134591. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  134592. }
  134593. if( iLangid>=0 ){
  134594. iLangVal = sqlite3_value_int(apVal[iLangid]);
  134595. /* If the user specified a negative value for the languageid, use zero
  134596. ** instead. This works, as the "languageid=?" constraint will also
  134597. ** be tested by the VDBE layer. The test will always be false (since
  134598. ** this module will not return a row with a negative languageid), and
  134599. ** so the overall query will return zero rows. */
  134600. if( iLangVal<0 ) iLangVal = 0;
  134601. }
  134602. pCsr->iLangid = iLangVal;
  134603. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  134604. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  134605. );
  134606. if( rc==SQLITE_OK ){
  134607. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  134608. }
  134609. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  134610. return rc;
  134611. }
  134612. /*
  134613. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  134614. */
  134615. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  134616. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  134617. return pCsr->isEof;
  134618. }
  134619. /*
  134620. ** xColumn - Return a column value.
  134621. */
  134622. static int fts3auxColumnMethod(
  134623. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  134624. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  134625. int iCol /* Index of column to read value from */
  134626. ){
  134627. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  134628. assert( p->isEof==0 );
  134629. switch( iCol ){
  134630. case 0: /* term */
  134631. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  134632. break;
  134633. case 1: /* col */
  134634. if( p->iCol ){
  134635. sqlite3_result_int(pCtx, p->iCol-1);
  134636. }else{
  134637. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  134638. }
  134639. break;
  134640. case 2: /* documents */
  134641. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  134642. break;
  134643. case 3: /* occurrences */
  134644. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  134645. break;
  134646. default: /* languageid */
  134647. assert( iCol==4 );
  134648. sqlite3_result_int(pCtx, p->iLangid);
  134649. break;
  134650. }
  134651. return SQLITE_OK;
  134652. }
  134653. /*
  134654. ** xRowid - Return the current rowid for the cursor.
  134655. */
  134656. static int fts3auxRowidMethod(
  134657. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  134658. sqlite_int64 *pRowid /* OUT: Rowid value */
  134659. ){
  134660. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  134661. *pRowid = pCsr->iRowid;
  134662. return SQLITE_OK;
  134663. }
  134664. /*
  134665. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  134666. ** if successful or an error code if sqlite3_create_module() fails.
  134667. */
  134668. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  134669. static const sqlite3_module fts3aux_module = {
  134670. 0, /* iVersion */
  134671. fts3auxConnectMethod, /* xCreate */
  134672. fts3auxConnectMethod, /* xConnect */
  134673. fts3auxBestIndexMethod, /* xBestIndex */
  134674. fts3auxDisconnectMethod, /* xDisconnect */
  134675. fts3auxDisconnectMethod, /* xDestroy */
  134676. fts3auxOpenMethod, /* xOpen */
  134677. fts3auxCloseMethod, /* xClose */
  134678. fts3auxFilterMethod, /* xFilter */
  134679. fts3auxNextMethod, /* xNext */
  134680. fts3auxEofMethod, /* xEof */
  134681. fts3auxColumnMethod, /* xColumn */
  134682. fts3auxRowidMethod, /* xRowid */
  134683. 0, /* xUpdate */
  134684. 0, /* xBegin */
  134685. 0, /* xSync */
  134686. 0, /* xCommit */
  134687. 0, /* xRollback */
  134688. 0, /* xFindFunction */
  134689. 0, /* xRename */
  134690. 0, /* xSavepoint */
  134691. 0, /* xRelease */
  134692. 0 /* xRollbackTo */
  134693. };
  134694. int rc; /* Return code */
  134695. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  134696. return rc;
  134697. }
  134698. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  134699. /************** End of fts3_aux.c ********************************************/
  134700. /************** Begin file fts3_expr.c ***************************************/
  134701. /*
  134702. ** 2008 Nov 28
  134703. **
  134704. ** The author disclaims copyright to this source code. In place of
  134705. ** a legal notice, here is a blessing:
  134706. **
  134707. ** May you do good and not evil.
  134708. ** May you find forgiveness for yourself and forgive others.
  134709. ** May you share freely, never taking more than you give.
  134710. **
  134711. ******************************************************************************
  134712. **
  134713. ** This module contains code that implements a parser for fts3 query strings
  134714. ** (the right-hand argument to the MATCH operator). Because the supported
  134715. ** syntax is relatively simple, the whole tokenizer/parser system is
  134716. ** hand-coded.
  134717. */
  134718. /* #include "fts3Int.h" */
  134719. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  134720. /*
  134721. ** By default, this module parses the legacy syntax that has been
  134722. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  134723. ** is defined, then it uses the new syntax. The differences between
  134724. ** the new and the old syntaxes are:
  134725. **
  134726. ** a) The new syntax supports parenthesis. The old does not.
  134727. **
  134728. ** b) The new syntax supports the AND and NOT operators. The old does not.
  134729. **
  134730. ** c) The old syntax supports the "-" token qualifier. This is not
  134731. ** supported by the new syntax (it is replaced by the NOT operator).
  134732. **
  134733. ** d) When using the old syntax, the OR operator has a greater precedence
  134734. ** than an implicit AND. When using the new, both implicity and explicit
  134735. ** AND operators have a higher precedence than OR.
  134736. **
  134737. ** If compiled with SQLITE_TEST defined, then this module exports the
  134738. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  134739. ** to zero causes the module to use the old syntax. If it is set to
  134740. ** non-zero the new syntax is activated. This is so both syntaxes can
  134741. ** be tested using a single build of testfixture.
  134742. **
  134743. ** The following describes the syntax supported by the fts3 MATCH
  134744. ** operator in a similar format to that used by the lemon parser
  134745. ** generator. This module does not use actually lemon, it uses a
  134746. ** custom parser.
  134747. **
  134748. ** query ::= andexpr (OR andexpr)*.
  134749. **
  134750. ** andexpr ::= notexpr (AND? notexpr)*.
  134751. **
  134752. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  134753. ** notexpr ::= LP query RP.
  134754. **
  134755. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  134756. **
  134757. ** distance_opt ::= .
  134758. ** distance_opt ::= / INTEGER.
  134759. **
  134760. ** phrase ::= TOKEN.
  134761. ** phrase ::= COLUMN:TOKEN.
  134762. ** phrase ::= "TOKEN TOKEN TOKEN...".
  134763. */
  134764. #ifdef SQLITE_TEST
  134765. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  134766. #else
  134767. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  134768. # define sqlite3_fts3_enable_parentheses 1
  134769. # else
  134770. # define sqlite3_fts3_enable_parentheses 0
  134771. # endif
  134772. #endif
  134773. /*
  134774. ** Default span for NEAR operators.
  134775. */
  134776. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  134777. /* #include <string.h> */
  134778. /* #include <assert.h> */
  134779. /*
  134780. ** isNot:
  134781. ** This variable is used by function getNextNode(). When getNextNode() is
  134782. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  134783. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  134784. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  134785. ** zero.
  134786. */
  134787. typedef struct ParseContext ParseContext;
  134788. struct ParseContext {
  134789. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  134790. int iLangid; /* Language id used with tokenizer */
  134791. const char **azCol; /* Array of column names for fts3 table */
  134792. int bFts4; /* True to allow FTS4-only syntax */
  134793. int nCol; /* Number of entries in azCol[] */
  134794. int iDefaultCol; /* Default column to query */
  134795. int isNot; /* True if getNextNode() sees a unary - */
  134796. sqlite3_context *pCtx; /* Write error message here */
  134797. int nNest; /* Number of nested brackets */
  134798. };
  134799. /*
  134800. ** This function is equivalent to the standard isspace() function.
  134801. **
  134802. ** The standard isspace() can be awkward to use safely, because although it
  134803. ** is defined to accept an argument of type int, its behavior when passed
  134804. ** an integer that falls outside of the range of the unsigned char type
  134805. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  134806. ** is defined to accept an argument of type char, and always returns 0 for
  134807. ** any values that fall outside of the range of the unsigned char type (i.e.
  134808. ** negative values).
  134809. */
  134810. static int fts3isspace(char c){
  134811. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  134812. }
  134813. /*
  134814. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  134815. ** zero the memory before returning a pointer to it. If unsuccessful,
  134816. ** return NULL.
  134817. */
  134818. static void *fts3MallocZero(int nByte){
  134819. void *pRet = sqlite3_malloc(nByte);
  134820. if( pRet ) memset(pRet, 0, nByte);
  134821. return pRet;
  134822. }
  134823. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  134824. sqlite3_tokenizer *pTokenizer,
  134825. int iLangid,
  134826. const char *z,
  134827. int n,
  134828. sqlite3_tokenizer_cursor **ppCsr
  134829. ){
  134830. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  134831. sqlite3_tokenizer_cursor *pCsr = 0;
  134832. int rc;
  134833. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  134834. assert( rc==SQLITE_OK || pCsr==0 );
  134835. if( rc==SQLITE_OK ){
  134836. pCsr->pTokenizer = pTokenizer;
  134837. if( pModule->iVersion>=1 ){
  134838. rc = pModule->xLanguageid(pCsr, iLangid);
  134839. if( rc!=SQLITE_OK ){
  134840. pModule->xClose(pCsr);
  134841. pCsr = 0;
  134842. }
  134843. }
  134844. }
  134845. *ppCsr = pCsr;
  134846. return rc;
  134847. }
  134848. /*
  134849. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  134850. ** call fts3ExprParse(). So this forward declaration is required.
  134851. */
  134852. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  134853. /*
  134854. ** Extract the next token from buffer z (length n) using the tokenizer
  134855. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  134856. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  134857. ** single token and set *ppExpr to point to it. If the end of the buffer is
  134858. ** reached before a token is found, set *ppExpr to zero. It is the
  134859. ** responsibility of the caller to eventually deallocate the allocated
  134860. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  134861. **
  134862. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  134863. ** fails.
  134864. */
  134865. static int getNextToken(
  134866. ParseContext *pParse, /* fts3 query parse context */
  134867. int iCol, /* Value for Fts3Phrase.iColumn */
  134868. const char *z, int n, /* Input string */
  134869. Fts3Expr **ppExpr, /* OUT: expression */
  134870. int *pnConsumed /* OUT: Number of bytes consumed */
  134871. ){
  134872. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  134873. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  134874. int rc;
  134875. sqlite3_tokenizer_cursor *pCursor;
  134876. Fts3Expr *pRet = 0;
  134877. int i = 0;
  134878. /* Set variable i to the maximum number of bytes of input to tokenize. */
  134879. for(i=0; i<n; i++){
  134880. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  134881. if( z[i]=='"' ) break;
  134882. }
  134883. *pnConsumed = i;
  134884. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  134885. if( rc==SQLITE_OK ){
  134886. const char *zToken;
  134887. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  134888. int nByte; /* total space to allocate */
  134889. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  134890. if( rc==SQLITE_OK ){
  134891. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  134892. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  134893. if( !pRet ){
  134894. rc = SQLITE_NOMEM;
  134895. }else{
  134896. pRet->eType = FTSQUERY_PHRASE;
  134897. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  134898. pRet->pPhrase->nToken = 1;
  134899. pRet->pPhrase->iColumn = iCol;
  134900. pRet->pPhrase->aToken[0].n = nToken;
  134901. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  134902. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  134903. if( iEnd<n && z[iEnd]=='*' ){
  134904. pRet->pPhrase->aToken[0].isPrefix = 1;
  134905. iEnd++;
  134906. }
  134907. while( 1 ){
  134908. if( !sqlite3_fts3_enable_parentheses
  134909. && iStart>0 && z[iStart-1]=='-'
  134910. ){
  134911. pParse->isNot = 1;
  134912. iStart--;
  134913. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  134914. pRet->pPhrase->aToken[0].bFirst = 1;
  134915. iStart--;
  134916. }else{
  134917. break;
  134918. }
  134919. }
  134920. }
  134921. *pnConsumed = iEnd;
  134922. }else if( i && rc==SQLITE_DONE ){
  134923. rc = SQLITE_OK;
  134924. }
  134925. pModule->xClose(pCursor);
  134926. }
  134927. *ppExpr = pRet;
  134928. return rc;
  134929. }
  134930. /*
  134931. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  134932. ** then free the old allocation.
  134933. */
  134934. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  134935. void *pRet = sqlite3_realloc(pOrig, nNew);
  134936. if( !pRet ){
  134937. sqlite3_free(pOrig);
  134938. }
  134939. return pRet;
  134940. }
  134941. /*
  134942. ** Buffer zInput, length nInput, contains the contents of a quoted string
  134943. ** that appeared as part of an fts3 query expression. Neither quote character
  134944. ** is included in the buffer. This function attempts to tokenize the entire
  134945. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  134946. ** containing the results.
  134947. **
  134948. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  134949. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  134950. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  134951. ** to 0.
  134952. */
  134953. static int getNextString(
  134954. ParseContext *pParse, /* fts3 query parse context */
  134955. const char *zInput, int nInput, /* Input string */
  134956. Fts3Expr **ppExpr /* OUT: expression */
  134957. ){
  134958. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  134959. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  134960. int rc;
  134961. Fts3Expr *p = 0;
  134962. sqlite3_tokenizer_cursor *pCursor = 0;
  134963. char *zTemp = 0;
  134964. int nTemp = 0;
  134965. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  134966. int nToken = 0;
  134967. /* The final Fts3Expr data structure, including the Fts3Phrase,
  134968. ** Fts3PhraseToken structures token buffers are all stored as a single
  134969. ** allocation so that the expression can be freed with a single call to
  134970. ** sqlite3_free(). Setting this up requires a two pass approach.
  134971. **
  134972. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  134973. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  134974. ** to assemble data in two dynamic buffers:
  134975. **
  134976. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  134977. ** structure, followed by the array of Fts3PhraseToken
  134978. ** structures. This pass only populates the Fts3PhraseToken array.
  134979. **
  134980. ** Buffer zTemp: Contains copies of all tokens.
  134981. **
  134982. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  134983. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  134984. ** structures.
  134985. */
  134986. rc = sqlite3Fts3OpenTokenizer(
  134987. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  134988. if( rc==SQLITE_OK ){
  134989. int ii;
  134990. for(ii=0; rc==SQLITE_OK; ii++){
  134991. const char *zByte;
  134992. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  134993. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  134994. if( rc==SQLITE_OK ){
  134995. Fts3PhraseToken *pToken;
  134996. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  134997. if( !p ) goto no_mem;
  134998. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  134999. if( !zTemp ) goto no_mem;
  135000. assert( nToken==ii );
  135001. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  135002. memset(pToken, 0, sizeof(Fts3PhraseToken));
  135003. memcpy(&zTemp[nTemp], zByte, nByte);
  135004. nTemp += nByte;
  135005. pToken->n = nByte;
  135006. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  135007. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  135008. nToken = ii+1;
  135009. }
  135010. }
  135011. pModule->xClose(pCursor);
  135012. pCursor = 0;
  135013. }
  135014. if( rc==SQLITE_DONE ){
  135015. int jj;
  135016. char *zBuf = 0;
  135017. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  135018. if( !p ) goto no_mem;
  135019. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  135020. p->eType = FTSQUERY_PHRASE;
  135021. p->pPhrase = (Fts3Phrase *)&p[1];
  135022. p->pPhrase->iColumn = pParse->iDefaultCol;
  135023. p->pPhrase->nToken = nToken;
  135024. zBuf = (char *)&p->pPhrase->aToken[nToken];
  135025. if( zTemp ){
  135026. memcpy(zBuf, zTemp, nTemp);
  135027. sqlite3_free(zTemp);
  135028. }else{
  135029. assert( nTemp==0 );
  135030. }
  135031. for(jj=0; jj<p->pPhrase->nToken; jj++){
  135032. p->pPhrase->aToken[jj].z = zBuf;
  135033. zBuf += p->pPhrase->aToken[jj].n;
  135034. }
  135035. rc = SQLITE_OK;
  135036. }
  135037. *ppExpr = p;
  135038. return rc;
  135039. no_mem:
  135040. if( pCursor ){
  135041. pModule->xClose(pCursor);
  135042. }
  135043. sqlite3_free(zTemp);
  135044. sqlite3_free(p);
  135045. *ppExpr = 0;
  135046. return SQLITE_NOMEM;
  135047. }
  135048. /*
  135049. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  135050. ** structure, or set to 0 if the end of the input buffer is reached.
  135051. **
  135052. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  135053. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  135054. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  135055. */
  135056. static int getNextNode(
  135057. ParseContext *pParse, /* fts3 query parse context */
  135058. const char *z, int n, /* Input string */
  135059. Fts3Expr **ppExpr, /* OUT: expression */
  135060. int *pnConsumed /* OUT: Number of bytes consumed */
  135061. ){
  135062. static const struct Fts3Keyword {
  135063. char *z; /* Keyword text */
  135064. unsigned char n; /* Length of the keyword */
  135065. unsigned char parenOnly; /* Only valid in paren mode */
  135066. unsigned char eType; /* Keyword code */
  135067. } aKeyword[] = {
  135068. { "OR" , 2, 0, FTSQUERY_OR },
  135069. { "AND", 3, 1, FTSQUERY_AND },
  135070. { "NOT", 3, 1, FTSQUERY_NOT },
  135071. { "NEAR", 4, 0, FTSQUERY_NEAR }
  135072. };
  135073. int ii;
  135074. int iCol;
  135075. int iColLen;
  135076. int rc;
  135077. Fts3Expr *pRet = 0;
  135078. const char *zInput = z;
  135079. int nInput = n;
  135080. pParse->isNot = 0;
  135081. /* Skip over any whitespace before checking for a keyword, an open or
  135082. ** close bracket, or a quoted string.
  135083. */
  135084. while( nInput>0 && fts3isspace(*zInput) ){
  135085. nInput--;
  135086. zInput++;
  135087. }
  135088. if( nInput==0 ){
  135089. return SQLITE_DONE;
  135090. }
  135091. /* See if we are dealing with a keyword. */
  135092. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  135093. const struct Fts3Keyword *pKey = &aKeyword[ii];
  135094. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  135095. continue;
  135096. }
  135097. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  135098. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  135099. int nKey = pKey->n;
  135100. char cNext;
  135101. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  135102. if( pKey->eType==FTSQUERY_NEAR ){
  135103. assert( nKey==4 );
  135104. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  135105. nNear = 0;
  135106. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  135107. nNear = nNear * 10 + (zInput[nKey] - '0');
  135108. }
  135109. }
  135110. }
  135111. /* At this point this is probably a keyword. But for that to be true,
  135112. ** the next byte must contain either whitespace, an open or close
  135113. ** parenthesis, a quote character, or EOF.
  135114. */
  135115. cNext = zInput[nKey];
  135116. if( fts3isspace(cNext)
  135117. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  135118. ){
  135119. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  135120. if( !pRet ){
  135121. return SQLITE_NOMEM;
  135122. }
  135123. pRet->eType = pKey->eType;
  135124. pRet->nNear = nNear;
  135125. *ppExpr = pRet;
  135126. *pnConsumed = (int)((zInput - z) + nKey);
  135127. return SQLITE_OK;
  135128. }
  135129. /* Turns out that wasn't a keyword after all. This happens if the
  135130. ** user has supplied a token such as "ORacle". Continue.
  135131. */
  135132. }
  135133. }
  135134. /* See if we are dealing with a quoted phrase. If this is the case, then
  135135. ** search for the closing quote and pass the whole string to getNextString()
  135136. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  135137. ** a quote character embedded in a string.
  135138. */
  135139. if( *zInput=='"' ){
  135140. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  135141. *pnConsumed = (int)((zInput - z) + ii + 1);
  135142. if( ii==nInput ){
  135143. return SQLITE_ERROR;
  135144. }
  135145. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  135146. }
  135147. if( sqlite3_fts3_enable_parentheses ){
  135148. if( *zInput=='(' ){
  135149. int nConsumed = 0;
  135150. pParse->nNest++;
  135151. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  135152. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  135153. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  135154. return rc;
  135155. }else if( *zInput==')' ){
  135156. pParse->nNest--;
  135157. *pnConsumed = (int)((zInput - z) + 1);
  135158. *ppExpr = 0;
  135159. return SQLITE_DONE;
  135160. }
  135161. }
  135162. /* If control flows to this point, this must be a regular token, or
  135163. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  135164. ** interface. Before doing so, figure out if there is an explicit
  135165. ** column specifier for the token.
  135166. **
  135167. ** TODO: Strangely, it is not possible to associate a column specifier
  135168. ** with a quoted phrase, only with a single token. Not sure if this was
  135169. ** an implementation artifact or an intentional decision when fts3 was
  135170. ** first implemented. Whichever it was, this module duplicates the
  135171. ** limitation.
  135172. */
  135173. iCol = pParse->iDefaultCol;
  135174. iColLen = 0;
  135175. for(ii=0; ii<pParse->nCol; ii++){
  135176. const char *zStr = pParse->azCol[ii];
  135177. int nStr = (int)strlen(zStr);
  135178. if( nInput>nStr && zInput[nStr]==':'
  135179. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  135180. ){
  135181. iCol = ii;
  135182. iColLen = (int)((zInput - z) + nStr + 1);
  135183. break;
  135184. }
  135185. }
  135186. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  135187. *pnConsumed += iColLen;
  135188. return rc;
  135189. }
  135190. /*
  135191. ** The argument is an Fts3Expr structure for a binary operator (any type
  135192. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  135193. ** precedence of the operator. Lower values have a higher precedence (i.e.
  135194. ** group more tightly). For example, in the C language, the == operator
  135195. ** groups more tightly than ||, and would therefore have a higher precedence.
  135196. **
  135197. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  135198. ** is defined), the order of the operators in precedence from highest to
  135199. ** lowest is:
  135200. **
  135201. ** NEAR
  135202. ** NOT
  135203. ** AND (including implicit ANDs)
  135204. ** OR
  135205. **
  135206. ** Note that when using the old query syntax, the OR operator has a higher
  135207. ** precedence than the AND operator.
  135208. */
  135209. static int opPrecedence(Fts3Expr *p){
  135210. assert( p->eType!=FTSQUERY_PHRASE );
  135211. if( sqlite3_fts3_enable_parentheses ){
  135212. return p->eType;
  135213. }else if( p->eType==FTSQUERY_NEAR ){
  135214. return 1;
  135215. }else if( p->eType==FTSQUERY_OR ){
  135216. return 2;
  135217. }
  135218. assert( p->eType==FTSQUERY_AND );
  135219. return 3;
  135220. }
  135221. /*
  135222. ** Argument ppHead contains a pointer to the current head of a query
  135223. ** expression tree being parsed. pPrev is the expression node most recently
  135224. ** inserted into the tree. This function adds pNew, which is always a binary
  135225. ** operator node, into the expression tree based on the relative precedence
  135226. ** of pNew and the existing nodes of the tree. This may result in the head
  135227. ** of the tree changing, in which case *ppHead is set to the new root node.
  135228. */
  135229. static void insertBinaryOperator(
  135230. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  135231. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  135232. Fts3Expr *pNew /* New binary node to insert into expression tree */
  135233. ){
  135234. Fts3Expr *pSplit = pPrev;
  135235. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  135236. pSplit = pSplit->pParent;
  135237. }
  135238. if( pSplit->pParent ){
  135239. assert( pSplit->pParent->pRight==pSplit );
  135240. pSplit->pParent->pRight = pNew;
  135241. pNew->pParent = pSplit->pParent;
  135242. }else{
  135243. *ppHead = pNew;
  135244. }
  135245. pNew->pLeft = pSplit;
  135246. pSplit->pParent = pNew;
  135247. }
  135248. /*
  135249. ** Parse the fts3 query expression found in buffer z, length n. This function
  135250. ** returns either when the end of the buffer is reached or an unmatched
  135251. ** closing bracket - ')' - is encountered.
  135252. **
  135253. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  135254. ** parsed form of the expression and *pnConsumed is set to the number of
  135255. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  135256. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  135257. */
  135258. static int fts3ExprParse(
  135259. ParseContext *pParse, /* fts3 query parse context */
  135260. const char *z, int n, /* Text of MATCH query */
  135261. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  135262. int *pnConsumed /* OUT: Number of bytes consumed */
  135263. ){
  135264. Fts3Expr *pRet = 0;
  135265. Fts3Expr *pPrev = 0;
  135266. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  135267. int nIn = n;
  135268. const char *zIn = z;
  135269. int rc = SQLITE_OK;
  135270. int isRequirePhrase = 1;
  135271. while( rc==SQLITE_OK ){
  135272. Fts3Expr *p = 0;
  135273. int nByte = 0;
  135274. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  135275. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  135276. if( rc==SQLITE_OK ){
  135277. if( p ){
  135278. int isPhrase;
  135279. if( !sqlite3_fts3_enable_parentheses
  135280. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  135281. ){
  135282. /* Create an implicit NOT operator. */
  135283. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  135284. if( !pNot ){
  135285. sqlite3Fts3ExprFree(p);
  135286. rc = SQLITE_NOMEM;
  135287. goto exprparse_out;
  135288. }
  135289. pNot->eType = FTSQUERY_NOT;
  135290. pNot->pRight = p;
  135291. p->pParent = pNot;
  135292. if( pNotBranch ){
  135293. pNot->pLeft = pNotBranch;
  135294. pNotBranch->pParent = pNot;
  135295. }
  135296. pNotBranch = pNot;
  135297. p = pPrev;
  135298. }else{
  135299. int eType = p->eType;
  135300. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  135301. /* The isRequirePhrase variable is set to true if a phrase or
  135302. ** an expression contained in parenthesis is required. If a
  135303. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  135304. ** isRequirePhrase is set, this is a syntax error.
  135305. */
  135306. if( !isPhrase && isRequirePhrase ){
  135307. sqlite3Fts3ExprFree(p);
  135308. rc = SQLITE_ERROR;
  135309. goto exprparse_out;
  135310. }
  135311. if( isPhrase && !isRequirePhrase ){
  135312. /* Insert an implicit AND operator. */
  135313. Fts3Expr *pAnd;
  135314. assert( pRet && pPrev );
  135315. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  135316. if( !pAnd ){
  135317. sqlite3Fts3ExprFree(p);
  135318. rc = SQLITE_NOMEM;
  135319. goto exprparse_out;
  135320. }
  135321. pAnd->eType = FTSQUERY_AND;
  135322. insertBinaryOperator(&pRet, pPrev, pAnd);
  135323. pPrev = pAnd;
  135324. }
  135325. /* This test catches attempts to make either operand of a NEAR
  135326. ** operator something other than a phrase. For example, either of
  135327. ** the following:
  135328. **
  135329. ** (bracketed expression) NEAR phrase
  135330. ** phrase NEAR (bracketed expression)
  135331. **
  135332. ** Return an error in either case.
  135333. */
  135334. if( pPrev && (
  135335. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  135336. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  135337. )){
  135338. sqlite3Fts3ExprFree(p);
  135339. rc = SQLITE_ERROR;
  135340. goto exprparse_out;
  135341. }
  135342. if( isPhrase ){
  135343. if( pRet ){
  135344. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  135345. pPrev->pRight = p;
  135346. p->pParent = pPrev;
  135347. }else{
  135348. pRet = p;
  135349. }
  135350. }else{
  135351. insertBinaryOperator(&pRet, pPrev, p);
  135352. }
  135353. isRequirePhrase = !isPhrase;
  135354. }
  135355. pPrev = p;
  135356. }
  135357. assert( nByte>0 );
  135358. }
  135359. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  135360. nIn -= nByte;
  135361. zIn += nByte;
  135362. }
  135363. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  135364. rc = SQLITE_ERROR;
  135365. }
  135366. if( rc==SQLITE_DONE ){
  135367. rc = SQLITE_OK;
  135368. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  135369. if( !pRet ){
  135370. rc = SQLITE_ERROR;
  135371. }else{
  135372. Fts3Expr *pIter = pNotBranch;
  135373. while( pIter->pLeft ){
  135374. pIter = pIter->pLeft;
  135375. }
  135376. pIter->pLeft = pRet;
  135377. pRet->pParent = pIter;
  135378. pRet = pNotBranch;
  135379. }
  135380. }
  135381. }
  135382. *pnConsumed = n - nIn;
  135383. exprparse_out:
  135384. if( rc!=SQLITE_OK ){
  135385. sqlite3Fts3ExprFree(pRet);
  135386. sqlite3Fts3ExprFree(pNotBranch);
  135387. pRet = 0;
  135388. }
  135389. *ppExpr = pRet;
  135390. return rc;
  135391. }
  135392. /*
  135393. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  135394. ** as the only argument is more than nMaxDepth.
  135395. */
  135396. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  135397. int rc = SQLITE_OK;
  135398. if( p ){
  135399. if( nMaxDepth<0 ){
  135400. rc = SQLITE_TOOBIG;
  135401. }else{
  135402. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  135403. if( rc==SQLITE_OK ){
  135404. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  135405. }
  135406. }
  135407. }
  135408. return rc;
  135409. }
  135410. /*
  135411. ** This function attempts to transform the expression tree at (*pp) to
  135412. ** an equivalent but more balanced form. The tree is modified in place.
  135413. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  135414. ** new root expression node.
  135415. **
  135416. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  135417. **
  135418. ** Otherwise, if an error occurs, an SQLite error code is returned and
  135419. ** expression (*pp) freed.
  135420. */
  135421. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  135422. int rc = SQLITE_OK; /* Return code */
  135423. Fts3Expr *pRoot = *pp; /* Initial root node */
  135424. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  135425. int eType = pRoot->eType; /* Type of node in this tree */
  135426. if( nMaxDepth==0 ){
  135427. rc = SQLITE_ERROR;
  135428. }
  135429. if( rc==SQLITE_OK ){
  135430. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  135431. Fts3Expr **apLeaf;
  135432. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  135433. if( 0==apLeaf ){
  135434. rc = SQLITE_NOMEM;
  135435. }else{
  135436. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  135437. }
  135438. if( rc==SQLITE_OK ){
  135439. int i;
  135440. Fts3Expr *p;
  135441. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  135442. for(p=pRoot; p->eType==eType; p=p->pLeft){
  135443. assert( p->pParent==0 || p->pParent->pLeft==p );
  135444. assert( p->pLeft && p->pRight );
  135445. }
  135446. /* This loop runs once for each leaf in the tree of eType nodes. */
  135447. while( 1 ){
  135448. int iLvl;
  135449. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  135450. assert( pParent==0 || pParent->pLeft==p );
  135451. p->pParent = 0;
  135452. if( pParent ){
  135453. pParent->pLeft = 0;
  135454. }else{
  135455. pRoot = 0;
  135456. }
  135457. rc = fts3ExprBalance(&p, nMaxDepth-1);
  135458. if( rc!=SQLITE_OK ) break;
  135459. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  135460. if( apLeaf[iLvl]==0 ){
  135461. apLeaf[iLvl] = p;
  135462. p = 0;
  135463. }else{
  135464. assert( pFree );
  135465. pFree->pLeft = apLeaf[iLvl];
  135466. pFree->pRight = p;
  135467. pFree->pLeft->pParent = pFree;
  135468. pFree->pRight->pParent = pFree;
  135469. p = pFree;
  135470. pFree = pFree->pParent;
  135471. p->pParent = 0;
  135472. apLeaf[iLvl] = 0;
  135473. }
  135474. }
  135475. if( p ){
  135476. sqlite3Fts3ExprFree(p);
  135477. rc = SQLITE_TOOBIG;
  135478. break;
  135479. }
  135480. /* If that was the last leaf node, break out of the loop */
  135481. if( pParent==0 ) break;
  135482. /* Set $p to point to the next leaf in the tree of eType nodes */
  135483. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  135484. /* Remove pParent from the original tree. */
  135485. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  135486. pParent->pRight->pParent = pParent->pParent;
  135487. if( pParent->pParent ){
  135488. pParent->pParent->pLeft = pParent->pRight;
  135489. }else{
  135490. assert( pParent==pRoot );
  135491. pRoot = pParent->pRight;
  135492. }
  135493. /* Link pParent into the free node list. It will be used as an
  135494. ** internal node of the new tree. */
  135495. pParent->pParent = pFree;
  135496. pFree = pParent;
  135497. }
  135498. if( rc==SQLITE_OK ){
  135499. p = 0;
  135500. for(i=0; i<nMaxDepth; i++){
  135501. if( apLeaf[i] ){
  135502. if( p==0 ){
  135503. p = apLeaf[i];
  135504. p->pParent = 0;
  135505. }else{
  135506. assert( pFree!=0 );
  135507. pFree->pRight = p;
  135508. pFree->pLeft = apLeaf[i];
  135509. pFree->pLeft->pParent = pFree;
  135510. pFree->pRight->pParent = pFree;
  135511. p = pFree;
  135512. pFree = pFree->pParent;
  135513. p->pParent = 0;
  135514. }
  135515. }
  135516. }
  135517. pRoot = p;
  135518. }else{
  135519. /* An error occurred. Delete the contents of the apLeaf[] array
  135520. ** and pFree list. Everything else is cleaned up by the call to
  135521. ** sqlite3Fts3ExprFree(pRoot) below. */
  135522. Fts3Expr *pDel;
  135523. for(i=0; i<nMaxDepth; i++){
  135524. sqlite3Fts3ExprFree(apLeaf[i]);
  135525. }
  135526. while( (pDel=pFree)!=0 ){
  135527. pFree = pDel->pParent;
  135528. sqlite3_free(pDel);
  135529. }
  135530. }
  135531. assert( pFree==0 );
  135532. sqlite3_free( apLeaf );
  135533. }
  135534. }else if( eType==FTSQUERY_NOT ){
  135535. Fts3Expr *pLeft = pRoot->pLeft;
  135536. Fts3Expr *pRight = pRoot->pRight;
  135537. pRoot->pLeft = 0;
  135538. pRoot->pRight = 0;
  135539. pLeft->pParent = 0;
  135540. pRight->pParent = 0;
  135541. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  135542. if( rc==SQLITE_OK ){
  135543. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  135544. }
  135545. if( rc!=SQLITE_OK ){
  135546. sqlite3Fts3ExprFree(pRight);
  135547. sqlite3Fts3ExprFree(pLeft);
  135548. }else{
  135549. assert( pLeft && pRight );
  135550. pRoot->pLeft = pLeft;
  135551. pLeft->pParent = pRoot;
  135552. pRoot->pRight = pRight;
  135553. pRight->pParent = pRoot;
  135554. }
  135555. }
  135556. }
  135557. if( rc!=SQLITE_OK ){
  135558. sqlite3Fts3ExprFree(pRoot);
  135559. pRoot = 0;
  135560. }
  135561. *pp = pRoot;
  135562. return rc;
  135563. }
  135564. /*
  135565. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  135566. ** differences:
  135567. **
  135568. ** 1. It does not do expression rebalancing.
  135569. ** 2. It does not check that the expression does not exceed the
  135570. ** maximum allowable depth.
  135571. ** 3. Even if it fails, *ppExpr may still be set to point to an
  135572. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  135573. ** in this case.
  135574. */
  135575. static int fts3ExprParseUnbalanced(
  135576. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  135577. int iLangid, /* Language id for tokenizer */
  135578. char **azCol, /* Array of column names for fts3 table */
  135579. int bFts4, /* True to allow FTS4-only syntax */
  135580. int nCol, /* Number of entries in azCol[] */
  135581. int iDefaultCol, /* Default column to query */
  135582. const char *z, int n, /* Text of MATCH query */
  135583. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  135584. ){
  135585. int nParsed;
  135586. int rc;
  135587. ParseContext sParse;
  135588. memset(&sParse, 0, sizeof(ParseContext));
  135589. sParse.pTokenizer = pTokenizer;
  135590. sParse.iLangid = iLangid;
  135591. sParse.azCol = (const char **)azCol;
  135592. sParse.nCol = nCol;
  135593. sParse.iDefaultCol = iDefaultCol;
  135594. sParse.bFts4 = bFts4;
  135595. if( z==0 ){
  135596. *ppExpr = 0;
  135597. return SQLITE_OK;
  135598. }
  135599. if( n<0 ){
  135600. n = (int)strlen(z);
  135601. }
  135602. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  135603. assert( rc==SQLITE_OK || *ppExpr==0 );
  135604. /* Check for mismatched parenthesis */
  135605. if( rc==SQLITE_OK && sParse.nNest ){
  135606. rc = SQLITE_ERROR;
  135607. }
  135608. return rc;
  135609. }
  135610. /*
  135611. ** Parameters z and n contain a pointer to and length of a buffer containing
  135612. ** an fts3 query expression, respectively. This function attempts to parse the
  135613. ** query expression and create a tree of Fts3Expr structures representing the
  135614. ** parsed expression. If successful, *ppExpr is set to point to the head
  135615. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  135616. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  135617. ** error) is returned and *ppExpr is set to 0.
  135618. **
  135619. ** If parameter n is a negative number, then z is assumed to point to a
  135620. ** nul-terminated string and the length is determined using strlen().
  135621. **
  135622. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  135623. ** use to normalize query tokens while parsing the expression. The azCol[]
  135624. ** array, which is assumed to contain nCol entries, should contain the names
  135625. ** of each column in the target fts3 table, in order from left to right.
  135626. ** Column names must be nul-terminated strings.
  135627. **
  135628. ** The iDefaultCol parameter should be passed the index of the table column
  135629. ** that appears on the left-hand-side of the MATCH operator (the default
  135630. ** column to match against for tokens for which a column name is not explicitly
  135631. ** specified as part of the query string), or -1 if tokens may by default
  135632. ** match any table column.
  135633. */
  135634. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  135635. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  135636. int iLangid, /* Language id for tokenizer */
  135637. char **azCol, /* Array of column names for fts3 table */
  135638. int bFts4, /* True to allow FTS4-only syntax */
  135639. int nCol, /* Number of entries in azCol[] */
  135640. int iDefaultCol, /* Default column to query */
  135641. const char *z, int n, /* Text of MATCH query */
  135642. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  135643. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  135644. ){
  135645. int rc = fts3ExprParseUnbalanced(
  135646. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  135647. );
  135648. /* Rebalance the expression. And check that its depth does not exceed
  135649. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  135650. if( rc==SQLITE_OK && *ppExpr ){
  135651. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  135652. if( rc==SQLITE_OK ){
  135653. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  135654. }
  135655. }
  135656. if( rc!=SQLITE_OK ){
  135657. sqlite3Fts3ExprFree(*ppExpr);
  135658. *ppExpr = 0;
  135659. if( rc==SQLITE_TOOBIG ){
  135660. sqlite3Fts3ErrMsg(pzErr,
  135661. "FTS expression tree is too large (maximum depth %d)",
  135662. SQLITE_FTS3_MAX_EXPR_DEPTH
  135663. );
  135664. rc = SQLITE_ERROR;
  135665. }else if( rc==SQLITE_ERROR ){
  135666. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  135667. }
  135668. }
  135669. return rc;
  135670. }
  135671. /*
  135672. ** Free a single node of an expression tree.
  135673. */
  135674. static void fts3FreeExprNode(Fts3Expr *p){
  135675. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  135676. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  135677. sqlite3_free(p->aMI);
  135678. sqlite3_free(p);
  135679. }
  135680. /*
  135681. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  135682. **
  135683. ** This function would be simpler if it recursively called itself. But
  135684. ** that would mean passing a sufficiently large expression to ExprParse()
  135685. ** could cause a stack overflow.
  135686. */
  135687. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  135688. Fts3Expr *p;
  135689. assert( pDel==0 || pDel->pParent==0 );
  135690. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  135691. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  135692. }
  135693. while( p ){
  135694. Fts3Expr *pParent = p->pParent;
  135695. fts3FreeExprNode(p);
  135696. if( pParent && p==pParent->pLeft && pParent->pRight ){
  135697. p = pParent->pRight;
  135698. while( p && (p->pLeft || p->pRight) ){
  135699. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  135700. p = (p->pLeft ? p->pLeft : p->pRight);
  135701. }
  135702. }else{
  135703. p = pParent;
  135704. }
  135705. }
  135706. }
  135707. /****************************************************************************
  135708. *****************************************************************************
  135709. ** Everything after this point is just test code.
  135710. */
  135711. #ifdef SQLITE_TEST
  135712. /* #include <stdio.h> */
  135713. /*
  135714. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  135715. */
  135716. static int queryTestTokenizer(
  135717. sqlite3 *db,
  135718. const char *zName,
  135719. const sqlite3_tokenizer_module **pp
  135720. ){
  135721. int rc;
  135722. sqlite3_stmt *pStmt;
  135723. const char zSql[] = "SELECT fts3_tokenizer(?)";
  135724. *pp = 0;
  135725. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  135726. if( rc!=SQLITE_OK ){
  135727. return rc;
  135728. }
  135729. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  135730. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  135731. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  135732. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  135733. }
  135734. }
  135735. return sqlite3_finalize(pStmt);
  135736. }
  135737. /*
  135738. ** Return a pointer to a buffer containing a text representation of the
  135739. ** expression passed as the first argument. The buffer is obtained from
  135740. ** sqlite3_malloc(). It is the responsibility of the caller to use
  135741. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  135742. ** NULL is returned.
  135743. **
  135744. ** If the second argument is not NULL, then its contents are prepended to
  135745. ** the returned expression text and then freed using sqlite3_free().
  135746. */
  135747. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  135748. if( pExpr==0 ){
  135749. return sqlite3_mprintf("");
  135750. }
  135751. switch( pExpr->eType ){
  135752. case FTSQUERY_PHRASE: {
  135753. Fts3Phrase *pPhrase = pExpr->pPhrase;
  135754. int i;
  135755. zBuf = sqlite3_mprintf(
  135756. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  135757. for(i=0; zBuf && i<pPhrase->nToken; i++){
  135758. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  135759. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  135760. (pPhrase->aToken[i].isPrefix?"+":"")
  135761. );
  135762. }
  135763. return zBuf;
  135764. }
  135765. case FTSQUERY_NEAR:
  135766. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  135767. break;
  135768. case FTSQUERY_NOT:
  135769. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  135770. break;
  135771. case FTSQUERY_AND:
  135772. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  135773. break;
  135774. case FTSQUERY_OR:
  135775. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  135776. break;
  135777. }
  135778. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  135779. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  135780. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  135781. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  135782. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  135783. return zBuf;
  135784. }
  135785. /*
  135786. ** This is the implementation of a scalar SQL function used to test the
  135787. ** expression parser. It should be called as follows:
  135788. **
  135789. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  135790. **
  135791. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  135792. ** to parse the query expression (see README.tokenizers). The second argument
  135793. ** is the query expression to parse. Each subsequent argument is the name
  135794. ** of a column of the fts3 table that the query expression may refer to.
  135795. ** For example:
  135796. **
  135797. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  135798. */
  135799. static void fts3ExprTest(
  135800. sqlite3_context *context,
  135801. int argc,
  135802. sqlite3_value **argv
  135803. ){
  135804. sqlite3_tokenizer_module const *pModule = 0;
  135805. sqlite3_tokenizer *pTokenizer = 0;
  135806. int rc;
  135807. char **azCol = 0;
  135808. const char *zExpr;
  135809. int nExpr;
  135810. int nCol;
  135811. int ii;
  135812. Fts3Expr *pExpr;
  135813. char *zBuf = 0;
  135814. sqlite3 *db = sqlite3_context_db_handle(context);
  135815. if( argc<3 ){
  135816. sqlite3_result_error(context,
  135817. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  135818. );
  135819. return;
  135820. }
  135821. rc = queryTestTokenizer(db,
  135822. (const char *)sqlite3_value_text(argv[0]), &pModule);
  135823. if( rc==SQLITE_NOMEM ){
  135824. sqlite3_result_error_nomem(context);
  135825. goto exprtest_out;
  135826. }else if( !pModule ){
  135827. sqlite3_result_error(context, "No such tokenizer module", -1);
  135828. goto exprtest_out;
  135829. }
  135830. rc = pModule->xCreate(0, 0, &pTokenizer);
  135831. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  135832. if( rc==SQLITE_NOMEM ){
  135833. sqlite3_result_error_nomem(context);
  135834. goto exprtest_out;
  135835. }
  135836. pTokenizer->pModule = pModule;
  135837. zExpr = (const char *)sqlite3_value_text(argv[1]);
  135838. nExpr = sqlite3_value_bytes(argv[1]);
  135839. nCol = argc-2;
  135840. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  135841. if( !azCol ){
  135842. sqlite3_result_error_nomem(context);
  135843. goto exprtest_out;
  135844. }
  135845. for(ii=0; ii<nCol; ii++){
  135846. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  135847. }
  135848. if( sqlite3_user_data(context) ){
  135849. char *zDummy = 0;
  135850. rc = sqlite3Fts3ExprParse(
  135851. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  135852. );
  135853. assert( rc==SQLITE_OK || pExpr==0 );
  135854. sqlite3_free(zDummy);
  135855. }else{
  135856. rc = fts3ExprParseUnbalanced(
  135857. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  135858. );
  135859. }
  135860. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  135861. sqlite3Fts3ExprFree(pExpr);
  135862. sqlite3_result_error(context, "Error parsing expression", -1);
  135863. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  135864. sqlite3_result_error_nomem(context);
  135865. }else{
  135866. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  135867. sqlite3_free(zBuf);
  135868. }
  135869. sqlite3Fts3ExprFree(pExpr);
  135870. exprtest_out:
  135871. if( pModule && pTokenizer ){
  135872. rc = pModule->xDestroy(pTokenizer);
  135873. }
  135874. sqlite3_free(azCol);
  135875. }
  135876. /*
  135877. ** Register the query expression parser test function fts3_exprtest()
  135878. ** with database connection db.
  135879. */
  135880. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  135881. int rc = sqlite3_create_function(
  135882. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  135883. );
  135884. if( rc==SQLITE_OK ){
  135885. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  135886. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  135887. );
  135888. }
  135889. return rc;
  135890. }
  135891. #endif
  135892. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  135893. /************** End of fts3_expr.c *******************************************/
  135894. /************** Begin file fts3_hash.c ***************************************/
  135895. /*
  135896. ** 2001 September 22
  135897. **
  135898. ** The author disclaims copyright to this source code. In place of
  135899. ** a legal notice, here is a blessing:
  135900. **
  135901. ** May you do good and not evil.
  135902. ** May you find forgiveness for yourself and forgive others.
  135903. ** May you share freely, never taking more than you give.
  135904. **
  135905. *************************************************************************
  135906. ** This is the implementation of generic hash-tables used in SQLite.
  135907. ** We've modified it slightly to serve as a standalone hash table
  135908. ** implementation for the full-text indexing module.
  135909. */
  135910. /*
  135911. ** The code in this file is only compiled if:
  135912. **
  135913. ** * The FTS3 module is being built as an extension
  135914. ** (in which case SQLITE_CORE is not defined), or
  135915. **
  135916. ** * The FTS3 module is being built into the core of
  135917. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  135918. */
  135919. /* #include "fts3Int.h" */
  135920. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  135921. /* #include <assert.h> */
  135922. /* #include <stdlib.h> */
  135923. /* #include <string.h> */
  135924. /* #include "fts3_hash.h" */
  135925. /*
  135926. ** Malloc and Free functions
  135927. */
  135928. static void *fts3HashMalloc(int n){
  135929. void *p = sqlite3_malloc(n);
  135930. if( p ){
  135931. memset(p, 0, n);
  135932. }
  135933. return p;
  135934. }
  135935. static void fts3HashFree(void *p){
  135936. sqlite3_free(p);
  135937. }
  135938. /* Turn bulk memory into a hash table object by initializing the
  135939. ** fields of the Hash structure.
  135940. **
  135941. ** "pNew" is a pointer to the hash table that is to be initialized.
  135942. ** keyClass is one of the constants
  135943. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  135944. ** determines what kind of key the hash table will use. "copyKey" is
  135945. ** true if the hash table should make its own private copy of keys and
  135946. ** false if it should just use the supplied pointer.
  135947. */
  135948. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  135949. assert( pNew!=0 );
  135950. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  135951. pNew->keyClass = keyClass;
  135952. pNew->copyKey = copyKey;
  135953. pNew->first = 0;
  135954. pNew->count = 0;
  135955. pNew->htsize = 0;
  135956. pNew->ht = 0;
  135957. }
  135958. /* Remove all entries from a hash table. Reclaim all memory.
  135959. ** Call this routine to delete a hash table or to reset a hash table
  135960. ** to the empty state.
  135961. */
  135962. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  135963. Fts3HashElem *elem; /* For looping over all elements of the table */
  135964. assert( pH!=0 );
  135965. elem = pH->first;
  135966. pH->first = 0;
  135967. fts3HashFree(pH->ht);
  135968. pH->ht = 0;
  135969. pH->htsize = 0;
  135970. while( elem ){
  135971. Fts3HashElem *next_elem = elem->next;
  135972. if( pH->copyKey && elem->pKey ){
  135973. fts3HashFree(elem->pKey);
  135974. }
  135975. fts3HashFree(elem);
  135976. elem = next_elem;
  135977. }
  135978. pH->count = 0;
  135979. }
  135980. /*
  135981. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  135982. */
  135983. static int fts3StrHash(const void *pKey, int nKey){
  135984. const char *z = (const char *)pKey;
  135985. unsigned h = 0;
  135986. if( nKey<=0 ) nKey = (int) strlen(z);
  135987. while( nKey > 0 ){
  135988. h = (h<<3) ^ h ^ *z++;
  135989. nKey--;
  135990. }
  135991. return (int)(h & 0x7fffffff);
  135992. }
  135993. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  135994. if( n1!=n2 ) return 1;
  135995. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  135996. }
  135997. /*
  135998. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  135999. */
  136000. static int fts3BinHash(const void *pKey, int nKey){
  136001. int h = 0;
  136002. const char *z = (const char *)pKey;
  136003. while( nKey-- > 0 ){
  136004. h = (h<<3) ^ h ^ *(z++);
  136005. }
  136006. return h & 0x7fffffff;
  136007. }
  136008. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  136009. if( n1!=n2 ) return 1;
  136010. return memcmp(pKey1,pKey2,n1);
  136011. }
  136012. /*
  136013. ** Return a pointer to the appropriate hash function given the key class.
  136014. **
  136015. ** The C syntax in this function definition may be unfamilar to some
  136016. ** programmers, so we provide the following additional explanation:
  136017. **
  136018. ** The name of the function is "ftsHashFunction". The function takes a
  136019. ** single parameter "keyClass". The return value of ftsHashFunction()
  136020. ** is a pointer to another function. Specifically, the return value
  136021. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  136022. ** with types "const void*" and "int" and returns an "int".
  136023. */
  136024. static int (*ftsHashFunction(int keyClass))(const void*,int){
  136025. if( keyClass==FTS3_HASH_STRING ){
  136026. return &fts3StrHash;
  136027. }else{
  136028. assert( keyClass==FTS3_HASH_BINARY );
  136029. return &fts3BinHash;
  136030. }
  136031. }
  136032. /*
  136033. ** Return a pointer to the appropriate hash function given the key class.
  136034. **
  136035. ** For help in interpreted the obscure C code in the function definition,
  136036. ** see the header comment on the previous function.
  136037. */
  136038. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  136039. if( keyClass==FTS3_HASH_STRING ){
  136040. return &fts3StrCompare;
  136041. }else{
  136042. assert( keyClass==FTS3_HASH_BINARY );
  136043. return &fts3BinCompare;
  136044. }
  136045. }
  136046. /* Link an element into the hash table
  136047. */
  136048. static void fts3HashInsertElement(
  136049. Fts3Hash *pH, /* The complete hash table */
  136050. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  136051. Fts3HashElem *pNew /* The element to be inserted */
  136052. ){
  136053. Fts3HashElem *pHead; /* First element already in pEntry */
  136054. pHead = pEntry->chain;
  136055. if( pHead ){
  136056. pNew->next = pHead;
  136057. pNew->prev = pHead->prev;
  136058. if( pHead->prev ){ pHead->prev->next = pNew; }
  136059. else { pH->first = pNew; }
  136060. pHead->prev = pNew;
  136061. }else{
  136062. pNew->next = pH->first;
  136063. if( pH->first ){ pH->first->prev = pNew; }
  136064. pNew->prev = 0;
  136065. pH->first = pNew;
  136066. }
  136067. pEntry->count++;
  136068. pEntry->chain = pNew;
  136069. }
  136070. /* Resize the hash table so that it cantains "new_size" buckets.
  136071. ** "new_size" must be a power of 2. The hash table might fail
  136072. ** to resize if sqliteMalloc() fails.
  136073. **
  136074. ** Return non-zero if a memory allocation error occurs.
  136075. */
  136076. static int fts3Rehash(Fts3Hash *pH, int new_size){
  136077. struct _fts3ht *new_ht; /* The new hash table */
  136078. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  136079. int (*xHash)(const void*,int); /* The hash function */
  136080. assert( (new_size & (new_size-1))==0 );
  136081. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  136082. if( new_ht==0 ) return 1;
  136083. fts3HashFree(pH->ht);
  136084. pH->ht = new_ht;
  136085. pH->htsize = new_size;
  136086. xHash = ftsHashFunction(pH->keyClass);
  136087. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  136088. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  136089. next_elem = elem->next;
  136090. fts3HashInsertElement(pH, &new_ht[h], elem);
  136091. }
  136092. return 0;
  136093. }
  136094. /* This function (for internal use only) locates an element in an
  136095. ** hash table that matches the given key. The hash for this key has
  136096. ** already been computed and is passed as the 4th parameter.
  136097. */
  136098. static Fts3HashElem *fts3FindElementByHash(
  136099. const Fts3Hash *pH, /* The pH to be searched */
  136100. const void *pKey, /* The key we are searching for */
  136101. int nKey,
  136102. int h /* The hash for this key. */
  136103. ){
  136104. Fts3HashElem *elem; /* Used to loop thru the element list */
  136105. int count; /* Number of elements left to test */
  136106. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  136107. if( pH->ht ){
  136108. struct _fts3ht *pEntry = &pH->ht[h];
  136109. elem = pEntry->chain;
  136110. count = pEntry->count;
  136111. xCompare = ftsCompareFunction(pH->keyClass);
  136112. while( count-- && elem ){
  136113. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  136114. return elem;
  136115. }
  136116. elem = elem->next;
  136117. }
  136118. }
  136119. return 0;
  136120. }
  136121. /* Remove a single entry from the hash table given a pointer to that
  136122. ** element and a hash on the element's key.
  136123. */
  136124. static void fts3RemoveElementByHash(
  136125. Fts3Hash *pH, /* The pH containing "elem" */
  136126. Fts3HashElem* elem, /* The element to be removed from the pH */
  136127. int h /* Hash value for the element */
  136128. ){
  136129. struct _fts3ht *pEntry;
  136130. if( elem->prev ){
  136131. elem->prev->next = elem->next;
  136132. }else{
  136133. pH->first = elem->next;
  136134. }
  136135. if( elem->next ){
  136136. elem->next->prev = elem->prev;
  136137. }
  136138. pEntry = &pH->ht[h];
  136139. if( pEntry->chain==elem ){
  136140. pEntry->chain = elem->next;
  136141. }
  136142. pEntry->count--;
  136143. if( pEntry->count<=0 ){
  136144. pEntry->chain = 0;
  136145. }
  136146. if( pH->copyKey && elem->pKey ){
  136147. fts3HashFree(elem->pKey);
  136148. }
  136149. fts3HashFree( elem );
  136150. pH->count--;
  136151. if( pH->count<=0 ){
  136152. assert( pH->first==0 );
  136153. assert( pH->count==0 );
  136154. fts3HashClear(pH);
  136155. }
  136156. }
  136157. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  136158. const Fts3Hash *pH,
  136159. const void *pKey,
  136160. int nKey
  136161. ){
  136162. int h; /* A hash on key */
  136163. int (*xHash)(const void*,int); /* The hash function */
  136164. if( pH==0 || pH->ht==0 ) return 0;
  136165. xHash = ftsHashFunction(pH->keyClass);
  136166. assert( xHash!=0 );
  136167. h = (*xHash)(pKey,nKey);
  136168. assert( (pH->htsize & (pH->htsize-1))==0 );
  136169. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  136170. }
  136171. /*
  136172. ** Attempt to locate an element of the hash table pH with a key
  136173. ** that matches pKey,nKey. Return the data for this element if it is
  136174. ** found, or NULL if there is no match.
  136175. */
  136176. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  136177. Fts3HashElem *pElem; /* The element that matches key (if any) */
  136178. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  136179. return pElem ? pElem->data : 0;
  136180. }
  136181. /* Insert an element into the hash table pH. The key is pKey,nKey
  136182. ** and the data is "data".
  136183. **
  136184. ** If no element exists with a matching key, then a new
  136185. ** element is created. A copy of the key is made if the copyKey
  136186. ** flag is set. NULL is returned.
  136187. **
  136188. ** If another element already exists with the same key, then the
  136189. ** new data replaces the old data and the old data is returned.
  136190. ** The key is not copied in this instance. If a malloc fails, then
  136191. ** the new data is returned and the hash table is unchanged.
  136192. **
  136193. ** If the "data" parameter to this function is NULL, then the
  136194. ** element corresponding to "key" is removed from the hash table.
  136195. */
  136196. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  136197. Fts3Hash *pH, /* The hash table to insert into */
  136198. const void *pKey, /* The key */
  136199. int nKey, /* Number of bytes in the key */
  136200. void *data /* The data */
  136201. ){
  136202. int hraw; /* Raw hash value of the key */
  136203. int h; /* the hash of the key modulo hash table size */
  136204. Fts3HashElem *elem; /* Used to loop thru the element list */
  136205. Fts3HashElem *new_elem; /* New element added to the pH */
  136206. int (*xHash)(const void*,int); /* The hash function */
  136207. assert( pH!=0 );
  136208. xHash = ftsHashFunction(pH->keyClass);
  136209. assert( xHash!=0 );
  136210. hraw = (*xHash)(pKey, nKey);
  136211. assert( (pH->htsize & (pH->htsize-1))==0 );
  136212. h = hraw & (pH->htsize-1);
  136213. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  136214. if( elem ){
  136215. void *old_data = elem->data;
  136216. if( data==0 ){
  136217. fts3RemoveElementByHash(pH,elem,h);
  136218. }else{
  136219. elem->data = data;
  136220. }
  136221. return old_data;
  136222. }
  136223. if( data==0 ) return 0;
  136224. if( (pH->htsize==0 && fts3Rehash(pH,8))
  136225. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  136226. ){
  136227. pH->count = 0;
  136228. return data;
  136229. }
  136230. assert( pH->htsize>0 );
  136231. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  136232. if( new_elem==0 ) return data;
  136233. if( pH->copyKey && pKey!=0 ){
  136234. new_elem->pKey = fts3HashMalloc( nKey );
  136235. if( new_elem->pKey==0 ){
  136236. fts3HashFree(new_elem);
  136237. return data;
  136238. }
  136239. memcpy((void*)new_elem->pKey, pKey, nKey);
  136240. }else{
  136241. new_elem->pKey = (void*)pKey;
  136242. }
  136243. new_elem->nKey = nKey;
  136244. pH->count++;
  136245. assert( pH->htsize>0 );
  136246. assert( (pH->htsize & (pH->htsize-1))==0 );
  136247. h = hraw & (pH->htsize-1);
  136248. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  136249. new_elem->data = data;
  136250. return 0;
  136251. }
  136252. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  136253. /************** End of fts3_hash.c *******************************************/
  136254. /************** Begin file fts3_porter.c *************************************/
  136255. /*
  136256. ** 2006 September 30
  136257. **
  136258. ** The author disclaims copyright to this source code. In place of
  136259. ** a legal notice, here is a blessing:
  136260. **
  136261. ** May you do good and not evil.
  136262. ** May you find forgiveness for yourself and forgive others.
  136263. ** May you share freely, never taking more than you give.
  136264. **
  136265. *************************************************************************
  136266. ** Implementation of the full-text-search tokenizer that implements
  136267. ** a Porter stemmer.
  136268. */
  136269. /*
  136270. ** The code in this file is only compiled if:
  136271. **
  136272. ** * The FTS3 module is being built as an extension
  136273. ** (in which case SQLITE_CORE is not defined), or
  136274. **
  136275. ** * The FTS3 module is being built into the core of
  136276. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  136277. */
  136278. /* #include "fts3Int.h" */
  136279. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136280. /* #include <assert.h> */
  136281. /* #include <stdlib.h> */
  136282. /* #include <stdio.h> */
  136283. /* #include <string.h> */
  136284. /* #include "fts3_tokenizer.h" */
  136285. /*
  136286. ** Class derived from sqlite3_tokenizer
  136287. */
  136288. typedef struct porter_tokenizer {
  136289. sqlite3_tokenizer base; /* Base class */
  136290. } porter_tokenizer;
  136291. /*
  136292. ** Class derived from sqlite3_tokenizer_cursor
  136293. */
  136294. typedef struct porter_tokenizer_cursor {
  136295. sqlite3_tokenizer_cursor base;
  136296. const char *zInput; /* input we are tokenizing */
  136297. int nInput; /* size of the input */
  136298. int iOffset; /* current position in zInput */
  136299. int iToken; /* index of next token to be returned */
  136300. char *zToken; /* storage for current token */
  136301. int nAllocated; /* space allocated to zToken buffer */
  136302. } porter_tokenizer_cursor;
  136303. /*
  136304. ** Create a new tokenizer instance.
  136305. */
  136306. static int porterCreate(
  136307. int argc, const char * const *argv,
  136308. sqlite3_tokenizer **ppTokenizer
  136309. ){
  136310. porter_tokenizer *t;
  136311. UNUSED_PARAMETER(argc);
  136312. UNUSED_PARAMETER(argv);
  136313. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  136314. if( t==NULL ) return SQLITE_NOMEM;
  136315. memset(t, 0, sizeof(*t));
  136316. *ppTokenizer = &t->base;
  136317. return SQLITE_OK;
  136318. }
  136319. /*
  136320. ** Destroy a tokenizer
  136321. */
  136322. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  136323. sqlite3_free(pTokenizer);
  136324. return SQLITE_OK;
  136325. }
  136326. /*
  136327. ** Prepare to begin tokenizing a particular string. The input
  136328. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  136329. ** used to incrementally tokenize this string is returned in
  136330. ** *ppCursor.
  136331. */
  136332. static int porterOpen(
  136333. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  136334. const char *zInput, int nInput, /* String to be tokenized */
  136335. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  136336. ){
  136337. porter_tokenizer_cursor *c;
  136338. UNUSED_PARAMETER(pTokenizer);
  136339. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  136340. if( c==NULL ) return SQLITE_NOMEM;
  136341. c->zInput = zInput;
  136342. if( zInput==0 ){
  136343. c->nInput = 0;
  136344. }else if( nInput<0 ){
  136345. c->nInput = (int)strlen(zInput);
  136346. }else{
  136347. c->nInput = nInput;
  136348. }
  136349. c->iOffset = 0; /* start tokenizing at the beginning */
  136350. c->iToken = 0;
  136351. c->zToken = NULL; /* no space allocated, yet. */
  136352. c->nAllocated = 0;
  136353. *ppCursor = &c->base;
  136354. return SQLITE_OK;
  136355. }
  136356. /*
  136357. ** Close a tokenization cursor previously opened by a call to
  136358. ** porterOpen() above.
  136359. */
  136360. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  136361. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  136362. sqlite3_free(c->zToken);
  136363. sqlite3_free(c);
  136364. return SQLITE_OK;
  136365. }
  136366. /*
  136367. ** Vowel or consonant
  136368. */
  136369. static const char cType[] = {
  136370. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  136371. 1, 1, 1, 2, 1
  136372. };
  136373. /*
  136374. ** isConsonant() and isVowel() determine if their first character in
  136375. ** the string they point to is a consonant or a vowel, according
  136376. ** to Porter ruls.
  136377. **
  136378. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  136379. ** 'Y' is a consonant unless it follows another consonant,
  136380. ** in which case it is a vowel.
  136381. **
  136382. ** In these routine, the letters are in reverse order. So the 'y' rule
  136383. ** is that 'y' is a consonant unless it is followed by another
  136384. ** consonent.
  136385. */
  136386. static int isVowel(const char*);
  136387. static int isConsonant(const char *z){
  136388. int j;
  136389. char x = *z;
  136390. if( x==0 ) return 0;
  136391. assert( x>='a' && x<='z' );
  136392. j = cType[x-'a'];
  136393. if( j<2 ) return j;
  136394. return z[1]==0 || isVowel(z + 1);
  136395. }
  136396. static int isVowel(const char *z){
  136397. int j;
  136398. char x = *z;
  136399. if( x==0 ) return 0;
  136400. assert( x>='a' && x<='z' );
  136401. j = cType[x-'a'];
  136402. if( j<2 ) return 1-j;
  136403. return isConsonant(z + 1);
  136404. }
  136405. /*
  136406. ** Let any sequence of one or more vowels be represented by V and let
  136407. ** C be sequence of one or more consonants. Then every word can be
  136408. ** represented as:
  136409. **
  136410. ** [C] (VC){m} [V]
  136411. **
  136412. ** In prose: A word is an optional consonant followed by zero or
  136413. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  136414. ** number of vowel consonant pairs. This routine computes the value
  136415. ** of m for the first i bytes of a word.
  136416. **
  136417. ** Return true if the m-value for z is 1 or more. In other words,
  136418. ** return true if z contains at least one vowel that is followed
  136419. ** by a consonant.
  136420. **
  136421. ** In this routine z[] is in reverse order. So we are really looking
  136422. ** for an instance of a consonant followed by a vowel.
  136423. */
  136424. static int m_gt_0(const char *z){
  136425. while( isVowel(z) ){ z++; }
  136426. if( *z==0 ) return 0;
  136427. while( isConsonant(z) ){ z++; }
  136428. return *z!=0;
  136429. }
  136430. /* Like mgt0 above except we are looking for a value of m which is
  136431. ** exactly 1
  136432. */
  136433. static int m_eq_1(const char *z){
  136434. while( isVowel(z) ){ z++; }
  136435. if( *z==0 ) return 0;
  136436. while( isConsonant(z) ){ z++; }
  136437. if( *z==0 ) return 0;
  136438. while( isVowel(z) ){ z++; }
  136439. if( *z==0 ) return 1;
  136440. while( isConsonant(z) ){ z++; }
  136441. return *z==0;
  136442. }
  136443. /* Like mgt0 above except we are looking for a value of m>1 instead
  136444. ** or m>0
  136445. */
  136446. static int m_gt_1(const char *z){
  136447. while( isVowel(z) ){ z++; }
  136448. if( *z==0 ) return 0;
  136449. while( isConsonant(z) ){ z++; }
  136450. if( *z==0 ) return 0;
  136451. while( isVowel(z) ){ z++; }
  136452. if( *z==0 ) return 0;
  136453. while( isConsonant(z) ){ z++; }
  136454. return *z!=0;
  136455. }
  136456. /*
  136457. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  136458. */
  136459. static int hasVowel(const char *z){
  136460. while( isConsonant(z) ){ z++; }
  136461. return *z!=0;
  136462. }
  136463. /*
  136464. ** Return TRUE if the word ends in a double consonant.
  136465. **
  136466. ** The text is reversed here. So we are really looking at
  136467. ** the first two characters of z[].
  136468. */
  136469. static int doubleConsonant(const char *z){
  136470. return isConsonant(z) && z[0]==z[1];
  136471. }
  136472. /*
  136473. ** Return TRUE if the word ends with three letters which
  136474. ** are consonant-vowel-consonent and where the final consonant
  136475. ** is not 'w', 'x', or 'y'.
  136476. **
  136477. ** The word is reversed here. So we are really checking the
  136478. ** first three letters and the first one cannot be in [wxy].
  136479. */
  136480. static int star_oh(const char *z){
  136481. return
  136482. isConsonant(z) &&
  136483. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  136484. isVowel(z+1) &&
  136485. isConsonant(z+2);
  136486. }
  136487. /*
  136488. ** If the word ends with zFrom and xCond() is true for the stem
  136489. ** of the word that preceeds the zFrom ending, then change the
  136490. ** ending to zTo.
  136491. **
  136492. ** The input word *pz and zFrom are both in reverse order. zTo
  136493. ** is in normal order.
  136494. **
  136495. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  136496. ** match. Not that TRUE is returned even if xCond() fails and
  136497. ** no substitution occurs.
  136498. */
  136499. static int stem(
  136500. char **pz, /* The word being stemmed (Reversed) */
  136501. const char *zFrom, /* If the ending matches this... (Reversed) */
  136502. const char *zTo, /* ... change the ending to this (not reversed) */
  136503. int (*xCond)(const char*) /* Condition that must be true */
  136504. ){
  136505. char *z = *pz;
  136506. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  136507. if( *zFrom!=0 ) return 0;
  136508. if( xCond && !xCond(z) ) return 1;
  136509. while( *zTo ){
  136510. *(--z) = *(zTo++);
  136511. }
  136512. *pz = z;
  136513. return 1;
  136514. }
  136515. /*
  136516. ** This is the fallback stemmer used when the porter stemmer is
  136517. ** inappropriate. The input word is copied into the output with
  136518. ** US-ASCII case folding. If the input word is too long (more
  136519. ** than 20 bytes if it contains no digits or more than 6 bytes if
  136520. ** it contains digits) then word is truncated to 20 or 6 bytes
  136521. ** by taking 10 or 3 bytes from the beginning and end.
  136522. */
  136523. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  136524. int i, mx, j;
  136525. int hasDigit = 0;
  136526. for(i=0; i<nIn; i++){
  136527. char c = zIn[i];
  136528. if( c>='A' && c<='Z' ){
  136529. zOut[i] = c - 'A' + 'a';
  136530. }else{
  136531. if( c>='0' && c<='9' ) hasDigit = 1;
  136532. zOut[i] = c;
  136533. }
  136534. }
  136535. mx = hasDigit ? 3 : 10;
  136536. if( nIn>mx*2 ){
  136537. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  136538. zOut[j] = zOut[i];
  136539. }
  136540. i = j;
  136541. }
  136542. zOut[i] = 0;
  136543. *pnOut = i;
  136544. }
  136545. /*
  136546. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  136547. ** zOut is at least big enough to hold nIn bytes. Write the actual
  136548. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  136549. **
  136550. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  136551. ** are converted to lower case. Upper-case UTF characters are
  136552. ** unchanged.
  136553. **
  136554. ** Words that are longer than about 20 bytes are stemmed by retaining
  136555. ** a few bytes from the beginning and the end of the word. If the
  136556. ** word contains digits, 3 bytes are taken from the beginning and
  136557. ** 3 bytes from the end. For long words without digits, 10 bytes
  136558. ** are taken from each end. US-ASCII case folding still applies.
  136559. **
  136560. ** If the input word contains not digits but does characters not
  136561. ** in [a-zA-Z] then no stemming is attempted and this routine just
  136562. ** copies the input into the input into the output with US-ASCII
  136563. ** case folding.
  136564. **
  136565. ** Stemming never increases the length of the word. So there is
  136566. ** no chance of overflowing the zOut buffer.
  136567. */
  136568. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  136569. int i, j;
  136570. char zReverse[28];
  136571. char *z, *z2;
  136572. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  136573. /* The word is too big or too small for the porter stemmer.
  136574. ** Fallback to the copy stemmer */
  136575. copy_stemmer(zIn, nIn, zOut, pnOut);
  136576. return;
  136577. }
  136578. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  136579. char c = zIn[i];
  136580. if( c>='A' && c<='Z' ){
  136581. zReverse[j] = c + 'a' - 'A';
  136582. }else if( c>='a' && c<='z' ){
  136583. zReverse[j] = c;
  136584. }else{
  136585. /* The use of a character not in [a-zA-Z] means that we fallback
  136586. ** to the copy stemmer */
  136587. copy_stemmer(zIn, nIn, zOut, pnOut);
  136588. return;
  136589. }
  136590. }
  136591. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  136592. z = &zReverse[j+1];
  136593. /* Step 1a */
  136594. if( z[0]=='s' ){
  136595. if(
  136596. !stem(&z, "sess", "ss", 0) &&
  136597. !stem(&z, "sei", "i", 0) &&
  136598. !stem(&z, "ss", "ss", 0)
  136599. ){
  136600. z++;
  136601. }
  136602. }
  136603. /* Step 1b */
  136604. z2 = z;
  136605. if( stem(&z, "dee", "ee", m_gt_0) ){
  136606. /* Do nothing. The work was all in the test */
  136607. }else if(
  136608. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  136609. && z!=z2
  136610. ){
  136611. if( stem(&z, "ta", "ate", 0) ||
  136612. stem(&z, "lb", "ble", 0) ||
  136613. stem(&z, "zi", "ize", 0) ){
  136614. /* Do nothing. The work was all in the test */
  136615. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  136616. z++;
  136617. }else if( m_eq_1(z) && star_oh(z) ){
  136618. *(--z) = 'e';
  136619. }
  136620. }
  136621. /* Step 1c */
  136622. if( z[0]=='y' && hasVowel(z+1) ){
  136623. z[0] = 'i';
  136624. }
  136625. /* Step 2 */
  136626. switch( z[1] ){
  136627. case 'a':
  136628. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  136629. stem(&z, "lanoit", "tion", m_gt_0);
  136630. }
  136631. break;
  136632. case 'c':
  136633. if( !stem(&z, "icne", "ence", m_gt_0) ){
  136634. stem(&z, "icna", "ance", m_gt_0);
  136635. }
  136636. break;
  136637. case 'e':
  136638. stem(&z, "rezi", "ize", m_gt_0);
  136639. break;
  136640. case 'g':
  136641. stem(&z, "igol", "log", m_gt_0);
  136642. break;
  136643. case 'l':
  136644. if( !stem(&z, "ilb", "ble", m_gt_0)
  136645. && !stem(&z, "illa", "al", m_gt_0)
  136646. && !stem(&z, "iltne", "ent", m_gt_0)
  136647. && !stem(&z, "ile", "e", m_gt_0)
  136648. ){
  136649. stem(&z, "ilsuo", "ous", m_gt_0);
  136650. }
  136651. break;
  136652. case 'o':
  136653. if( !stem(&z, "noitazi", "ize", m_gt_0)
  136654. && !stem(&z, "noita", "ate", m_gt_0)
  136655. ){
  136656. stem(&z, "rota", "ate", m_gt_0);
  136657. }
  136658. break;
  136659. case 's':
  136660. if( !stem(&z, "msila", "al", m_gt_0)
  136661. && !stem(&z, "ssenevi", "ive", m_gt_0)
  136662. && !stem(&z, "ssenluf", "ful", m_gt_0)
  136663. ){
  136664. stem(&z, "ssensuo", "ous", m_gt_0);
  136665. }
  136666. break;
  136667. case 't':
  136668. if( !stem(&z, "itila", "al", m_gt_0)
  136669. && !stem(&z, "itivi", "ive", m_gt_0)
  136670. ){
  136671. stem(&z, "itilib", "ble", m_gt_0);
  136672. }
  136673. break;
  136674. }
  136675. /* Step 3 */
  136676. switch( z[0] ){
  136677. case 'e':
  136678. if( !stem(&z, "etaci", "ic", m_gt_0)
  136679. && !stem(&z, "evita", "", m_gt_0)
  136680. ){
  136681. stem(&z, "ezila", "al", m_gt_0);
  136682. }
  136683. break;
  136684. case 'i':
  136685. stem(&z, "itici", "ic", m_gt_0);
  136686. break;
  136687. case 'l':
  136688. if( !stem(&z, "laci", "ic", m_gt_0) ){
  136689. stem(&z, "luf", "", m_gt_0);
  136690. }
  136691. break;
  136692. case 's':
  136693. stem(&z, "ssen", "", m_gt_0);
  136694. break;
  136695. }
  136696. /* Step 4 */
  136697. switch( z[1] ){
  136698. case 'a':
  136699. if( z[0]=='l' && m_gt_1(z+2) ){
  136700. z += 2;
  136701. }
  136702. break;
  136703. case 'c':
  136704. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  136705. z += 4;
  136706. }
  136707. break;
  136708. case 'e':
  136709. if( z[0]=='r' && m_gt_1(z+2) ){
  136710. z += 2;
  136711. }
  136712. break;
  136713. case 'i':
  136714. if( z[0]=='c' && m_gt_1(z+2) ){
  136715. z += 2;
  136716. }
  136717. break;
  136718. case 'l':
  136719. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  136720. z += 4;
  136721. }
  136722. break;
  136723. case 'n':
  136724. if( z[0]=='t' ){
  136725. if( z[2]=='a' ){
  136726. if( m_gt_1(z+3) ){
  136727. z += 3;
  136728. }
  136729. }else if( z[2]=='e' ){
  136730. if( !stem(&z, "tneme", "", m_gt_1)
  136731. && !stem(&z, "tnem", "", m_gt_1)
  136732. ){
  136733. stem(&z, "tne", "", m_gt_1);
  136734. }
  136735. }
  136736. }
  136737. break;
  136738. case 'o':
  136739. if( z[0]=='u' ){
  136740. if( m_gt_1(z+2) ){
  136741. z += 2;
  136742. }
  136743. }else if( z[3]=='s' || z[3]=='t' ){
  136744. stem(&z, "noi", "", m_gt_1);
  136745. }
  136746. break;
  136747. case 's':
  136748. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  136749. z += 3;
  136750. }
  136751. break;
  136752. case 't':
  136753. if( !stem(&z, "eta", "", m_gt_1) ){
  136754. stem(&z, "iti", "", m_gt_1);
  136755. }
  136756. break;
  136757. case 'u':
  136758. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  136759. z += 3;
  136760. }
  136761. break;
  136762. case 'v':
  136763. case 'z':
  136764. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  136765. z += 3;
  136766. }
  136767. break;
  136768. }
  136769. /* Step 5a */
  136770. if( z[0]=='e' ){
  136771. if( m_gt_1(z+1) ){
  136772. z++;
  136773. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  136774. z++;
  136775. }
  136776. }
  136777. /* Step 5b */
  136778. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  136779. z++;
  136780. }
  136781. /* z[] is now the stemmed word in reverse order. Flip it back
  136782. ** around into forward order and return.
  136783. */
  136784. *pnOut = i = (int)strlen(z);
  136785. zOut[i] = 0;
  136786. while( *z ){
  136787. zOut[--i] = *(z++);
  136788. }
  136789. }
  136790. /*
  136791. ** Characters that can be part of a token. We assume any character
  136792. ** whose value is greater than 0x80 (any UTF character) can be
  136793. ** part of a token. In other words, delimiters all must have
  136794. ** values of 0x7f or lower.
  136795. */
  136796. static const char porterIdChar[] = {
  136797. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  136798. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  136799. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  136800. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  136801. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  136802. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  136803. };
  136804. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  136805. /*
  136806. ** Extract the next token from a tokenization cursor. The cursor must
  136807. ** have been opened by a prior call to porterOpen().
  136808. */
  136809. static int porterNext(
  136810. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  136811. const char **pzToken, /* OUT: *pzToken is the token text */
  136812. int *pnBytes, /* OUT: Number of bytes in token */
  136813. int *piStartOffset, /* OUT: Starting offset of token */
  136814. int *piEndOffset, /* OUT: Ending offset of token */
  136815. int *piPosition /* OUT: Position integer of token */
  136816. ){
  136817. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  136818. const char *z = c->zInput;
  136819. while( c->iOffset<c->nInput ){
  136820. int iStartOffset, ch;
  136821. /* Scan past delimiter characters */
  136822. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  136823. c->iOffset++;
  136824. }
  136825. /* Count non-delimiter characters. */
  136826. iStartOffset = c->iOffset;
  136827. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  136828. c->iOffset++;
  136829. }
  136830. if( c->iOffset>iStartOffset ){
  136831. int n = c->iOffset-iStartOffset;
  136832. if( n>c->nAllocated ){
  136833. char *pNew;
  136834. c->nAllocated = n+20;
  136835. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  136836. if( !pNew ) return SQLITE_NOMEM;
  136837. c->zToken = pNew;
  136838. }
  136839. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  136840. *pzToken = c->zToken;
  136841. *piStartOffset = iStartOffset;
  136842. *piEndOffset = c->iOffset;
  136843. *piPosition = c->iToken++;
  136844. return SQLITE_OK;
  136845. }
  136846. }
  136847. return SQLITE_DONE;
  136848. }
  136849. /*
  136850. ** The set of routines that implement the porter-stemmer tokenizer
  136851. */
  136852. static const sqlite3_tokenizer_module porterTokenizerModule = {
  136853. 0,
  136854. porterCreate,
  136855. porterDestroy,
  136856. porterOpen,
  136857. porterClose,
  136858. porterNext,
  136859. 0
  136860. };
  136861. /*
  136862. ** Allocate a new porter tokenizer. Return a pointer to the new
  136863. ** tokenizer in *ppModule
  136864. */
  136865. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  136866. sqlite3_tokenizer_module const**ppModule
  136867. ){
  136868. *ppModule = &porterTokenizerModule;
  136869. }
  136870. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  136871. /************** End of fts3_porter.c *****************************************/
  136872. /************** Begin file fts3_tokenizer.c **********************************/
  136873. /*
  136874. ** 2007 June 22
  136875. **
  136876. ** The author disclaims copyright to this source code. In place of
  136877. ** a legal notice, here is a blessing:
  136878. **
  136879. ** May you do good and not evil.
  136880. ** May you find forgiveness for yourself and forgive others.
  136881. ** May you share freely, never taking more than you give.
  136882. **
  136883. ******************************************************************************
  136884. **
  136885. ** This is part of an SQLite module implementing full-text search.
  136886. ** This particular file implements the generic tokenizer interface.
  136887. */
  136888. /*
  136889. ** The code in this file is only compiled if:
  136890. **
  136891. ** * The FTS3 module is being built as an extension
  136892. ** (in which case SQLITE_CORE is not defined), or
  136893. **
  136894. ** * The FTS3 module is being built into the core of
  136895. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  136896. */
  136897. /* #include "fts3Int.h" */
  136898. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136899. /* #include <assert.h> */
  136900. /* #include <string.h> */
  136901. /*
  136902. ** Implementation of the SQL scalar function for accessing the underlying
  136903. ** hash table. This function may be called as follows:
  136904. **
  136905. ** SELECT <function-name>(<key-name>);
  136906. ** SELECT <function-name>(<key-name>, <pointer>);
  136907. **
  136908. ** where <function-name> is the name passed as the second argument
  136909. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  136910. **
  136911. ** If the <pointer> argument is specified, it must be a blob value
  136912. ** containing a pointer to be stored as the hash data corresponding
  136913. ** to the string <key-name>. If <pointer> is not specified, then
  136914. ** the string <key-name> must already exist in the has table. Otherwise,
  136915. ** an error is returned.
  136916. **
  136917. ** Whether or not the <pointer> argument is specified, the value returned
  136918. ** is a blob containing the pointer stored as the hash data corresponding
  136919. ** to string <key-name> (after the hash-table is updated, if applicable).
  136920. */
  136921. static void scalarFunc(
  136922. sqlite3_context *context,
  136923. int argc,
  136924. sqlite3_value **argv
  136925. ){
  136926. Fts3Hash *pHash;
  136927. void *pPtr = 0;
  136928. const unsigned char *zName;
  136929. int nName;
  136930. assert( argc==1 || argc==2 );
  136931. pHash = (Fts3Hash *)sqlite3_user_data(context);
  136932. zName = sqlite3_value_text(argv[0]);
  136933. nName = sqlite3_value_bytes(argv[0])+1;
  136934. if( argc==2 ){
  136935. void *pOld;
  136936. int n = sqlite3_value_bytes(argv[1]);
  136937. if( zName==0 || n!=sizeof(pPtr) ){
  136938. sqlite3_result_error(context, "argument type mismatch", -1);
  136939. return;
  136940. }
  136941. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  136942. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  136943. if( pOld==pPtr ){
  136944. sqlite3_result_error(context, "out of memory", -1);
  136945. return;
  136946. }
  136947. }else{
  136948. if( zName ){
  136949. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  136950. }
  136951. if( !pPtr ){
  136952. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  136953. sqlite3_result_error(context, zErr, -1);
  136954. sqlite3_free(zErr);
  136955. return;
  136956. }
  136957. }
  136958. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  136959. }
  136960. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  136961. static const char isFtsIdChar[] = {
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  136964. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  136965. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  136966. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  136967. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  136968. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  136969. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  136970. };
  136971. return (c&0x80 || isFtsIdChar[(int)(c)]);
  136972. }
  136973. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  136974. const char *z1;
  136975. const char *z2 = 0;
  136976. /* Find the start of the next token. */
  136977. z1 = zStr;
  136978. while( z2==0 ){
  136979. char c = *z1;
  136980. switch( c ){
  136981. case '\0': return 0; /* No more tokens here */
  136982. case '\'':
  136983. case '"':
  136984. case '`': {
  136985. z2 = z1;
  136986. while( *++z2 && (*z2!=c || *++z2==c) );
  136987. break;
  136988. }
  136989. case '[':
  136990. z2 = &z1[1];
  136991. while( *z2 && z2[0]!=']' ) z2++;
  136992. if( *z2 ) z2++;
  136993. break;
  136994. default:
  136995. if( sqlite3Fts3IsIdChar(*z1) ){
  136996. z2 = &z1[1];
  136997. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  136998. }else{
  136999. z1++;
  137000. }
  137001. }
  137002. }
  137003. *pn = (int)(z2-z1);
  137004. return z1;
  137005. }
  137006. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  137007. Fts3Hash *pHash, /* Tokenizer hash table */
  137008. const char *zArg, /* Tokenizer name */
  137009. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  137010. char **pzErr /* OUT: Set to malloced error message */
  137011. ){
  137012. int rc;
  137013. char *z = (char *)zArg;
  137014. int n = 0;
  137015. char *zCopy;
  137016. char *zEnd; /* Pointer to nul-term of zCopy */
  137017. sqlite3_tokenizer_module *m;
  137018. zCopy = sqlite3_mprintf("%s", zArg);
  137019. if( !zCopy ) return SQLITE_NOMEM;
  137020. zEnd = &zCopy[strlen(zCopy)];
  137021. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  137022. if( z==0 ){
  137023. assert( n==0 );
  137024. z = zCopy;
  137025. }
  137026. z[n] = '\0';
  137027. sqlite3Fts3Dequote(z);
  137028. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  137029. if( !m ){
  137030. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  137031. rc = SQLITE_ERROR;
  137032. }else{
  137033. char const **aArg = 0;
  137034. int iArg = 0;
  137035. z = &z[n+1];
  137036. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  137037. int nNew = sizeof(char *)*(iArg+1);
  137038. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  137039. if( !aNew ){
  137040. sqlite3_free(zCopy);
  137041. sqlite3_free((void *)aArg);
  137042. return SQLITE_NOMEM;
  137043. }
  137044. aArg = aNew;
  137045. aArg[iArg++] = z;
  137046. z[n] = '\0';
  137047. sqlite3Fts3Dequote(z);
  137048. z = &z[n+1];
  137049. }
  137050. rc = m->xCreate(iArg, aArg, ppTok);
  137051. assert( rc!=SQLITE_OK || *ppTok );
  137052. if( rc!=SQLITE_OK ){
  137053. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  137054. }else{
  137055. (*ppTok)->pModule = m;
  137056. }
  137057. sqlite3_free((void *)aArg);
  137058. }
  137059. sqlite3_free(zCopy);
  137060. return rc;
  137061. }
  137062. #ifdef SQLITE_TEST
  137063. #include <tcl.h>
  137064. /* #include <string.h> */
  137065. /*
  137066. ** Implementation of a special SQL scalar function for testing tokenizers
  137067. ** designed to be used in concert with the Tcl testing framework. This
  137068. ** function must be called with two or more arguments:
  137069. **
  137070. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  137071. **
  137072. ** where <function-name> is the name passed as the second argument
  137073. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  137074. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  137075. **
  137076. ** The return value is a string that may be interpreted as a Tcl
  137077. ** list. For each token in the <input-string>, three elements are
  137078. ** added to the returned list. The first is the token position, the
  137079. ** second is the token text (folded, stemmed, etc.) and the third is the
  137080. ** substring of <input-string> associated with the token. For example,
  137081. ** using the built-in "simple" tokenizer:
  137082. **
  137083. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  137084. **
  137085. ** will return the string:
  137086. **
  137087. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  137088. **
  137089. */
  137090. static void testFunc(
  137091. sqlite3_context *context,
  137092. int argc,
  137093. sqlite3_value **argv
  137094. ){
  137095. Fts3Hash *pHash;
  137096. sqlite3_tokenizer_module *p;
  137097. sqlite3_tokenizer *pTokenizer = 0;
  137098. sqlite3_tokenizer_cursor *pCsr = 0;
  137099. const char *zErr = 0;
  137100. const char *zName;
  137101. int nName;
  137102. const char *zInput;
  137103. int nInput;
  137104. const char *azArg[64];
  137105. const char *zToken;
  137106. int nToken = 0;
  137107. int iStart = 0;
  137108. int iEnd = 0;
  137109. int iPos = 0;
  137110. int i;
  137111. Tcl_Obj *pRet;
  137112. if( argc<2 ){
  137113. sqlite3_result_error(context, "insufficient arguments", -1);
  137114. return;
  137115. }
  137116. nName = sqlite3_value_bytes(argv[0]);
  137117. zName = (const char *)sqlite3_value_text(argv[0]);
  137118. nInput = sqlite3_value_bytes(argv[argc-1]);
  137119. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  137120. pHash = (Fts3Hash *)sqlite3_user_data(context);
  137121. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  137122. if( !p ){
  137123. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  137124. sqlite3_result_error(context, zErr2, -1);
  137125. sqlite3_free(zErr2);
  137126. return;
  137127. }
  137128. pRet = Tcl_NewObj();
  137129. Tcl_IncrRefCount(pRet);
  137130. for(i=1; i<argc-1; i++){
  137131. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  137132. }
  137133. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  137134. zErr = "error in xCreate()";
  137135. goto finish;
  137136. }
  137137. pTokenizer->pModule = p;
  137138. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  137139. zErr = "error in xOpen()";
  137140. goto finish;
  137141. }
  137142. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  137143. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  137144. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  137145. zToken = &zInput[iStart];
  137146. nToken = iEnd-iStart;
  137147. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  137148. }
  137149. if( SQLITE_OK!=p->xClose(pCsr) ){
  137150. zErr = "error in xClose()";
  137151. goto finish;
  137152. }
  137153. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  137154. zErr = "error in xDestroy()";
  137155. goto finish;
  137156. }
  137157. finish:
  137158. if( zErr ){
  137159. sqlite3_result_error(context, zErr, -1);
  137160. }else{
  137161. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  137162. }
  137163. Tcl_DecrRefCount(pRet);
  137164. }
  137165. static
  137166. int registerTokenizer(
  137167. sqlite3 *db,
  137168. char *zName,
  137169. const sqlite3_tokenizer_module *p
  137170. ){
  137171. int rc;
  137172. sqlite3_stmt *pStmt;
  137173. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  137174. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  137175. if( rc!=SQLITE_OK ){
  137176. return rc;
  137177. }
  137178. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  137179. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  137180. sqlite3_step(pStmt);
  137181. return sqlite3_finalize(pStmt);
  137182. }
  137183. static
  137184. int queryTokenizer(
  137185. sqlite3 *db,
  137186. char *zName,
  137187. const sqlite3_tokenizer_module **pp
  137188. ){
  137189. int rc;
  137190. sqlite3_stmt *pStmt;
  137191. const char zSql[] = "SELECT fts3_tokenizer(?)";
  137192. *pp = 0;
  137193. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  137194. if( rc!=SQLITE_OK ){
  137195. return rc;
  137196. }
  137197. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  137198. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  137199. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  137200. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  137201. }
  137202. }
  137203. return sqlite3_finalize(pStmt);
  137204. }
  137205. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  137206. /*
  137207. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  137208. ** This function is used for testing only, it is not included in the
  137209. ** build unless SQLITE_TEST is defined.
  137210. **
  137211. ** The purpose of this is to test that the fts3_tokenizer() function
  137212. ** can be used as designed by the C-code in the queryTokenizer and
  137213. ** registerTokenizer() functions above. These two functions are repeated
  137214. ** in the README.tokenizer file as an example, so it is important to
  137215. ** test them.
  137216. **
  137217. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  137218. ** function with no arguments. An assert() will fail if a problem is
  137219. ** detected. i.e.:
  137220. **
  137221. ** SELECT fts3_tokenizer_internal_test();
  137222. **
  137223. */
  137224. static void intTestFunc(
  137225. sqlite3_context *context,
  137226. int argc,
  137227. sqlite3_value **argv
  137228. ){
  137229. int rc;
  137230. const sqlite3_tokenizer_module *p1;
  137231. const sqlite3_tokenizer_module *p2;
  137232. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  137233. UNUSED_PARAMETER(argc);
  137234. UNUSED_PARAMETER(argv);
  137235. /* Test the query function */
  137236. sqlite3Fts3SimpleTokenizerModule(&p1);
  137237. rc = queryTokenizer(db, "simple", &p2);
  137238. assert( rc==SQLITE_OK );
  137239. assert( p1==p2 );
  137240. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  137241. assert( rc==SQLITE_ERROR );
  137242. assert( p2==0 );
  137243. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  137244. /* Test the storage function */
  137245. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  137246. assert( rc==SQLITE_OK );
  137247. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  137248. assert( rc==SQLITE_OK );
  137249. assert( p2==p1 );
  137250. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  137251. }
  137252. #endif
  137253. /*
  137254. ** Set up SQL objects in database db used to access the contents of
  137255. ** the hash table pointed to by argument pHash. The hash table must
  137256. ** been initialized to use string keys, and to take a private copy
  137257. ** of the key when a value is inserted. i.e. by a call similar to:
  137258. **
  137259. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  137260. **
  137261. ** This function adds a scalar function (see header comment above
  137262. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  137263. ** defined at compilation time, a temporary virtual table (see header
  137264. ** comment above struct HashTableVtab) to the database schema. Both
  137265. ** provide read/write access to the contents of *pHash.
  137266. **
  137267. ** The third argument to this function, zName, is used as the name
  137268. ** of both the scalar and, if created, the virtual table.
  137269. */
  137270. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  137271. sqlite3 *db,
  137272. Fts3Hash *pHash,
  137273. const char *zName
  137274. ){
  137275. int rc = SQLITE_OK;
  137276. void *p = (void *)pHash;
  137277. const int any = SQLITE_ANY;
  137278. #ifdef SQLITE_TEST
  137279. char *zTest = 0;
  137280. char *zTest2 = 0;
  137281. void *pdb = (void *)db;
  137282. zTest = sqlite3_mprintf("%s_test", zName);
  137283. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  137284. if( !zTest || !zTest2 ){
  137285. rc = SQLITE_NOMEM;
  137286. }
  137287. #endif
  137288. if( SQLITE_OK==rc ){
  137289. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  137290. }
  137291. if( SQLITE_OK==rc ){
  137292. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  137293. }
  137294. #ifdef SQLITE_TEST
  137295. if( SQLITE_OK==rc ){
  137296. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  137297. }
  137298. if( SQLITE_OK==rc ){
  137299. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  137300. }
  137301. #endif
  137302. #ifdef SQLITE_TEST
  137303. sqlite3_free(zTest);
  137304. sqlite3_free(zTest2);
  137305. #endif
  137306. return rc;
  137307. }
  137308. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  137309. /************** End of fts3_tokenizer.c **************************************/
  137310. /************** Begin file fts3_tokenizer1.c *********************************/
  137311. /*
  137312. ** 2006 Oct 10
  137313. **
  137314. ** The author disclaims copyright to this source code. In place of
  137315. ** a legal notice, here is a blessing:
  137316. **
  137317. ** May you do good and not evil.
  137318. ** May you find forgiveness for yourself and forgive others.
  137319. ** May you share freely, never taking more than you give.
  137320. **
  137321. ******************************************************************************
  137322. **
  137323. ** Implementation of the "simple" full-text-search tokenizer.
  137324. */
  137325. /*
  137326. ** The code in this file is only compiled if:
  137327. **
  137328. ** * The FTS3 module is being built as an extension
  137329. ** (in which case SQLITE_CORE is not defined), or
  137330. **
  137331. ** * The FTS3 module is being built into the core of
  137332. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  137333. */
  137334. /* #include "fts3Int.h" */
  137335. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137336. /* #include <assert.h> */
  137337. /* #include <stdlib.h> */
  137338. /* #include <stdio.h> */
  137339. /* #include <string.h> */
  137340. /* #include "fts3_tokenizer.h" */
  137341. typedef struct simple_tokenizer {
  137342. sqlite3_tokenizer base;
  137343. char delim[128]; /* flag ASCII delimiters */
  137344. } simple_tokenizer;
  137345. typedef struct simple_tokenizer_cursor {
  137346. sqlite3_tokenizer_cursor base;
  137347. const char *pInput; /* input we are tokenizing */
  137348. int nBytes; /* size of the input */
  137349. int iOffset; /* current position in pInput */
  137350. int iToken; /* index of next token to be returned */
  137351. char *pToken; /* storage for current token */
  137352. int nTokenAllocated; /* space allocated to zToken buffer */
  137353. } simple_tokenizer_cursor;
  137354. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  137355. return c<0x80 && t->delim[c];
  137356. }
  137357. static int fts3_isalnum(int x){
  137358. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  137359. }
  137360. /*
  137361. ** Create a new tokenizer instance.
  137362. */
  137363. static int simpleCreate(
  137364. int argc, const char * const *argv,
  137365. sqlite3_tokenizer **ppTokenizer
  137366. ){
  137367. simple_tokenizer *t;
  137368. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  137369. if( t==NULL ) return SQLITE_NOMEM;
  137370. memset(t, 0, sizeof(*t));
  137371. /* TODO(shess) Delimiters need to remain the same from run to run,
  137372. ** else we need to reindex. One solution would be a meta-table to
  137373. ** track such information in the database, then we'd only want this
  137374. ** information on the initial create.
  137375. */
  137376. if( argc>1 ){
  137377. int i, n = (int)strlen(argv[1]);
  137378. for(i=0; i<n; i++){
  137379. unsigned char ch = argv[1][i];
  137380. /* We explicitly don't support UTF-8 delimiters for now. */
  137381. if( ch>=0x80 ){
  137382. sqlite3_free(t);
  137383. return SQLITE_ERROR;
  137384. }
  137385. t->delim[ch] = 1;
  137386. }
  137387. } else {
  137388. /* Mark non-alphanumeric ASCII characters as delimiters */
  137389. int i;
  137390. for(i=1; i<0x80; i++){
  137391. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  137392. }
  137393. }
  137394. *ppTokenizer = &t->base;
  137395. return SQLITE_OK;
  137396. }
  137397. /*
  137398. ** Destroy a tokenizer
  137399. */
  137400. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  137401. sqlite3_free(pTokenizer);
  137402. return SQLITE_OK;
  137403. }
  137404. /*
  137405. ** Prepare to begin tokenizing a particular string. The input
  137406. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  137407. ** used to incrementally tokenize this string is returned in
  137408. ** *ppCursor.
  137409. */
  137410. static int simpleOpen(
  137411. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  137412. const char *pInput, int nBytes, /* String to be tokenized */
  137413. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  137414. ){
  137415. simple_tokenizer_cursor *c;
  137416. UNUSED_PARAMETER(pTokenizer);
  137417. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  137418. if( c==NULL ) return SQLITE_NOMEM;
  137419. c->pInput = pInput;
  137420. if( pInput==0 ){
  137421. c->nBytes = 0;
  137422. }else if( nBytes<0 ){
  137423. c->nBytes = (int)strlen(pInput);
  137424. }else{
  137425. c->nBytes = nBytes;
  137426. }
  137427. c->iOffset = 0; /* start tokenizing at the beginning */
  137428. c->iToken = 0;
  137429. c->pToken = NULL; /* no space allocated, yet. */
  137430. c->nTokenAllocated = 0;
  137431. *ppCursor = &c->base;
  137432. return SQLITE_OK;
  137433. }
  137434. /*
  137435. ** Close a tokenization cursor previously opened by a call to
  137436. ** simpleOpen() above.
  137437. */
  137438. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  137439. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  137440. sqlite3_free(c->pToken);
  137441. sqlite3_free(c);
  137442. return SQLITE_OK;
  137443. }
  137444. /*
  137445. ** Extract the next token from a tokenization cursor. The cursor must
  137446. ** have been opened by a prior call to simpleOpen().
  137447. */
  137448. static int simpleNext(
  137449. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  137450. const char **ppToken, /* OUT: *ppToken is the token text */
  137451. int *pnBytes, /* OUT: Number of bytes in token */
  137452. int *piStartOffset, /* OUT: Starting offset of token */
  137453. int *piEndOffset, /* OUT: Ending offset of token */
  137454. int *piPosition /* OUT: Position integer of token */
  137455. ){
  137456. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  137457. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  137458. unsigned char *p = (unsigned char *)c->pInput;
  137459. while( c->iOffset<c->nBytes ){
  137460. int iStartOffset;
  137461. /* Scan past delimiter characters */
  137462. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  137463. c->iOffset++;
  137464. }
  137465. /* Count non-delimiter characters. */
  137466. iStartOffset = c->iOffset;
  137467. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  137468. c->iOffset++;
  137469. }
  137470. if( c->iOffset>iStartOffset ){
  137471. int i, n = c->iOffset-iStartOffset;
  137472. if( n>c->nTokenAllocated ){
  137473. char *pNew;
  137474. c->nTokenAllocated = n+20;
  137475. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  137476. if( !pNew ) return SQLITE_NOMEM;
  137477. c->pToken = pNew;
  137478. }
  137479. for(i=0; i<n; i++){
  137480. /* TODO(shess) This needs expansion to handle UTF-8
  137481. ** case-insensitivity.
  137482. */
  137483. unsigned char ch = p[iStartOffset+i];
  137484. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  137485. }
  137486. *ppToken = c->pToken;
  137487. *pnBytes = n;
  137488. *piStartOffset = iStartOffset;
  137489. *piEndOffset = c->iOffset;
  137490. *piPosition = c->iToken++;
  137491. return SQLITE_OK;
  137492. }
  137493. }
  137494. return SQLITE_DONE;
  137495. }
  137496. /*
  137497. ** The set of routines that implement the simple tokenizer
  137498. */
  137499. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  137500. 0,
  137501. simpleCreate,
  137502. simpleDestroy,
  137503. simpleOpen,
  137504. simpleClose,
  137505. simpleNext,
  137506. 0,
  137507. };
  137508. /*
  137509. ** Allocate a new simple tokenizer. Return a pointer to the new
  137510. ** tokenizer in *ppModule
  137511. */
  137512. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  137513. sqlite3_tokenizer_module const**ppModule
  137514. ){
  137515. *ppModule = &simpleTokenizerModule;
  137516. }
  137517. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  137518. /************** End of fts3_tokenizer1.c *************************************/
  137519. /************** Begin file fts3_tokenize_vtab.c ******************************/
  137520. /*
  137521. ** 2013 Apr 22
  137522. **
  137523. ** The author disclaims copyright to this source code. In place of
  137524. ** a legal notice, here is a blessing:
  137525. **
  137526. ** May you do good and not evil.
  137527. ** May you find forgiveness for yourself and forgive others.
  137528. ** May you share freely, never taking more than you give.
  137529. **
  137530. ******************************************************************************
  137531. **
  137532. ** This file contains code for the "fts3tokenize" virtual table module.
  137533. ** An fts3tokenize virtual table is created as follows:
  137534. **
  137535. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  137536. ** <tokenizer-name>, <arg-1>, ...
  137537. ** );
  137538. **
  137539. ** The table created has the following schema:
  137540. **
  137541. ** CREATE TABLE <tbl>(input, token, start, end, position)
  137542. **
  137543. ** When queried, the query must include a WHERE clause of type:
  137544. **
  137545. ** input = <string>
  137546. **
  137547. ** The virtual table module tokenizes this <string>, using the FTS3
  137548. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  137549. ** statement and returns one row for each token in the result. With
  137550. ** fields set as follows:
  137551. **
  137552. ** input: Always set to a copy of <string>
  137553. ** token: A token from the input.
  137554. ** start: Byte offset of the token within the input <string>.
  137555. ** end: Byte offset of the byte immediately following the end of the
  137556. ** token within the input string.
  137557. ** pos: Token offset of token within input.
  137558. **
  137559. */
  137560. /* #include "fts3Int.h" */
  137561. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137562. /* #include <string.h> */
  137563. /* #include <assert.h> */
  137564. typedef struct Fts3tokTable Fts3tokTable;
  137565. typedef struct Fts3tokCursor Fts3tokCursor;
  137566. /*
  137567. ** Virtual table structure.
  137568. */
  137569. struct Fts3tokTable {
  137570. sqlite3_vtab base; /* Base class used by SQLite core */
  137571. const sqlite3_tokenizer_module *pMod;
  137572. sqlite3_tokenizer *pTok;
  137573. };
  137574. /*
  137575. ** Virtual table cursor structure.
  137576. */
  137577. struct Fts3tokCursor {
  137578. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  137579. char *zInput; /* Input string */
  137580. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  137581. int iRowid; /* Current 'rowid' value */
  137582. const char *zToken; /* Current 'token' value */
  137583. int nToken; /* Size of zToken in bytes */
  137584. int iStart; /* Current 'start' value */
  137585. int iEnd; /* Current 'end' value */
  137586. int iPos; /* Current 'pos' value */
  137587. };
  137588. /*
  137589. ** Query FTS for the tokenizer implementation named zName.
  137590. */
  137591. static int fts3tokQueryTokenizer(
  137592. Fts3Hash *pHash,
  137593. const char *zName,
  137594. const sqlite3_tokenizer_module **pp,
  137595. char **pzErr
  137596. ){
  137597. sqlite3_tokenizer_module *p;
  137598. int nName = (int)strlen(zName);
  137599. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  137600. if( !p ){
  137601. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  137602. return SQLITE_ERROR;
  137603. }
  137604. *pp = p;
  137605. return SQLITE_OK;
  137606. }
  137607. /*
  137608. ** The second argument, argv[], is an array of pointers to nul-terminated
  137609. ** strings. This function makes a copy of the array and strings into a
  137610. ** single block of memory. It then dequotes any of the strings that appear
  137611. ** to be quoted.
  137612. **
  137613. ** If successful, output parameter *pazDequote is set to point at the
  137614. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  137615. ** responsible for eventually calling sqlite3_free() to free the array
  137616. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  137617. ** The final value of *pazDequote is undefined in this case.
  137618. */
  137619. static int fts3tokDequoteArray(
  137620. int argc, /* Number of elements in argv[] */
  137621. const char * const *argv, /* Input array */
  137622. char ***pazDequote /* Output array */
  137623. ){
  137624. int rc = SQLITE_OK; /* Return code */
  137625. if( argc==0 ){
  137626. *pazDequote = 0;
  137627. }else{
  137628. int i;
  137629. int nByte = 0;
  137630. char **azDequote;
  137631. for(i=0; i<argc; i++){
  137632. nByte += (int)(strlen(argv[i]) + 1);
  137633. }
  137634. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  137635. if( azDequote==0 ){
  137636. rc = SQLITE_NOMEM;
  137637. }else{
  137638. char *pSpace = (char *)&azDequote[argc];
  137639. for(i=0; i<argc; i++){
  137640. int n = (int)strlen(argv[i]);
  137641. azDequote[i] = pSpace;
  137642. memcpy(pSpace, argv[i], n+1);
  137643. sqlite3Fts3Dequote(pSpace);
  137644. pSpace += (n+1);
  137645. }
  137646. }
  137647. }
  137648. return rc;
  137649. }
  137650. /*
  137651. ** Schema of the tokenizer table.
  137652. */
  137653. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  137654. /*
  137655. ** This function does all the work for both the xConnect and xCreate methods.
  137656. ** These tables have no persistent representation of their own, so xConnect
  137657. ** and xCreate are identical operations.
  137658. **
  137659. ** argv[0]: module name
  137660. ** argv[1]: database name
  137661. ** argv[2]: table name
  137662. ** argv[3]: first argument (tokenizer name)
  137663. */
  137664. static int fts3tokConnectMethod(
  137665. sqlite3 *db, /* Database connection */
  137666. void *pHash, /* Hash table of tokenizers */
  137667. int argc, /* Number of elements in argv array */
  137668. const char * const *argv, /* xCreate/xConnect argument array */
  137669. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  137670. char **pzErr /* OUT: sqlite3_malloc'd error message */
  137671. ){
  137672. Fts3tokTable *pTab = 0;
  137673. const sqlite3_tokenizer_module *pMod = 0;
  137674. sqlite3_tokenizer *pTok = 0;
  137675. int rc;
  137676. char **azDequote = 0;
  137677. int nDequote;
  137678. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  137679. if( rc!=SQLITE_OK ) return rc;
  137680. nDequote = argc-3;
  137681. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  137682. if( rc==SQLITE_OK ){
  137683. const char *zModule;
  137684. if( nDequote<1 ){
  137685. zModule = "simple";
  137686. }else{
  137687. zModule = azDequote[0];
  137688. }
  137689. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  137690. }
  137691. assert( (rc==SQLITE_OK)==(pMod!=0) );
  137692. if( rc==SQLITE_OK ){
  137693. const char * const *azArg = (const char * const *)&azDequote[1];
  137694. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  137695. }
  137696. if( rc==SQLITE_OK ){
  137697. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  137698. if( pTab==0 ){
  137699. rc = SQLITE_NOMEM;
  137700. }
  137701. }
  137702. if( rc==SQLITE_OK ){
  137703. memset(pTab, 0, sizeof(Fts3tokTable));
  137704. pTab->pMod = pMod;
  137705. pTab->pTok = pTok;
  137706. *ppVtab = &pTab->base;
  137707. }else{
  137708. if( pTok ){
  137709. pMod->xDestroy(pTok);
  137710. }
  137711. }
  137712. sqlite3_free(azDequote);
  137713. return rc;
  137714. }
  137715. /*
  137716. ** This function does the work for both the xDisconnect and xDestroy methods.
  137717. ** These tables have no persistent representation of their own, so xDisconnect
  137718. ** and xDestroy are identical operations.
  137719. */
  137720. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  137721. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  137722. pTab->pMod->xDestroy(pTab->pTok);
  137723. sqlite3_free(pTab);
  137724. return SQLITE_OK;
  137725. }
  137726. /*
  137727. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  137728. */
  137729. static int fts3tokBestIndexMethod(
  137730. sqlite3_vtab *pVTab,
  137731. sqlite3_index_info *pInfo
  137732. ){
  137733. int i;
  137734. UNUSED_PARAMETER(pVTab);
  137735. for(i=0; i<pInfo->nConstraint; i++){
  137736. if( pInfo->aConstraint[i].usable
  137737. && pInfo->aConstraint[i].iColumn==0
  137738. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  137739. ){
  137740. pInfo->idxNum = 1;
  137741. pInfo->aConstraintUsage[i].argvIndex = 1;
  137742. pInfo->aConstraintUsage[i].omit = 1;
  137743. pInfo->estimatedCost = 1;
  137744. return SQLITE_OK;
  137745. }
  137746. }
  137747. pInfo->idxNum = 0;
  137748. assert( pInfo->estimatedCost>1000000.0 );
  137749. return SQLITE_OK;
  137750. }
  137751. /*
  137752. ** xOpen - Open a cursor.
  137753. */
  137754. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  137755. Fts3tokCursor *pCsr;
  137756. UNUSED_PARAMETER(pVTab);
  137757. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  137758. if( pCsr==0 ){
  137759. return SQLITE_NOMEM;
  137760. }
  137761. memset(pCsr, 0, sizeof(Fts3tokCursor));
  137762. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  137763. return SQLITE_OK;
  137764. }
  137765. /*
  137766. ** Reset the tokenizer cursor passed as the only argument. As if it had
  137767. ** just been returned by fts3tokOpenMethod().
  137768. */
  137769. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  137770. if( pCsr->pCsr ){
  137771. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  137772. pTab->pMod->xClose(pCsr->pCsr);
  137773. pCsr->pCsr = 0;
  137774. }
  137775. sqlite3_free(pCsr->zInput);
  137776. pCsr->zInput = 0;
  137777. pCsr->zToken = 0;
  137778. pCsr->nToken = 0;
  137779. pCsr->iStart = 0;
  137780. pCsr->iEnd = 0;
  137781. pCsr->iPos = 0;
  137782. pCsr->iRowid = 0;
  137783. }
  137784. /*
  137785. ** xClose - Close a cursor.
  137786. */
  137787. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  137788. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  137789. fts3tokResetCursor(pCsr);
  137790. sqlite3_free(pCsr);
  137791. return SQLITE_OK;
  137792. }
  137793. /*
  137794. ** xNext - Advance the cursor to the next row, if any.
  137795. */
  137796. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  137797. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  137798. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  137799. int rc; /* Return code */
  137800. pCsr->iRowid++;
  137801. rc = pTab->pMod->xNext(pCsr->pCsr,
  137802. &pCsr->zToken, &pCsr->nToken,
  137803. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  137804. );
  137805. if( rc!=SQLITE_OK ){
  137806. fts3tokResetCursor(pCsr);
  137807. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  137808. }
  137809. return rc;
  137810. }
  137811. /*
  137812. ** xFilter - Initialize a cursor to point at the start of its data.
  137813. */
  137814. static int fts3tokFilterMethod(
  137815. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  137816. int idxNum, /* Strategy index */
  137817. const char *idxStr, /* Unused */
  137818. int nVal, /* Number of elements in apVal */
  137819. sqlite3_value **apVal /* Arguments for the indexing scheme */
  137820. ){
  137821. int rc = SQLITE_ERROR;
  137822. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  137823. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  137824. UNUSED_PARAMETER(idxStr);
  137825. UNUSED_PARAMETER(nVal);
  137826. fts3tokResetCursor(pCsr);
  137827. if( idxNum==1 ){
  137828. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  137829. int nByte = sqlite3_value_bytes(apVal[0]);
  137830. pCsr->zInput = sqlite3_malloc(nByte+1);
  137831. if( pCsr->zInput==0 ){
  137832. rc = SQLITE_NOMEM;
  137833. }else{
  137834. memcpy(pCsr->zInput, zByte, nByte);
  137835. pCsr->zInput[nByte] = 0;
  137836. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  137837. if( rc==SQLITE_OK ){
  137838. pCsr->pCsr->pTokenizer = pTab->pTok;
  137839. }
  137840. }
  137841. }
  137842. if( rc!=SQLITE_OK ) return rc;
  137843. return fts3tokNextMethod(pCursor);
  137844. }
  137845. /*
  137846. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  137847. */
  137848. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  137849. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  137850. return (pCsr->zToken==0);
  137851. }
  137852. /*
  137853. ** xColumn - Return a column value.
  137854. */
  137855. static int fts3tokColumnMethod(
  137856. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  137857. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  137858. int iCol /* Index of column to read value from */
  137859. ){
  137860. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  137861. /* CREATE TABLE x(input, token, start, end, position) */
  137862. switch( iCol ){
  137863. case 0:
  137864. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  137865. break;
  137866. case 1:
  137867. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  137868. break;
  137869. case 2:
  137870. sqlite3_result_int(pCtx, pCsr->iStart);
  137871. break;
  137872. case 3:
  137873. sqlite3_result_int(pCtx, pCsr->iEnd);
  137874. break;
  137875. default:
  137876. assert( iCol==4 );
  137877. sqlite3_result_int(pCtx, pCsr->iPos);
  137878. break;
  137879. }
  137880. return SQLITE_OK;
  137881. }
  137882. /*
  137883. ** xRowid - Return the current rowid for the cursor.
  137884. */
  137885. static int fts3tokRowidMethod(
  137886. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  137887. sqlite_int64 *pRowid /* OUT: Rowid value */
  137888. ){
  137889. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  137890. *pRowid = (sqlite3_int64)pCsr->iRowid;
  137891. return SQLITE_OK;
  137892. }
  137893. /*
  137894. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  137895. ** if successful or an error code if sqlite3_create_module() fails.
  137896. */
  137897. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  137898. static const sqlite3_module fts3tok_module = {
  137899. 0, /* iVersion */
  137900. fts3tokConnectMethod, /* xCreate */
  137901. fts3tokConnectMethod, /* xConnect */
  137902. fts3tokBestIndexMethod, /* xBestIndex */
  137903. fts3tokDisconnectMethod, /* xDisconnect */
  137904. fts3tokDisconnectMethod, /* xDestroy */
  137905. fts3tokOpenMethod, /* xOpen */
  137906. fts3tokCloseMethod, /* xClose */
  137907. fts3tokFilterMethod, /* xFilter */
  137908. fts3tokNextMethod, /* xNext */
  137909. fts3tokEofMethod, /* xEof */
  137910. fts3tokColumnMethod, /* xColumn */
  137911. fts3tokRowidMethod, /* xRowid */
  137912. 0, /* xUpdate */
  137913. 0, /* xBegin */
  137914. 0, /* xSync */
  137915. 0, /* xCommit */
  137916. 0, /* xRollback */
  137917. 0, /* xFindFunction */
  137918. 0, /* xRename */
  137919. 0, /* xSavepoint */
  137920. 0, /* xRelease */
  137921. 0 /* xRollbackTo */
  137922. };
  137923. int rc; /* Return code */
  137924. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  137925. return rc;
  137926. }
  137927. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  137928. /************** End of fts3_tokenize_vtab.c **********************************/
  137929. /************** Begin file fts3_write.c **************************************/
  137930. /*
  137931. ** 2009 Oct 23
  137932. **
  137933. ** The author disclaims copyright to this source code. In place of
  137934. ** a legal notice, here is a blessing:
  137935. **
  137936. ** May you do good and not evil.
  137937. ** May you find forgiveness for yourself and forgive others.
  137938. ** May you share freely, never taking more than you give.
  137939. **
  137940. ******************************************************************************
  137941. **
  137942. ** This file is part of the SQLite FTS3 extension module. Specifically,
  137943. ** this file contains code to insert, update and delete rows from FTS3
  137944. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  137945. ** of the sub-routines used to merge segments are also used by the query
  137946. ** code in fts3.c.
  137947. */
  137948. /* #include "fts3Int.h" */
  137949. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137950. /* #include <string.h> */
  137951. /* #include <assert.h> */
  137952. /* #include <stdlib.h> */
  137953. #define FTS_MAX_APPENDABLE_HEIGHT 16
  137954. /*
  137955. ** When full-text index nodes are loaded from disk, the buffer that they
  137956. ** are loaded into has the following number of bytes of padding at the end
  137957. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  137958. ** of 920 bytes is allocated for it.
  137959. **
  137960. ** This means that if we have a pointer into a buffer containing node data,
  137961. ** it is always safe to read up to two varints from it without risking an
  137962. ** overread, even if the node data is corrupted.
  137963. */
  137964. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  137965. /*
  137966. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  137967. ** memory incrementally instead of all at once. This can be a big performance
  137968. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  137969. ** method before retrieving all query results (as may happen, for example,
  137970. ** if a query has a LIMIT clause).
  137971. **
  137972. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  137973. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  137974. ** The code is written so that the hard lower-limit for each of these values
  137975. ** is 1. Clearly such small values would be inefficient, but can be useful
  137976. ** for testing purposes.
  137977. **
  137978. ** If this module is built with SQLITE_TEST defined, these constants may
  137979. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  137980. ** a Tcl interface to read and write the values.
  137981. */
  137982. #ifdef SQLITE_TEST
  137983. int test_fts3_node_chunksize = (4*1024);
  137984. int test_fts3_node_chunk_threshold = (4*1024)*4;
  137985. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  137986. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  137987. #else
  137988. # define FTS3_NODE_CHUNKSIZE (4*1024)
  137989. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  137990. #endif
  137991. /*
  137992. ** The two values that may be meaningfully bound to the :1 parameter in
  137993. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  137994. */
  137995. #define FTS_STAT_DOCTOTAL 0
  137996. #define FTS_STAT_INCRMERGEHINT 1
  137997. #define FTS_STAT_AUTOINCRMERGE 2
  137998. /*
  137999. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  138000. ** and incremental merge operation that takes place. This is used for
  138001. ** debugging FTS only, it should not usually be turned on in production
  138002. ** systems.
  138003. */
  138004. #ifdef FTS3_LOG_MERGES
  138005. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  138006. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  138007. }
  138008. #else
  138009. #define fts3LogMerge(x, y)
  138010. #endif
  138011. typedef struct PendingList PendingList;
  138012. typedef struct SegmentNode SegmentNode;
  138013. typedef struct SegmentWriter SegmentWriter;
  138014. /*
  138015. ** An instance of the following data structure is used to build doclists
  138016. ** incrementally. See function fts3PendingListAppend() for details.
  138017. */
  138018. struct PendingList {
  138019. int nData;
  138020. char *aData;
  138021. int nSpace;
  138022. sqlite3_int64 iLastDocid;
  138023. sqlite3_int64 iLastCol;
  138024. sqlite3_int64 iLastPos;
  138025. };
  138026. /*
  138027. ** Each cursor has a (possibly empty) linked list of the following objects.
  138028. */
  138029. struct Fts3DeferredToken {
  138030. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  138031. int iCol; /* Column token must occur in */
  138032. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  138033. PendingList *pList; /* Doclist is assembled here */
  138034. };
  138035. /*
  138036. ** An instance of this structure is used to iterate through the terms on
  138037. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  138038. ** this structure are only manipulated by code in this file, opaque handles
  138039. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  138040. ** terms when querying the full-text index. See functions:
  138041. **
  138042. ** sqlite3Fts3SegReaderNew()
  138043. ** sqlite3Fts3SegReaderFree()
  138044. ** sqlite3Fts3SegReaderIterate()
  138045. **
  138046. ** Methods used to manipulate Fts3SegReader structures:
  138047. **
  138048. ** fts3SegReaderNext()
  138049. ** fts3SegReaderFirstDocid()
  138050. ** fts3SegReaderNextDocid()
  138051. */
  138052. struct Fts3SegReader {
  138053. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  138054. u8 bLookup; /* True for a lookup only */
  138055. u8 rootOnly; /* True for a root-only reader */
  138056. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  138057. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  138058. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  138059. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  138060. char *aNode; /* Pointer to node data (or NULL) */
  138061. int nNode; /* Size of buffer at aNode (or 0) */
  138062. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  138063. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  138064. Fts3HashElem **ppNextElem;
  138065. /* Variables set by fts3SegReaderNext(). These may be read directly
  138066. ** by the caller. They are valid from the time SegmentReaderNew() returns
  138067. ** until SegmentReaderNext() returns something other than SQLITE_OK
  138068. ** (i.e. SQLITE_DONE).
  138069. */
  138070. int nTerm; /* Number of bytes in current term */
  138071. char *zTerm; /* Pointer to current term */
  138072. int nTermAlloc; /* Allocated size of zTerm buffer */
  138073. char *aDoclist; /* Pointer to doclist of current entry */
  138074. int nDoclist; /* Size of doclist in current entry */
  138075. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  138076. ** through the current doclist (aDoclist/nDoclist).
  138077. */
  138078. char *pOffsetList;
  138079. int nOffsetList; /* For descending pending seg-readers only */
  138080. sqlite3_int64 iDocid;
  138081. };
  138082. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  138083. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  138084. /*
  138085. ** An instance of this structure is used to create a segment b-tree in the
  138086. ** database. The internal details of this type are only accessed by the
  138087. ** following functions:
  138088. **
  138089. ** fts3SegWriterAdd()
  138090. ** fts3SegWriterFlush()
  138091. ** fts3SegWriterFree()
  138092. */
  138093. struct SegmentWriter {
  138094. SegmentNode *pTree; /* Pointer to interior tree structure */
  138095. sqlite3_int64 iFirst; /* First slot in %_segments written */
  138096. sqlite3_int64 iFree; /* Next free slot in %_segments */
  138097. char *zTerm; /* Pointer to previous term buffer */
  138098. int nTerm; /* Number of bytes in zTerm */
  138099. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  138100. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  138101. int nSize; /* Size of allocation at aData */
  138102. int nData; /* Bytes of data in aData */
  138103. char *aData; /* Pointer to block from malloc() */
  138104. i64 nLeafData; /* Number of bytes of leaf data written */
  138105. };
  138106. /*
  138107. ** Type SegmentNode is used by the following three functions to create
  138108. ** the interior part of the segment b+-tree structures (everything except
  138109. ** the leaf nodes). These functions and type are only ever used by code
  138110. ** within the fts3SegWriterXXX() family of functions described above.
  138111. **
  138112. ** fts3NodeAddTerm()
  138113. ** fts3NodeWrite()
  138114. ** fts3NodeFree()
  138115. **
  138116. ** When a b+tree is written to the database (either as a result of a merge
  138117. ** or the pending-terms table being flushed), leaves are written into the
  138118. ** database file as soon as they are completely populated. The interior of
  138119. ** the tree is assembled in memory and written out only once all leaves have
  138120. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  138121. ** very large, meaning that the interior of the tree consumes relatively
  138122. ** little memory.
  138123. */
  138124. struct SegmentNode {
  138125. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  138126. SegmentNode *pRight; /* Pointer to right-sibling */
  138127. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  138128. int nEntry; /* Number of terms written to node so far */
  138129. char *zTerm; /* Pointer to previous term buffer */
  138130. int nTerm; /* Number of bytes in zTerm */
  138131. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  138132. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  138133. int nData; /* Bytes of valid data so far */
  138134. char *aData; /* Node data */
  138135. };
  138136. /*
  138137. ** Valid values for the second argument to fts3SqlStmt().
  138138. */
  138139. #define SQL_DELETE_CONTENT 0
  138140. #define SQL_IS_EMPTY 1
  138141. #define SQL_DELETE_ALL_CONTENT 2
  138142. #define SQL_DELETE_ALL_SEGMENTS 3
  138143. #define SQL_DELETE_ALL_SEGDIR 4
  138144. #define SQL_DELETE_ALL_DOCSIZE 5
  138145. #define SQL_DELETE_ALL_STAT 6
  138146. #define SQL_SELECT_CONTENT_BY_ROWID 7
  138147. #define SQL_NEXT_SEGMENT_INDEX 8
  138148. #define SQL_INSERT_SEGMENTS 9
  138149. #define SQL_NEXT_SEGMENTS_ID 10
  138150. #define SQL_INSERT_SEGDIR 11
  138151. #define SQL_SELECT_LEVEL 12
  138152. #define SQL_SELECT_LEVEL_RANGE 13
  138153. #define SQL_SELECT_LEVEL_COUNT 14
  138154. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  138155. #define SQL_DELETE_SEGDIR_LEVEL 16
  138156. #define SQL_DELETE_SEGMENTS_RANGE 17
  138157. #define SQL_CONTENT_INSERT 18
  138158. #define SQL_DELETE_DOCSIZE 19
  138159. #define SQL_REPLACE_DOCSIZE 20
  138160. #define SQL_SELECT_DOCSIZE 21
  138161. #define SQL_SELECT_STAT 22
  138162. #define SQL_REPLACE_STAT 23
  138163. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  138164. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  138165. #define SQL_DELETE_SEGDIR_RANGE 26
  138166. #define SQL_SELECT_ALL_LANGID 27
  138167. #define SQL_FIND_MERGE_LEVEL 28
  138168. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  138169. #define SQL_DELETE_SEGDIR_ENTRY 30
  138170. #define SQL_SHIFT_SEGDIR_ENTRY 31
  138171. #define SQL_SELECT_SEGDIR 32
  138172. #define SQL_CHOMP_SEGDIR 33
  138173. #define SQL_SEGMENT_IS_APPENDABLE 34
  138174. #define SQL_SELECT_INDEXES 35
  138175. #define SQL_SELECT_MXLEVEL 36
  138176. #define SQL_SELECT_LEVEL_RANGE2 37
  138177. #define SQL_UPDATE_LEVEL_IDX 38
  138178. #define SQL_UPDATE_LEVEL 39
  138179. /*
  138180. ** This function is used to obtain an SQLite prepared statement handle
  138181. ** for the statement identified by the second argument. If successful,
  138182. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  138183. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  138184. **
  138185. ** If argument apVal is not NULL, then it must point to an array with
  138186. ** at least as many entries as the requested statement has bound
  138187. ** parameters. The values are bound to the statements parameters before
  138188. ** returning.
  138189. */
  138190. static int fts3SqlStmt(
  138191. Fts3Table *p, /* Virtual table handle */
  138192. int eStmt, /* One of the SQL_XXX constants above */
  138193. sqlite3_stmt **pp, /* OUT: Statement handle */
  138194. sqlite3_value **apVal /* Values to bind to statement */
  138195. ){
  138196. const char *azSql[] = {
  138197. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  138198. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  138199. /* 2 */ "DELETE FROM %Q.'%q_content'",
  138200. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  138201. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  138202. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  138203. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  138204. /* 7 */ "SELECT %s WHERE rowid=?",
  138205. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  138206. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  138207. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  138208. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  138209. /* Return segments in order from oldest to newest.*/
  138210. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  138211. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  138212. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  138213. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  138214. "ORDER BY level DESC, idx ASC",
  138215. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  138216. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  138217. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  138218. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  138219. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  138220. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  138221. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  138222. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  138223. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  138224. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  138225. /* 24 */ "",
  138226. /* 25 */ "",
  138227. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  138228. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  138229. /* This statement is used to determine which level to read the input from
  138230. ** when performing an incremental merge. It returns the absolute level number
  138231. ** of the oldest level in the db that contains at least ? segments. Or,
  138232. ** if no level in the FTS index contains more than ? segments, the statement
  138233. ** returns zero rows. */
  138234. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  138235. " ORDER BY (level %% 1024) ASC LIMIT 1",
  138236. /* Estimate the upper limit on the number of leaf nodes in a new segment
  138237. ** created by merging the oldest :2 segments from absolute level :1. See
  138238. ** function sqlite3Fts3Incrmerge() for details. */
  138239. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  138240. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  138241. /* SQL_DELETE_SEGDIR_ENTRY
  138242. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  138243. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  138244. /* SQL_SHIFT_SEGDIR_ENTRY
  138245. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  138246. ** to :1. */
  138247. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  138248. /* SQL_SELECT_SEGDIR
  138249. ** Read a single entry from the %_segdir table. The entry from absolute
  138250. ** level :1 with index value :2. */
  138251. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  138252. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  138253. /* SQL_CHOMP_SEGDIR
  138254. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  138255. ** entry located on absolute level :3 with index :4. */
  138256. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  138257. "WHERE level = ? AND idx = ?",
  138258. /* SQL_SEGMENT_IS_APPENDABLE
  138259. ** Return a single row if the segment with end_block=? is appendable. Or
  138260. ** no rows otherwise. */
  138261. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  138262. /* SQL_SELECT_INDEXES
  138263. ** Return the list of valid segment indexes for absolute level ? */
  138264. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  138265. /* SQL_SELECT_MXLEVEL
  138266. ** Return the largest relative level in the FTS index or indexes. */
  138267. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  138268. /* Return segments in order from oldest to newest.*/
  138269. /* 37 */ "SELECT level, idx, end_block "
  138270. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  138271. "ORDER BY level DESC, idx ASC",
  138272. /* Update statements used while promoting segments */
  138273. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  138274. "WHERE level=? AND idx=?",
  138275. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  138276. };
  138277. int rc = SQLITE_OK;
  138278. sqlite3_stmt *pStmt;
  138279. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  138280. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  138281. pStmt = p->aStmt[eStmt];
  138282. if( !pStmt ){
  138283. char *zSql;
  138284. if( eStmt==SQL_CONTENT_INSERT ){
  138285. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  138286. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  138287. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  138288. }else{
  138289. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  138290. }
  138291. if( !zSql ){
  138292. rc = SQLITE_NOMEM;
  138293. }else{
  138294. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  138295. sqlite3_free(zSql);
  138296. assert( rc==SQLITE_OK || pStmt==0 );
  138297. p->aStmt[eStmt] = pStmt;
  138298. }
  138299. }
  138300. if( apVal ){
  138301. int i;
  138302. int nParam = sqlite3_bind_parameter_count(pStmt);
  138303. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  138304. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  138305. }
  138306. }
  138307. *pp = pStmt;
  138308. return rc;
  138309. }
  138310. static int fts3SelectDocsize(
  138311. Fts3Table *pTab, /* FTS3 table handle */
  138312. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  138313. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  138314. ){
  138315. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  138316. int rc; /* Return code */
  138317. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  138318. if( rc==SQLITE_OK ){
  138319. sqlite3_bind_int64(pStmt, 1, iDocid);
  138320. rc = sqlite3_step(pStmt);
  138321. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  138322. rc = sqlite3_reset(pStmt);
  138323. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  138324. pStmt = 0;
  138325. }else{
  138326. rc = SQLITE_OK;
  138327. }
  138328. }
  138329. *ppStmt = pStmt;
  138330. return rc;
  138331. }
  138332. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  138333. Fts3Table *pTab, /* Fts3 table handle */
  138334. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  138335. ){
  138336. sqlite3_stmt *pStmt = 0;
  138337. int rc;
  138338. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  138339. if( rc==SQLITE_OK ){
  138340. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  138341. if( sqlite3_step(pStmt)!=SQLITE_ROW
  138342. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  138343. ){
  138344. rc = sqlite3_reset(pStmt);
  138345. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  138346. pStmt = 0;
  138347. }
  138348. }
  138349. *ppStmt = pStmt;
  138350. return rc;
  138351. }
  138352. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  138353. Fts3Table *pTab, /* Fts3 table handle */
  138354. sqlite3_int64 iDocid, /* Docid to read size data for */
  138355. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  138356. ){
  138357. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  138358. }
  138359. /*
  138360. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  138361. ** array apVal[] to the SQL statement identified by eStmt, the statement
  138362. ** is executed.
  138363. **
  138364. ** Returns SQLITE_OK if the statement is successfully executed, or an
  138365. ** SQLite error code otherwise.
  138366. */
  138367. static void fts3SqlExec(
  138368. int *pRC, /* Result code */
  138369. Fts3Table *p, /* The FTS3 table */
  138370. int eStmt, /* Index of statement to evaluate */
  138371. sqlite3_value **apVal /* Parameters to bind */
  138372. ){
  138373. sqlite3_stmt *pStmt;
  138374. int rc;
  138375. if( *pRC ) return;
  138376. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  138377. if( rc==SQLITE_OK ){
  138378. sqlite3_step(pStmt);
  138379. rc = sqlite3_reset(pStmt);
  138380. }
  138381. *pRC = rc;
  138382. }
  138383. /*
  138384. ** This function ensures that the caller has obtained an exclusive
  138385. ** shared-cache table-lock on the %_segdir table. This is required before
  138386. ** writing data to the fts3 table. If this lock is not acquired first, then
  138387. ** the caller may end up attempting to take this lock as part of committing
  138388. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  138389. ** LOCKED_SHAREDCACHEto a COMMIT command.
  138390. **
  138391. ** It is best to avoid this because if FTS3 returns any error when
  138392. ** committing a transaction, the whole transaction will be rolled back.
  138393. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  138394. ** It can still happen if the user locks the underlying tables directly
  138395. ** instead of accessing them via FTS.
  138396. */
  138397. static int fts3Writelock(Fts3Table *p){
  138398. int rc = SQLITE_OK;
  138399. if( p->nPendingData==0 ){
  138400. sqlite3_stmt *pStmt;
  138401. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  138402. if( rc==SQLITE_OK ){
  138403. sqlite3_bind_null(pStmt, 1);
  138404. sqlite3_step(pStmt);
  138405. rc = sqlite3_reset(pStmt);
  138406. }
  138407. }
  138408. return rc;
  138409. }
  138410. /*
  138411. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  138412. ** Within each language id, a separate index is maintained to store the
  138413. ** document terms, and each configured prefix size (configured the FTS
  138414. ** "prefix=" option). And each index consists of multiple levels ("relative
  138415. ** levels").
  138416. **
  138417. ** All three of these values (the language id, the specific index and the
  138418. ** level within the index) are encoded in 64-bit integer values stored
  138419. ** in the %_segdir table on disk. This function is used to convert three
  138420. ** separate component values into the single 64-bit integer value that
  138421. ** can be used to query the %_segdir table.
  138422. **
  138423. ** Specifically, each language-id/index combination is allocated 1024
  138424. ** 64-bit integer level values ("absolute levels"). The main terms index
  138425. ** for language-id 0 is allocate values 0-1023. The first prefix index
  138426. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  138427. ** Language 1 indexes are allocated immediately following language 0.
  138428. **
  138429. ** So, for a system with nPrefix prefix indexes configured, the block of
  138430. ** absolute levels that corresponds to language-id iLangid and index
  138431. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  138432. */
  138433. static sqlite3_int64 getAbsoluteLevel(
  138434. Fts3Table *p, /* FTS3 table handle */
  138435. int iLangid, /* Language id */
  138436. int iIndex, /* Index in p->aIndex[] */
  138437. int iLevel /* Level of segments */
  138438. ){
  138439. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  138440. assert( iLangid>=0 );
  138441. assert( p->nIndex>0 );
  138442. assert( iIndex>=0 && iIndex<p->nIndex );
  138443. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  138444. return iBase + iLevel;
  138445. }
  138446. /*
  138447. ** Set *ppStmt to a statement handle that may be used to iterate through
  138448. ** all rows in the %_segdir table, from oldest to newest. If successful,
  138449. ** return SQLITE_OK. If an error occurs while preparing the statement,
  138450. ** return an SQLite error code.
  138451. **
  138452. ** There is only ever one instance of this SQL statement compiled for
  138453. ** each FTS3 table.
  138454. **
  138455. ** The statement returns the following columns from the %_segdir table:
  138456. **
  138457. ** 0: idx
  138458. ** 1: start_block
  138459. ** 2: leaves_end_block
  138460. ** 3: end_block
  138461. ** 4: root
  138462. */
  138463. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  138464. Fts3Table *p, /* FTS3 table */
  138465. int iLangid, /* Language being queried */
  138466. int iIndex, /* Index for p->aIndex[] */
  138467. int iLevel, /* Level to select (relative level) */
  138468. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  138469. ){
  138470. int rc;
  138471. sqlite3_stmt *pStmt = 0;
  138472. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  138473. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  138474. assert( iIndex>=0 && iIndex<p->nIndex );
  138475. if( iLevel<0 ){
  138476. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  138477. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  138478. if( rc==SQLITE_OK ){
  138479. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  138480. sqlite3_bind_int64(pStmt, 2,
  138481. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  138482. );
  138483. }
  138484. }else{
  138485. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  138486. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  138487. if( rc==SQLITE_OK ){
  138488. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  138489. }
  138490. }
  138491. *ppStmt = pStmt;
  138492. return rc;
  138493. }
  138494. /*
  138495. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  138496. ** if successful, or an SQLite error code otherwise.
  138497. **
  138498. ** This function also serves to allocate the PendingList structure itself.
  138499. ** For example, to create a new PendingList structure containing two
  138500. ** varints:
  138501. **
  138502. ** PendingList *p = 0;
  138503. ** fts3PendingListAppendVarint(&p, 1);
  138504. ** fts3PendingListAppendVarint(&p, 2);
  138505. */
  138506. static int fts3PendingListAppendVarint(
  138507. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  138508. sqlite3_int64 i /* Value to append to data */
  138509. ){
  138510. PendingList *p = *pp;
  138511. /* Allocate or grow the PendingList as required. */
  138512. if( !p ){
  138513. p = sqlite3_malloc(sizeof(*p) + 100);
  138514. if( !p ){
  138515. return SQLITE_NOMEM;
  138516. }
  138517. p->nSpace = 100;
  138518. p->aData = (char *)&p[1];
  138519. p->nData = 0;
  138520. }
  138521. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  138522. int nNew = p->nSpace * 2;
  138523. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  138524. if( !p ){
  138525. sqlite3_free(*pp);
  138526. *pp = 0;
  138527. return SQLITE_NOMEM;
  138528. }
  138529. p->nSpace = nNew;
  138530. p->aData = (char *)&p[1];
  138531. }
  138532. /* Append the new serialized varint to the end of the list. */
  138533. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  138534. p->aData[p->nData] = '\0';
  138535. *pp = p;
  138536. return SQLITE_OK;
  138537. }
  138538. /*
  138539. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  138540. ** is returned if the structure is sqlite3_realloced as part of adding
  138541. ** the entry. Otherwise, zero.
  138542. **
  138543. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  138544. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  138545. ** it is set to SQLITE_OK.
  138546. */
  138547. static int fts3PendingListAppend(
  138548. PendingList **pp, /* IN/OUT: PendingList structure */
  138549. sqlite3_int64 iDocid, /* Docid for entry to add */
  138550. sqlite3_int64 iCol, /* Column for entry to add */
  138551. sqlite3_int64 iPos, /* Position of term for entry to add */
  138552. int *pRc /* OUT: Return code */
  138553. ){
  138554. PendingList *p = *pp;
  138555. int rc = SQLITE_OK;
  138556. assert( !p || p->iLastDocid<=iDocid );
  138557. if( !p || p->iLastDocid!=iDocid ){
  138558. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  138559. if( p ){
  138560. assert( p->nData<p->nSpace );
  138561. assert( p->aData[p->nData]==0 );
  138562. p->nData++;
  138563. }
  138564. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  138565. goto pendinglistappend_out;
  138566. }
  138567. p->iLastCol = -1;
  138568. p->iLastPos = 0;
  138569. p->iLastDocid = iDocid;
  138570. }
  138571. if( iCol>0 && p->iLastCol!=iCol ){
  138572. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  138573. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  138574. ){
  138575. goto pendinglistappend_out;
  138576. }
  138577. p->iLastCol = iCol;
  138578. p->iLastPos = 0;
  138579. }
  138580. if( iCol>=0 ){
  138581. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  138582. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  138583. if( rc==SQLITE_OK ){
  138584. p->iLastPos = iPos;
  138585. }
  138586. }
  138587. pendinglistappend_out:
  138588. *pRc = rc;
  138589. if( p!=*pp ){
  138590. *pp = p;
  138591. return 1;
  138592. }
  138593. return 0;
  138594. }
  138595. /*
  138596. ** Free a PendingList object allocated by fts3PendingListAppend().
  138597. */
  138598. static void fts3PendingListDelete(PendingList *pList){
  138599. sqlite3_free(pList);
  138600. }
  138601. /*
  138602. ** Add an entry to one of the pending-terms hash tables.
  138603. */
  138604. static int fts3PendingTermsAddOne(
  138605. Fts3Table *p,
  138606. int iCol,
  138607. int iPos,
  138608. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  138609. const char *zToken,
  138610. int nToken
  138611. ){
  138612. PendingList *pList;
  138613. int rc = SQLITE_OK;
  138614. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  138615. if( pList ){
  138616. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  138617. }
  138618. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  138619. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  138620. /* Malloc failed while inserting the new entry. This can only
  138621. ** happen if there was no previous entry for this token.
  138622. */
  138623. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  138624. sqlite3_free(pList);
  138625. rc = SQLITE_NOMEM;
  138626. }
  138627. }
  138628. if( rc==SQLITE_OK ){
  138629. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  138630. }
  138631. return rc;
  138632. }
  138633. /*
  138634. ** Tokenize the nul-terminated string zText and add all tokens to the
  138635. ** pending-terms hash-table. The docid used is that currently stored in
  138636. ** p->iPrevDocid, and the column is specified by argument iCol.
  138637. **
  138638. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  138639. */
  138640. static int fts3PendingTermsAdd(
  138641. Fts3Table *p, /* Table into which text will be inserted */
  138642. int iLangid, /* Language id to use */
  138643. const char *zText, /* Text of document to be inserted */
  138644. int iCol, /* Column into which text is being inserted */
  138645. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  138646. ){
  138647. int rc;
  138648. int iStart = 0;
  138649. int iEnd = 0;
  138650. int iPos = 0;
  138651. int nWord = 0;
  138652. char const *zToken;
  138653. int nToken = 0;
  138654. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  138655. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  138656. sqlite3_tokenizer_cursor *pCsr;
  138657. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  138658. const char**,int*,int*,int*,int*);
  138659. assert( pTokenizer && pModule );
  138660. /* If the user has inserted a NULL value, this function may be called with
  138661. ** zText==0. In this case, add zero token entries to the hash table and
  138662. ** return early. */
  138663. if( zText==0 ){
  138664. *pnWord = 0;
  138665. return SQLITE_OK;
  138666. }
  138667. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  138668. if( rc!=SQLITE_OK ){
  138669. return rc;
  138670. }
  138671. xNext = pModule->xNext;
  138672. while( SQLITE_OK==rc
  138673. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  138674. ){
  138675. int i;
  138676. if( iPos>=nWord ) nWord = iPos+1;
  138677. /* Positions cannot be negative; we use -1 as a terminator internally.
  138678. ** Tokens must have a non-zero length.
  138679. */
  138680. if( iPos<0 || !zToken || nToken<=0 ){
  138681. rc = SQLITE_ERROR;
  138682. break;
  138683. }
  138684. /* Add the term to the terms index */
  138685. rc = fts3PendingTermsAddOne(
  138686. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  138687. );
  138688. /* Add the term to each of the prefix indexes that it is not too
  138689. ** short for. */
  138690. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  138691. struct Fts3Index *pIndex = &p->aIndex[i];
  138692. if( nToken<pIndex->nPrefix ) continue;
  138693. rc = fts3PendingTermsAddOne(
  138694. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  138695. );
  138696. }
  138697. }
  138698. pModule->xClose(pCsr);
  138699. *pnWord += nWord;
  138700. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  138701. }
  138702. /*
  138703. ** Calling this function indicates that subsequent calls to
  138704. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  138705. ** contents of the document with docid iDocid.
  138706. */
  138707. static int fts3PendingTermsDocid(
  138708. Fts3Table *p, /* Full-text table handle */
  138709. int bDelete, /* True if this op is a delete */
  138710. int iLangid, /* Language id of row being written */
  138711. sqlite_int64 iDocid /* Docid of row being written */
  138712. ){
  138713. assert( iLangid>=0 );
  138714. assert( bDelete==1 || bDelete==0 );
  138715. /* TODO(shess) Explore whether partially flushing the buffer on
  138716. ** forced-flush would provide better performance. I suspect that if
  138717. ** we ordered the doclists by size and flushed the largest until the
  138718. ** buffer was half empty, that would let the less frequent terms
  138719. ** generate longer doclists.
  138720. */
  138721. if( iDocid<p->iPrevDocid
  138722. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  138723. || p->iPrevLangid!=iLangid
  138724. || p->nPendingData>p->nMaxPendingData
  138725. ){
  138726. int rc = sqlite3Fts3PendingTermsFlush(p);
  138727. if( rc!=SQLITE_OK ) return rc;
  138728. }
  138729. p->iPrevDocid = iDocid;
  138730. p->iPrevLangid = iLangid;
  138731. p->bPrevDelete = bDelete;
  138732. return SQLITE_OK;
  138733. }
  138734. /*
  138735. ** Discard the contents of the pending-terms hash tables.
  138736. */
  138737. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  138738. int i;
  138739. for(i=0; i<p->nIndex; i++){
  138740. Fts3HashElem *pElem;
  138741. Fts3Hash *pHash = &p->aIndex[i].hPending;
  138742. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  138743. PendingList *pList = (PendingList *)fts3HashData(pElem);
  138744. fts3PendingListDelete(pList);
  138745. }
  138746. fts3HashClear(pHash);
  138747. }
  138748. p->nPendingData = 0;
  138749. }
  138750. /*
  138751. ** This function is called by the xUpdate() method as part of an INSERT
  138752. ** operation. It adds entries for each term in the new record to the
  138753. ** pendingTerms hash table.
  138754. **
  138755. ** Argument apVal is the same as the similarly named argument passed to
  138756. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  138757. */
  138758. static int fts3InsertTerms(
  138759. Fts3Table *p,
  138760. int iLangid,
  138761. sqlite3_value **apVal,
  138762. u32 *aSz
  138763. ){
  138764. int i; /* Iterator variable */
  138765. for(i=2; i<p->nColumn+2; i++){
  138766. int iCol = i-2;
  138767. if( p->abNotindexed[iCol]==0 ){
  138768. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  138769. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  138770. if( rc!=SQLITE_OK ){
  138771. return rc;
  138772. }
  138773. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  138774. }
  138775. }
  138776. return SQLITE_OK;
  138777. }
  138778. /*
  138779. ** This function is called by the xUpdate() method for an INSERT operation.
  138780. ** The apVal parameter is passed a copy of the apVal argument passed by
  138781. ** SQLite to the xUpdate() method. i.e:
  138782. **
  138783. ** apVal[0] Not used for INSERT.
  138784. ** apVal[1] rowid
  138785. ** apVal[2] Left-most user-defined column
  138786. ** ...
  138787. ** apVal[p->nColumn+1] Right-most user-defined column
  138788. ** apVal[p->nColumn+2] Hidden column with same name as table
  138789. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  138790. ** apVal[p->nColumn+4] Hidden languageid column
  138791. */
  138792. static int fts3InsertData(
  138793. Fts3Table *p, /* Full-text table */
  138794. sqlite3_value **apVal, /* Array of values to insert */
  138795. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  138796. ){
  138797. int rc; /* Return code */
  138798. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  138799. if( p->zContentTbl ){
  138800. sqlite3_value *pRowid = apVal[p->nColumn+3];
  138801. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  138802. pRowid = apVal[1];
  138803. }
  138804. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  138805. return SQLITE_CONSTRAINT;
  138806. }
  138807. *piDocid = sqlite3_value_int64(pRowid);
  138808. return SQLITE_OK;
  138809. }
  138810. /* Locate the statement handle used to insert data into the %_content
  138811. ** table. The SQL for this statement is:
  138812. **
  138813. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  138814. **
  138815. ** The statement features N '?' variables, where N is the number of user
  138816. ** defined columns in the FTS3 table, plus one for the docid field.
  138817. */
  138818. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  138819. if( rc==SQLITE_OK && p->zLanguageid ){
  138820. rc = sqlite3_bind_int(
  138821. pContentInsert, p->nColumn+2,
  138822. sqlite3_value_int(apVal[p->nColumn+4])
  138823. );
  138824. }
  138825. if( rc!=SQLITE_OK ) return rc;
  138826. /* There is a quirk here. The users INSERT statement may have specified
  138827. ** a value for the "rowid" field, for the "docid" field, or for both.
  138828. ** Which is a problem, since "rowid" and "docid" are aliases for the
  138829. ** same value. For example:
  138830. **
  138831. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  138832. **
  138833. ** In FTS3, this is an error. It is an error to specify non-NULL values
  138834. ** for both docid and some other rowid alias.
  138835. */
  138836. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  138837. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  138838. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  138839. ){
  138840. /* A rowid/docid conflict. */
  138841. return SQLITE_ERROR;
  138842. }
  138843. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  138844. if( rc!=SQLITE_OK ) return rc;
  138845. }
  138846. /* Execute the statement to insert the record. Set *piDocid to the
  138847. ** new docid value.
  138848. */
  138849. sqlite3_step(pContentInsert);
  138850. rc = sqlite3_reset(pContentInsert);
  138851. *piDocid = sqlite3_last_insert_rowid(p->db);
  138852. return rc;
  138853. }
  138854. /*
  138855. ** Remove all data from the FTS3 table. Clear the hash table containing
  138856. ** pending terms.
  138857. */
  138858. static int fts3DeleteAll(Fts3Table *p, int bContent){
  138859. int rc = SQLITE_OK; /* Return code */
  138860. /* Discard the contents of the pending-terms hash table. */
  138861. sqlite3Fts3PendingTermsClear(p);
  138862. /* Delete everything from the shadow tables. Except, leave %_content as
  138863. ** is if bContent is false. */
  138864. assert( p->zContentTbl==0 || bContent==0 );
  138865. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  138866. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  138867. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  138868. if( p->bHasDocsize ){
  138869. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  138870. }
  138871. if( p->bHasStat ){
  138872. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  138873. }
  138874. return rc;
  138875. }
  138876. /*
  138877. **
  138878. */
  138879. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  138880. int iLangid = 0;
  138881. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  138882. return iLangid;
  138883. }
  138884. /*
  138885. ** The first element in the apVal[] array is assumed to contain the docid
  138886. ** (an integer) of a row about to be deleted. Remove all terms from the
  138887. ** full-text index.
  138888. */
  138889. static void fts3DeleteTerms(
  138890. int *pRC, /* Result code */
  138891. Fts3Table *p, /* The FTS table to delete from */
  138892. sqlite3_value *pRowid, /* The docid to be deleted */
  138893. u32 *aSz, /* Sizes of deleted document written here */
  138894. int *pbFound /* OUT: Set to true if row really does exist */
  138895. ){
  138896. int rc;
  138897. sqlite3_stmt *pSelect;
  138898. assert( *pbFound==0 );
  138899. if( *pRC ) return;
  138900. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  138901. if( rc==SQLITE_OK ){
  138902. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  138903. int i;
  138904. int iLangid = langidFromSelect(p, pSelect);
  138905. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  138906. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  138907. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  138908. int iCol = i-1;
  138909. if( p->abNotindexed[iCol]==0 ){
  138910. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  138911. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  138912. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  138913. }
  138914. }
  138915. if( rc!=SQLITE_OK ){
  138916. sqlite3_reset(pSelect);
  138917. *pRC = rc;
  138918. return;
  138919. }
  138920. *pbFound = 1;
  138921. }
  138922. rc = sqlite3_reset(pSelect);
  138923. }else{
  138924. sqlite3_reset(pSelect);
  138925. }
  138926. *pRC = rc;
  138927. }
  138928. /*
  138929. ** Forward declaration to account for the circular dependency between
  138930. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  138931. */
  138932. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  138933. /*
  138934. ** This function allocates a new level iLevel index in the segdir table.
  138935. ** Usually, indexes are allocated within a level sequentially starting
  138936. ** with 0, so the allocated index is one greater than the value returned
  138937. ** by:
  138938. **
  138939. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  138940. **
  138941. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  138942. ** level, they are merged into a single level (iLevel+1) segment and the
  138943. ** allocated index is 0.
  138944. **
  138945. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  138946. ** returned. Otherwise, an SQLite error code is returned.
  138947. */
  138948. static int fts3AllocateSegdirIdx(
  138949. Fts3Table *p,
  138950. int iLangid, /* Language id */
  138951. int iIndex, /* Index for p->aIndex */
  138952. int iLevel,
  138953. int *piIdx
  138954. ){
  138955. int rc; /* Return Code */
  138956. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  138957. int iNext = 0; /* Result of query pNextIdx */
  138958. assert( iLangid>=0 );
  138959. assert( p->nIndex>=1 );
  138960. /* Set variable iNext to the next available segdir index at level iLevel. */
  138961. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  138962. if( rc==SQLITE_OK ){
  138963. sqlite3_bind_int64(
  138964. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  138965. );
  138966. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  138967. iNext = sqlite3_column_int(pNextIdx, 0);
  138968. }
  138969. rc = sqlite3_reset(pNextIdx);
  138970. }
  138971. if( rc==SQLITE_OK ){
  138972. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  138973. ** full, merge all segments in level iLevel into a single iLevel+1
  138974. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  138975. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  138976. */
  138977. if( iNext>=FTS3_MERGE_COUNT ){
  138978. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  138979. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  138980. *piIdx = 0;
  138981. }else{
  138982. *piIdx = iNext;
  138983. }
  138984. }
  138985. return rc;
  138986. }
  138987. /*
  138988. ** The %_segments table is declared as follows:
  138989. **
  138990. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  138991. **
  138992. ** This function reads data from a single row of the %_segments table. The
  138993. ** specific row is identified by the iBlockid parameter. If paBlob is not
  138994. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  138995. ** with the contents of the blob stored in the "block" column of the
  138996. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  138997. ** to the size of the blob in bytes before returning.
  138998. **
  138999. ** If an error occurs, or the table does not contain the specified row,
  139000. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  139001. ** paBlob is non-NULL, then it is the responsibility of the caller to
  139002. ** eventually free the returned buffer.
  139003. **
  139004. ** This function may leave an open sqlite3_blob* handle in the
  139005. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  139006. ** to this function. The handle may be closed by calling the
  139007. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  139008. ** performance improvement, but the blob handle should always be closed
  139009. ** before control is returned to the user (to prevent a lock being held
  139010. ** on the database file for longer than necessary). Thus, any virtual table
  139011. ** method (xFilter etc.) that may directly or indirectly call this function
  139012. ** must call sqlite3Fts3SegmentsClose() before returning.
  139013. */
  139014. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  139015. Fts3Table *p, /* FTS3 table handle */
  139016. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  139017. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  139018. int *pnBlob, /* OUT: Size of blob data */
  139019. int *pnLoad /* OUT: Bytes actually loaded */
  139020. ){
  139021. int rc; /* Return code */
  139022. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  139023. assert( pnBlob );
  139024. if( p->pSegments ){
  139025. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  139026. }else{
  139027. if( 0==p->zSegmentsTbl ){
  139028. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  139029. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  139030. }
  139031. rc = sqlite3_blob_open(
  139032. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  139033. );
  139034. }
  139035. if( rc==SQLITE_OK ){
  139036. int nByte = sqlite3_blob_bytes(p->pSegments);
  139037. *pnBlob = nByte;
  139038. if( paBlob ){
  139039. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  139040. if( !aByte ){
  139041. rc = SQLITE_NOMEM;
  139042. }else{
  139043. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  139044. nByte = FTS3_NODE_CHUNKSIZE;
  139045. *pnLoad = nByte;
  139046. }
  139047. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  139048. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  139049. if( rc!=SQLITE_OK ){
  139050. sqlite3_free(aByte);
  139051. aByte = 0;
  139052. }
  139053. }
  139054. *paBlob = aByte;
  139055. }
  139056. }
  139057. return rc;
  139058. }
  139059. /*
  139060. ** Close the blob handle at p->pSegments, if it is open. See comments above
  139061. ** the sqlite3Fts3ReadBlock() function for details.
  139062. */
  139063. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  139064. sqlite3_blob_close(p->pSegments);
  139065. p->pSegments = 0;
  139066. }
  139067. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  139068. int nRead; /* Number of bytes to read */
  139069. int rc; /* Return code */
  139070. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  139071. rc = sqlite3_blob_read(
  139072. pReader->pBlob,
  139073. &pReader->aNode[pReader->nPopulate],
  139074. nRead,
  139075. pReader->nPopulate
  139076. );
  139077. if( rc==SQLITE_OK ){
  139078. pReader->nPopulate += nRead;
  139079. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  139080. if( pReader->nPopulate==pReader->nNode ){
  139081. sqlite3_blob_close(pReader->pBlob);
  139082. pReader->pBlob = 0;
  139083. pReader->nPopulate = 0;
  139084. }
  139085. }
  139086. return rc;
  139087. }
  139088. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  139089. int rc = SQLITE_OK;
  139090. assert( !pReader->pBlob
  139091. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  139092. );
  139093. while( pReader->pBlob && rc==SQLITE_OK
  139094. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  139095. ){
  139096. rc = fts3SegReaderIncrRead(pReader);
  139097. }
  139098. return rc;
  139099. }
  139100. /*
  139101. ** Set an Fts3SegReader cursor to point at EOF.
  139102. */
  139103. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  139104. if( !fts3SegReaderIsRootOnly(pSeg) ){
  139105. sqlite3_free(pSeg->aNode);
  139106. sqlite3_blob_close(pSeg->pBlob);
  139107. pSeg->pBlob = 0;
  139108. }
  139109. pSeg->aNode = 0;
  139110. }
  139111. /*
  139112. ** Move the iterator passed as the first argument to the next term in the
  139113. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  139114. ** SQLITE_DONE. Otherwise, an SQLite error code.
  139115. */
  139116. static int fts3SegReaderNext(
  139117. Fts3Table *p,
  139118. Fts3SegReader *pReader,
  139119. int bIncr
  139120. ){
  139121. int rc; /* Return code of various sub-routines */
  139122. char *pNext; /* Cursor variable */
  139123. int nPrefix; /* Number of bytes in term prefix */
  139124. int nSuffix; /* Number of bytes in term suffix */
  139125. if( !pReader->aDoclist ){
  139126. pNext = pReader->aNode;
  139127. }else{
  139128. pNext = &pReader->aDoclist[pReader->nDoclist];
  139129. }
  139130. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  139131. if( fts3SegReaderIsPending(pReader) ){
  139132. Fts3HashElem *pElem = *(pReader->ppNextElem);
  139133. sqlite3_free(pReader->aNode);
  139134. pReader->aNode = 0;
  139135. if( pElem ){
  139136. char *aCopy;
  139137. PendingList *pList = (PendingList *)fts3HashData(pElem);
  139138. int nCopy = pList->nData+1;
  139139. pReader->zTerm = (char *)fts3HashKey(pElem);
  139140. pReader->nTerm = fts3HashKeysize(pElem);
  139141. aCopy = (char*)sqlite3_malloc(nCopy);
  139142. if( !aCopy ) return SQLITE_NOMEM;
  139143. memcpy(aCopy, pList->aData, nCopy);
  139144. pReader->nNode = pReader->nDoclist = nCopy;
  139145. pReader->aNode = pReader->aDoclist = aCopy;
  139146. pReader->ppNextElem++;
  139147. assert( pReader->aNode );
  139148. }
  139149. return SQLITE_OK;
  139150. }
  139151. fts3SegReaderSetEof(pReader);
  139152. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  139153. ** blocks have already been traversed. */
  139154. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  139155. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  139156. return SQLITE_OK;
  139157. }
  139158. rc = sqlite3Fts3ReadBlock(
  139159. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  139160. (bIncr ? &pReader->nPopulate : 0)
  139161. );
  139162. if( rc!=SQLITE_OK ) return rc;
  139163. assert( pReader->pBlob==0 );
  139164. if( bIncr && pReader->nPopulate<pReader->nNode ){
  139165. pReader->pBlob = p->pSegments;
  139166. p->pSegments = 0;
  139167. }
  139168. pNext = pReader->aNode;
  139169. }
  139170. assert( !fts3SegReaderIsPending(pReader) );
  139171. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  139172. if( rc!=SQLITE_OK ) return rc;
  139173. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  139174. ** safe (no risk of overread) even if the node data is corrupted. */
  139175. pNext += fts3GetVarint32(pNext, &nPrefix);
  139176. pNext += fts3GetVarint32(pNext, &nSuffix);
  139177. if( nPrefix<0 || nSuffix<=0
  139178. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  139179. ){
  139180. return FTS_CORRUPT_VTAB;
  139181. }
  139182. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  139183. int nNew = (nPrefix+nSuffix)*2;
  139184. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  139185. if( !zNew ){
  139186. return SQLITE_NOMEM;
  139187. }
  139188. pReader->zTerm = zNew;
  139189. pReader->nTermAlloc = nNew;
  139190. }
  139191. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  139192. if( rc!=SQLITE_OK ) return rc;
  139193. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  139194. pReader->nTerm = nPrefix+nSuffix;
  139195. pNext += nSuffix;
  139196. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  139197. pReader->aDoclist = pNext;
  139198. pReader->pOffsetList = 0;
  139199. /* Check that the doclist does not appear to extend past the end of the
  139200. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  139201. ** of these statements is untrue, then the data structure is corrupt.
  139202. */
  139203. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  139204. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  139205. ){
  139206. return FTS_CORRUPT_VTAB;
  139207. }
  139208. return SQLITE_OK;
  139209. }
  139210. /*
  139211. ** Set the SegReader to point to the first docid in the doclist associated
  139212. ** with the current term.
  139213. */
  139214. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  139215. int rc = SQLITE_OK;
  139216. assert( pReader->aDoclist );
  139217. assert( !pReader->pOffsetList );
  139218. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  139219. u8 bEof = 0;
  139220. pReader->iDocid = 0;
  139221. pReader->nOffsetList = 0;
  139222. sqlite3Fts3DoclistPrev(0,
  139223. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  139224. &pReader->iDocid, &pReader->nOffsetList, &bEof
  139225. );
  139226. }else{
  139227. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  139228. if( rc==SQLITE_OK ){
  139229. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  139230. pReader->pOffsetList = &pReader->aDoclist[n];
  139231. }
  139232. }
  139233. return rc;
  139234. }
  139235. /*
  139236. ** Advance the SegReader to point to the next docid in the doclist
  139237. ** associated with the current term.
  139238. **
  139239. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  139240. ** *ppOffsetList is set to point to the first column-offset list
  139241. ** in the doclist entry (i.e. immediately past the docid varint).
  139242. ** *pnOffsetList is set to the length of the set of column-offset
  139243. ** lists, not including the nul-terminator byte. For example:
  139244. */
  139245. static int fts3SegReaderNextDocid(
  139246. Fts3Table *pTab,
  139247. Fts3SegReader *pReader, /* Reader to advance to next docid */
  139248. char **ppOffsetList, /* OUT: Pointer to current position-list */
  139249. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  139250. ){
  139251. int rc = SQLITE_OK;
  139252. char *p = pReader->pOffsetList;
  139253. char c = 0;
  139254. assert( p );
  139255. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  139256. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  139257. ** Pending-terms doclists are always built up in ascending order, so
  139258. ** we have to iterate through them backwards here. */
  139259. u8 bEof = 0;
  139260. if( ppOffsetList ){
  139261. *ppOffsetList = pReader->pOffsetList;
  139262. *pnOffsetList = pReader->nOffsetList - 1;
  139263. }
  139264. sqlite3Fts3DoclistPrev(0,
  139265. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  139266. &pReader->nOffsetList, &bEof
  139267. );
  139268. if( bEof ){
  139269. pReader->pOffsetList = 0;
  139270. }else{
  139271. pReader->pOffsetList = p;
  139272. }
  139273. }else{
  139274. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  139275. /* Pointer p currently points at the first byte of an offset list. The
  139276. ** following block advances it to point one byte past the end of
  139277. ** the same offset list. */
  139278. while( 1 ){
  139279. /* The following line of code (and the "p++" below the while() loop) is
  139280. ** normally all that is required to move pointer p to the desired
  139281. ** position. The exception is if this node is being loaded from disk
  139282. ** incrementally and pointer "p" now points to the first byte past
  139283. ** the populated part of pReader->aNode[].
  139284. */
  139285. while( *p | c ) c = *p++ & 0x80;
  139286. assert( *p==0 );
  139287. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  139288. rc = fts3SegReaderIncrRead(pReader);
  139289. if( rc!=SQLITE_OK ) return rc;
  139290. }
  139291. p++;
  139292. /* If required, populate the output variables with a pointer to and the
  139293. ** size of the previous offset-list.
  139294. */
  139295. if( ppOffsetList ){
  139296. *ppOffsetList = pReader->pOffsetList;
  139297. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  139298. }
  139299. /* List may have been edited in place by fts3EvalNearTrim() */
  139300. while( p<pEnd && *p==0 ) p++;
  139301. /* If there are no more entries in the doclist, set pOffsetList to
  139302. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  139303. ** Fts3SegReader.pOffsetList to point to the next offset list before
  139304. ** returning.
  139305. */
  139306. if( p>=pEnd ){
  139307. pReader->pOffsetList = 0;
  139308. }else{
  139309. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  139310. if( rc==SQLITE_OK ){
  139311. sqlite3_int64 iDelta;
  139312. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  139313. if( pTab->bDescIdx ){
  139314. pReader->iDocid -= iDelta;
  139315. }else{
  139316. pReader->iDocid += iDelta;
  139317. }
  139318. }
  139319. }
  139320. }
  139321. return SQLITE_OK;
  139322. }
  139323. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  139324. Fts3Cursor *pCsr,
  139325. Fts3MultiSegReader *pMsr,
  139326. int *pnOvfl
  139327. ){
  139328. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  139329. int nOvfl = 0;
  139330. int ii;
  139331. int rc = SQLITE_OK;
  139332. int pgsz = p->nPgsz;
  139333. assert( p->bFts4 );
  139334. assert( pgsz>0 );
  139335. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  139336. Fts3SegReader *pReader = pMsr->apSegment[ii];
  139337. if( !fts3SegReaderIsPending(pReader)
  139338. && !fts3SegReaderIsRootOnly(pReader)
  139339. ){
  139340. sqlite3_int64 jj;
  139341. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  139342. int nBlob;
  139343. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  139344. if( rc!=SQLITE_OK ) break;
  139345. if( (nBlob+35)>pgsz ){
  139346. nOvfl += (nBlob + 34)/pgsz;
  139347. }
  139348. }
  139349. }
  139350. }
  139351. *pnOvfl = nOvfl;
  139352. return rc;
  139353. }
  139354. /*
  139355. ** Free all allocations associated with the iterator passed as the
  139356. ** second argument.
  139357. */
  139358. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  139359. if( pReader ){
  139360. if( !fts3SegReaderIsPending(pReader) ){
  139361. sqlite3_free(pReader->zTerm);
  139362. }
  139363. if( !fts3SegReaderIsRootOnly(pReader) ){
  139364. sqlite3_free(pReader->aNode);
  139365. }
  139366. sqlite3_blob_close(pReader->pBlob);
  139367. }
  139368. sqlite3_free(pReader);
  139369. }
  139370. /*
  139371. ** Allocate a new SegReader object.
  139372. */
  139373. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  139374. int iAge, /* Segment "age". */
  139375. int bLookup, /* True for a lookup only */
  139376. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  139377. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  139378. sqlite3_int64 iEndBlock, /* Final block of segment */
  139379. const char *zRoot, /* Buffer containing root node */
  139380. int nRoot, /* Size of buffer containing root node */
  139381. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  139382. ){
  139383. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  139384. int nExtra = 0; /* Bytes to allocate segment root node */
  139385. assert( iStartLeaf<=iEndLeaf );
  139386. if( iStartLeaf==0 ){
  139387. nExtra = nRoot + FTS3_NODE_PADDING;
  139388. }
  139389. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  139390. if( !pReader ){
  139391. return SQLITE_NOMEM;
  139392. }
  139393. memset(pReader, 0, sizeof(Fts3SegReader));
  139394. pReader->iIdx = iAge;
  139395. pReader->bLookup = bLookup!=0;
  139396. pReader->iStartBlock = iStartLeaf;
  139397. pReader->iLeafEndBlock = iEndLeaf;
  139398. pReader->iEndBlock = iEndBlock;
  139399. if( nExtra ){
  139400. /* The entire segment is stored in the root node. */
  139401. pReader->aNode = (char *)&pReader[1];
  139402. pReader->rootOnly = 1;
  139403. pReader->nNode = nRoot;
  139404. memcpy(pReader->aNode, zRoot, nRoot);
  139405. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  139406. }else{
  139407. pReader->iCurrentBlock = iStartLeaf-1;
  139408. }
  139409. *ppReader = pReader;
  139410. return SQLITE_OK;
  139411. }
  139412. /*
  139413. ** This is a comparison function used as a qsort() callback when sorting
  139414. ** an array of pending terms by term. This occurs as part of flushing
  139415. ** the contents of the pending-terms hash table to the database.
  139416. */
  139417. static int SQLITE_CDECL fts3CompareElemByTerm(
  139418. const void *lhs,
  139419. const void *rhs
  139420. ){
  139421. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  139422. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  139423. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  139424. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  139425. int n = (n1<n2 ? n1 : n2);
  139426. int c = memcmp(z1, z2, n);
  139427. if( c==0 ){
  139428. c = n1 - n2;
  139429. }
  139430. return c;
  139431. }
  139432. /*
  139433. ** This function is used to allocate an Fts3SegReader that iterates through
  139434. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  139435. **
  139436. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  139437. ** through each term in the pending-terms table. Or, if isPrefixIter is
  139438. ** non-zero, it iterates through each term and its prefixes. For example, if
  139439. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  139440. ** "firebird", then the iterator visits the following 'terms' (in the order
  139441. ** shown):
  139442. **
  139443. ** f fi fir fire fireb firebi firebir firebird
  139444. ** m my mys mysq mysql
  139445. ** s sq sql sqli sqlit sqlite
  139446. **
  139447. ** Whereas if isPrefixIter is zero, the terms visited are:
  139448. **
  139449. ** firebird mysql sqlite
  139450. */
  139451. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  139452. Fts3Table *p, /* Virtual table handle */
  139453. int iIndex, /* Index for p->aIndex */
  139454. const char *zTerm, /* Term to search for */
  139455. int nTerm, /* Size of buffer zTerm */
  139456. int bPrefix, /* True for a prefix iterator */
  139457. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  139458. ){
  139459. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  139460. Fts3HashElem *pE; /* Iterator variable */
  139461. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  139462. int nElem = 0; /* Size of array at aElem */
  139463. int rc = SQLITE_OK; /* Return Code */
  139464. Fts3Hash *pHash;
  139465. pHash = &p->aIndex[iIndex].hPending;
  139466. if( bPrefix ){
  139467. int nAlloc = 0; /* Size of allocated array at aElem */
  139468. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  139469. char *zKey = (char *)fts3HashKey(pE);
  139470. int nKey = fts3HashKeysize(pE);
  139471. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  139472. if( nElem==nAlloc ){
  139473. Fts3HashElem **aElem2;
  139474. nAlloc += 16;
  139475. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  139476. aElem, nAlloc*sizeof(Fts3HashElem *)
  139477. );
  139478. if( !aElem2 ){
  139479. rc = SQLITE_NOMEM;
  139480. nElem = 0;
  139481. break;
  139482. }
  139483. aElem = aElem2;
  139484. }
  139485. aElem[nElem++] = pE;
  139486. }
  139487. }
  139488. /* If more than one term matches the prefix, sort the Fts3HashElem
  139489. ** objects in term order using qsort(). This uses the same comparison
  139490. ** callback as is used when flushing terms to disk.
  139491. */
  139492. if( nElem>1 ){
  139493. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  139494. }
  139495. }else{
  139496. /* The query is a simple term lookup that matches at most one term in
  139497. ** the index. All that is required is a straight hash-lookup.
  139498. **
  139499. ** Because the stack address of pE may be accessed via the aElem pointer
  139500. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  139501. ** within this entire function, not just this "else{...}" block.
  139502. */
  139503. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  139504. if( pE ){
  139505. aElem = &pE;
  139506. nElem = 1;
  139507. }
  139508. }
  139509. if( nElem>0 ){
  139510. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  139511. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  139512. if( !pReader ){
  139513. rc = SQLITE_NOMEM;
  139514. }else{
  139515. memset(pReader, 0, nByte);
  139516. pReader->iIdx = 0x7FFFFFFF;
  139517. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  139518. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  139519. }
  139520. }
  139521. if( bPrefix ){
  139522. sqlite3_free(aElem);
  139523. }
  139524. *ppReader = pReader;
  139525. return rc;
  139526. }
  139527. /*
  139528. ** Compare the entries pointed to by two Fts3SegReader structures.
  139529. ** Comparison is as follows:
  139530. **
  139531. ** 1) EOF is greater than not EOF.
  139532. **
  139533. ** 2) The current terms (if any) are compared using memcmp(). If one
  139534. ** term is a prefix of another, the longer term is considered the
  139535. ** larger.
  139536. **
  139537. ** 3) By segment age. An older segment is considered larger.
  139538. */
  139539. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  139540. int rc;
  139541. if( pLhs->aNode && pRhs->aNode ){
  139542. int rc2 = pLhs->nTerm - pRhs->nTerm;
  139543. if( rc2<0 ){
  139544. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  139545. }else{
  139546. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  139547. }
  139548. if( rc==0 ){
  139549. rc = rc2;
  139550. }
  139551. }else{
  139552. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  139553. }
  139554. if( rc==0 ){
  139555. rc = pRhs->iIdx - pLhs->iIdx;
  139556. }
  139557. assert( rc!=0 );
  139558. return rc;
  139559. }
  139560. /*
  139561. ** A different comparison function for SegReader structures. In this
  139562. ** version, it is assumed that each SegReader points to an entry in
  139563. ** a doclist for identical terms. Comparison is made as follows:
  139564. **
  139565. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  139566. **
  139567. ** 2) By current docid.
  139568. **
  139569. ** 3) By segment age. An older segment is considered larger.
  139570. */
  139571. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  139572. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  139573. if( rc==0 ){
  139574. if( pLhs->iDocid==pRhs->iDocid ){
  139575. rc = pRhs->iIdx - pLhs->iIdx;
  139576. }else{
  139577. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  139578. }
  139579. }
  139580. assert( pLhs->aNode && pRhs->aNode );
  139581. return rc;
  139582. }
  139583. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  139584. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  139585. if( rc==0 ){
  139586. if( pLhs->iDocid==pRhs->iDocid ){
  139587. rc = pRhs->iIdx - pLhs->iIdx;
  139588. }else{
  139589. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  139590. }
  139591. }
  139592. assert( pLhs->aNode && pRhs->aNode );
  139593. return rc;
  139594. }
  139595. /*
  139596. ** Compare the term that the Fts3SegReader object passed as the first argument
  139597. ** points to with the term specified by arguments zTerm and nTerm.
  139598. **
  139599. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  139600. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  139601. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  139602. */
  139603. static int fts3SegReaderTermCmp(
  139604. Fts3SegReader *pSeg, /* Segment reader object */
  139605. const char *zTerm, /* Term to compare to */
  139606. int nTerm /* Size of term zTerm in bytes */
  139607. ){
  139608. int res = 0;
  139609. if( pSeg->aNode ){
  139610. if( pSeg->nTerm>nTerm ){
  139611. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  139612. }else{
  139613. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  139614. }
  139615. if( res==0 ){
  139616. res = pSeg->nTerm-nTerm;
  139617. }
  139618. }
  139619. return res;
  139620. }
  139621. /*
  139622. ** Argument apSegment is an array of nSegment elements. It is known that
  139623. ** the final (nSegment-nSuspect) members are already in sorted order
  139624. ** (according to the comparison function provided). This function shuffles
  139625. ** the array around until all entries are in sorted order.
  139626. */
  139627. static void fts3SegReaderSort(
  139628. Fts3SegReader **apSegment, /* Array to sort entries of */
  139629. int nSegment, /* Size of apSegment array */
  139630. int nSuspect, /* Unsorted entry count */
  139631. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  139632. ){
  139633. int i; /* Iterator variable */
  139634. assert( nSuspect<=nSegment );
  139635. if( nSuspect==nSegment ) nSuspect--;
  139636. for(i=nSuspect-1; i>=0; i--){
  139637. int j;
  139638. for(j=i; j<(nSegment-1); j++){
  139639. Fts3SegReader *pTmp;
  139640. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  139641. pTmp = apSegment[j+1];
  139642. apSegment[j+1] = apSegment[j];
  139643. apSegment[j] = pTmp;
  139644. }
  139645. }
  139646. #ifndef NDEBUG
  139647. /* Check that the list really is sorted now. */
  139648. for(i=0; i<(nSuspect-1); i++){
  139649. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  139650. }
  139651. #endif
  139652. }
  139653. /*
  139654. ** Insert a record into the %_segments table.
  139655. */
  139656. static int fts3WriteSegment(
  139657. Fts3Table *p, /* Virtual table handle */
  139658. sqlite3_int64 iBlock, /* Block id for new block */
  139659. char *z, /* Pointer to buffer containing block data */
  139660. int n /* Size of buffer z in bytes */
  139661. ){
  139662. sqlite3_stmt *pStmt;
  139663. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  139664. if( rc==SQLITE_OK ){
  139665. sqlite3_bind_int64(pStmt, 1, iBlock);
  139666. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  139667. sqlite3_step(pStmt);
  139668. rc = sqlite3_reset(pStmt);
  139669. }
  139670. return rc;
  139671. }
  139672. /*
  139673. ** Find the largest relative level number in the table. If successful, set
  139674. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  139675. ** set *pnMax to zero and return an SQLite error code.
  139676. */
  139677. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  139678. int rc;
  139679. int mxLevel = 0;
  139680. sqlite3_stmt *pStmt = 0;
  139681. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  139682. if( rc==SQLITE_OK ){
  139683. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  139684. mxLevel = sqlite3_column_int(pStmt, 0);
  139685. }
  139686. rc = sqlite3_reset(pStmt);
  139687. }
  139688. *pnMax = mxLevel;
  139689. return rc;
  139690. }
  139691. /*
  139692. ** Insert a record into the %_segdir table.
  139693. */
  139694. static int fts3WriteSegdir(
  139695. Fts3Table *p, /* Virtual table handle */
  139696. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  139697. int iIdx, /* Value for "idx" field */
  139698. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  139699. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  139700. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  139701. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  139702. char *zRoot, /* Blob value for "root" field */
  139703. int nRoot /* Number of bytes in buffer zRoot */
  139704. ){
  139705. sqlite3_stmt *pStmt;
  139706. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  139707. if( rc==SQLITE_OK ){
  139708. sqlite3_bind_int64(pStmt, 1, iLevel);
  139709. sqlite3_bind_int(pStmt, 2, iIdx);
  139710. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  139711. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  139712. if( nLeafData==0 ){
  139713. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  139714. }else{
  139715. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  139716. if( !zEnd ) return SQLITE_NOMEM;
  139717. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  139718. }
  139719. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  139720. sqlite3_step(pStmt);
  139721. rc = sqlite3_reset(pStmt);
  139722. }
  139723. return rc;
  139724. }
  139725. /*
  139726. ** Return the size of the common prefix (if any) shared by zPrev and
  139727. ** zNext, in bytes. For example,
  139728. **
  139729. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  139730. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  139731. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  139732. */
  139733. static int fts3PrefixCompress(
  139734. const char *zPrev, /* Buffer containing previous term */
  139735. int nPrev, /* Size of buffer zPrev in bytes */
  139736. const char *zNext, /* Buffer containing next term */
  139737. int nNext /* Size of buffer zNext in bytes */
  139738. ){
  139739. int n;
  139740. UNUSED_PARAMETER(nNext);
  139741. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  139742. return n;
  139743. }
  139744. /*
  139745. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  139746. ** (according to memcmp) than the previous term.
  139747. */
  139748. static int fts3NodeAddTerm(
  139749. Fts3Table *p, /* Virtual table handle */
  139750. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  139751. int isCopyTerm, /* True if zTerm/nTerm is transient */
  139752. const char *zTerm, /* Pointer to buffer containing term */
  139753. int nTerm /* Size of term in bytes */
  139754. ){
  139755. SegmentNode *pTree = *ppTree;
  139756. int rc;
  139757. SegmentNode *pNew;
  139758. /* First try to append the term to the current node. Return early if
  139759. ** this is possible.
  139760. */
  139761. if( pTree ){
  139762. int nData = pTree->nData; /* Current size of node in bytes */
  139763. int nReq = nData; /* Required space after adding zTerm */
  139764. int nPrefix; /* Number of bytes of prefix compression */
  139765. int nSuffix; /* Suffix length */
  139766. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  139767. nSuffix = nTerm-nPrefix;
  139768. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  139769. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  139770. if( nReq>p->nNodeSize ){
  139771. /* An unusual case: this is the first term to be added to the node
  139772. ** and the static node buffer (p->nNodeSize bytes) is not large
  139773. ** enough. Use a separately malloced buffer instead This wastes
  139774. ** p->nNodeSize bytes, but since this scenario only comes about when
  139775. ** the database contain two terms that share a prefix of almost 2KB,
  139776. ** this is not expected to be a serious problem.
  139777. */
  139778. assert( pTree->aData==(char *)&pTree[1] );
  139779. pTree->aData = (char *)sqlite3_malloc(nReq);
  139780. if( !pTree->aData ){
  139781. return SQLITE_NOMEM;
  139782. }
  139783. }
  139784. if( pTree->zTerm ){
  139785. /* There is no prefix-length field for first term in a node */
  139786. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  139787. }
  139788. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  139789. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  139790. pTree->nData = nData + nSuffix;
  139791. pTree->nEntry++;
  139792. if( isCopyTerm ){
  139793. if( pTree->nMalloc<nTerm ){
  139794. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  139795. if( !zNew ){
  139796. return SQLITE_NOMEM;
  139797. }
  139798. pTree->nMalloc = nTerm*2;
  139799. pTree->zMalloc = zNew;
  139800. }
  139801. pTree->zTerm = pTree->zMalloc;
  139802. memcpy(pTree->zTerm, zTerm, nTerm);
  139803. pTree->nTerm = nTerm;
  139804. }else{
  139805. pTree->zTerm = (char *)zTerm;
  139806. pTree->nTerm = nTerm;
  139807. }
  139808. return SQLITE_OK;
  139809. }
  139810. }
  139811. /* If control flows to here, it was not possible to append zTerm to the
  139812. ** current node. Create a new node (a right-sibling of the current node).
  139813. ** If this is the first node in the tree, the term is added to it.
  139814. **
  139815. ** Otherwise, the term is not added to the new node, it is left empty for
  139816. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  139817. ** has no parent, one is created here.
  139818. */
  139819. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  139820. if( !pNew ){
  139821. return SQLITE_NOMEM;
  139822. }
  139823. memset(pNew, 0, sizeof(SegmentNode));
  139824. pNew->nData = 1 + FTS3_VARINT_MAX;
  139825. pNew->aData = (char *)&pNew[1];
  139826. if( pTree ){
  139827. SegmentNode *pParent = pTree->pParent;
  139828. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  139829. if( pTree->pParent==0 ){
  139830. pTree->pParent = pParent;
  139831. }
  139832. pTree->pRight = pNew;
  139833. pNew->pLeftmost = pTree->pLeftmost;
  139834. pNew->pParent = pParent;
  139835. pNew->zMalloc = pTree->zMalloc;
  139836. pNew->nMalloc = pTree->nMalloc;
  139837. pTree->zMalloc = 0;
  139838. }else{
  139839. pNew->pLeftmost = pNew;
  139840. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  139841. }
  139842. *ppTree = pNew;
  139843. return rc;
  139844. }
  139845. /*
  139846. ** Helper function for fts3NodeWrite().
  139847. */
  139848. static int fts3TreeFinishNode(
  139849. SegmentNode *pTree,
  139850. int iHeight,
  139851. sqlite3_int64 iLeftChild
  139852. ){
  139853. int nStart;
  139854. assert( iHeight>=1 && iHeight<128 );
  139855. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  139856. pTree->aData[nStart] = (char)iHeight;
  139857. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  139858. return nStart;
  139859. }
  139860. /*
  139861. ** Write the buffer for the segment node pTree and all of its peers to the
  139862. ** database. Then call this function recursively to write the parent of
  139863. ** pTree and its peers to the database.
  139864. **
  139865. ** Except, if pTree is a root node, do not write it to the database. Instead,
  139866. ** set output variables *paRoot and *pnRoot to contain the root node.
  139867. **
  139868. ** If successful, SQLITE_OK is returned and output variable *piLast is
  139869. ** set to the largest blockid written to the database (or zero if no
  139870. ** blocks were written to the db). Otherwise, an SQLite error code is
  139871. ** returned.
  139872. */
  139873. static int fts3NodeWrite(
  139874. Fts3Table *p, /* Virtual table handle */
  139875. SegmentNode *pTree, /* SegmentNode handle */
  139876. int iHeight, /* Height of this node in tree */
  139877. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  139878. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  139879. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  139880. char **paRoot, /* OUT: Data for root node */
  139881. int *pnRoot /* OUT: Size of root node in bytes */
  139882. ){
  139883. int rc = SQLITE_OK;
  139884. if( !pTree->pParent ){
  139885. /* Root node of the tree. */
  139886. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  139887. *piLast = iFree-1;
  139888. *pnRoot = pTree->nData - nStart;
  139889. *paRoot = &pTree->aData[nStart];
  139890. }else{
  139891. SegmentNode *pIter;
  139892. sqlite3_int64 iNextFree = iFree;
  139893. sqlite3_int64 iNextLeaf = iLeaf;
  139894. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  139895. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  139896. int nWrite = pIter->nData - nStart;
  139897. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  139898. iNextFree++;
  139899. iNextLeaf += (pIter->nEntry+1);
  139900. }
  139901. if( rc==SQLITE_OK ){
  139902. assert( iNextLeaf==iFree );
  139903. rc = fts3NodeWrite(
  139904. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  139905. );
  139906. }
  139907. }
  139908. return rc;
  139909. }
  139910. /*
  139911. ** Free all memory allocations associated with the tree pTree.
  139912. */
  139913. static void fts3NodeFree(SegmentNode *pTree){
  139914. if( pTree ){
  139915. SegmentNode *p = pTree->pLeftmost;
  139916. fts3NodeFree(p->pParent);
  139917. while( p ){
  139918. SegmentNode *pRight = p->pRight;
  139919. if( p->aData!=(char *)&p[1] ){
  139920. sqlite3_free(p->aData);
  139921. }
  139922. assert( pRight==0 || p->zMalloc==0 );
  139923. sqlite3_free(p->zMalloc);
  139924. sqlite3_free(p);
  139925. p = pRight;
  139926. }
  139927. }
  139928. }
  139929. /*
  139930. ** Add a term to the segment being constructed by the SegmentWriter object
  139931. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  139932. ** be passed NULL. This function will allocate a new SegmentWriter object
  139933. ** and return it via the input/output variable *ppWriter in this case.
  139934. **
  139935. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  139936. */
  139937. static int fts3SegWriterAdd(
  139938. Fts3Table *p, /* Virtual table handle */
  139939. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  139940. int isCopyTerm, /* True if buffer zTerm must be copied */
  139941. const char *zTerm, /* Pointer to buffer containing term */
  139942. int nTerm, /* Size of term in bytes */
  139943. const char *aDoclist, /* Pointer to buffer containing doclist */
  139944. int nDoclist /* Size of doclist in bytes */
  139945. ){
  139946. int nPrefix; /* Size of term prefix in bytes */
  139947. int nSuffix; /* Size of term suffix in bytes */
  139948. int nReq; /* Number of bytes required on leaf page */
  139949. int nData;
  139950. SegmentWriter *pWriter = *ppWriter;
  139951. if( !pWriter ){
  139952. int rc;
  139953. sqlite3_stmt *pStmt;
  139954. /* Allocate the SegmentWriter structure */
  139955. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  139956. if( !pWriter ) return SQLITE_NOMEM;
  139957. memset(pWriter, 0, sizeof(SegmentWriter));
  139958. *ppWriter = pWriter;
  139959. /* Allocate a buffer in which to accumulate data */
  139960. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  139961. if( !pWriter->aData ) return SQLITE_NOMEM;
  139962. pWriter->nSize = p->nNodeSize;
  139963. /* Find the next free blockid in the %_segments table */
  139964. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  139965. if( rc!=SQLITE_OK ) return rc;
  139966. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  139967. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  139968. pWriter->iFirst = pWriter->iFree;
  139969. }
  139970. rc = sqlite3_reset(pStmt);
  139971. if( rc!=SQLITE_OK ) return rc;
  139972. }
  139973. nData = pWriter->nData;
  139974. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  139975. nSuffix = nTerm-nPrefix;
  139976. /* Figure out how many bytes are required by this new entry */
  139977. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  139978. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  139979. nSuffix + /* Term suffix */
  139980. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  139981. nDoclist; /* Doclist data */
  139982. if( nData>0 && nData+nReq>p->nNodeSize ){
  139983. int rc;
  139984. /* The current leaf node is full. Write it out to the database. */
  139985. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  139986. if( rc!=SQLITE_OK ) return rc;
  139987. p->nLeafAdd++;
  139988. /* Add the current term to the interior node tree. The term added to
  139989. ** the interior tree must:
  139990. **
  139991. ** a) be greater than the largest term on the leaf node just written
  139992. ** to the database (still available in pWriter->zTerm), and
  139993. **
  139994. ** b) be less than or equal to the term about to be added to the new
  139995. ** leaf node (zTerm/nTerm).
  139996. **
  139997. ** In other words, it must be the prefix of zTerm 1 byte longer than
  139998. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  139999. */
  140000. assert( nPrefix<nTerm );
  140001. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  140002. if( rc!=SQLITE_OK ) return rc;
  140003. nData = 0;
  140004. pWriter->nTerm = 0;
  140005. nPrefix = 0;
  140006. nSuffix = nTerm;
  140007. nReq = 1 + /* varint containing prefix size */
  140008. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  140009. nTerm + /* Term suffix */
  140010. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  140011. nDoclist; /* Doclist data */
  140012. }
  140013. /* Increase the total number of bytes written to account for the new entry. */
  140014. pWriter->nLeafData += nReq;
  140015. /* If the buffer currently allocated is too small for this entry, realloc
  140016. ** the buffer to make it large enough.
  140017. */
  140018. if( nReq>pWriter->nSize ){
  140019. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  140020. if( !aNew ) return SQLITE_NOMEM;
  140021. pWriter->aData = aNew;
  140022. pWriter->nSize = nReq;
  140023. }
  140024. assert( nData+nReq<=pWriter->nSize );
  140025. /* Append the prefix-compressed term and doclist to the buffer. */
  140026. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  140027. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  140028. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  140029. nData += nSuffix;
  140030. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  140031. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  140032. pWriter->nData = nData + nDoclist;
  140033. /* Save the current term so that it can be used to prefix-compress the next.
  140034. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  140035. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  140036. ** store a copy of the pointer.
  140037. */
  140038. if( isCopyTerm ){
  140039. if( nTerm>pWriter->nMalloc ){
  140040. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  140041. if( !zNew ){
  140042. return SQLITE_NOMEM;
  140043. }
  140044. pWriter->nMalloc = nTerm*2;
  140045. pWriter->zMalloc = zNew;
  140046. pWriter->zTerm = zNew;
  140047. }
  140048. assert( pWriter->zTerm==pWriter->zMalloc );
  140049. memcpy(pWriter->zTerm, zTerm, nTerm);
  140050. }else{
  140051. pWriter->zTerm = (char *)zTerm;
  140052. }
  140053. pWriter->nTerm = nTerm;
  140054. return SQLITE_OK;
  140055. }
  140056. /*
  140057. ** Flush all data associated with the SegmentWriter object pWriter to the
  140058. ** database. This function must be called after all terms have been added
  140059. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  140060. ** returned. Otherwise, an SQLite error code.
  140061. */
  140062. static int fts3SegWriterFlush(
  140063. Fts3Table *p, /* Virtual table handle */
  140064. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  140065. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  140066. int iIdx /* Value for 'idx' column of %_segdir */
  140067. ){
  140068. int rc; /* Return code */
  140069. if( pWriter->pTree ){
  140070. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  140071. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  140072. char *zRoot = NULL; /* Pointer to buffer containing root node */
  140073. int nRoot = 0; /* Size of buffer zRoot */
  140074. iLastLeaf = pWriter->iFree;
  140075. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  140076. if( rc==SQLITE_OK ){
  140077. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  140078. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  140079. }
  140080. if( rc==SQLITE_OK ){
  140081. rc = fts3WriteSegdir(p, iLevel, iIdx,
  140082. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  140083. }
  140084. }else{
  140085. /* The entire tree fits on the root node. Write it to the segdir table. */
  140086. rc = fts3WriteSegdir(p, iLevel, iIdx,
  140087. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  140088. }
  140089. p->nLeafAdd++;
  140090. return rc;
  140091. }
  140092. /*
  140093. ** Release all memory held by the SegmentWriter object passed as the
  140094. ** first argument.
  140095. */
  140096. static void fts3SegWriterFree(SegmentWriter *pWriter){
  140097. if( pWriter ){
  140098. sqlite3_free(pWriter->aData);
  140099. sqlite3_free(pWriter->zMalloc);
  140100. fts3NodeFree(pWriter->pTree);
  140101. sqlite3_free(pWriter);
  140102. }
  140103. }
  140104. /*
  140105. ** The first value in the apVal[] array is assumed to contain an integer.
  140106. ** This function tests if there exist any documents with docid values that
  140107. ** are different from that integer. i.e. if deleting the document with docid
  140108. ** pRowid would mean the FTS3 table were empty.
  140109. **
  140110. ** If successful, *pisEmpty is set to true if the table is empty except for
  140111. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  140112. ** error occurs, an SQLite error code is returned.
  140113. */
  140114. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  140115. sqlite3_stmt *pStmt;
  140116. int rc;
  140117. if( p->zContentTbl ){
  140118. /* If using the content=xxx option, assume the table is never empty */
  140119. *pisEmpty = 0;
  140120. rc = SQLITE_OK;
  140121. }else{
  140122. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  140123. if( rc==SQLITE_OK ){
  140124. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  140125. *pisEmpty = sqlite3_column_int(pStmt, 0);
  140126. }
  140127. rc = sqlite3_reset(pStmt);
  140128. }
  140129. }
  140130. return rc;
  140131. }
  140132. /*
  140133. ** Set *pnMax to the largest segment level in the database for the index
  140134. ** iIndex.
  140135. **
  140136. ** Segment levels are stored in the 'level' column of the %_segdir table.
  140137. **
  140138. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  140139. */
  140140. static int fts3SegmentMaxLevel(
  140141. Fts3Table *p,
  140142. int iLangid,
  140143. int iIndex,
  140144. sqlite3_int64 *pnMax
  140145. ){
  140146. sqlite3_stmt *pStmt;
  140147. int rc;
  140148. assert( iIndex>=0 && iIndex<p->nIndex );
  140149. /* Set pStmt to the compiled version of:
  140150. **
  140151. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  140152. **
  140153. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  140154. */
  140155. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  140156. if( rc!=SQLITE_OK ) return rc;
  140157. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  140158. sqlite3_bind_int64(pStmt, 2,
  140159. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  140160. );
  140161. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  140162. *pnMax = sqlite3_column_int64(pStmt, 0);
  140163. }
  140164. return sqlite3_reset(pStmt);
  140165. }
  140166. /*
  140167. ** iAbsLevel is an absolute level that may be assumed to exist within
  140168. ** the database. This function checks if it is the largest level number
  140169. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  140170. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  140171. ** is returned. If an error occurs, an error code is returned and the
  140172. ** final value of *pbMax is undefined.
  140173. */
  140174. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  140175. /* Set pStmt to the compiled version of:
  140176. **
  140177. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  140178. **
  140179. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  140180. */
  140181. sqlite3_stmt *pStmt;
  140182. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  140183. if( rc!=SQLITE_OK ) return rc;
  140184. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  140185. sqlite3_bind_int64(pStmt, 2,
  140186. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  140187. );
  140188. *pbMax = 0;
  140189. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  140190. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  140191. }
  140192. return sqlite3_reset(pStmt);
  140193. }
  140194. /*
  140195. ** Delete all entries in the %_segments table associated with the segment
  140196. ** opened with seg-reader pSeg. This function does not affect the contents
  140197. ** of the %_segdir table.
  140198. */
  140199. static int fts3DeleteSegment(
  140200. Fts3Table *p, /* FTS table handle */
  140201. Fts3SegReader *pSeg /* Segment to delete */
  140202. ){
  140203. int rc = SQLITE_OK; /* Return code */
  140204. if( pSeg->iStartBlock ){
  140205. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  140206. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  140207. if( rc==SQLITE_OK ){
  140208. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  140209. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  140210. sqlite3_step(pDelete);
  140211. rc = sqlite3_reset(pDelete);
  140212. }
  140213. }
  140214. return rc;
  140215. }
  140216. /*
  140217. ** This function is used after merging multiple segments into a single large
  140218. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  140219. ** it:
  140220. **
  140221. ** 1) Deletes all %_segments entries for the segments associated with
  140222. ** each of the SegReader objects in the array passed as the third
  140223. ** argument, and
  140224. **
  140225. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  140226. ** entries regardless of level if (iLevel<0).
  140227. **
  140228. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  140229. */
  140230. static int fts3DeleteSegdir(
  140231. Fts3Table *p, /* Virtual table handle */
  140232. int iLangid, /* Language id */
  140233. int iIndex, /* Index for p->aIndex */
  140234. int iLevel, /* Level of %_segdir entries to delete */
  140235. Fts3SegReader **apSegment, /* Array of SegReader objects */
  140236. int nReader /* Size of array apSegment */
  140237. ){
  140238. int rc = SQLITE_OK; /* Return Code */
  140239. int i; /* Iterator variable */
  140240. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  140241. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  140242. rc = fts3DeleteSegment(p, apSegment[i]);
  140243. }
  140244. if( rc!=SQLITE_OK ){
  140245. return rc;
  140246. }
  140247. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  140248. if( iLevel==FTS3_SEGCURSOR_ALL ){
  140249. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  140250. if( rc==SQLITE_OK ){
  140251. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  140252. sqlite3_bind_int64(pDelete, 2,
  140253. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  140254. );
  140255. }
  140256. }else{
  140257. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  140258. if( rc==SQLITE_OK ){
  140259. sqlite3_bind_int64(
  140260. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  140261. );
  140262. }
  140263. }
  140264. if( rc==SQLITE_OK ){
  140265. sqlite3_step(pDelete);
  140266. rc = sqlite3_reset(pDelete);
  140267. }
  140268. return rc;
  140269. }
  140270. /*
  140271. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  140272. ** a position list that may (or may not) feature multiple columns. This
  140273. ** function adjusts the pointer *ppList and the length *pnList so that they
  140274. ** identify the subset of the position list that corresponds to column iCol.
  140275. **
  140276. ** If there are no entries in the input position list for column iCol, then
  140277. ** *pnList is set to zero before returning.
  140278. **
  140279. ** If parameter bZero is non-zero, then any part of the input list following
  140280. ** the end of the output list is zeroed before returning.
  140281. */
  140282. static void fts3ColumnFilter(
  140283. int iCol, /* Column to filter on */
  140284. int bZero, /* Zero out anything following *ppList */
  140285. char **ppList, /* IN/OUT: Pointer to position list */
  140286. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  140287. ){
  140288. char *pList = *ppList;
  140289. int nList = *pnList;
  140290. char *pEnd = &pList[nList];
  140291. int iCurrent = 0;
  140292. char *p = pList;
  140293. assert( iCol>=0 );
  140294. while( 1 ){
  140295. char c = 0;
  140296. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  140297. if( iCol==iCurrent ){
  140298. nList = (int)(p - pList);
  140299. break;
  140300. }
  140301. nList -= (int)(p - pList);
  140302. pList = p;
  140303. if( nList==0 ){
  140304. break;
  140305. }
  140306. p = &pList[1];
  140307. p += fts3GetVarint32(p, &iCurrent);
  140308. }
  140309. if( bZero && &pList[nList]!=pEnd ){
  140310. memset(&pList[nList], 0, pEnd - &pList[nList]);
  140311. }
  140312. *ppList = pList;
  140313. *pnList = nList;
  140314. }
  140315. /*
  140316. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  140317. ** existing data). Grow the buffer if required.
  140318. **
  140319. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  140320. ** trying to resize the buffer, return SQLITE_NOMEM.
  140321. */
  140322. static int fts3MsrBufferData(
  140323. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  140324. char *pList,
  140325. int nList
  140326. ){
  140327. if( nList>pMsr->nBuffer ){
  140328. char *pNew;
  140329. pMsr->nBuffer = nList*2;
  140330. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  140331. if( !pNew ) return SQLITE_NOMEM;
  140332. pMsr->aBuffer = pNew;
  140333. }
  140334. memcpy(pMsr->aBuffer, pList, nList);
  140335. return SQLITE_OK;
  140336. }
  140337. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  140338. Fts3Table *p, /* Virtual table handle */
  140339. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  140340. sqlite3_int64 *piDocid, /* OUT: Docid value */
  140341. char **paPoslist, /* OUT: Pointer to position list */
  140342. int *pnPoslist /* OUT: Size of position list in bytes */
  140343. ){
  140344. int nMerge = pMsr->nAdvance;
  140345. Fts3SegReader **apSegment = pMsr->apSegment;
  140346. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  140347. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  140348. );
  140349. if( nMerge==0 ){
  140350. *paPoslist = 0;
  140351. return SQLITE_OK;
  140352. }
  140353. while( 1 ){
  140354. Fts3SegReader *pSeg;
  140355. pSeg = pMsr->apSegment[0];
  140356. if( pSeg->pOffsetList==0 ){
  140357. *paPoslist = 0;
  140358. break;
  140359. }else{
  140360. int rc;
  140361. char *pList;
  140362. int nList;
  140363. int j;
  140364. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  140365. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  140366. j = 1;
  140367. while( rc==SQLITE_OK
  140368. && j<nMerge
  140369. && apSegment[j]->pOffsetList
  140370. && apSegment[j]->iDocid==iDocid
  140371. ){
  140372. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  140373. j++;
  140374. }
  140375. if( rc!=SQLITE_OK ) return rc;
  140376. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  140377. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  140378. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  140379. if( rc!=SQLITE_OK ) return rc;
  140380. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  140381. pList = pMsr->aBuffer;
  140382. }
  140383. if( pMsr->iColFilter>=0 ){
  140384. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  140385. }
  140386. if( nList>0 ){
  140387. *paPoslist = pList;
  140388. *piDocid = iDocid;
  140389. *pnPoslist = nList;
  140390. break;
  140391. }
  140392. }
  140393. }
  140394. return SQLITE_OK;
  140395. }
  140396. static int fts3SegReaderStart(
  140397. Fts3Table *p, /* Virtual table handle */
  140398. Fts3MultiSegReader *pCsr, /* Cursor object */
  140399. const char *zTerm, /* Term searched for (or NULL) */
  140400. int nTerm /* Length of zTerm in bytes */
  140401. ){
  140402. int i;
  140403. int nSeg = pCsr->nSegment;
  140404. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  140405. ** for, then advance each segment iterator until it points to a term of
  140406. ** equal or greater value than the specified term. This prevents many
  140407. ** unnecessary merge/sort operations for the case where single segment
  140408. ** b-tree leaf nodes contain more than one term.
  140409. */
  140410. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  140411. int res = 0;
  140412. Fts3SegReader *pSeg = pCsr->apSegment[i];
  140413. do {
  140414. int rc = fts3SegReaderNext(p, pSeg, 0);
  140415. if( rc!=SQLITE_OK ) return rc;
  140416. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  140417. if( pSeg->bLookup && res!=0 ){
  140418. fts3SegReaderSetEof(pSeg);
  140419. }
  140420. }
  140421. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  140422. return SQLITE_OK;
  140423. }
  140424. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  140425. Fts3Table *p, /* Virtual table handle */
  140426. Fts3MultiSegReader *pCsr, /* Cursor object */
  140427. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  140428. ){
  140429. pCsr->pFilter = pFilter;
  140430. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  140431. }
  140432. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  140433. Fts3Table *p, /* Virtual table handle */
  140434. Fts3MultiSegReader *pCsr, /* Cursor object */
  140435. int iCol, /* Column to match on. */
  140436. const char *zTerm, /* Term to iterate through a doclist for */
  140437. int nTerm /* Number of bytes in zTerm */
  140438. ){
  140439. int i;
  140440. int rc;
  140441. int nSegment = pCsr->nSegment;
  140442. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  140443. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  140444. );
  140445. assert( pCsr->pFilter==0 );
  140446. assert( zTerm && nTerm>0 );
  140447. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  140448. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  140449. if( rc!=SQLITE_OK ) return rc;
  140450. /* Determine how many of the segments actually point to zTerm/nTerm. */
  140451. for(i=0; i<nSegment; i++){
  140452. Fts3SegReader *pSeg = pCsr->apSegment[i];
  140453. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  140454. break;
  140455. }
  140456. }
  140457. pCsr->nAdvance = i;
  140458. /* Advance each of the segments to point to the first docid. */
  140459. for(i=0; i<pCsr->nAdvance; i++){
  140460. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  140461. if( rc!=SQLITE_OK ) return rc;
  140462. }
  140463. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  140464. assert( iCol<0 || iCol<p->nColumn );
  140465. pCsr->iColFilter = iCol;
  140466. return SQLITE_OK;
  140467. }
  140468. /*
  140469. ** This function is called on a MultiSegReader that has been started using
  140470. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  140471. ** have been made. Calling this function puts the MultiSegReader in such
  140472. ** a state that if the next two calls are:
  140473. **
  140474. ** sqlite3Fts3SegReaderStart()
  140475. ** sqlite3Fts3SegReaderStep()
  140476. **
  140477. ** then the entire doclist for the term is available in
  140478. ** MultiSegReader.aDoclist/nDoclist.
  140479. */
  140480. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  140481. int i; /* Used to iterate through segment-readers */
  140482. assert( pCsr->zTerm==0 );
  140483. assert( pCsr->nTerm==0 );
  140484. assert( pCsr->aDoclist==0 );
  140485. assert( pCsr->nDoclist==0 );
  140486. pCsr->nAdvance = 0;
  140487. pCsr->bRestart = 1;
  140488. for(i=0; i<pCsr->nSegment; i++){
  140489. pCsr->apSegment[i]->pOffsetList = 0;
  140490. pCsr->apSegment[i]->nOffsetList = 0;
  140491. pCsr->apSegment[i]->iDocid = 0;
  140492. }
  140493. return SQLITE_OK;
  140494. }
  140495. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  140496. Fts3Table *p, /* Virtual table handle */
  140497. Fts3MultiSegReader *pCsr /* Cursor object */
  140498. ){
  140499. int rc = SQLITE_OK;
  140500. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  140501. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  140502. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  140503. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  140504. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  140505. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  140506. Fts3SegReader **apSegment = pCsr->apSegment;
  140507. int nSegment = pCsr->nSegment;
  140508. Fts3SegFilter *pFilter = pCsr->pFilter;
  140509. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  140510. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  140511. );
  140512. if( pCsr->nSegment==0 ) return SQLITE_OK;
  140513. do {
  140514. int nMerge;
  140515. int i;
  140516. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  140517. ** forward. Then sort the list in order of current term again.
  140518. */
  140519. for(i=0; i<pCsr->nAdvance; i++){
  140520. Fts3SegReader *pSeg = apSegment[i];
  140521. if( pSeg->bLookup ){
  140522. fts3SegReaderSetEof(pSeg);
  140523. }else{
  140524. rc = fts3SegReaderNext(p, pSeg, 0);
  140525. }
  140526. if( rc!=SQLITE_OK ) return rc;
  140527. }
  140528. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  140529. pCsr->nAdvance = 0;
  140530. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  140531. assert( rc==SQLITE_OK );
  140532. if( apSegment[0]->aNode==0 ) break;
  140533. pCsr->nTerm = apSegment[0]->nTerm;
  140534. pCsr->zTerm = apSegment[0]->zTerm;
  140535. /* If this is a prefix-search, and if the term that apSegment[0] points
  140536. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  140537. ** required callbacks have been made. In this case exit early.
  140538. **
  140539. ** Similarly, if this is a search for an exact match, and the first term
  140540. ** of segment apSegment[0] is not a match, exit early.
  140541. */
  140542. if( pFilter->zTerm && !isScan ){
  140543. if( pCsr->nTerm<pFilter->nTerm
  140544. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  140545. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  140546. ){
  140547. break;
  140548. }
  140549. }
  140550. nMerge = 1;
  140551. while( nMerge<nSegment
  140552. && apSegment[nMerge]->aNode
  140553. && apSegment[nMerge]->nTerm==pCsr->nTerm
  140554. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  140555. ){
  140556. nMerge++;
  140557. }
  140558. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  140559. if( nMerge==1
  140560. && !isIgnoreEmpty
  140561. && !isFirst
  140562. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  140563. ){
  140564. pCsr->nDoclist = apSegment[0]->nDoclist;
  140565. if( fts3SegReaderIsPending(apSegment[0]) ){
  140566. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  140567. pCsr->aDoclist = pCsr->aBuffer;
  140568. }else{
  140569. pCsr->aDoclist = apSegment[0]->aDoclist;
  140570. }
  140571. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  140572. }else{
  140573. int nDoclist = 0; /* Size of doclist */
  140574. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  140575. /* The current term of the first nMerge entries in the array
  140576. ** of Fts3SegReader objects is the same. The doclists must be merged
  140577. ** and a single term returned with the merged doclist.
  140578. */
  140579. for(i=0; i<nMerge; i++){
  140580. fts3SegReaderFirstDocid(p, apSegment[i]);
  140581. }
  140582. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  140583. while( apSegment[0]->pOffsetList ){
  140584. int j; /* Number of segments that share a docid */
  140585. char *pList = 0;
  140586. int nList = 0;
  140587. int nByte;
  140588. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  140589. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  140590. j = 1;
  140591. while( j<nMerge
  140592. && apSegment[j]->pOffsetList
  140593. && apSegment[j]->iDocid==iDocid
  140594. ){
  140595. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  140596. j++;
  140597. }
  140598. if( isColFilter ){
  140599. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  140600. }
  140601. if( !isIgnoreEmpty || nList>0 ){
  140602. /* Calculate the 'docid' delta value to write into the merged
  140603. ** doclist. */
  140604. sqlite3_int64 iDelta;
  140605. if( p->bDescIdx && nDoclist>0 ){
  140606. iDelta = iPrev - iDocid;
  140607. }else{
  140608. iDelta = iDocid - iPrev;
  140609. }
  140610. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  140611. assert( nDoclist>0 || iDelta==iDocid );
  140612. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  140613. if( nDoclist+nByte>pCsr->nBuffer ){
  140614. char *aNew;
  140615. pCsr->nBuffer = (nDoclist+nByte)*2;
  140616. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  140617. if( !aNew ){
  140618. return SQLITE_NOMEM;
  140619. }
  140620. pCsr->aBuffer = aNew;
  140621. }
  140622. if( isFirst ){
  140623. char *a = &pCsr->aBuffer[nDoclist];
  140624. int nWrite;
  140625. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  140626. if( nWrite ){
  140627. iPrev = iDocid;
  140628. nDoclist += nWrite;
  140629. }
  140630. }else{
  140631. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  140632. iPrev = iDocid;
  140633. if( isRequirePos ){
  140634. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  140635. nDoclist += nList;
  140636. pCsr->aBuffer[nDoclist++] = '\0';
  140637. }
  140638. }
  140639. }
  140640. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  140641. }
  140642. if( nDoclist>0 ){
  140643. pCsr->aDoclist = pCsr->aBuffer;
  140644. pCsr->nDoclist = nDoclist;
  140645. rc = SQLITE_ROW;
  140646. }
  140647. }
  140648. pCsr->nAdvance = nMerge;
  140649. }while( rc==SQLITE_OK );
  140650. return rc;
  140651. }
  140652. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  140653. Fts3MultiSegReader *pCsr /* Cursor object */
  140654. ){
  140655. if( pCsr ){
  140656. int i;
  140657. for(i=0; i<pCsr->nSegment; i++){
  140658. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  140659. }
  140660. sqlite3_free(pCsr->apSegment);
  140661. sqlite3_free(pCsr->aBuffer);
  140662. pCsr->nSegment = 0;
  140663. pCsr->apSegment = 0;
  140664. pCsr->aBuffer = 0;
  140665. }
  140666. }
  140667. /*
  140668. ** Decode the "end_block" field, selected by column iCol of the SELECT
  140669. ** statement passed as the first argument.
  140670. **
  140671. ** The "end_block" field may contain either an integer, or a text field
  140672. ** containing the text representation of two non-negative integers separated
  140673. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  140674. ** to the integer value and *pnByte to zero before returning. In the second,
  140675. ** set *piEndBlock to the first value and *pnByte to the second.
  140676. */
  140677. static void fts3ReadEndBlockField(
  140678. sqlite3_stmt *pStmt,
  140679. int iCol,
  140680. i64 *piEndBlock,
  140681. i64 *pnByte
  140682. ){
  140683. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  140684. if( zText ){
  140685. int i;
  140686. int iMul = 1;
  140687. i64 iVal = 0;
  140688. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  140689. iVal = iVal*10 + (zText[i] - '0');
  140690. }
  140691. *piEndBlock = iVal;
  140692. while( zText[i]==' ' ) i++;
  140693. iVal = 0;
  140694. if( zText[i]=='-' ){
  140695. i++;
  140696. iMul = -1;
  140697. }
  140698. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  140699. iVal = iVal*10 + (zText[i] - '0');
  140700. }
  140701. *pnByte = (iVal * (i64)iMul);
  140702. }
  140703. }
  140704. /*
  140705. ** A segment of size nByte bytes has just been written to absolute level
  140706. ** iAbsLevel. Promote any segments that should be promoted as a result.
  140707. */
  140708. static int fts3PromoteSegments(
  140709. Fts3Table *p, /* FTS table handle */
  140710. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  140711. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  140712. ){
  140713. int rc = SQLITE_OK;
  140714. sqlite3_stmt *pRange;
  140715. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  140716. if( rc==SQLITE_OK ){
  140717. int bOk = 0;
  140718. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  140719. i64 nLimit = (nByte*3)/2;
  140720. /* Loop through all entries in the %_segdir table corresponding to
  140721. ** segments in this index on levels greater than iAbsLevel. If there is
  140722. ** at least one such segment, and it is possible to determine that all
  140723. ** such segments are smaller than nLimit bytes in size, they will be
  140724. ** promoted to level iAbsLevel. */
  140725. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  140726. sqlite3_bind_int64(pRange, 2, iLast);
  140727. while( SQLITE_ROW==sqlite3_step(pRange) ){
  140728. i64 nSize = 0, dummy;
  140729. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  140730. if( nSize<=0 || nSize>nLimit ){
  140731. /* If nSize==0, then the %_segdir.end_block field does not not
  140732. ** contain a size value. This happens if it was written by an
  140733. ** old version of FTS. In this case it is not possible to determine
  140734. ** the size of the segment, and so segment promotion does not
  140735. ** take place. */
  140736. bOk = 0;
  140737. break;
  140738. }
  140739. bOk = 1;
  140740. }
  140741. rc = sqlite3_reset(pRange);
  140742. if( bOk ){
  140743. int iIdx = 0;
  140744. sqlite3_stmt *pUpdate1 = 0;
  140745. sqlite3_stmt *pUpdate2 = 0;
  140746. if( rc==SQLITE_OK ){
  140747. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  140748. }
  140749. if( rc==SQLITE_OK ){
  140750. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  140751. }
  140752. if( rc==SQLITE_OK ){
  140753. /* Loop through all %_segdir entries for segments in this index with
  140754. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  140755. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  140756. ** oldest segment in the range, 1 for the next oldest, and so on.
  140757. **
  140758. ** In other words, move all segments being promoted to level -1,
  140759. ** setting the "idx" fields as appropriate to keep them in the same
  140760. ** order. The contents of level -1 (which is never used, except
  140761. ** transiently here), will be moved back to level iAbsLevel below. */
  140762. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  140763. while( SQLITE_ROW==sqlite3_step(pRange) ){
  140764. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  140765. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  140766. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  140767. sqlite3_step(pUpdate1);
  140768. rc = sqlite3_reset(pUpdate1);
  140769. if( rc!=SQLITE_OK ){
  140770. sqlite3_reset(pRange);
  140771. break;
  140772. }
  140773. }
  140774. }
  140775. if( rc==SQLITE_OK ){
  140776. rc = sqlite3_reset(pRange);
  140777. }
  140778. /* Move level -1 to level iAbsLevel */
  140779. if( rc==SQLITE_OK ){
  140780. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  140781. sqlite3_step(pUpdate2);
  140782. rc = sqlite3_reset(pUpdate2);
  140783. }
  140784. }
  140785. }
  140786. return rc;
  140787. }
  140788. /*
  140789. ** Merge all level iLevel segments in the database into a single
  140790. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  140791. ** single segment with a level equal to the numerically largest level
  140792. ** currently present in the database.
  140793. **
  140794. ** If this function is called with iLevel<0, but there is only one
  140795. ** segment in the database, SQLITE_DONE is returned immediately.
  140796. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  140797. ** an SQLite error code is returned.
  140798. */
  140799. static int fts3SegmentMerge(
  140800. Fts3Table *p,
  140801. int iLangid, /* Language id to merge */
  140802. int iIndex, /* Index in p->aIndex[] to merge */
  140803. int iLevel /* Level to merge */
  140804. ){
  140805. int rc; /* Return code */
  140806. int iIdx = 0; /* Index of new segment */
  140807. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  140808. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  140809. Fts3SegFilter filter; /* Segment term filter condition */
  140810. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  140811. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  140812. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  140813. assert( iLevel==FTS3_SEGCURSOR_ALL
  140814. || iLevel==FTS3_SEGCURSOR_PENDING
  140815. || iLevel>=0
  140816. );
  140817. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  140818. assert( iIndex>=0 && iIndex<p->nIndex );
  140819. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  140820. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  140821. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  140822. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  140823. if( rc!=SQLITE_OK ) goto finished;
  140824. }
  140825. if( iLevel==FTS3_SEGCURSOR_ALL ){
  140826. /* This call is to merge all segments in the database to a single
  140827. ** segment. The level of the new segment is equal to the numerically
  140828. ** greatest segment level currently present in the database for this
  140829. ** index. The idx of the new segment is always 0. */
  140830. if( csr.nSegment==1 ){
  140831. rc = SQLITE_DONE;
  140832. goto finished;
  140833. }
  140834. iNewLevel = iMaxLevel;
  140835. bIgnoreEmpty = 1;
  140836. }else{
  140837. /* This call is to merge all segments at level iLevel. find the next
  140838. ** available segment index at level iLevel+1. The call to
  140839. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  140840. ** a single iLevel+2 segment if necessary. */
  140841. assert( FTS3_SEGCURSOR_PENDING==-1 );
  140842. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  140843. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  140844. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  140845. }
  140846. if( rc!=SQLITE_OK ) goto finished;
  140847. assert( csr.nSegment>0 );
  140848. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  140849. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  140850. memset(&filter, 0, sizeof(Fts3SegFilter));
  140851. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  140852. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  140853. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  140854. while( SQLITE_OK==rc ){
  140855. rc = sqlite3Fts3SegReaderStep(p, &csr);
  140856. if( rc!=SQLITE_ROW ) break;
  140857. rc = fts3SegWriterAdd(p, &pWriter, 1,
  140858. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  140859. }
  140860. if( rc!=SQLITE_OK ) goto finished;
  140861. assert( pWriter || bIgnoreEmpty );
  140862. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  140863. rc = fts3DeleteSegdir(
  140864. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  140865. );
  140866. if( rc!=SQLITE_OK ) goto finished;
  140867. }
  140868. if( pWriter ){
  140869. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  140870. if( rc==SQLITE_OK ){
  140871. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  140872. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  140873. }
  140874. }
  140875. }
  140876. finished:
  140877. fts3SegWriterFree(pWriter);
  140878. sqlite3Fts3SegReaderFinish(&csr);
  140879. return rc;
  140880. }
  140881. /*
  140882. ** Flush the contents of pendingTerms to level 0 segments.
  140883. */
  140884. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  140885. int rc = SQLITE_OK;
  140886. int i;
  140887. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  140888. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  140889. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  140890. }
  140891. sqlite3Fts3PendingTermsClear(p);
  140892. /* Determine the auto-incr-merge setting if unknown. If enabled,
  140893. ** estimate the number of leaf blocks of content to be written
  140894. */
  140895. if( rc==SQLITE_OK && p->bHasStat
  140896. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  140897. ){
  140898. sqlite3_stmt *pStmt = 0;
  140899. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  140900. if( rc==SQLITE_OK ){
  140901. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  140902. rc = sqlite3_step(pStmt);
  140903. if( rc==SQLITE_ROW ){
  140904. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  140905. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  140906. }else if( rc==SQLITE_DONE ){
  140907. p->nAutoincrmerge = 0;
  140908. }
  140909. rc = sqlite3_reset(pStmt);
  140910. }
  140911. }
  140912. return rc;
  140913. }
  140914. /*
  140915. ** Encode N integers as varints into a blob.
  140916. */
  140917. static void fts3EncodeIntArray(
  140918. int N, /* The number of integers to encode */
  140919. u32 *a, /* The integer values */
  140920. char *zBuf, /* Write the BLOB here */
  140921. int *pNBuf /* Write number of bytes if zBuf[] used here */
  140922. ){
  140923. int i, j;
  140924. for(i=j=0; i<N; i++){
  140925. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  140926. }
  140927. *pNBuf = j;
  140928. }
  140929. /*
  140930. ** Decode a blob of varints into N integers
  140931. */
  140932. static void fts3DecodeIntArray(
  140933. int N, /* The number of integers to decode */
  140934. u32 *a, /* Write the integer values */
  140935. const char *zBuf, /* The BLOB containing the varints */
  140936. int nBuf /* size of the BLOB */
  140937. ){
  140938. int i, j;
  140939. UNUSED_PARAMETER(nBuf);
  140940. for(i=j=0; i<N; i++){
  140941. sqlite3_int64 x;
  140942. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  140943. assert(j<=nBuf);
  140944. a[i] = (u32)(x & 0xffffffff);
  140945. }
  140946. }
  140947. /*
  140948. ** Insert the sizes (in tokens) for each column of the document
  140949. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  140950. ** a blob of varints.
  140951. */
  140952. static void fts3InsertDocsize(
  140953. int *pRC, /* Result code */
  140954. Fts3Table *p, /* Table into which to insert */
  140955. u32 *aSz /* Sizes of each column, in tokens */
  140956. ){
  140957. char *pBlob; /* The BLOB encoding of the document size */
  140958. int nBlob; /* Number of bytes in the BLOB */
  140959. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  140960. int rc; /* Result code from subfunctions */
  140961. if( *pRC ) return;
  140962. pBlob = sqlite3_malloc( 10*p->nColumn );
  140963. if( pBlob==0 ){
  140964. *pRC = SQLITE_NOMEM;
  140965. return;
  140966. }
  140967. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  140968. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  140969. if( rc ){
  140970. sqlite3_free(pBlob);
  140971. *pRC = rc;
  140972. return;
  140973. }
  140974. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  140975. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  140976. sqlite3_step(pStmt);
  140977. *pRC = sqlite3_reset(pStmt);
  140978. }
  140979. /*
  140980. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  140981. ** where N is the number of user defined columns in the fts3 table plus
  140982. ** two. If nCol is the number of user defined columns, then values of the
  140983. ** varints are set as follows:
  140984. **
  140985. ** Varint 0: Total number of rows in the table.
  140986. **
  140987. ** Varint 1..nCol: For each column, the total number of tokens stored in
  140988. ** the column for all rows of the table.
  140989. **
  140990. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  140991. ** columns of all rows of the table.
  140992. **
  140993. */
  140994. static void fts3UpdateDocTotals(
  140995. int *pRC, /* The result code */
  140996. Fts3Table *p, /* Table being updated */
  140997. u32 *aSzIns, /* Size increases */
  140998. u32 *aSzDel, /* Size decreases */
  140999. int nChng /* Change in the number of documents */
  141000. ){
  141001. char *pBlob; /* Storage for BLOB written into %_stat */
  141002. int nBlob; /* Size of BLOB written into %_stat */
  141003. u32 *a; /* Array of integers that becomes the BLOB */
  141004. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  141005. int i; /* Loop counter */
  141006. int rc; /* Result code from subfunctions */
  141007. const int nStat = p->nColumn+2;
  141008. if( *pRC ) return;
  141009. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  141010. if( a==0 ){
  141011. *pRC = SQLITE_NOMEM;
  141012. return;
  141013. }
  141014. pBlob = (char*)&a[nStat];
  141015. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  141016. if( rc ){
  141017. sqlite3_free(a);
  141018. *pRC = rc;
  141019. return;
  141020. }
  141021. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  141022. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  141023. fts3DecodeIntArray(nStat, a,
  141024. sqlite3_column_blob(pStmt, 0),
  141025. sqlite3_column_bytes(pStmt, 0));
  141026. }else{
  141027. memset(a, 0, sizeof(u32)*(nStat) );
  141028. }
  141029. rc = sqlite3_reset(pStmt);
  141030. if( rc!=SQLITE_OK ){
  141031. sqlite3_free(a);
  141032. *pRC = rc;
  141033. return;
  141034. }
  141035. if( nChng<0 && a[0]<(u32)(-nChng) ){
  141036. a[0] = 0;
  141037. }else{
  141038. a[0] += nChng;
  141039. }
  141040. for(i=0; i<p->nColumn+1; i++){
  141041. u32 x = a[i+1];
  141042. if( x+aSzIns[i] < aSzDel[i] ){
  141043. x = 0;
  141044. }else{
  141045. x = x + aSzIns[i] - aSzDel[i];
  141046. }
  141047. a[i+1] = x;
  141048. }
  141049. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  141050. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  141051. if( rc ){
  141052. sqlite3_free(a);
  141053. *pRC = rc;
  141054. return;
  141055. }
  141056. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  141057. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  141058. sqlite3_step(pStmt);
  141059. *pRC = sqlite3_reset(pStmt);
  141060. sqlite3_free(a);
  141061. }
  141062. /*
  141063. ** Merge the entire database so that there is one segment for each
  141064. ** iIndex/iLangid combination.
  141065. */
  141066. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  141067. int bSeenDone = 0;
  141068. int rc;
  141069. sqlite3_stmt *pAllLangid = 0;
  141070. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  141071. if( rc==SQLITE_OK ){
  141072. int rc2;
  141073. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  141074. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  141075. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  141076. int i;
  141077. int iLangid = sqlite3_column_int(pAllLangid, 0);
  141078. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  141079. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  141080. if( rc==SQLITE_DONE ){
  141081. bSeenDone = 1;
  141082. rc = SQLITE_OK;
  141083. }
  141084. }
  141085. }
  141086. rc2 = sqlite3_reset(pAllLangid);
  141087. if( rc==SQLITE_OK ) rc = rc2;
  141088. }
  141089. sqlite3Fts3SegmentsClose(p);
  141090. sqlite3Fts3PendingTermsClear(p);
  141091. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  141092. }
  141093. /*
  141094. ** This function is called when the user executes the following statement:
  141095. **
  141096. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  141097. **
  141098. ** The entire FTS index is discarded and rebuilt. If the table is one
  141099. ** created using the content=xxx option, then the new index is based on
  141100. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  141101. ** on the contents of the %_content table.
  141102. */
  141103. static int fts3DoRebuild(Fts3Table *p){
  141104. int rc; /* Return Code */
  141105. rc = fts3DeleteAll(p, 0);
  141106. if( rc==SQLITE_OK ){
  141107. u32 *aSz = 0;
  141108. u32 *aSzIns = 0;
  141109. u32 *aSzDel = 0;
  141110. sqlite3_stmt *pStmt = 0;
  141111. int nEntry = 0;
  141112. /* Compose and prepare an SQL statement to loop through the content table */
  141113. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  141114. if( !zSql ){
  141115. rc = SQLITE_NOMEM;
  141116. }else{
  141117. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  141118. sqlite3_free(zSql);
  141119. }
  141120. if( rc==SQLITE_OK ){
  141121. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  141122. aSz = (u32 *)sqlite3_malloc(nByte);
  141123. if( aSz==0 ){
  141124. rc = SQLITE_NOMEM;
  141125. }else{
  141126. memset(aSz, 0, nByte);
  141127. aSzIns = &aSz[p->nColumn+1];
  141128. aSzDel = &aSzIns[p->nColumn+1];
  141129. }
  141130. }
  141131. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  141132. int iCol;
  141133. int iLangid = langidFromSelect(p, pStmt);
  141134. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  141135. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  141136. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  141137. if( p->abNotindexed[iCol]==0 ){
  141138. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  141139. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  141140. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  141141. }
  141142. }
  141143. if( p->bHasDocsize ){
  141144. fts3InsertDocsize(&rc, p, aSz);
  141145. }
  141146. if( rc!=SQLITE_OK ){
  141147. sqlite3_finalize(pStmt);
  141148. pStmt = 0;
  141149. }else{
  141150. nEntry++;
  141151. for(iCol=0; iCol<=p->nColumn; iCol++){
  141152. aSzIns[iCol] += aSz[iCol];
  141153. }
  141154. }
  141155. }
  141156. if( p->bFts4 ){
  141157. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  141158. }
  141159. sqlite3_free(aSz);
  141160. if( pStmt ){
  141161. int rc2 = sqlite3_finalize(pStmt);
  141162. if( rc==SQLITE_OK ){
  141163. rc = rc2;
  141164. }
  141165. }
  141166. }
  141167. return rc;
  141168. }
  141169. /*
  141170. ** This function opens a cursor used to read the input data for an
  141171. ** incremental merge operation. Specifically, it opens a cursor to scan
  141172. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  141173. ** level iAbsLevel.
  141174. */
  141175. static int fts3IncrmergeCsr(
  141176. Fts3Table *p, /* FTS3 table handle */
  141177. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  141178. int nSeg, /* Number of segments to merge */
  141179. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  141180. ){
  141181. int rc; /* Return Code */
  141182. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  141183. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  141184. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  141185. memset(pCsr, 0, sizeof(*pCsr));
  141186. nByte = sizeof(Fts3SegReader *) * nSeg;
  141187. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  141188. if( pCsr->apSegment==0 ){
  141189. rc = SQLITE_NOMEM;
  141190. }else{
  141191. memset(pCsr->apSegment, 0, nByte);
  141192. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  141193. }
  141194. if( rc==SQLITE_OK ){
  141195. int i;
  141196. int rc2;
  141197. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  141198. assert( pCsr->nSegment==0 );
  141199. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  141200. rc = sqlite3Fts3SegReaderNew(i, 0,
  141201. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  141202. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  141203. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  141204. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  141205. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  141206. &pCsr->apSegment[i]
  141207. );
  141208. pCsr->nSegment++;
  141209. }
  141210. rc2 = sqlite3_reset(pStmt);
  141211. if( rc==SQLITE_OK ) rc = rc2;
  141212. }
  141213. return rc;
  141214. }
  141215. typedef struct IncrmergeWriter IncrmergeWriter;
  141216. typedef struct NodeWriter NodeWriter;
  141217. typedef struct Blob Blob;
  141218. typedef struct NodeReader NodeReader;
  141219. /*
  141220. ** An instance of the following structure is used as a dynamic buffer
  141221. ** to build up nodes or other blobs of data in.
  141222. **
  141223. ** The function blobGrowBuffer() is used to extend the allocation.
  141224. */
  141225. struct Blob {
  141226. char *a; /* Pointer to allocation */
  141227. int n; /* Number of valid bytes of data in a[] */
  141228. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  141229. };
  141230. /*
  141231. ** This structure is used to build up buffers containing segment b-tree
  141232. ** nodes (blocks).
  141233. */
  141234. struct NodeWriter {
  141235. sqlite3_int64 iBlock; /* Current block id */
  141236. Blob key; /* Last key written to the current block */
  141237. Blob block; /* Current block image */
  141238. };
  141239. /*
  141240. ** An object of this type contains the state required to create or append
  141241. ** to an appendable b-tree segment.
  141242. */
  141243. struct IncrmergeWriter {
  141244. int nLeafEst; /* Space allocated for leaf blocks */
  141245. int nWork; /* Number of leaf pages flushed */
  141246. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  141247. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  141248. sqlite3_int64 iStart; /* Block number of first allocated block */
  141249. sqlite3_int64 iEnd; /* Block number of last allocated block */
  141250. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  141251. u8 bNoLeafData; /* If true, store 0 for segment size */
  141252. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  141253. };
  141254. /*
  141255. ** An object of the following type is used to read data from a single
  141256. ** FTS segment node. See the following functions:
  141257. **
  141258. ** nodeReaderInit()
  141259. ** nodeReaderNext()
  141260. ** nodeReaderRelease()
  141261. */
  141262. struct NodeReader {
  141263. const char *aNode;
  141264. int nNode;
  141265. int iOff; /* Current offset within aNode[] */
  141266. /* Output variables. Containing the current node entry. */
  141267. sqlite3_int64 iChild; /* Pointer to child node */
  141268. Blob term; /* Current term */
  141269. const char *aDoclist; /* Pointer to doclist */
  141270. int nDoclist; /* Size of doclist in bytes */
  141271. };
  141272. /*
  141273. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  141274. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  141275. ** bytes in size, extend (realloc) it to be so.
  141276. **
  141277. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  141278. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  141279. ** to reflect the new size of the pBlob->a[] buffer.
  141280. */
  141281. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  141282. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  141283. int nAlloc = nMin;
  141284. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  141285. if( a ){
  141286. pBlob->nAlloc = nAlloc;
  141287. pBlob->a = a;
  141288. }else{
  141289. *pRc = SQLITE_NOMEM;
  141290. }
  141291. }
  141292. }
  141293. /*
  141294. ** Attempt to advance the node-reader object passed as the first argument to
  141295. ** the next entry on the node.
  141296. **
  141297. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  141298. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  141299. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  141300. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  141301. ** variables for the new entry.
  141302. */
  141303. static int nodeReaderNext(NodeReader *p){
  141304. int bFirst = (p->term.n==0); /* True for first term on the node */
  141305. int nPrefix = 0; /* Bytes to copy from previous term */
  141306. int nSuffix = 0; /* Bytes to append to the prefix */
  141307. int rc = SQLITE_OK; /* Return code */
  141308. assert( p->aNode );
  141309. if( p->iChild && bFirst==0 ) p->iChild++;
  141310. if( p->iOff>=p->nNode ){
  141311. /* EOF */
  141312. p->aNode = 0;
  141313. }else{
  141314. if( bFirst==0 ){
  141315. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  141316. }
  141317. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  141318. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  141319. if( rc==SQLITE_OK ){
  141320. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  141321. p->term.n = nPrefix+nSuffix;
  141322. p->iOff += nSuffix;
  141323. if( p->iChild==0 ){
  141324. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  141325. p->aDoclist = &p->aNode[p->iOff];
  141326. p->iOff += p->nDoclist;
  141327. }
  141328. }
  141329. }
  141330. assert( p->iOff<=p->nNode );
  141331. return rc;
  141332. }
  141333. /*
  141334. ** Release all dynamic resources held by node-reader object *p.
  141335. */
  141336. static void nodeReaderRelease(NodeReader *p){
  141337. sqlite3_free(p->term.a);
  141338. }
  141339. /*
  141340. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  141341. **
  141342. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  141343. ** point to the first entry on the node (if any). Otherwise, an SQLite
  141344. ** error code is returned.
  141345. */
  141346. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  141347. memset(p, 0, sizeof(NodeReader));
  141348. p->aNode = aNode;
  141349. p->nNode = nNode;
  141350. /* Figure out if this is a leaf or an internal node. */
  141351. if( p->aNode[0] ){
  141352. /* An internal node. */
  141353. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  141354. }else{
  141355. p->iOff = 1;
  141356. }
  141357. return nodeReaderNext(p);
  141358. }
  141359. /*
  141360. ** This function is called while writing an FTS segment each time a leaf o
  141361. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  141362. ** to be greater than the largest key on the node just written, but smaller
  141363. ** than or equal to the first key that will be written to the next leaf
  141364. ** node.
  141365. **
  141366. ** The block id of the leaf node just written to disk may be found in
  141367. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  141368. */
  141369. static int fts3IncrmergePush(
  141370. Fts3Table *p, /* Fts3 table handle */
  141371. IncrmergeWriter *pWriter, /* Writer object */
  141372. const char *zTerm, /* Term to write to internal node */
  141373. int nTerm /* Bytes at zTerm */
  141374. ){
  141375. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  141376. int iLayer;
  141377. assert( nTerm>0 );
  141378. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  141379. sqlite3_int64 iNextPtr = 0;
  141380. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  141381. int rc = SQLITE_OK;
  141382. int nPrefix;
  141383. int nSuffix;
  141384. int nSpace;
  141385. /* Figure out how much space the key will consume if it is written to
  141386. ** the current node of layer iLayer. Due to the prefix compression,
  141387. ** the space required changes depending on which node the key is to
  141388. ** be added to. */
  141389. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  141390. nSuffix = nTerm - nPrefix;
  141391. nSpace = sqlite3Fts3VarintLen(nPrefix);
  141392. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  141393. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  141394. /* If the current node of layer iLayer contains zero keys, or if adding
  141395. ** the key to it will not cause it to grow to larger than nNodeSize
  141396. ** bytes in size, write the key here. */
  141397. Blob *pBlk = &pNode->block;
  141398. if( pBlk->n==0 ){
  141399. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  141400. if( rc==SQLITE_OK ){
  141401. pBlk->a[0] = (char)iLayer;
  141402. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  141403. }
  141404. }
  141405. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  141406. blobGrowBuffer(&pNode->key, nTerm, &rc);
  141407. if( rc==SQLITE_OK ){
  141408. if( pNode->key.n ){
  141409. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  141410. }
  141411. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  141412. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  141413. pBlk->n += nSuffix;
  141414. memcpy(pNode->key.a, zTerm, nTerm);
  141415. pNode->key.n = nTerm;
  141416. }
  141417. }else{
  141418. /* Otherwise, flush the current node of layer iLayer to disk.
  141419. ** Then allocate a new, empty sibling node. The key will be written
  141420. ** into the parent of this node. */
  141421. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  141422. assert( pNode->block.nAlloc>=p->nNodeSize );
  141423. pNode->block.a[0] = (char)iLayer;
  141424. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  141425. iNextPtr = pNode->iBlock;
  141426. pNode->iBlock++;
  141427. pNode->key.n = 0;
  141428. }
  141429. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  141430. iPtr = iNextPtr;
  141431. }
  141432. assert( 0 );
  141433. return 0;
  141434. }
  141435. /*
  141436. ** Append a term and (optionally) doclist to the FTS segment node currently
  141437. ** stored in blob *pNode. The node need not contain any terms, but the
  141438. ** header must be written before this function is called.
  141439. **
  141440. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  141441. ** followed by the left-hand-child varint for an internal node.
  141442. **
  141443. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  141444. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  141445. ** node, both aDoclist and nDoclist must be passed 0.
  141446. **
  141447. ** If the size of the value in blob pPrev is zero, then this is the first
  141448. ** term written to the node. Otherwise, pPrev contains a copy of the
  141449. ** previous term. Before this function returns, it is updated to contain a
  141450. ** copy of zTerm/nTerm.
  141451. **
  141452. ** It is assumed that the buffer associated with pNode is already large
  141453. ** enough to accommodate the new entry. The buffer associated with pPrev
  141454. ** is extended by this function if requrired.
  141455. **
  141456. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  141457. ** returned. Otherwise, SQLITE_OK.
  141458. */
  141459. static int fts3AppendToNode(
  141460. Blob *pNode, /* Current node image to append to */
  141461. Blob *pPrev, /* Buffer containing previous term written */
  141462. const char *zTerm, /* New term to write */
  141463. int nTerm, /* Size of zTerm in bytes */
  141464. const char *aDoclist, /* Doclist (or NULL) to write */
  141465. int nDoclist /* Size of aDoclist in bytes */
  141466. ){
  141467. int rc = SQLITE_OK; /* Return code */
  141468. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  141469. int nPrefix; /* Size of term prefix in bytes */
  141470. int nSuffix; /* Size of term suffix in bytes */
  141471. /* Node must have already been started. There must be a doclist for a
  141472. ** leaf node, and there must not be a doclist for an internal node. */
  141473. assert( pNode->n>0 );
  141474. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  141475. blobGrowBuffer(pPrev, nTerm, &rc);
  141476. if( rc!=SQLITE_OK ) return rc;
  141477. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  141478. nSuffix = nTerm - nPrefix;
  141479. memcpy(pPrev->a, zTerm, nTerm);
  141480. pPrev->n = nTerm;
  141481. if( bFirst==0 ){
  141482. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  141483. }
  141484. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  141485. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  141486. pNode->n += nSuffix;
  141487. if( aDoclist ){
  141488. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  141489. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  141490. pNode->n += nDoclist;
  141491. }
  141492. assert( pNode->n<=pNode->nAlloc );
  141493. return SQLITE_OK;
  141494. }
  141495. /*
  141496. ** Append the current term and doclist pointed to by cursor pCsr to the
  141497. ** appendable b-tree segment opened for writing by pWriter.
  141498. **
  141499. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  141500. */
  141501. static int fts3IncrmergeAppend(
  141502. Fts3Table *p, /* Fts3 table handle */
  141503. IncrmergeWriter *pWriter, /* Writer object */
  141504. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  141505. ){
  141506. const char *zTerm = pCsr->zTerm;
  141507. int nTerm = pCsr->nTerm;
  141508. const char *aDoclist = pCsr->aDoclist;
  141509. int nDoclist = pCsr->nDoclist;
  141510. int rc = SQLITE_OK; /* Return code */
  141511. int nSpace; /* Total space in bytes required on leaf */
  141512. int nPrefix; /* Size of prefix shared with previous term */
  141513. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  141514. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  141515. pLeaf = &pWriter->aNodeWriter[0];
  141516. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  141517. nSuffix = nTerm - nPrefix;
  141518. nSpace = sqlite3Fts3VarintLen(nPrefix);
  141519. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  141520. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  141521. /* If the current block is not empty, and if adding this term/doclist
  141522. ** to the current block would make it larger than Fts3Table.nNodeSize
  141523. ** bytes, write this block out to the database. */
  141524. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  141525. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  141526. pWriter->nWork++;
  141527. /* Add the current term to the parent node. The term added to the
  141528. ** parent must:
  141529. **
  141530. ** a) be greater than the largest term on the leaf node just written
  141531. ** to the database (still available in pLeaf->key), and
  141532. **
  141533. ** b) be less than or equal to the term about to be added to the new
  141534. ** leaf node (zTerm/nTerm).
  141535. **
  141536. ** In other words, it must be the prefix of zTerm 1 byte longer than
  141537. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  141538. */
  141539. if( rc==SQLITE_OK ){
  141540. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  141541. }
  141542. /* Advance to the next output block */
  141543. pLeaf->iBlock++;
  141544. pLeaf->key.n = 0;
  141545. pLeaf->block.n = 0;
  141546. nSuffix = nTerm;
  141547. nSpace = 1;
  141548. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  141549. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  141550. }
  141551. pWriter->nLeafData += nSpace;
  141552. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  141553. if( rc==SQLITE_OK ){
  141554. if( pLeaf->block.n==0 ){
  141555. pLeaf->block.n = 1;
  141556. pLeaf->block.a[0] = '\0';
  141557. }
  141558. rc = fts3AppendToNode(
  141559. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  141560. );
  141561. }
  141562. return rc;
  141563. }
  141564. /*
  141565. ** This function is called to release all dynamic resources held by the
  141566. ** merge-writer object pWriter, and if no error has occurred, to flush
  141567. ** all outstanding node buffers held by pWriter to disk.
  141568. **
  141569. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  141570. ** is made to write any data to disk. Instead, this function serves only
  141571. ** to release outstanding resources.
  141572. **
  141573. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  141574. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  141575. ** returning.
  141576. */
  141577. static void fts3IncrmergeRelease(
  141578. Fts3Table *p, /* FTS3 table handle */
  141579. IncrmergeWriter *pWriter, /* Merge-writer object */
  141580. int *pRc /* IN/OUT: Error code */
  141581. ){
  141582. int i; /* Used to iterate through non-root layers */
  141583. int iRoot; /* Index of root in pWriter->aNodeWriter */
  141584. NodeWriter *pRoot; /* NodeWriter for root node */
  141585. int rc = *pRc; /* Error code */
  141586. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  141587. ** root node. If the segment fits entirely on a single leaf node, iRoot
  141588. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  141589. ** will be 1. And so on. */
  141590. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  141591. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  141592. if( pNode->block.n>0 ) break;
  141593. assert( *pRc || pNode->block.nAlloc==0 );
  141594. assert( *pRc || pNode->key.nAlloc==0 );
  141595. sqlite3_free(pNode->block.a);
  141596. sqlite3_free(pNode->key.a);
  141597. }
  141598. /* Empty output segment. This is a no-op. */
  141599. if( iRoot<0 ) return;
  141600. /* The entire output segment fits on a single node. Normally, this means
  141601. ** the node would be stored as a blob in the "root" column of the %_segdir
  141602. ** table. However, this is not permitted in this case. The problem is that
  141603. ** space has already been reserved in the %_segments table, and so the
  141604. ** start_block and end_block fields of the %_segdir table must be populated.
  141605. ** And, by design or by accident, released versions of FTS cannot handle
  141606. ** segments that fit entirely on the root node with start_block!=0.
  141607. **
  141608. ** Instead, create a synthetic root node that contains nothing but a
  141609. ** pointer to the single content node. So that the segment consists of a
  141610. ** single leaf and a single interior (root) node.
  141611. **
  141612. ** Todo: Better might be to defer allocating space in the %_segments
  141613. ** table until we are sure it is needed.
  141614. */
  141615. if( iRoot==0 ){
  141616. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  141617. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  141618. if( rc==SQLITE_OK ){
  141619. pBlock->a[0] = 0x01;
  141620. pBlock->n = 1 + sqlite3Fts3PutVarint(
  141621. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  141622. );
  141623. }
  141624. iRoot = 1;
  141625. }
  141626. pRoot = &pWriter->aNodeWriter[iRoot];
  141627. /* Flush all currently outstanding nodes to disk. */
  141628. for(i=0; i<iRoot; i++){
  141629. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  141630. if( pNode->block.n>0 && rc==SQLITE_OK ){
  141631. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  141632. }
  141633. sqlite3_free(pNode->block.a);
  141634. sqlite3_free(pNode->key.a);
  141635. }
  141636. /* Write the %_segdir record. */
  141637. if( rc==SQLITE_OK ){
  141638. rc = fts3WriteSegdir(p,
  141639. pWriter->iAbsLevel+1, /* level */
  141640. pWriter->iIdx, /* idx */
  141641. pWriter->iStart, /* start_block */
  141642. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  141643. pWriter->iEnd, /* end_block */
  141644. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  141645. pRoot->block.a, pRoot->block.n /* root */
  141646. );
  141647. }
  141648. sqlite3_free(pRoot->block.a);
  141649. sqlite3_free(pRoot->key.a);
  141650. *pRc = rc;
  141651. }
  141652. /*
  141653. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  141654. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  141655. ** the other, it is considered to be smaller than the other.
  141656. **
  141657. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  141658. ** if it is greater.
  141659. */
  141660. static int fts3TermCmp(
  141661. const char *zLhs, int nLhs, /* LHS of comparison */
  141662. const char *zRhs, int nRhs /* RHS of comparison */
  141663. ){
  141664. int nCmp = MIN(nLhs, nRhs);
  141665. int res;
  141666. res = memcmp(zLhs, zRhs, nCmp);
  141667. if( res==0 ) res = nLhs - nRhs;
  141668. return res;
  141669. }
  141670. /*
  141671. ** Query to see if the entry in the %_segments table with blockid iEnd is
  141672. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  141673. ** returning. Otherwise, set *pbRes to 0.
  141674. **
  141675. ** Or, if an error occurs while querying the database, return an SQLite
  141676. ** error code. The final value of *pbRes is undefined in this case.
  141677. **
  141678. ** This is used to test if a segment is an "appendable" segment. If it
  141679. ** is, then a NULL entry has been inserted into the %_segments table
  141680. ** with blockid %_segdir.end_block.
  141681. */
  141682. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  141683. int bRes = 0; /* Result to set *pbRes to */
  141684. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  141685. int rc; /* Return code */
  141686. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  141687. if( rc==SQLITE_OK ){
  141688. sqlite3_bind_int64(pCheck, 1, iEnd);
  141689. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  141690. rc = sqlite3_reset(pCheck);
  141691. }
  141692. *pbRes = bRes;
  141693. return rc;
  141694. }
  141695. /*
  141696. ** This function is called when initializing an incremental-merge operation.
  141697. ** It checks if the existing segment with index value iIdx at absolute level
  141698. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  141699. ** merge-writer object *pWriter is initialized to write to it.
  141700. **
  141701. ** An existing segment can be appended to by an incremental merge if:
  141702. **
  141703. ** * It was initially created as an appendable segment (with all required
  141704. ** space pre-allocated), and
  141705. **
  141706. ** * The first key read from the input (arguments zKey and nKey) is
  141707. ** greater than the largest key currently stored in the potential
  141708. ** output segment.
  141709. */
  141710. static int fts3IncrmergeLoad(
  141711. Fts3Table *p, /* Fts3 table handle */
  141712. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  141713. int iIdx, /* Index of candidate output segment */
  141714. const char *zKey, /* First key to write */
  141715. int nKey, /* Number of bytes in nKey */
  141716. IncrmergeWriter *pWriter /* Populate this object */
  141717. ){
  141718. int rc; /* Return code */
  141719. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  141720. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  141721. if( rc==SQLITE_OK ){
  141722. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  141723. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  141724. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  141725. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  141726. int nRoot = 0; /* Size of aRoot[] in bytes */
  141727. int rc2; /* Return code from sqlite3_reset() */
  141728. int bAppendable = 0; /* Set to true if segment is appendable */
  141729. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  141730. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  141731. sqlite3_bind_int(pSelect, 2, iIdx);
  141732. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  141733. iStart = sqlite3_column_int64(pSelect, 1);
  141734. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  141735. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  141736. if( pWriter->nLeafData<0 ){
  141737. pWriter->nLeafData = pWriter->nLeafData * -1;
  141738. }
  141739. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  141740. nRoot = sqlite3_column_bytes(pSelect, 4);
  141741. aRoot = sqlite3_column_blob(pSelect, 4);
  141742. }else{
  141743. return sqlite3_reset(pSelect);
  141744. }
  141745. /* Check for the zero-length marker in the %_segments table */
  141746. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  141747. /* Check that zKey/nKey is larger than the largest key the candidate */
  141748. if( rc==SQLITE_OK && bAppendable ){
  141749. char *aLeaf = 0;
  141750. int nLeaf = 0;
  141751. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  141752. if( rc==SQLITE_OK ){
  141753. NodeReader reader;
  141754. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  141755. rc==SQLITE_OK && reader.aNode;
  141756. rc = nodeReaderNext(&reader)
  141757. ){
  141758. assert( reader.aNode );
  141759. }
  141760. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  141761. bAppendable = 0;
  141762. }
  141763. nodeReaderRelease(&reader);
  141764. }
  141765. sqlite3_free(aLeaf);
  141766. }
  141767. if( rc==SQLITE_OK && bAppendable ){
  141768. /* It is possible to append to this segment. Set up the IncrmergeWriter
  141769. ** object to do so. */
  141770. int i;
  141771. int nHeight = (int)aRoot[0];
  141772. NodeWriter *pNode;
  141773. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  141774. pWriter->iStart = iStart;
  141775. pWriter->iEnd = iEnd;
  141776. pWriter->iAbsLevel = iAbsLevel;
  141777. pWriter->iIdx = iIdx;
  141778. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  141779. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  141780. }
  141781. pNode = &pWriter->aNodeWriter[nHeight];
  141782. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  141783. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  141784. if( rc==SQLITE_OK ){
  141785. memcpy(pNode->block.a, aRoot, nRoot);
  141786. pNode->block.n = nRoot;
  141787. }
  141788. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  141789. NodeReader reader;
  141790. pNode = &pWriter->aNodeWriter[i];
  141791. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  141792. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  141793. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  141794. if( rc==SQLITE_OK ){
  141795. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  141796. pNode->key.n = reader.term.n;
  141797. if( i>0 ){
  141798. char *aBlock = 0;
  141799. int nBlock = 0;
  141800. pNode = &pWriter->aNodeWriter[i-1];
  141801. pNode->iBlock = reader.iChild;
  141802. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  141803. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  141804. if( rc==SQLITE_OK ){
  141805. memcpy(pNode->block.a, aBlock, nBlock);
  141806. pNode->block.n = nBlock;
  141807. }
  141808. sqlite3_free(aBlock);
  141809. }
  141810. }
  141811. nodeReaderRelease(&reader);
  141812. }
  141813. }
  141814. rc2 = sqlite3_reset(pSelect);
  141815. if( rc==SQLITE_OK ) rc = rc2;
  141816. }
  141817. return rc;
  141818. }
  141819. /*
  141820. ** Determine the largest segment index value that exists within absolute
  141821. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  141822. ** one before returning SQLITE_OK. Or, if there are no segments at all
  141823. ** within level iAbsLevel, set *piIdx to zero.
  141824. **
  141825. ** If an error occurs, return an SQLite error code. The final value of
  141826. ** *piIdx is undefined in this case.
  141827. */
  141828. static int fts3IncrmergeOutputIdx(
  141829. Fts3Table *p, /* FTS Table handle */
  141830. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  141831. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  141832. ){
  141833. int rc;
  141834. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  141835. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  141836. if( rc==SQLITE_OK ){
  141837. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  141838. sqlite3_step(pOutputIdx);
  141839. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  141840. rc = sqlite3_reset(pOutputIdx);
  141841. }
  141842. return rc;
  141843. }
  141844. /*
  141845. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  141846. ** with idx value iIdx.
  141847. **
  141848. ** In the %_segdir table, a segment is defined by the values in three
  141849. ** columns:
  141850. **
  141851. ** start_block
  141852. ** leaves_end_block
  141853. ** end_block
  141854. **
  141855. ** When an appendable segment is allocated, it is estimated that the
  141856. ** maximum number of leaf blocks that may be required is the sum of the
  141857. ** number of leaf blocks consumed by the input segments, plus the number
  141858. ** of input segments, multiplied by two. This value is stored in stack
  141859. ** variable nLeafEst.
  141860. **
  141861. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  141862. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  141863. ** array of leaf nodes starts at the first block allocated. The array
  141864. ** of interior nodes that are parents of the leaf nodes start at block
  141865. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  141866. **
  141867. ** In the actual code below, the value "16" is replaced with the
  141868. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  141869. */
  141870. static int fts3IncrmergeWriter(
  141871. Fts3Table *p, /* Fts3 table handle */
  141872. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  141873. int iIdx, /* Index of new output segment */
  141874. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  141875. IncrmergeWriter *pWriter /* Populate this object */
  141876. ){
  141877. int rc; /* Return Code */
  141878. int i; /* Iterator variable */
  141879. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  141880. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  141881. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  141882. /* Calculate nLeafEst. */
  141883. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  141884. if( rc==SQLITE_OK ){
  141885. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  141886. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  141887. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  141888. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  141889. }
  141890. rc = sqlite3_reset(pLeafEst);
  141891. }
  141892. if( rc!=SQLITE_OK ) return rc;
  141893. /* Calculate the first block to use in the output segment */
  141894. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  141895. if( rc==SQLITE_OK ){
  141896. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  141897. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  141898. pWriter->iEnd = pWriter->iStart - 1;
  141899. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  141900. }
  141901. rc = sqlite3_reset(pFirstBlock);
  141902. }
  141903. if( rc!=SQLITE_OK ) return rc;
  141904. /* Insert the marker in the %_segments table to make sure nobody tries
  141905. ** to steal the space just allocated. This is also used to identify
  141906. ** appendable segments. */
  141907. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  141908. if( rc!=SQLITE_OK ) return rc;
  141909. pWriter->iAbsLevel = iAbsLevel;
  141910. pWriter->nLeafEst = nLeafEst;
  141911. pWriter->iIdx = iIdx;
  141912. /* Set up the array of NodeWriter objects */
  141913. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  141914. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  141915. }
  141916. return SQLITE_OK;
  141917. }
  141918. /*
  141919. ** Remove an entry from the %_segdir table. This involves running the
  141920. ** following two statements:
  141921. **
  141922. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  141923. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  141924. **
  141925. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  141926. ** statement ensures that the remaining segments have contiguously allocated
  141927. ** idx values.
  141928. */
  141929. static int fts3RemoveSegdirEntry(
  141930. Fts3Table *p, /* FTS3 table handle */
  141931. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  141932. int iIdx /* Index of %_segdir entry to delete */
  141933. ){
  141934. int rc; /* Return code */
  141935. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  141936. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  141937. if( rc==SQLITE_OK ){
  141938. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  141939. sqlite3_bind_int(pDelete, 2, iIdx);
  141940. sqlite3_step(pDelete);
  141941. rc = sqlite3_reset(pDelete);
  141942. }
  141943. return rc;
  141944. }
  141945. /*
  141946. ** One or more segments have just been removed from absolute level iAbsLevel.
  141947. ** Update the 'idx' values of the remaining segments in the level so that
  141948. ** the idx values are a contiguous sequence starting from 0.
  141949. */
  141950. static int fts3RepackSegdirLevel(
  141951. Fts3Table *p, /* FTS3 table handle */
  141952. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  141953. ){
  141954. int rc; /* Return code */
  141955. int *aIdx = 0; /* Array of remaining idx values */
  141956. int nIdx = 0; /* Valid entries in aIdx[] */
  141957. int nAlloc = 0; /* Allocated size of aIdx[] */
  141958. int i; /* Iterator variable */
  141959. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  141960. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  141961. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  141962. if( rc==SQLITE_OK ){
  141963. int rc2;
  141964. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  141965. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  141966. if( nIdx>=nAlloc ){
  141967. int *aNew;
  141968. nAlloc += 16;
  141969. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  141970. if( !aNew ){
  141971. rc = SQLITE_NOMEM;
  141972. break;
  141973. }
  141974. aIdx = aNew;
  141975. }
  141976. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  141977. }
  141978. rc2 = sqlite3_reset(pSelect);
  141979. if( rc==SQLITE_OK ) rc = rc2;
  141980. }
  141981. if( rc==SQLITE_OK ){
  141982. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  141983. }
  141984. if( rc==SQLITE_OK ){
  141985. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  141986. }
  141987. assert( p->bIgnoreSavepoint==0 );
  141988. p->bIgnoreSavepoint = 1;
  141989. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  141990. if( aIdx[i]!=i ){
  141991. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  141992. sqlite3_bind_int(pUpdate, 1, i);
  141993. sqlite3_step(pUpdate);
  141994. rc = sqlite3_reset(pUpdate);
  141995. }
  141996. }
  141997. p->bIgnoreSavepoint = 0;
  141998. sqlite3_free(aIdx);
  141999. return rc;
  142000. }
  142001. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  142002. pNode->a[0] = (char)iHeight;
  142003. if( iChild ){
  142004. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  142005. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  142006. }else{
  142007. assert( pNode->nAlloc>=1 );
  142008. pNode->n = 1;
  142009. }
  142010. }
  142011. /*
  142012. ** The first two arguments are a pointer to and the size of a segment b-tree
  142013. ** node. The node may be a leaf or an internal node.
  142014. **
  142015. ** This function creates a new node image in blob object *pNew by copying
  142016. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  142017. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  142018. */
  142019. static int fts3TruncateNode(
  142020. const char *aNode, /* Current node image */
  142021. int nNode, /* Size of aNode in bytes */
  142022. Blob *pNew, /* OUT: Write new node image here */
  142023. const char *zTerm, /* Omit all terms smaller than this */
  142024. int nTerm, /* Size of zTerm in bytes */
  142025. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  142026. ){
  142027. NodeReader reader; /* Reader object */
  142028. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  142029. int rc = SQLITE_OK; /* Return code */
  142030. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  142031. /* Allocate required output space */
  142032. blobGrowBuffer(pNew, nNode, &rc);
  142033. if( rc!=SQLITE_OK ) return rc;
  142034. pNew->n = 0;
  142035. /* Populate new node buffer */
  142036. for(rc = nodeReaderInit(&reader, aNode, nNode);
  142037. rc==SQLITE_OK && reader.aNode;
  142038. rc = nodeReaderNext(&reader)
  142039. ){
  142040. if( pNew->n==0 ){
  142041. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  142042. if( res<0 || (bLeaf==0 && res==0) ) continue;
  142043. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  142044. *piBlock = reader.iChild;
  142045. }
  142046. rc = fts3AppendToNode(
  142047. pNew, &prev, reader.term.a, reader.term.n,
  142048. reader.aDoclist, reader.nDoclist
  142049. );
  142050. if( rc!=SQLITE_OK ) break;
  142051. }
  142052. if( pNew->n==0 ){
  142053. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  142054. *piBlock = reader.iChild;
  142055. }
  142056. assert( pNew->n<=pNew->nAlloc );
  142057. nodeReaderRelease(&reader);
  142058. sqlite3_free(prev.a);
  142059. return rc;
  142060. }
  142061. /*
  142062. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  142063. ** level iAbsLevel. This may involve deleting entries from the %_segments
  142064. ** table, and modifying existing entries in both the %_segments and %_segdir
  142065. ** tables.
  142066. **
  142067. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  142068. ** SQLite error code otherwise.
  142069. */
  142070. static int fts3TruncateSegment(
  142071. Fts3Table *p, /* FTS3 table handle */
  142072. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  142073. int iIdx, /* Index within level of segment to modify */
  142074. const char *zTerm, /* Remove terms smaller than this */
  142075. int nTerm /* Number of bytes in buffer zTerm */
  142076. ){
  142077. int rc = SQLITE_OK; /* Return code */
  142078. Blob root = {0,0,0}; /* New root page image */
  142079. Blob block = {0,0,0}; /* Buffer used for any other block */
  142080. sqlite3_int64 iBlock = 0; /* Block id */
  142081. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  142082. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  142083. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  142084. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  142085. if( rc==SQLITE_OK ){
  142086. int rc2; /* sqlite3_reset() return code */
  142087. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  142088. sqlite3_bind_int(pFetch, 2, iIdx);
  142089. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  142090. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  142091. int nRoot = sqlite3_column_bytes(pFetch, 4);
  142092. iOldStart = sqlite3_column_int64(pFetch, 1);
  142093. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  142094. }
  142095. rc2 = sqlite3_reset(pFetch);
  142096. if( rc==SQLITE_OK ) rc = rc2;
  142097. }
  142098. while( rc==SQLITE_OK && iBlock ){
  142099. char *aBlock = 0;
  142100. int nBlock = 0;
  142101. iNewStart = iBlock;
  142102. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  142103. if( rc==SQLITE_OK ){
  142104. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  142105. }
  142106. if( rc==SQLITE_OK ){
  142107. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  142108. }
  142109. sqlite3_free(aBlock);
  142110. }
  142111. /* Variable iNewStart now contains the first valid leaf node. */
  142112. if( rc==SQLITE_OK && iNewStart ){
  142113. sqlite3_stmt *pDel = 0;
  142114. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  142115. if( rc==SQLITE_OK ){
  142116. sqlite3_bind_int64(pDel, 1, iOldStart);
  142117. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  142118. sqlite3_step(pDel);
  142119. rc = sqlite3_reset(pDel);
  142120. }
  142121. }
  142122. if( rc==SQLITE_OK ){
  142123. sqlite3_stmt *pChomp = 0;
  142124. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  142125. if( rc==SQLITE_OK ){
  142126. sqlite3_bind_int64(pChomp, 1, iNewStart);
  142127. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  142128. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  142129. sqlite3_bind_int(pChomp, 4, iIdx);
  142130. sqlite3_step(pChomp);
  142131. rc = sqlite3_reset(pChomp);
  142132. }
  142133. }
  142134. sqlite3_free(root.a);
  142135. sqlite3_free(block.a);
  142136. return rc;
  142137. }
  142138. /*
  142139. ** This function is called after an incrmental-merge operation has run to
  142140. ** merge (or partially merge) two or more segments from absolute level
  142141. ** iAbsLevel.
  142142. **
  142143. ** Each input segment is either removed from the db completely (if all of
  142144. ** its data was copied to the output segment by the incrmerge operation)
  142145. ** or modified in place so that it no longer contains those entries that
  142146. ** have been duplicated in the output segment.
  142147. */
  142148. static int fts3IncrmergeChomp(
  142149. Fts3Table *p, /* FTS table handle */
  142150. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  142151. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  142152. int *pnRem /* Number of segments not deleted */
  142153. ){
  142154. int i;
  142155. int nRem = 0;
  142156. int rc = SQLITE_OK;
  142157. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  142158. Fts3SegReader *pSeg = 0;
  142159. int j;
  142160. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  142161. ** somewhere in the pCsr->apSegment[] array. */
  142162. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  142163. pSeg = pCsr->apSegment[j];
  142164. if( pSeg->iIdx==i ) break;
  142165. }
  142166. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  142167. if( pSeg->aNode==0 ){
  142168. /* Seg-reader is at EOF. Remove the entire input segment. */
  142169. rc = fts3DeleteSegment(p, pSeg);
  142170. if( rc==SQLITE_OK ){
  142171. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  142172. }
  142173. *pnRem = 0;
  142174. }else{
  142175. /* The incremental merge did not copy all the data from this
  142176. ** segment to the upper level. The segment is modified in place
  142177. ** so that it contains no keys smaller than zTerm/nTerm. */
  142178. const char *zTerm = pSeg->zTerm;
  142179. int nTerm = pSeg->nTerm;
  142180. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  142181. nRem++;
  142182. }
  142183. }
  142184. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  142185. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  142186. }
  142187. *pnRem = nRem;
  142188. return rc;
  142189. }
  142190. /*
  142191. ** Store an incr-merge hint in the database.
  142192. */
  142193. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  142194. sqlite3_stmt *pReplace = 0;
  142195. int rc; /* Return code */
  142196. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  142197. if( rc==SQLITE_OK ){
  142198. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  142199. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  142200. sqlite3_step(pReplace);
  142201. rc = sqlite3_reset(pReplace);
  142202. }
  142203. return rc;
  142204. }
  142205. /*
  142206. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  142207. ** exists, is stored in the rowid==1 row of the %_stat table.
  142208. **
  142209. ** If successful, populate blob *pHint with the value read from the %_stat
  142210. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  142211. ** SQLite error code.
  142212. */
  142213. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  142214. sqlite3_stmt *pSelect = 0;
  142215. int rc;
  142216. pHint->n = 0;
  142217. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  142218. if( rc==SQLITE_OK ){
  142219. int rc2;
  142220. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  142221. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  142222. const char *aHint = sqlite3_column_blob(pSelect, 0);
  142223. int nHint = sqlite3_column_bytes(pSelect, 0);
  142224. if( aHint ){
  142225. blobGrowBuffer(pHint, nHint, &rc);
  142226. if( rc==SQLITE_OK ){
  142227. memcpy(pHint->a, aHint, nHint);
  142228. pHint->n = nHint;
  142229. }
  142230. }
  142231. }
  142232. rc2 = sqlite3_reset(pSelect);
  142233. if( rc==SQLITE_OK ) rc = rc2;
  142234. }
  142235. return rc;
  142236. }
  142237. /*
  142238. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  142239. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  142240. ** consists of two varints, the absolute level number of the input segments
  142241. ** and the number of input segments.
  142242. **
  142243. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  142244. ** set *pRc to an SQLite error code before returning.
  142245. */
  142246. static void fts3IncrmergeHintPush(
  142247. Blob *pHint, /* Hint blob to append to */
  142248. i64 iAbsLevel, /* First varint to store in hint */
  142249. int nInput, /* Second varint to store in hint */
  142250. int *pRc /* IN/OUT: Error code */
  142251. ){
  142252. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  142253. if( *pRc==SQLITE_OK ){
  142254. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  142255. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  142256. }
  142257. }
  142258. /*
  142259. ** Read the last entry (most recently pushed) from the hint blob *pHint
  142260. ** and then remove the entry. Write the two values read to *piAbsLevel and
  142261. ** *pnInput before returning.
  142262. **
  142263. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  142264. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  142265. */
  142266. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  142267. const int nHint = pHint->n;
  142268. int i;
  142269. i = pHint->n-2;
  142270. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  142271. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  142272. pHint->n = i;
  142273. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  142274. i += fts3GetVarint32(&pHint->a[i], pnInput);
  142275. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  142276. return SQLITE_OK;
  142277. }
  142278. /*
  142279. ** Attempt an incremental merge that writes nMerge leaf blocks.
  142280. **
  142281. ** Incremental merges happen nMin segments at a time. The segments
  142282. ** to be merged are the nMin oldest segments (the ones with the smallest
  142283. ** values for the _segdir.idx field) in the highest level that contains
  142284. ** at least nMin segments. Multiple merges might occur in an attempt to
  142285. ** write the quota of nMerge leaf blocks.
  142286. */
  142287. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  142288. int rc; /* Return code */
  142289. int nRem = nMerge; /* Number of leaf pages yet to be written */
  142290. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  142291. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  142292. IncrmergeWriter *pWriter; /* Writer object */
  142293. int nSeg = 0; /* Number of input segments */
  142294. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  142295. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  142296. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  142297. /* Allocate space for the cursor, filter and writer objects */
  142298. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  142299. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  142300. if( !pWriter ) return SQLITE_NOMEM;
  142301. pFilter = (Fts3SegFilter *)&pWriter[1];
  142302. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  142303. rc = fts3IncrmergeHintLoad(p, &hint);
  142304. while( rc==SQLITE_OK && nRem>0 ){
  142305. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  142306. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  142307. int bUseHint = 0; /* True if attempting to append */
  142308. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  142309. /* Search the %_segdir table for the absolute level with the smallest
  142310. ** relative level number that contains at least nMin segments, if any.
  142311. ** If one is found, set iAbsLevel to the absolute level number and
  142312. ** nSeg to nMin. If no level with at least nMin segments can be found,
  142313. ** set nSeg to -1.
  142314. */
  142315. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  142316. sqlite3_bind_int(pFindLevel, 1, nMin);
  142317. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  142318. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  142319. nSeg = nMin;
  142320. }else{
  142321. nSeg = -1;
  142322. }
  142323. rc = sqlite3_reset(pFindLevel);
  142324. /* If the hint read from the %_stat table is not empty, check if the
  142325. ** last entry in it specifies a relative level smaller than or equal
  142326. ** to the level identified by the block above (if any). If so, this
  142327. ** iteration of the loop will work on merging at the hinted level.
  142328. */
  142329. if( rc==SQLITE_OK && hint.n ){
  142330. int nHint = hint.n;
  142331. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  142332. int nHintSeg = 0; /* Hint number of segments */
  142333. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  142334. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  142335. iAbsLevel = iHintAbsLevel;
  142336. nSeg = nHintSeg;
  142337. bUseHint = 1;
  142338. bDirtyHint = 1;
  142339. }else{
  142340. /* This undoes the effect of the HintPop() above - so that no entry
  142341. ** is removed from the hint blob. */
  142342. hint.n = nHint;
  142343. }
  142344. }
  142345. /* If nSeg is less that zero, then there is no level with at least
  142346. ** nMin segments and no hint in the %_stat table. No work to do.
  142347. ** Exit early in this case. */
  142348. if( nSeg<0 ) break;
  142349. /* Open a cursor to iterate through the contents of the oldest nSeg
  142350. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  142351. ** the 'hint' parameters, it is possible that there are less than nSeg
  142352. ** segments available in level iAbsLevel. In this case, no work is
  142353. ** done on iAbsLevel - fall through to the next iteration of the loop
  142354. ** to start work on some other level. */
  142355. memset(pWriter, 0, nAlloc);
  142356. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  142357. if( rc==SQLITE_OK ){
  142358. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  142359. assert( bUseHint==1 || bUseHint==0 );
  142360. if( iIdx==0 || (bUseHint && iIdx==1) ){
  142361. int bIgnore = 0;
  142362. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  142363. if( bIgnore ){
  142364. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  142365. }
  142366. }
  142367. }
  142368. if( rc==SQLITE_OK ){
  142369. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  142370. }
  142371. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  142372. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  142373. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  142374. ){
  142375. if( bUseHint && iIdx>0 ){
  142376. const char *zKey = pCsr->zTerm;
  142377. int nKey = pCsr->nTerm;
  142378. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  142379. }else{
  142380. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  142381. }
  142382. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  142383. fts3LogMerge(nSeg, iAbsLevel);
  142384. do {
  142385. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  142386. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  142387. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  142388. }while( rc==SQLITE_ROW );
  142389. /* Update or delete the input segments */
  142390. if( rc==SQLITE_OK ){
  142391. nRem -= (1 + pWriter->nWork);
  142392. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  142393. if( nSeg!=0 ){
  142394. bDirtyHint = 1;
  142395. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  142396. }
  142397. }
  142398. }
  142399. if( nSeg!=0 ){
  142400. pWriter->nLeafData = pWriter->nLeafData * -1;
  142401. }
  142402. fts3IncrmergeRelease(p, pWriter, &rc);
  142403. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  142404. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  142405. }
  142406. }
  142407. sqlite3Fts3SegReaderFinish(pCsr);
  142408. }
  142409. /* Write the hint values into the %_stat table for the next incr-merger */
  142410. if( bDirtyHint && rc==SQLITE_OK ){
  142411. rc = fts3IncrmergeHintStore(p, &hint);
  142412. }
  142413. sqlite3_free(pWriter);
  142414. sqlite3_free(hint.a);
  142415. return rc;
  142416. }
  142417. /*
  142418. ** Convert the text beginning at *pz into an integer and return
  142419. ** its value. Advance *pz to point to the first character past
  142420. ** the integer.
  142421. */
  142422. static int fts3Getint(const char **pz){
  142423. const char *z = *pz;
  142424. int i = 0;
  142425. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  142426. *pz = z;
  142427. return i;
  142428. }
  142429. /*
  142430. ** Process statements of the form:
  142431. **
  142432. ** INSERT INTO table(table) VALUES('merge=A,B');
  142433. **
  142434. ** A and B are integers that decode to be the number of leaf pages
  142435. ** written for the merge, and the minimum number of segments on a level
  142436. ** before it will be selected for a merge, respectively.
  142437. */
  142438. static int fts3DoIncrmerge(
  142439. Fts3Table *p, /* FTS3 table handle */
  142440. const char *zParam /* Nul-terminated string containing "A,B" */
  142441. ){
  142442. int rc;
  142443. int nMin = (FTS3_MERGE_COUNT / 2);
  142444. int nMerge = 0;
  142445. const char *z = zParam;
  142446. /* Read the first integer value */
  142447. nMerge = fts3Getint(&z);
  142448. /* If the first integer value is followed by a ',', read the second
  142449. ** integer value. */
  142450. if( z[0]==',' && z[1]!='\0' ){
  142451. z++;
  142452. nMin = fts3Getint(&z);
  142453. }
  142454. if( z[0]!='\0' || nMin<2 ){
  142455. rc = SQLITE_ERROR;
  142456. }else{
  142457. rc = SQLITE_OK;
  142458. if( !p->bHasStat ){
  142459. assert( p->bFts4==0 );
  142460. sqlite3Fts3CreateStatTable(&rc, p);
  142461. }
  142462. if( rc==SQLITE_OK ){
  142463. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  142464. }
  142465. sqlite3Fts3SegmentsClose(p);
  142466. }
  142467. return rc;
  142468. }
  142469. /*
  142470. ** Process statements of the form:
  142471. **
  142472. ** INSERT INTO table(table) VALUES('automerge=X');
  142473. **
  142474. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  142475. ** turn it on. The setting is persistent.
  142476. */
  142477. static int fts3DoAutoincrmerge(
  142478. Fts3Table *p, /* FTS3 table handle */
  142479. const char *zParam /* Nul-terminated string containing boolean */
  142480. ){
  142481. int rc = SQLITE_OK;
  142482. sqlite3_stmt *pStmt = 0;
  142483. p->nAutoincrmerge = fts3Getint(&zParam);
  142484. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  142485. p->nAutoincrmerge = 8;
  142486. }
  142487. if( !p->bHasStat ){
  142488. assert( p->bFts4==0 );
  142489. sqlite3Fts3CreateStatTable(&rc, p);
  142490. if( rc ) return rc;
  142491. }
  142492. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  142493. if( rc ) return rc;
  142494. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  142495. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  142496. sqlite3_step(pStmt);
  142497. rc = sqlite3_reset(pStmt);
  142498. return rc;
  142499. }
  142500. /*
  142501. ** Return a 64-bit checksum for the FTS index entry specified by the
  142502. ** arguments to this function.
  142503. */
  142504. static u64 fts3ChecksumEntry(
  142505. const char *zTerm, /* Pointer to buffer containing term */
  142506. int nTerm, /* Size of zTerm in bytes */
  142507. int iLangid, /* Language id for current row */
  142508. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  142509. i64 iDocid, /* Docid for current row. */
  142510. int iCol, /* Column number */
  142511. int iPos /* Position */
  142512. ){
  142513. int i;
  142514. u64 ret = (u64)iDocid;
  142515. ret += (ret<<3) + iLangid;
  142516. ret += (ret<<3) + iIndex;
  142517. ret += (ret<<3) + iCol;
  142518. ret += (ret<<3) + iPos;
  142519. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  142520. return ret;
  142521. }
  142522. /*
  142523. ** Return a checksum of all entries in the FTS index that correspond to
  142524. ** language id iLangid. The checksum is calculated by XORing the checksums
  142525. ** of each individual entry (see fts3ChecksumEntry()) together.
  142526. **
  142527. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  142528. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  142529. ** return value is undefined in this case.
  142530. */
  142531. static u64 fts3ChecksumIndex(
  142532. Fts3Table *p, /* FTS3 table handle */
  142533. int iLangid, /* Language id to return cksum for */
  142534. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  142535. int *pRc /* OUT: Return code */
  142536. ){
  142537. Fts3SegFilter filter;
  142538. Fts3MultiSegReader csr;
  142539. int rc;
  142540. u64 cksum = 0;
  142541. assert( *pRc==SQLITE_OK );
  142542. memset(&filter, 0, sizeof(filter));
  142543. memset(&csr, 0, sizeof(csr));
  142544. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  142545. filter.flags |= FTS3_SEGMENT_SCAN;
  142546. rc = sqlite3Fts3SegReaderCursor(
  142547. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  142548. );
  142549. if( rc==SQLITE_OK ){
  142550. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  142551. }
  142552. if( rc==SQLITE_OK ){
  142553. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  142554. char *pCsr = csr.aDoclist;
  142555. char *pEnd = &pCsr[csr.nDoclist];
  142556. i64 iDocid = 0;
  142557. i64 iCol = 0;
  142558. i64 iPos = 0;
  142559. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  142560. while( pCsr<pEnd ){
  142561. i64 iVal = 0;
  142562. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  142563. if( pCsr<pEnd ){
  142564. if( iVal==0 || iVal==1 ){
  142565. iCol = 0;
  142566. iPos = 0;
  142567. if( iVal ){
  142568. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  142569. }else{
  142570. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  142571. iDocid += iVal;
  142572. }
  142573. }else{
  142574. iPos += (iVal - 2);
  142575. cksum = cksum ^ fts3ChecksumEntry(
  142576. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  142577. (int)iCol, (int)iPos
  142578. );
  142579. }
  142580. }
  142581. }
  142582. }
  142583. }
  142584. sqlite3Fts3SegReaderFinish(&csr);
  142585. *pRc = rc;
  142586. return cksum;
  142587. }
  142588. /*
  142589. ** Check if the contents of the FTS index match the current contents of the
  142590. ** content table. If no error occurs and the contents do match, set *pbOk
  142591. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  142592. ** to false before returning.
  142593. **
  142594. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  142595. ** code. The final value of *pbOk is undefined in this case.
  142596. */
  142597. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  142598. int rc = SQLITE_OK; /* Return code */
  142599. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  142600. u64 cksum2 = 0; /* Checksum based on %_content contents */
  142601. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  142602. /* This block calculates the checksum according to the FTS index. */
  142603. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  142604. if( rc==SQLITE_OK ){
  142605. int rc2;
  142606. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  142607. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  142608. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  142609. int iLangid = sqlite3_column_int(pAllLangid, 0);
  142610. int i;
  142611. for(i=0; i<p->nIndex; i++){
  142612. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  142613. }
  142614. }
  142615. rc2 = sqlite3_reset(pAllLangid);
  142616. if( rc==SQLITE_OK ) rc = rc2;
  142617. }
  142618. /* This block calculates the checksum according to the %_content table */
  142619. if( rc==SQLITE_OK ){
  142620. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  142621. sqlite3_stmt *pStmt = 0;
  142622. char *zSql;
  142623. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  142624. if( !zSql ){
  142625. rc = SQLITE_NOMEM;
  142626. }else{
  142627. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  142628. sqlite3_free(zSql);
  142629. }
  142630. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  142631. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  142632. int iLang = langidFromSelect(p, pStmt);
  142633. int iCol;
  142634. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  142635. if( p->abNotindexed[iCol]==0 ){
  142636. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  142637. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  142638. sqlite3_tokenizer_cursor *pT = 0;
  142639. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  142640. while( rc==SQLITE_OK ){
  142641. char const *zToken; /* Buffer containing token */
  142642. int nToken = 0; /* Number of bytes in token */
  142643. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  142644. int iPos = 0; /* Position of token in zText */
  142645. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  142646. if( rc==SQLITE_OK ){
  142647. int i;
  142648. cksum2 = cksum2 ^ fts3ChecksumEntry(
  142649. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  142650. );
  142651. for(i=1; i<p->nIndex; i++){
  142652. if( p->aIndex[i].nPrefix<=nToken ){
  142653. cksum2 = cksum2 ^ fts3ChecksumEntry(
  142654. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  142655. );
  142656. }
  142657. }
  142658. }
  142659. }
  142660. if( pT ) pModule->xClose(pT);
  142661. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  142662. }
  142663. }
  142664. }
  142665. sqlite3_finalize(pStmt);
  142666. }
  142667. *pbOk = (cksum1==cksum2);
  142668. return rc;
  142669. }
  142670. /*
  142671. ** Run the integrity-check. If no error occurs and the current contents of
  142672. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  142673. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  142674. **
  142675. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  142676. ** error code.
  142677. **
  142678. ** The integrity-check works as follows. For each token and indexed token
  142679. ** prefix in the document set, a 64-bit checksum is calculated (by code
  142680. ** in fts3ChecksumEntry()) based on the following:
  142681. **
  142682. ** + The index number (0 for the main index, 1 for the first prefix
  142683. ** index etc.),
  142684. ** + The token (or token prefix) text itself,
  142685. ** + The language-id of the row it appears in,
  142686. ** + The docid of the row it appears in,
  142687. ** + The column it appears in, and
  142688. ** + The tokens position within that column.
  142689. **
  142690. ** The checksums for all entries in the index are XORed together to create
  142691. ** a single checksum for the entire index.
  142692. **
  142693. ** The integrity-check code calculates the same checksum in two ways:
  142694. **
  142695. ** 1. By scanning the contents of the FTS index, and
  142696. ** 2. By scanning and tokenizing the content table.
  142697. **
  142698. ** If the two checksums are identical, the integrity-check is deemed to have
  142699. ** passed.
  142700. */
  142701. static int fts3DoIntegrityCheck(
  142702. Fts3Table *p /* FTS3 table handle */
  142703. ){
  142704. int rc;
  142705. int bOk = 0;
  142706. rc = fts3IntegrityCheck(p, &bOk);
  142707. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  142708. return rc;
  142709. }
  142710. /*
  142711. ** Handle a 'special' INSERT of the form:
  142712. **
  142713. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  142714. **
  142715. ** Argument pVal contains the result of <expr>. Currently the only
  142716. ** meaningful value to insert is the text 'optimize'.
  142717. */
  142718. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  142719. int rc; /* Return Code */
  142720. const char *zVal = (const char *)sqlite3_value_text(pVal);
  142721. int nVal = sqlite3_value_bytes(pVal);
  142722. if( !zVal ){
  142723. return SQLITE_NOMEM;
  142724. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  142725. rc = fts3DoOptimize(p, 0);
  142726. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  142727. rc = fts3DoRebuild(p);
  142728. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  142729. rc = fts3DoIntegrityCheck(p);
  142730. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  142731. rc = fts3DoIncrmerge(p, &zVal[6]);
  142732. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  142733. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  142734. #ifdef SQLITE_TEST
  142735. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  142736. p->nNodeSize = atoi(&zVal[9]);
  142737. rc = SQLITE_OK;
  142738. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  142739. p->nMaxPendingData = atoi(&zVal[11]);
  142740. rc = SQLITE_OK;
  142741. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  142742. p->bNoIncrDoclist = atoi(&zVal[21]);
  142743. rc = SQLITE_OK;
  142744. #endif
  142745. }else{
  142746. rc = SQLITE_ERROR;
  142747. }
  142748. return rc;
  142749. }
  142750. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  142751. /*
  142752. ** Delete all cached deferred doclists. Deferred doclists are cached
  142753. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  142754. */
  142755. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  142756. Fts3DeferredToken *pDef;
  142757. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  142758. fts3PendingListDelete(pDef->pList);
  142759. pDef->pList = 0;
  142760. }
  142761. }
  142762. /*
  142763. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  142764. ** this list using sqlite3Fts3DeferToken().
  142765. */
  142766. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  142767. Fts3DeferredToken *pDef;
  142768. Fts3DeferredToken *pNext;
  142769. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  142770. pNext = pDef->pNext;
  142771. fts3PendingListDelete(pDef->pList);
  142772. sqlite3_free(pDef);
  142773. }
  142774. pCsr->pDeferred = 0;
  142775. }
  142776. /*
  142777. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  142778. ** based on the row that pCsr currently points to.
  142779. **
  142780. ** A deferred-doclist is like any other doclist with position information
  142781. ** included, except that it only contains entries for a single row of the
  142782. ** table, not for all rows.
  142783. */
  142784. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  142785. int rc = SQLITE_OK; /* Return code */
  142786. if( pCsr->pDeferred ){
  142787. int i; /* Used to iterate through table columns */
  142788. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  142789. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  142790. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  142791. sqlite3_tokenizer *pT = p->pTokenizer;
  142792. sqlite3_tokenizer_module const *pModule = pT->pModule;
  142793. assert( pCsr->isRequireSeek==0 );
  142794. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  142795. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  142796. if( p->abNotindexed[i]==0 ){
  142797. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  142798. sqlite3_tokenizer_cursor *pTC = 0;
  142799. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  142800. while( rc==SQLITE_OK ){
  142801. char const *zToken; /* Buffer containing token */
  142802. int nToken = 0; /* Number of bytes in token */
  142803. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  142804. int iPos = 0; /* Position of token in zText */
  142805. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  142806. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  142807. Fts3PhraseToken *pPT = pDef->pToken;
  142808. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  142809. && (pPT->bFirst==0 || iPos==0)
  142810. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  142811. && (0==memcmp(zToken, pPT->z, pPT->n))
  142812. ){
  142813. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  142814. }
  142815. }
  142816. }
  142817. if( pTC ) pModule->xClose(pTC);
  142818. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  142819. }
  142820. }
  142821. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  142822. if( pDef->pList ){
  142823. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  142824. }
  142825. }
  142826. }
  142827. return rc;
  142828. }
  142829. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  142830. Fts3DeferredToken *p,
  142831. char **ppData,
  142832. int *pnData
  142833. ){
  142834. char *pRet;
  142835. int nSkip;
  142836. sqlite3_int64 dummy;
  142837. *ppData = 0;
  142838. *pnData = 0;
  142839. if( p->pList==0 ){
  142840. return SQLITE_OK;
  142841. }
  142842. pRet = (char *)sqlite3_malloc(p->pList->nData);
  142843. if( !pRet ) return SQLITE_NOMEM;
  142844. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  142845. *pnData = p->pList->nData - nSkip;
  142846. *ppData = pRet;
  142847. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  142848. return SQLITE_OK;
  142849. }
  142850. /*
  142851. ** Add an entry for token pToken to the pCsr->pDeferred list.
  142852. */
  142853. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  142854. Fts3Cursor *pCsr, /* Fts3 table cursor */
  142855. Fts3PhraseToken *pToken, /* Token to defer */
  142856. int iCol /* Column that token must appear in (or -1) */
  142857. ){
  142858. Fts3DeferredToken *pDeferred;
  142859. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  142860. if( !pDeferred ){
  142861. return SQLITE_NOMEM;
  142862. }
  142863. memset(pDeferred, 0, sizeof(*pDeferred));
  142864. pDeferred->pToken = pToken;
  142865. pDeferred->pNext = pCsr->pDeferred;
  142866. pDeferred->iCol = iCol;
  142867. pCsr->pDeferred = pDeferred;
  142868. assert( pToken->pDeferred==0 );
  142869. pToken->pDeferred = pDeferred;
  142870. return SQLITE_OK;
  142871. }
  142872. #endif
  142873. /*
  142874. ** SQLite value pRowid contains the rowid of a row that may or may not be
  142875. ** present in the FTS3 table. If it is, delete it and adjust the contents
  142876. ** of subsiduary data structures accordingly.
  142877. */
  142878. static int fts3DeleteByRowid(
  142879. Fts3Table *p,
  142880. sqlite3_value *pRowid,
  142881. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  142882. u32 *aSzDel
  142883. ){
  142884. int rc = SQLITE_OK; /* Return code */
  142885. int bFound = 0; /* True if *pRowid really is in the table */
  142886. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  142887. if( bFound && rc==SQLITE_OK ){
  142888. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  142889. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  142890. if( rc==SQLITE_OK ){
  142891. if( isEmpty ){
  142892. /* Deleting this row means the whole table is empty. In this case
  142893. ** delete the contents of all three tables and throw away any
  142894. ** data in the pendingTerms hash table. */
  142895. rc = fts3DeleteAll(p, 1);
  142896. *pnChng = 0;
  142897. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  142898. }else{
  142899. *pnChng = *pnChng - 1;
  142900. if( p->zContentTbl==0 ){
  142901. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  142902. }
  142903. if( p->bHasDocsize ){
  142904. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  142905. }
  142906. }
  142907. }
  142908. }
  142909. return rc;
  142910. }
  142911. /*
  142912. ** This function does the work for the xUpdate method of FTS3 virtual
  142913. ** tables. The schema of the virtual table being:
  142914. **
  142915. ** CREATE TABLE <table name>(
  142916. ** <user columns>,
  142917. ** <table name> HIDDEN,
  142918. ** docid HIDDEN,
  142919. ** <langid> HIDDEN
  142920. ** );
  142921. **
  142922. **
  142923. */
  142924. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  142925. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  142926. int nArg, /* Size of argument array */
  142927. sqlite3_value **apVal, /* Array of arguments */
  142928. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  142929. ){
  142930. Fts3Table *p = (Fts3Table *)pVtab;
  142931. int rc = SQLITE_OK; /* Return Code */
  142932. int isRemove = 0; /* True for an UPDATE or DELETE */
  142933. u32 *aSzIns = 0; /* Sizes of inserted documents */
  142934. u32 *aSzDel = 0; /* Sizes of deleted documents */
  142935. int nChng = 0; /* Net change in number of documents */
  142936. int bInsertDone = 0;
  142937. /* At this point it must be known if the %_stat table exists or not.
  142938. ** So bHasStat may not be 2. */
  142939. assert( p->bHasStat==0 || p->bHasStat==1 );
  142940. assert( p->pSegments==0 );
  142941. assert(
  142942. nArg==1 /* DELETE operations */
  142943. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  142944. );
  142945. /* Check for a "special" INSERT operation. One of the form:
  142946. **
  142947. ** INSERT INTO xyz(xyz) VALUES('command');
  142948. */
  142949. if( nArg>1
  142950. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  142951. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  142952. ){
  142953. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  142954. goto update_out;
  142955. }
  142956. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  142957. rc = SQLITE_CONSTRAINT;
  142958. goto update_out;
  142959. }
  142960. /* Allocate space to hold the change in document sizes */
  142961. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  142962. if( aSzDel==0 ){
  142963. rc = SQLITE_NOMEM;
  142964. goto update_out;
  142965. }
  142966. aSzIns = &aSzDel[p->nColumn+1];
  142967. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  142968. rc = fts3Writelock(p);
  142969. if( rc!=SQLITE_OK ) goto update_out;
  142970. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  142971. ** value, then this operation requires constraint handling.
  142972. **
  142973. ** If the on-conflict mode is REPLACE, this means that the existing row
  142974. ** should be deleted from the database before inserting the new row. Or,
  142975. ** if the on-conflict mode is other than REPLACE, then this method must
  142976. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  142977. ** modify the database file.
  142978. */
  142979. if( nArg>1 && p->zContentTbl==0 ){
  142980. /* Find the value object that holds the new rowid value. */
  142981. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  142982. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  142983. pNewRowid = apVal[1];
  142984. }
  142985. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  142986. sqlite3_value_type(apVal[0])==SQLITE_NULL
  142987. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  142988. )){
  142989. /* The new rowid is not NULL (in this case the rowid will be
  142990. ** automatically assigned and there is no chance of a conflict), and
  142991. ** the statement is either an INSERT or an UPDATE that modifies the
  142992. ** rowid column. So if the conflict mode is REPLACE, then delete any
  142993. ** existing row with rowid=pNewRowid.
  142994. **
  142995. ** Or, if the conflict mode is not REPLACE, insert the new record into
  142996. ** the %_content table. If we hit the duplicate rowid constraint (or any
  142997. ** other error) while doing so, return immediately.
  142998. **
  142999. ** This branch may also run if pNewRowid contains a value that cannot
  143000. ** be losslessly converted to an integer. In this case, the eventual
  143001. ** call to fts3InsertData() (either just below or further on in this
  143002. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  143003. ** invoked, it will delete zero rows (since no row will have
  143004. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  143005. */
  143006. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  143007. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  143008. }else{
  143009. rc = fts3InsertData(p, apVal, pRowid);
  143010. bInsertDone = 1;
  143011. }
  143012. }
  143013. }
  143014. if( rc!=SQLITE_OK ){
  143015. goto update_out;
  143016. }
  143017. /* If this is a DELETE or UPDATE operation, remove the old record. */
  143018. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  143019. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  143020. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  143021. isRemove = 1;
  143022. }
  143023. /* If this is an INSERT or UPDATE operation, insert the new record. */
  143024. if( nArg>1 && rc==SQLITE_OK ){
  143025. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  143026. if( bInsertDone==0 ){
  143027. rc = fts3InsertData(p, apVal, pRowid);
  143028. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  143029. rc = FTS_CORRUPT_VTAB;
  143030. }
  143031. }
  143032. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  143033. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  143034. }
  143035. if( rc==SQLITE_OK ){
  143036. assert( p->iPrevDocid==*pRowid );
  143037. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  143038. }
  143039. if( p->bHasDocsize ){
  143040. fts3InsertDocsize(&rc, p, aSzIns);
  143041. }
  143042. nChng++;
  143043. }
  143044. if( p->bFts4 ){
  143045. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  143046. }
  143047. update_out:
  143048. sqlite3_free(aSzDel);
  143049. sqlite3Fts3SegmentsClose(p);
  143050. return rc;
  143051. }
  143052. /*
  143053. ** Flush any data in the pending-terms hash table to disk. If successful,
  143054. ** merge all segments in the database (including the new segment, if
  143055. ** there was any data to flush) into a single segment.
  143056. */
  143057. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  143058. int rc;
  143059. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  143060. if( rc==SQLITE_OK ){
  143061. rc = fts3DoOptimize(p, 1);
  143062. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  143063. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  143064. if( rc2!=SQLITE_OK ) rc = rc2;
  143065. }else{
  143066. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  143067. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  143068. }
  143069. }
  143070. sqlite3Fts3SegmentsClose(p);
  143071. return rc;
  143072. }
  143073. #endif
  143074. /************** End of fts3_write.c ******************************************/
  143075. /************** Begin file fts3_snippet.c ************************************/
  143076. /*
  143077. ** 2009 Oct 23
  143078. **
  143079. ** The author disclaims copyright to this source code. In place of
  143080. ** a legal notice, here is a blessing:
  143081. **
  143082. ** May you do good and not evil.
  143083. ** May you find forgiveness for yourself and forgive others.
  143084. ** May you share freely, never taking more than you give.
  143085. **
  143086. ******************************************************************************
  143087. */
  143088. /* #include "fts3Int.h" */
  143089. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  143090. /* #include <string.h> */
  143091. /* #include <assert.h> */
  143092. /*
  143093. ** Characters that may appear in the second argument to matchinfo().
  143094. */
  143095. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  143096. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  143097. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  143098. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  143099. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  143100. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  143101. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  143102. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  143103. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  143104. /*
  143105. ** The default value for the second argument to matchinfo().
  143106. */
  143107. #define FTS3_MATCHINFO_DEFAULT "pcx"
  143108. /*
  143109. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  143110. ** Fts3Expr.aDoclist[]/nDoclist.
  143111. */
  143112. typedef struct LoadDoclistCtx LoadDoclistCtx;
  143113. struct LoadDoclistCtx {
  143114. Fts3Cursor *pCsr; /* FTS3 Cursor */
  143115. int nPhrase; /* Number of phrases seen so far */
  143116. int nToken; /* Number of tokens seen so far */
  143117. };
  143118. /*
  143119. ** The following types are used as part of the implementation of the
  143120. ** fts3BestSnippet() routine.
  143121. */
  143122. typedef struct SnippetIter SnippetIter;
  143123. typedef struct SnippetPhrase SnippetPhrase;
  143124. typedef struct SnippetFragment SnippetFragment;
  143125. struct SnippetIter {
  143126. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  143127. int iCol; /* Extract snippet from this column */
  143128. int nSnippet; /* Requested snippet length (in tokens) */
  143129. int nPhrase; /* Number of phrases in query */
  143130. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  143131. int iCurrent; /* First token of current snippet */
  143132. };
  143133. struct SnippetPhrase {
  143134. int nToken; /* Number of tokens in phrase */
  143135. char *pList; /* Pointer to start of phrase position list */
  143136. int iHead; /* Next value in position list */
  143137. char *pHead; /* Position list data following iHead */
  143138. int iTail; /* Next value in trailing position list */
  143139. char *pTail; /* Position list data following iTail */
  143140. };
  143141. struct SnippetFragment {
  143142. int iCol; /* Column snippet is extracted from */
  143143. int iPos; /* Index of first token in snippet */
  143144. u64 covered; /* Mask of query phrases covered */
  143145. u64 hlmask; /* Mask of snippet terms to highlight */
  143146. };
  143147. /*
  143148. ** This type is used as an fts3ExprIterate() context object while
  143149. ** accumulating the data returned by the matchinfo() function.
  143150. */
  143151. typedef struct MatchInfo MatchInfo;
  143152. struct MatchInfo {
  143153. Fts3Cursor *pCursor; /* FTS3 Cursor */
  143154. int nCol; /* Number of columns in table */
  143155. int nPhrase; /* Number of matchable phrases in query */
  143156. sqlite3_int64 nDoc; /* Number of docs in database */
  143157. char flag;
  143158. u32 *aMatchinfo; /* Pre-allocated buffer */
  143159. };
  143160. /*
  143161. ** An instance of this structure is used to manage a pair of buffers, each
  143162. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  143163. ** for details.
  143164. */
  143165. struct MatchinfoBuffer {
  143166. u8 aRef[3];
  143167. int nElem;
  143168. int bGlobal; /* Set if global data is loaded */
  143169. char *zMatchinfo;
  143170. u32 aMatchinfo[1];
  143171. };
  143172. /*
  143173. ** The snippet() and offsets() functions both return text values. An instance
  143174. ** of the following structure is used to accumulate those values while the
  143175. ** functions are running. See fts3StringAppend() for details.
  143176. */
  143177. typedef struct StrBuffer StrBuffer;
  143178. struct StrBuffer {
  143179. char *z; /* Pointer to buffer containing string */
  143180. int n; /* Length of z in bytes (excl. nul-term) */
  143181. int nAlloc; /* Allocated size of buffer z in bytes */
  143182. };
  143183. /*************************************************************************
  143184. ** Start of MatchinfoBuffer code.
  143185. */
  143186. /*
  143187. ** Allocate a two-slot MatchinfoBuffer object.
  143188. */
  143189. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  143190. MatchinfoBuffer *pRet;
  143191. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  143192. int nStr = (int)strlen(zMatchinfo);
  143193. pRet = sqlite3_malloc(nByte + nStr+1);
  143194. if( pRet ){
  143195. memset(pRet, 0, nByte);
  143196. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  143197. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  143198. pRet->nElem = nElem;
  143199. pRet->zMatchinfo = ((char*)pRet) + nByte;
  143200. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  143201. pRet->aRef[0] = 1;
  143202. }
  143203. return pRet;
  143204. }
  143205. static void fts3MIBufferFree(void *p){
  143206. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  143207. assert( (u32*)p==&pBuf->aMatchinfo[1]
  143208. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  143209. );
  143210. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  143211. pBuf->aRef[1] = 0;
  143212. }else{
  143213. pBuf->aRef[2] = 0;
  143214. }
  143215. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  143216. sqlite3_free(pBuf);
  143217. }
  143218. }
  143219. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  143220. void (*xRet)(void*) = 0;
  143221. u32 *aOut = 0;
  143222. if( p->aRef[1]==0 ){
  143223. p->aRef[1] = 1;
  143224. aOut = &p->aMatchinfo[1];
  143225. xRet = fts3MIBufferFree;
  143226. }
  143227. else if( p->aRef[2]==0 ){
  143228. p->aRef[2] = 1;
  143229. aOut = &p->aMatchinfo[p->nElem+2];
  143230. xRet = fts3MIBufferFree;
  143231. }else{
  143232. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  143233. if( aOut ){
  143234. xRet = sqlite3_free;
  143235. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  143236. }
  143237. }
  143238. *paOut = aOut;
  143239. return xRet;
  143240. }
  143241. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  143242. p->bGlobal = 1;
  143243. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  143244. }
  143245. /*
  143246. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  143247. */
  143248. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  143249. if( p ){
  143250. assert( p->aRef[0]==1 );
  143251. p->aRef[0] = 0;
  143252. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  143253. sqlite3_free(p);
  143254. }
  143255. }
  143256. }
  143257. /*
  143258. ** End of MatchinfoBuffer code.
  143259. *************************************************************************/
  143260. /*
  143261. ** This function is used to help iterate through a position-list. A position
  143262. ** list is a list of unique integers, sorted from smallest to largest. Each
  143263. ** element of the list is represented by an FTS3 varint that takes the value
  143264. ** of the difference between the current element and the previous one plus
  143265. ** two. For example, to store the position-list:
  143266. **
  143267. ** 4 9 113
  143268. **
  143269. ** the three varints:
  143270. **
  143271. ** 6 7 106
  143272. **
  143273. ** are encoded.
  143274. **
  143275. ** When this function is called, *pp points to the start of an element of
  143276. ** the list. *piPos contains the value of the previous entry in the list.
  143277. ** After it returns, *piPos contains the value of the next element of the
  143278. ** list and *pp is advanced to the following varint.
  143279. */
  143280. static void fts3GetDeltaPosition(char **pp, int *piPos){
  143281. int iVal;
  143282. *pp += fts3GetVarint32(*pp, &iVal);
  143283. *piPos += (iVal-2);
  143284. }
  143285. /*
  143286. ** Helper function for fts3ExprIterate() (see below).
  143287. */
  143288. static int fts3ExprIterate2(
  143289. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  143290. int *piPhrase, /* Pointer to phrase counter */
  143291. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  143292. void *pCtx /* Second argument to pass to callback */
  143293. ){
  143294. int rc; /* Return code */
  143295. int eType = pExpr->eType; /* Type of expression node pExpr */
  143296. if( eType!=FTSQUERY_PHRASE ){
  143297. assert( pExpr->pLeft && pExpr->pRight );
  143298. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  143299. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  143300. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  143301. }
  143302. }else{
  143303. rc = x(pExpr, *piPhrase, pCtx);
  143304. (*piPhrase)++;
  143305. }
  143306. return rc;
  143307. }
  143308. /*
  143309. ** Iterate through all phrase nodes in an FTS3 query, except those that
  143310. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  143311. ** For each phrase node found, the supplied callback function is invoked.
  143312. **
  143313. ** If the callback function returns anything other than SQLITE_OK,
  143314. ** the iteration is abandoned and the error code returned immediately.
  143315. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  143316. ** all eligible phrase nodes.
  143317. */
  143318. static int fts3ExprIterate(
  143319. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  143320. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  143321. void *pCtx /* Second argument to pass to callback */
  143322. ){
  143323. int iPhrase = 0; /* Variable used as the phrase counter */
  143324. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  143325. }
  143326. /*
  143327. ** This is an fts3ExprIterate() callback used while loading the doclists
  143328. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  143329. ** fts3ExprLoadDoclists().
  143330. */
  143331. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  143332. int rc = SQLITE_OK;
  143333. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143334. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  143335. UNUSED_PARAMETER(iPhrase);
  143336. p->nPhrase++;
  143337. p->nToken += pPhrase->nToken;
  143338. return rc;
  143339. }
  143340. /*
  143341. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  143342. ** pCsr.
  143343. **
  143344. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  143345. ** phrases in the expression (all phrases except those directly or
  143346. ** indirectly descended from the right-hand-side of a NOT operator). If
  143347. ** pnToken is not NULL, then it is set to the number of tokens in all
  143348. ** matchable phrases of the expression.
  143349. */
  143350. static int fts3ExprLoadDoclists(
  143351. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  143352. int *pnPhrase, /* OUT: Number of phrases in query */
  143353. int *pnToken /* OUT: Number of tokens in query */
  143354. ){
  143355. int rc; /* Return Code */
  143356. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  143357. sCtx.pCsr = pCsr;
  143358. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  143359. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  143360. if( pnToken ) *pnToken = sCtx.nToken;
  143361. return rc;
  143362. }
  143363. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  143364. (*(int *)ctx)++;
  143365. pExpr->iPhrase = iPhrase;
  143366. return SQLITE_OK;
  143367. }
  143368. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  143369. int nPhrase = 0;
  143370. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  143371. return nPhrase;
  143372. }
  143373. /*
  143374. ** Advance the position list iterator specified by the first two
  143375. ** arguments so that it points to the first element with a value greater
  143376. ** than or equal to parameter iNext.
  143377. */
  143378. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  143379. char *pIter = *ppIter;
  143380. if( pIter ){
  143381. int iIter = *piIter;
  143382. while( iIter<iNext ){
  143383. if( 0==(*pIter & 0xFE) ){
  143384. iIter = -1;
  143385. pIter = 0;
  143386. break;
  143387. }
  143388. fts3GetDeltaPosition(&pIter, &iIter);
  143389. }
  143390. *piIter = iIter;
  143391. *ppIter = pIter;
  143392. }
  143393. }
  143394. /*
  143395. ** Advance the snippet iterator to the next candidate snippet.
  143396. */
  143397. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  143398. int i; /* Loop counter */
  143399. if( pIter->iCurrent<0 ){
  143400. /* The SnippetIter object has just been initialized. The first snippet
  143401. ** candidate always starts at offset 0 (even if this candidate has a
  143402. ** score of 0.0).
  143403. */
  143404. pIter->iCurrent = 0;
  143405. /* Advance the 'head' iterator of each phrase to the first offset that
  143406. ** is greater than or equal to (iNext+nSnippet).
  143407. */
  143408. for(i=0; i<pIter->nPhrase; i++){
  143409. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  143410. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  143411. }
  143412. }else{
  143413. int iStart;
  143414. int iEnd = 0x7FFFFFFF;
  143415. for(i=0; i<pIter->nPhrase; i++){
  143416. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  143417. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  143418. iEnd = pPhrase->iHead;
  143419. }
  143420. }
  143421. if( iEnd==0x7FFFFFFF ){
  143422. return 1;
  143423. }
  143424. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  143425. for(i=0; i<pIter->nPhrase; i++){
  143426. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  143427. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  143428. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  143429. }
  143430. }
  143431. return 0;
  143432. }
  143433. /*
  143434. ** Retrieve information about the current candidate snippet of snippet
  143435. ** iterator pIter.
  143436. */
  143437. static void fts3SnippetDetails(
  143438. SnippetIter *pIter, /* Snippet iterator */
  143439. u64 mCovered, /* Bitmask of phrases already covered */
  143440. int *piToken, /* OUT: First token of proposed snippet */
  143441. int *piScore, /* OUT: "Score" for this snippet */
  143442. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  143443. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  143444. ){
  143445. int iStart = pIter->iCurrent; /* First token of snippet */
  143446. int iScore = 0; /* Score of this snippet */
  143447. int i; /* Loop counter */
  143448. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  143449. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  143450. for(i=0; i<pIter->nPhrase; i++){
  143451. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  143452. if( pPhrase->pTail ){
  143453. char *pCsr = pPhrase->pTail;
  143454. int iCsr = pPhrase->iTail;
  143455. while( iCsr<(iStart+pIter->nSnippet) ){
  143456. int j;
  143457. u64 mPhrase = (u64)1 << i;
  143458. u64 mPos = (u64)1 << (iCsr - iStart);
  143459. assert( iCsr>=iStart );
  143460. if( (mCover|mCovered)&mPhrase ){
  143461. iScore++;
  143462. }else{
  143463. iScore += 1000;
  143464. }
  143465. mCover |= mPhrase;
  143466. for(j=0; j<pPhrase->nToken; j++){
  143467. mHighlight |= (mPos>>j);
  143468. }
  143469. if( 0==(*pCsr & 0x0FE) ) break;
  143470. fts3GetDeltaPosition(&pCsr, &iCsr);
  143471. }
  143472. }
  143473. }
  143474. /* Set the output variables before returning. */
  143475. *piToken = iStart;
  143476. *piScore = iScore;
  143477. *pmCover = mCover;
  143478. *pmHighlight = mHighlight;
  143479. }
  143480. /*
  143481. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  143482. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  143483. */
  143484. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  143485. SnippetIter *p = (SnippetIter *)ctx;
  143486. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  143487. char *pCsr;
  143488. int rc;
  143489. pPhrase->nToken = pExpr->pPhrase->nToken;
  143490. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  143491. assert( rc==SQLITE_OK || pCsr==0 );
  143492. if( pCsr ){
  143493. int iFirst = 0;
  143494. pPhrase->pList = pCsr;
  143495. fts3GetDeltaPosition(&pCsr, &iFirst);
  143496. assert( iFirst>=0 );
  143497. pPhrase->pHead = pCsr;
  143498. pPhrase->pTail = pCsr;
  143499. pPhrase->iHead = iFirst;
  143500. pPhrase->iTail = iFirst;
  143501. }else{
  143502. assert( rc!=SQLITE_OK || (
  143503. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  143504. ));
  143505. }
  143506. return rc;
  143507. }
  143508. /*
  143509. ** Select the fragment of text consisting of nFragment contiguous tokens
  143510. ** from column iCol that represent the "best" snippet. The best snippet
  143511. ** is the snippet with the highest score, where scores are calculated
  143512. ** by adding:
  143513. **
  143514. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  143515. **
  143516. ** (b) +1000 points for the first occurrence of each matchable phrase in
  143517. ** the snippet for which the corresponding mCovered bit is not set.
  143518. **
  143519. ** The selected snippet parameters are stored in structure *pFragment before
  143520. ** returning. The score of the selected snippet is stored in *piScore
  143521. ** before returning.
  143522. */
  143523. static int fts3BestSnippet(
  143524. int nSnippet, /* Desired snippet length */
  143525. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  143526. int iCol, /* Index of column to create snippet from */
  143527. u64 mCovered, /* Mask of phrases already covered */
  143528. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  143529. SnippetFragment *pFragment, /* OUT: Best snippet found */
  143530. int *piScore /* OUT: Score of snippet pFragment */
  143531. ){
  143532. int rc; /* Return Code */
  143533. int nList; /* Number of phrases in expression */
  143534. SnippetIter sIter; /* Iterates through snippet candidates */
  143535. int nByte; /* Number of bytes of space to allocate */
  143536. int iBestScore = -1; /* Best snippet score found so far */
  143537. int i; /* Loop counter */
  143538. memset(&sIter, 0, sizeof(sIter));
  143539. /* Iterate through the phrases in the expression to count them. The same
  143540. ** callback makes sure the doclists are loaded for each phrase.
  143541. */
  143542. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  143543. if( rc!=SQLITE_OK ){
  143544. return rc;
  143545. }
  143546. /* Now that it is known how many phrases there are, allocate and zero
  143547. ** the required space using malloc().
  143548. */
  143549. nByte = sizeof(SnippetPhrase) * nList;
  143550. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  143551. if( !sIter.aPhrase ){
  143552. return SQLITE_NOMEM;
  143553. }
  143554. memset(sIter.aPhrase, 0, nByte);
  143555. /* Initialize the contents of the SnippetIter object. Then iterate through
  143556. ** the set of phrases in the expression to populate the aPhrase[] array.
  143557. */
  143558. sIter.pCsr = pCsr;
  143559. sIter.iCol = iCol;
  143560. sIter.nSnippet = nSnippet;
  143561. sIter.nPhrase = nList;
  143562. sIter.iCurrent = -1;
  143563. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  143564. if( rc==SQLITE_OK ){
  143565. /* Set the *pmSeen output variable. */
  143566. for(i=0; i<nList; i++){
  143567. if( sIter.aPhrase[i].pHead ){
  143568. *pmSeen |= (u64)1 << i;
  143569. }
  143570. }
  143571. /* Loop through all candidate snippets. Store the best snippet in
  143572. ** *pFragment. Store its associated 'score' in iBestScore.
  143573. */
  143574. pFragment->iCol = iCol;
  143575. while( !fts3SnippetNextCandidate(&sIter) ){
  143576. int iPos;
  143577. int iScore;
  143578. u64 mCover;
  143579. u64 mHighlite;
  143580. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  143581. assert( iScore>=0 );
  143582. if( iScore>iBestScore ){
  143583. pFragment->iPos = iPos;
  143584. pFragment->hlmask = mHighlite;
  143585. pFragment->covered = mCover;
  143586. iBestScore = iScore;
  143587. }
  143588. }
  143589. *piScore = iBestScore;
  143590. }
  143591. sqlite3_free(sIter.aPhrase);
  143592. return rc;
  143593. }
  143594. /*
  143595. ** Append a string to the string-buffer passed as the first argument.
  143596. **
  143597. ** If nAppend is negative, then the length of the string zAppend is
  143598. ** determined using strlen().
  143599. */
  143600. static int fts3StringAppend(
  143601. StrBuffer *pStr, /* Buffer to append to */
  143602. const char *zAppend, /* Pointer to data to append to buffer */
  143603. int nAppend /* Size of zAppend in bytes (or -1) */
  143604. ){
  143605. if( nAppend<0 ){
  143606. nAppend = (int)strlen(zAppend);
  143607. }
  143608. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  143609. ** to grow the buffer until so that it is big enough to accomadate the
  143610. ** appended data.
  143611. */
  143612. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  143613. int nAlloc = pStr->nAlloc+nAppend+100;
  143614. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  143615. if( !zNew ){
  143616. return SQLITE_NOMEM;
  143617. }
  143618. pStr->z = zNew;
  143619. pStr->nAlloc = nAlloc;
  143620. }
  143621. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  143622. /* Append the data to the string buffer. */
  143623. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  143624. pStr->n += nAppend;
  143625. pStr->z[pStr->n] = '\0';
  143626. return SQLITE_OK;
  143627. }
  143628. /*
  143629. ** The fts3BestSnippet() function often selects snippets that end with a
  143630. ** query term. That is, the final term of the snippet is always a term
  143631. ** that requires highlighting. For example, if 'X' is a highlighted term
  143632. ** and '.' is a non-highlighted term, BestSnippet() may select:
  143633. **
  143634. ** ........X.....X
  143635. **
  143636. ** This function "shifts" the beginning of the snippet forward in the
  143637. ** document so that there are approximately the same number of
  143638. ** non-highlighted terms to the right of the final highlighted term as there
  143639. ** are to the left of the first highlighted term. For example, to this:
  143640. **
  143641. ** ....X.....X....
  143642. **
  143643. ** This is done as part of extracting the snippet text, not when selecting
  143644. ** the snippet. Snippet selection is done based on doclists only, so there
  143645. ** is no way for fts3BestSnippet() to know whether or not the document
  143646. ** actually contains terms that follow the final highlighted term.
  143647. */
  143648. static int fts3SnippetShift(
  143649. Fts3Table *pTab, /* FTS3 table snippet comes from */
  143650. int iLangid, /* Language id to use in tokenizing */
  143651. int nSnippet, /* Number of tokens desired for snippet */
  143652. const char *zDoc, /* Document text to extract snippet from */
  143653. int nDoc, /* Size of buffer zDoc in bytes */
  143654. int *piPos, /* IN/OUT: First token of snippet */
  143655. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  143656. ){
  143657. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  143658. if( hlmask ){
  143659. int nLeft; /* Tokens to the left of first highlight */
  143660. int nRight; /* Tokens to the right of last highlight */
  143661. int nDesired; /* Ideal number of tokens to shift forward */
  143662. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  143663. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  143664. nDesired = (nLeft-nRight)/2;
  143665. /* Ideally, the start of the snippet should be pushed forward in the
  143666. ** document nDesired tokens. This block checks if there are actually
  143667. ** nDesired tokens to the right of the snippet. If so, *piPos and
  143668. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  143669. ** right. Otherwise, the snippet is shifted by the number of tokens
  143670. ** available.
  143671. */
  143672. if( nDesired>0 ){
  143673. int nShift; /* Number of tokens to shift snippet by */
  143674. int iCurrent = 0; /* Token counter */
  143675. int rc; /* Return Code */
  143676. sqlite3_tokenizer_module *pMod;
  143677. sqlite3_tokenizer_cursor *pC;
  143678. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  143679. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  143680. ** or more tokens in zDoc/nDoc.
  143681. */
  143682. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  143683. if( rc!=SQLITE_OK ){
  143684. return rc;
  143685. }
  143686. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  143687. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  143688. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  143689. }
  143690. pMod->xClose(pC);
  143691. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  143692. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  143693. assert( nShift<=nDesired );
  143694. if( nShift>0 ){
  143695. *piPos += nShift;
  143696. *pHlmask = hlmask >> nShift;
  143697. }
  143698. }
  143699. }
  143700. return SQLITE_OK;
  143701. }
  143702. /*
  143703. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  143704. ** append it to string buffer pOut.
  143705. */
  143706. static int fts3SnippetText(
  143707. Fts3Cursor *pCsr, /* FTS3 Cursor */
  143708. SnippetFragment *pFragment, /* Snippet to extract */
  143709. int iFragment, /* Fragment number */
  143710. int isLast, /* True for final fragment in snippet */
  143711. int nSnippet, /* Number of tokens in extracted snippet */
  143712. const char *zOpen, /* String inserted before highlighted term */
  143713. const char *zClose, /* String inserted after highlighted term */
  143714. const char *zEllipsis, /* String inserted between snippets */
  143715. StrBuffer *pOut /* Write output here */
  143716. ){
  143717. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  143718. int rc; /* Return code */
  143719. const char *zDoc; /* Document text to extract snippet from */
  143720. int nDoc; /* Size of zDoc in bytes */
  143721. int iCurrent = 0; /* Current token number of document */
  143722. int iEnd = 0; /* Byte offset of end of current token */
  143723. int isShiftDone = 0; /* True after snippet is shifted */
  143724. int iPos = pFragment->iPos; /* First token of snippet */
  143725. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  143726. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  143727. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  143728. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  143729. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  143730. if( zDoc==0 ){
  143731. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  143732. return SQLITE_NOMEM;
  143733. }
  143734. return SQLITE_OK;
  143735. }
  143736. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  143737. /* Open a token cursor on the document. */
  143738. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  143739. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  143740. if( rc!=SQLITE_OK ){
  143741. return rc;
  143742. }
  143743. while( rc==SQLITE_OK ){
  143744. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  143745. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  143746. int iBegin = 0; /* Offset in zDoc of start of token */
  143747. int iFin = 0; /* Offset in zDoc of end of token */
  143748. int isHighlight = 0; /* True for highlighted terms */
  143749. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  143750. ** in the FTS code the variable that the third argument to xNext points to
  143751. ** is initialized to zero before the first (*but not necessarily
  143752. ** subsequent*) call to xNext(). This is done for a particular application
  143753. ** that needs to know whether or not the tokenizer is being used for
  143754. ** snippet generation or for some other purpose.
  143755. **
  143756. ** Extreme care is required when writing code to depend on this
  143757. ** initialization. It is not a documented part of the tokenizer interface.
  143758. ** If a tokenizer is used directly by any code outside of FTS, this
  143759. ** convention might not be respected. */
  143760. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  143761. if( rc!=SQLITE_OK ){
  143762. if( rc==SQLITE_DONE ){
  143763. /* Special case - the last token of the snippet is also the last token
  143764. ** of the column. Append any punctuation that occurred between the end
  143765. ** of the previous token and the end of the document to the output.
  143766. ** Then break out of the loop. */
  143767. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  143768. }
  143769. break;
  143770. }
  143771. if( iCurrent<iPos ){ continue; }
  143772. if( !isShiftDone ){
  143773. int n = nDoc - iBegin;
  143774. rc = fts3SnippetShift(
  143775. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  143776. );
  143777. isShiftDone = 1;
  143778. /* Now that the shift has been done, check if the initial "..." are
  143779. ** required. They are required if (a) this is not the first fragment,
  143780. ** or (b) this fragment does not begin at position 0 of its column.
  143781. */
  143782. if( rc==SQLITE_OK ){
  143783. if( iPos>0 || iFragment>0 ){
  143784. rc = fts3StringAppend(pOut, zEllipsis, -1);
  143785. }else if( iBegin ){
  143786. rc = fts3StringAppend(pOut, zDoc, iBegin);
  143787. }
  143788. }
  143789. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  143790. }
  143791. if( iCurrent>=(iPos+nSnippet) ){
  143792. if( isLast ){
  143793. rc = fts3StringAppend(pOut, zEllipsis, -1);
  143794. }
  143795. break;
  143796. }
  143797. /* Set isHighlight to true if this term should be highlighted. */
  143798. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  143799. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  143800. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  143801. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  143802. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  143803. iEnd = iFin;
  143804. }
  143805. pMod->xClose(pC);
  143806. return rc;
  143807. }
  143808. /*
  143809. ** This function is used to count the entries in a column-list (a
  143810. ** delta-encoded list of term offsets within a single column of a single
  143811. ** row). When this function is called, *ppCollist should point to the
  143812. ** beginning of the first varint in the column-list (the varint that
  143813. ** contains the position of the first matching term in the column data).
  143814. ** Before returning, *ppCollist is set to point to the first byte after
  143815. ** the last varint in the column-list (either the 0x00 signifying the end
  143816. ** of the position-list, or the 0x01 that precedes the column number of
  143817. ** the next column in the position-list).
  143818. **
  143819. ** The number of elements in the column-list is returned.
  143820. */
  143821. static int fts3ColumnlistCount(char **ppCollist){
  143822. char *pEnd = *ppCollist;
  143823. char c = 0;
  143824. int nEntry = 0;
  143825. /* A column-list is terminated by either a 0x01 or 0x00. */
  143826. while( 0xFE & (*pEnd | c) ){
  143827. c = *pEnd++ & 0x80;
  143828. if( !c ) nEntry++;
  143829. }
  143830. *ppCollist = pEnd;
  143831. return nEntry;
  143832. }
  143833. /*
  143834. ** This function gathers 'y' or 'b' data for a single phrase.
  143835. */
  143836. static void fts3ExprLHits(
  143837. Fts3Expr *pExpr, /* Phrase expression node */
  143838. MatchInfo *p /* Matchinfo context */
  143839. ){
  143840. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  143841. int iStart;
  143842. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143843. char *pIter = pPhrase->doclist.pList;
  143844. int iCol = 0;
  143845. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  143846. if( p->flag==FTS3_MATCHINFO_LHITS ){
  143847. iStart = pExpr->iPhrase * p->nCol;
  143848. }else{
  143849. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  143850. }
  143851. while( 1 ){
  143852. int nHit = fts3ColumnlistCount(&pIter);
  143853. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  143854. if( p->flag==FTS3_MATCHINFO_LHITS ){
  143855. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  143856. }else if( nHit ){
  143857. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  143858. }
  143859. }
  143860. assert( *pIter==0x00 || *pIter==0x01 );
  143861. if( *pIter!=0x01 ) break;
  143862. pIter++;
  143863. pIter += fts3GetVarint32(pIter, &iCol);
  143864. }
  143865. }
  143866. /*
  143867. ** Gather the results for matchinfo directives 'y' and 'b'.
  143868. */
  143869. static void fts3ExprLHitGather(
  143870. Fts3Expr *pExpr,
  143871. MatchInfo *p
  143872. ){
  143873. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  143874. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  143875. if( pExpr->pLeft ){
  143876. fts3ExprLHitGather(pExpr->pLeft, p);
  143877. fts3ExprLHitGather(pExpr->pRight, p);
  143878. }else{
  143879. fts3ExprLHits(pExpr, p);
  143880. }
  143881. }
  143882. }
  143883. /*
  143884. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  143885. ** for a single query.
  143886. **
  143887. ** fts3ExprIterate() callback to load the 'global' elements of a
  143888. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  143889. ** of the matchinfo array that are constant for all rows returned by the
  143890. ** current query.
  143891. **
  143892. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  143893. ** function populates Matchinfo.aMatchinfo[] as follows:
  143894. **
  143895. ** for(iCol=0; iCol<nCol; iCol++){
  143896. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  143897. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  143898. ** }
  143899. **
  143900. ** where X is the number of matches for phrase iPhrase is column iCol of all
  143901. ** rows of the table. Y is the number of rows for which column iCol contains
  143902. ** at least one instance of phrase iPhrase.
  143903. **
  143904. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  143905. ** Y values are set to nDoc, where nDoc is the number of documents in the
  143906. ** file system. This is done because the full-text index doclist is required
  143907. ** to calculate these values properly, and the full-text index doclist is
  143908. ** not available for deferred tokens.
  143909. */
  143910. static int fts3ExprGlobalHitsCb(
  143911. Fts3Expr *pExpr, /* Phrase expression node */
  143912. int iPhrase, /* Phrase number (numbered from zero) */
  143913. void *pCtx /* Pointer to MatchInfo structure */
  143914. ){
  143915. MatchInfo *p = (MatchInfo *)pCtx;
  143916. return sqlite3Fts3EvalPhraseStats(
  143917. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  143918. );
  143919. }
  143920. /*
  143921. ** fts3ExprIterate() callback used to collect the "local" part of the
  143922. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  143923. ** array that are different for each row returned by the query.
  143924. */
  143925. static int fts3ExprLocalHitsCb(
  143926. Fts3Expr *pExpr, /* Phrase expression node */
  143927. int iPhrase, /* Phrase number */
  143928. void *pCtx /* Pointer to MatchInfo structure */
  143929. ){
  143930. int rc = SQLITE_OK;
  143931. MatchInfo *p = (MatchInfo *)pCtx;
  143932. int iStart = iPhrase * p->nCol * 3;
  143933. int i;
  143934. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  143935. char *pCsr;
  143936. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  143937. if( pCsr ){
  143938. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  143939. }else{
  143940. p->aMatchinfo[iStart+i*3] = 0;
  143941. }
  143942. }
  143943. return rc;
  143944. }
  143945. static int fts3MatchinfoCheck(
  143946. Fts3Table *pTab,
  143947. char cArg,
  143948. char **pzErr
  143949. ){
  143950. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  143951. || (cArg==FTS3_MATCHINFO_NCOL)
  143952. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  143953. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  143954. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  143955. || (cArg==FTS3_MATCHINFO_LCS)
  143956. || (cArg==FTS3_MATCHINFO_HITS)
  143957. || (cArg==FTS3_MATCHINFO_LHITS)
  143958. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  143959. ){
  143960. return SQLITE_OK;
  143961. }
  143962. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  143963. return SQLITE_ERROR;
  143964. }
  143965. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  143966. int nVal; /* Number of integers output by cArg */
  143967. switch( cArg ){
  143968. case FTS3_MATCHINFO_NDOC:
  143969. case FTS3_MATCHINFO_NPHRASE:
  143970. case FTS3_MATCHINFO_NCOL:
  143971. nVal = 1;
  143972. break;
  143973. case FTS3_MATCHINFO_AVGLENGTH:
  143974. case FTS3_MATCHINFO_LENGTH:
  143975. case FTS3_MATCHINFO_LCS:
  143976. nVal = pInfo->nCol;
  143977. break;
  143978. case FTS3_MATCHINFO_LHITS:
  143979. nVal = pInfo->nCol * pInfo->nPhrase;
  143980. break;
  143981. case FTS3_MATCHINFO_LHITS_BM:
  143982. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  143983. break;
  143984. default:
  143985. assert( cArg==FTS3_MATCHINFO_HITS );
  143986. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  143987. break;
  143988. }
  143989. return nVal;
  143990. }
  143991. static int fts3MatchinfoSelectDoctotal(
  143992. Fts3Table *pTab,
  143993. sqlite3_stmt **ppStmt,
  143994. sqlite3_int64 *pnDoc,
  143995. const char **paLen
  143996. ){
  143997. sqlite3_stmt *pStmt;
  143998. const char *a;
  143999. sqlite3_int64 nDoc;
  144000. if( !*ppStmt ){
  144001. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  144002. if( rc!=SQLITE_OK ) return rc;
  144003. }
  144004. pStmt = *ppStmt;
  144005. assert( sqlite3_data_count(pStmt)==1 );
  144006. a = sqlite3_column_blob(pStmt, 0);
  144007. a += sqlite3Fts3GetVarint(a, &nDoc);
  144008. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  144009. *pnDoc = (u32)nDoc;
  144010. if( paLen ) *paLen = a;
  144011. return SQLITE_OK;
  144012. }
  144013. /*
  144014. ** An instance of the following structure is used to store state while
  144015. ** iterating through a multi-column position-list corresponding to the
  144016. ** hits for a single phrase on a single row in order to calculate the
  144017. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  144018. */
  144019. typedef struct LcsIterator LcsIterator;
  144020. struct LcsIterator {
  144021. Fts3Expr *pExpr; /* Pointer to phrase expression */
  144022. int iPosOffset; /* Tokens count up to end of this phrase */
  144023. char *pRead; /* Cursor used to iterate through aDoclist */
  144024. int iPos; /* Current position */
  144025. };
  144026. /*
  144027. ** If LcsIterator.iCol is set to the following value, the iterator has
  144028. ** finished iterating through all offsets for all columns.
  144029. */
  144030. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  144031. static int fts3MatchinfoLcsCb(
  144032. Fts3Expr *pExpr, /* Phrase expression node */
  144033. int iPhrase, /* Phrase number (numbered from zero) */
  144034. void *pCtx /* Pointer to MatchInfo structure */
  144035. ){
  144036. LcsIterator *aIter = (LcsIterator *)pCtx;
  144037. aIter[iPhrase].pExpr = pExpr;
  144038. return SQLITE_OK;
  144039. }
  144040. /*
  144041. ** Advance the iterator passed as an argument to the next position. Return
  144042. ** 1 if the iterator is at EOF or if it now points to the start of the
  144043. ** position list for the next column.
  144044. */
  144045. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  144046. char *pRead = pIter->pRead;
  144047. sqlite3_int64 iRead;
  144048. int rc = 0;
  144049. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  144050. if( iRead==0 || iRead==1 ){
  144051. pRead = 0;
  144052. rc = 1;
  144053. }else{
  144054. pIter->iPos += (int)(iRead-2);
  144055. }
  144056. pIter->pRead = pRead;
  144057. return rc;
  144058. }
  144059. /*
  144060. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  144061. **
  144062. ** If the call is successful, the longest-common-substring lengths for each
  144063. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  144064. ** array before returning. SQLITE_OK is returned in this case.
  144065. **
  144066. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  144067. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  144068. ** undefined.
  144069. */
  144070. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  144071. LcsIterator *aIter;
  144072. int i;
  144073. int iCol;
  144074. int nToken = 0;
  144075. /* Allocate and populate the array of LcsIterator objects. The array
  144076. ** contains one element for each matchable phrase in the query.
  144077. **/
  144078. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  144079. if( !aIter ) return SQLITE_NOMEM;
  144080. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  144081. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  144082. for(i=0; i<pInfo->nPhrase; i++){
  144083. LcsIterator *pIter = &aIter[i];
  144084. nToken -= pIter->pExpr->pPhrase->nToken;
  144085. pIter->iPosOffset = nToken;
  144086. }
  144087. for(iCol=0; iCol<pInfo->nCol; iCol++){
  144088. int nLcs = 0; /* LCS value for this column */
  144089. int nLive = 0; /* Number of iterators in aIter not at EOF */
  144090. for(i=0; i<pInfo->nPhrase; i++){
  144091. int rc;
  144092. LcsIterator *pIt = &aIter[i];
  144093. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  144094. if( rc!=SQLITE_OK ) return rc;
  144095. if( pIt->pRead ){
  144096. pIt->iPos = pIt->iPosOffset;
  144097. fts3LcsIteratorAdvance(&aIter[i]);
  144098. nLive++;
  144099. }
  144100. }
  144101. while( nLive>0 ){
  144102. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  144103. int nThisLcs = 0; /* LCS for the current iterator positions */
  144104. for(i=0; i<pInfo->nPhrase; i++){
  144105. LcsIterator *pIter = &aIter[i];
  144106. if( pIter->pRead==0 ){
  144107. /* This iterator is already at EOF for this column. */
  144108. nThisLcs = 0;
  144109. }else{
  144110. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  144111. pAdv = pIter;
  144112. }
  144113. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  144114. nThisLcs++;
  144115. }else{
  144116. nThisLcs = 1;
  144117. }
  144118. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  144119. }
  144120. }
  144121. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  144122. }
  144123. pInfo->aMatchinfo[iCol] = nLcs;
  144124. }
  144125. sqlite3_free(aIter);
  144126. return SQLITE_OK;
  144127. }
  144128. /*
  144129. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  144130. ** be returned by the matchinfo() function. Argument zArg contains the
  144131. ** format string passed as the second argument to matchinfo (or the
  144132. ** default value "pcx" if no second argument was specified). The format
  144133. ** string has already been validated and the pInfo->aMatchinfo[] array
  144134. ** is guaranteed to be large enough for the output.
  144135. **
  144136. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  144137. ** If it is false, then assume that those fields that do not change between
  144138. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  144139. ** have already been populated.
  144140. **
  144141. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  144142. ** occurs. If a value other than SQLITE_OK is returned, the state the
  144143. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  144144. */
  144145. static int fts3MatchinfoValues(
  144146. Fts3Cursor *pCsr, /* FTS3 cursor object */
  144147. int bGlobal, /* True to grab the global stats */
  144148. MatchInfo *pInfo, /* Matchinfo context object */
  144149. const char *zArg /* Matchinfo format string */
  144150. ){
  144151. int rc = SQLITE_OK;
  144152. int i;
  144153. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  144154. sqlite3_stmt *pSelect = 0;
  144155. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  144156. pInfo->flag = zArg[i];
  144157. switch( zArg[i] ){
  144158. case FTS3_MATCHINFO_NPHRASE:
  144159. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  144160. break;
  144161. case FTS3_MATCHINFO_NCOL:
  144162. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  144163. break;
  144164. case FTS3_MATCHINFO_NDOC:
  144165. if( bGlobal ){
  144166. sqlite3_int64 nDoc = 0;
  144167. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  144168. pInfo->aMatchinfo[0] = (u32)nDoc;
  144169. }
  144170. break;
  144171. case FTS3_MATCHINFO_AVGLENGTH:
  144172. if( bGlobal ){
  144173. sqlite3_int64 nDoc; /* Number of rows in table */
  144174. const char *a; /* Aggregate column length array */
  144175. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  144176. if( rc==SQLITE_OK ){
  144177. int iCol;
  144178. for(iCol=0; iCol<pInfo->nCol; iCol++){
  144179. u32 iVal;
  144180. sqlite3_int64 nToken;
  144181. a += sqlite3Fts3GetVarint(a, &nToken);
  144182. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  144183. pInfo->aMatchinfo[iCol] = iVal;
  144184. }
  144185. }
  144186. }
  144187. break;
  144188. case FTS3_MATCHINFO_LENGTH: {
  144189. sqlite3_stmt *pSelectDocsize = 0;
  144190. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  144191. if( rc==SQLITE_OK ){
  144192. int iCol;
  144193. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  144194. for(iCol=0; iCol<pInfo->nCol; iCol++){
  144195. sqlite3_int64 nToken;
  144196. a += sqlite3Fts3GetVarint(a, &nToken);
  144197. pInfo->aMatchinfo[iCol] = (u32)nToken;
  144198. }
  144199. }
  144200. sqlite3_reset(pSelectDocsize);
  144201. break;
  144202. }
  144203. case FTS3_MATCHINFO_LCS:
  144204. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  144205. if( rc==SQLITE_OK ){
  144206. rc = fts3MatchinfoLcs(pCsr, pInfo);
  144207. }
  144208. break;
  144209. case FTS3_MATCHINFO_LHITS_BM:
  144210. case FTS3_MATCHINFO_LHITS: {
  144211. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  144212. memset(pInfo->aMatchinfo, 0, nZero);
  144213. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  144214. break;
  144215. }
  144216. default: {
  144217. Fts3Expr *pExpr;
  144218. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  144219. pExpr = pCsr->pExpr;
  144220. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  144221. if( rc!=SQLITE_OK ) break;
  144222. if( bGlobal ){
  144223. if( pCsr->pDeferred ){
  144224. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  144225. if( rc!=SQLITE_OK ) break;
  144226. }
  144227. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  144228. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  144229. if( rc!=SQLITE_OK ) break;
  144230. }
  144231. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  144232. break;
  144233. }
  144234. }
  144235. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  144236. }
  144237. sqlite3_reset(pSelect);
  144238. return rc;
  144239. }
  144240. /*
  144241. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  144242. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  144243. */
  144244. static void fts3GetMatchinfo(
  144245. sqlite3_context *pCtx, /* Return results here */
  144246. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  144247. const char *zArg /* Second argument to matchinfo() function */
  144248. ){
  144249. MatchInfo sInfo;
  144250. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  144251. int rc = SQLITE_OK;
  144252. int bGlobal = 0; /* Collect 'global' stats as well as local */
  144253. u32 *aOut = 0;
  144254. void (*xDestroyOut)(void*) = 0;
  144255. memset(&sInfo, 0, sizeof(MatchInfo));
  144256. sInfo.pCursor = pCsr;
  144257. sInfo.nCol = pTab->nColumn;
  144258. /* If there is cached matchinfo() data, but the format string for the
  144259. ** cache does not match the format string for this request, discard
  144260. ** the cached data. */
  144261. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  144262. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  144263. pCsr->pMIBuffer = 0;
  144264. }
  144265. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  144266. ** matchinfo function has been called for this query. In this case
  144267. ** allocate the array used to accumulate the matchinfo data and
  144268. ** initialize those elements that are constant for every row.
  144269. */
  144270. if( pCsr->pMIBuffer==0 ){
  144271. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  144272. int i; /* Used to iterate through zArg */
  144273. /* Determine the number of phrases in the query */
  144274. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  144275. sInfo.nPhrase = pCsr->nPhrase;
  144276. /* Determine the number of integers in the buffer returned by this call. */
  144277. for(i=0; zArg[i]; i++){
  144278. char *zErr = 0;
  144279. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  144280. sqlite3_result_error(pCtx, zErr, -1);
  144281. sqlite3_free(zErr);
  144282. return;
  144283. }
  144284. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  144285. }
  144286. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  144287. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  144288. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  144289. pCsr->isMatchinfoNeeded = 1;
  144290. bGlobal = 1;
  144291. }
  144292. if( rc==SQLITE_OK ){
  144293. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  144294. if( xDestroyOut==0 ){
  144295. rc = SQLITE_NOMEM;
  144296. }
  144297. }
  144298. if( rc==SQLITE_OK ){
  144299. sInfo.aMatchinfo = aOut;
  144300. sInfo.nPhrase = pCsr->nPhrase;
  144301. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  144302. if( bGlobal ){
  144303. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  144304. }
  144305. }
  144306. if( rc!=SQLITE_OK ){
  144307. sqlite3_result_error_code(pCtx, rc);
  144308. if( xDestroyOut ) xDestroyOut(aOut);
  144309. }else{
  144310. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  144311. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  144312. }
  144313. }
  144314. /*
  144315. ** Implementation of snippet() function.
  144316. */
  144317. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  144318. sqlite3_context *pCtx, /* SQLite function call context */
  144319. Fts3Cursor *pCsr, /* Cursor object */
  144320. const char *zStart, /* Snippet start text - "<b>" */
  144321. const char *zEnd, /* Snippet end text - "</b>" */
  144322. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  144323. int iCol, /* Extract snippet from this column */
  144324. int nToken /* Approximate number of tokens in snippet */
  144325. ){
  144326. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  144327. int rc = SQLITE_OK;
  144328. int i;
  144329. StrBuffer res = {0, 0, 0};
  144330. /* The returned text includes up to four fragments of text extracted from
  144331. ** the data in the current row. The first iteration of the for(...) loop
  144332. ** below attempts to locate a single fragment of text nToken tokens in
  144333. ** size that contains at least one instance of all phrases in the query
  144334. ** expression that appear in the current row. If such a fragment of text
  144335. ** cannot be found, the second iteration of the loop attempts to locate
  144336. ** a pair of fragments, and so on.
  144337. */
  144338. int nSnippet = 0; /* Number of fragments in this snippet */
  144339. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  144340. int nFToken = -1; /* Number of tokens in each fragment */
  144341. if( !pCsr->pExpr ){
  144342. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  144343. return;
  144344. }
  144345. for(nSnippet=1; 1; nSnippet++){
  144346. int iSnip; /* Loop counter 0..nSnippet-1 */
  144347. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  144348. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  144349. if( nToken>=0 ){
  144350. nFToken = (nToken+nSnippet-1) / nSnippet;
  144351. }else{
  144352. nFToken = -1 * nToken;
  144353. }
  144354. for(iSnip=0; iSnip<nSnippet; iSnip++){
  144355. int iBestScore = -1; /* Best score of columns checked so far */
  144356. int iRead; /* Used to iterate through columns */
  144357. SnippetFragment *pFragment = &aSnippet[iSnip];
  144358. memset(pFragment, 0, sizeof(*pFragment));
  144359. /* Loop through all columns of the table being considered for snippets.
  144360. ** If the iCol argument to this function was negative, this means all
  144361. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  144362. */
  144363. for(iRead=0; iRead<pTab->nColumn; iRead++){
  144364. SnippetFragment sF = {0, 0, 0, 0};
  144365. int iS = 0;
  144366. if( iCol>=0 && iRead!=iCol ) continue;
  144367. /* Find the best snippet of nFToken tokens in column iRead. */
  144368. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  144369. if( rc!=SQLITE_OK ){
  144370. goto snippet_out;
  144371. }
  144372. if( iS>iBestScore ){
  144373. *pFragment = sF;
  144374. iBestScore = iS;
  144375. }
  144376. }
  144377. mCovered |= pFragment->covered;
  144378. }
  144379. /* If all query phrases seen by fts3BestSnippet() are present in at least
  144380. ** one of the nSnippet snippet fragments, break out of the loop.
  144381. */
  144382. assert( (mCovered&mSeen)==mCovered );
  144383. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  144384. }
  144385. assert( nFToken>0 );
  144386. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  144387. rc = fts3SnippetText(pCsr, &aSnippet[i],
  144388. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  144389. );
  144390. }
  144391. snippet_out:
  144392. sqlite3Fts3SegmentsClose(pTab);
  144393. if( rc!=SQLITE_OK ){
  144394. sqlite3_result_error_code(pCtx, rc);
  144395. sqlite3_free(res.z);
  144396. }else{
  144397. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  144398. }
  144399. }
  144400. typedef struct TermOffset TermOffset;
  144401. typedef struct TermOffsetCtx TermOffsetCtx;
  144402. struct TermOffset {
  144403. char *pList; /* Position-list */
  144404. int iPos; /* Position just read from pList */
  144405. int iOff; /* Offset of this term from read positions */
  144406. };
  144407. struct TermOffsetCtx {
  144408. Fts3Cursor *pCsr;
  144409. int iCol; /* Column of table to populate aTerm for */
  144410. int iTerm;
  144411. sqlite3_int64 iDocid;
  144412. TermOffset *aTerm;
  144413. };
  144414. /*
  144415. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  144416. */
  144417. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  144418. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  144419. int nTerm; /* Number of tokens in phrase */
  144420. int iTerm; /* For looping through nTerm phrase terms */
  144421. char *pList; /* Pointer to position list for phrase */
  144422. int iPos = 0; /* First position in position-list */
  144423. int rc;
  144424. UNUSED_PARAMETER(iPhrase);
  144425. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  144426. nTerm = pExpr->pPhrase->nToken;
  144427. if( pList ){
  144428. fts3GetDeltaPosition(&pList, &iPos);
  144429. assert( iPos>=0 );
  144430. }
  144431. for(iTerm=0; iTerm<nTerm; iTerm++){
  144432. TermOffset *pT = &p->aTerm[p->iTerm++];
  144433. pT->iOff = nTerm-iTerm-1;
  144434. pT->pList = pList;
  144435. pT->iPos = iPos;
  144436. }
  144437. return rc;
  144438. }
  144439. /*
  144440. ** Implementation of offsets() function.
  144441. */
  144442. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  144443. sqlite3_context *pCtx, /* SQLite function call context */
  144444. Fts3Cursor *pCsr /* Cursor object */
  144445. ){
  144446. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  144447. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  144448. int rc; /* Return Code */
  144449. int nToken; /* Number of tokens in query */
  144450. int iCol; /* Column currently being processed */
  144451. StrBuffer res = {0, 0, 0}; /* Result string */
  144452. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  144453. if( !pCsr->pExpr ){
  144454. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  144455. return;
  144456. }
  144457. memset(&sCtx, 0, sizeof(sCtx));
  144458. assert( pCsr->isRequireSeek==0 );
  144459. /* Count the number of terms in the query */
  144460. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  144461. if( rc!=SQLITE_OK ) goto offsets_out;
  144462. /* Allocate the array of TermOffset iterators. */
  144463. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  144464. if( 0==sCtx.aTerm ){
  144465. rc = SQLITE_NOMEM;
  144466. goto offsets_out;
  144467. }
  144468. sCtx.iDocid = pCsr->iPrevId;
  144469. sCtx.pCsr = pCsr;
  144470. /* Loop through the table columns, appending offset information to
  144471. ** string-buffer res for each column.
  144472. */
  144473. for(iCol=0; iCol<pTab->nColumn; iCol++){
  144474. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  144475. const char *ZDUMMY; /* Dummy argument used with xNext() */
  144476. int NDUMMY = 0; /* Dummy argument used with xNext() */
  144477. int iStart = 0;
  144478. int iEnd = 0;
  144479. int iCurrent = 0;
  144480. const char *zDoc;
  144481. int nDoc;
  144482. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  144483. ** no way that this operation can fail, so the return code from
  144484. ** fts3ExprIterate() can be discarded.
  144485. */
  144486. sCtx.iCol = iCol;
  144487. sCtx.iTerm = 0;
  144488. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  144489. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  144490. ** in column iCol, jump immediately to the next iteration of the loop.
  144491. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  144492. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  144493. ** to the caller.
  144494. */
  144495. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  144496. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  144497. if( zDoc==0 ){
  144498. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  144499. continue;
  144500. }
  144501. rc = SQLITE_NOMEM;
  144502. goto offsets_out;
  144503. }
  144504. /* Initialize a tokenizer iterator to iterate through column iCol. */
  144505. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  144506. zDoc, nDoc, &pC
  144507. );
  144508. if( rc!=SQLITE_OK ) goto offsets_out;
  144509. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  144510. while( rc==SQLITE_OK ){
  144511. int i; /* Used to loop through terms */
  144512. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  144513. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  144514. for(i=0; i<nToken; i++){
  144515. TermOffset *pT = &sCtx.aTerm[i];
  144516. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  144517. iMinPos = pT->iPos-pT->iOff;
  144518. pTerm = pT;
  144519. }
  144520. }
  144521. if( !pTerm ){
  144522. /* All offsets for this column have been gathered. */
  144523. rc = SQLITE_DONE;
  144524. }else{
  144525. assert( iCurrent<=iMinPos );
  144526. if( 0==(0xFE&*pTerm->pList) ){
  144527. pTerm->pList = 0;
  144528. }else{
  144529. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  144530. }
  144531. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  144532. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  144533. }
  144534. if( rc==SQLITE_OK ){
  144535. char aBuffer[64];
  144536. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  144537. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  144538. );
  144539. rc = fts3StringAppend(&res, aBuffer, -1);
  144540. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  144541. rc = FTS_CORRUPT_VTAB;
  144542. }
  144543. }
  144544. }
  144545. if( rc==SQLITE_DONE ){
  144546. rc = SQLITE_OK;
  144547. }
  144548. pMod->xClose(pC);
  144549. if( rc!=SQLITE_OK ) goto offsets_out;
  144550. }
  144551. offsets_out:
  144552. sqlite3_free(sCtx.aTerm);
  144553. assert( rc!=SQLITE_DONE );
  144554. sqlite3Fts3SegmentsClose(pTab);
  144555. if( rc!=SQLITE_OK ){
  144556. sqlite3_result_error_code(pCtx, rc);
  144557. sqlite3_free(res.z);
  144558. }else{
  144559. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  144560. }
  144561. return;
  144562. }
  144563. /*
  144564. ** Implementation of matchinfo() function.
  144565. */
  144566. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  144567. sqlite3_context *pContext, /* Function call context */
  144568. Fts3Cursor *pCsr, /* FTS3 table cursor */
  144569. const char *zArg /* Second arg to matchinfo() function */
  144570. ){
  144571. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  144572. const char *zFormat;
  144573. if( zArg ){
  144574. zFormat = zArg;
  144575. }else{
  144576. zFormat = FTS3_MATCHINFO_DEFAULT;
  144577. }
  144578. if( !pCsr->pExpr ){
  144579. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  144580. return;
  144581. }else{
  144582. /* Retrieve matchinfo() data. */
  144583. fts3GetMatchinfo(pContext, pCsr, zFormat);
  144584. sqlite3Fts3SegmentsClose(pTab);
  144585. }
  144586. }
  144587. #endif
  144588. /************** End of fts3_snippet.c ****************************************/
  144589. /************** Begin file fts3_unicode.c ************************************/
  144590. /*
  144591. ** 2012 May 24
  144592. **
  144593. ** The author disclaims copyright to this source code. In place of
  144594. ** a legal notice, here is a blessing:
  144595. **
  144596. ** May you do good and not evil.
  144597. ** May you find forgiveness for yourself and forgive others.
  144598. ** May you share freely, never taking more than you give.
  144599. **
  144600. ******************************************************************************
  144601. **
  144602. ** Implementation of the "unicode" full-text-search tokenizer.
  144603. */
  144604. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  144605. /* #include "fts3Int.h" */
  144606. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  144607. /* #include <assert.h> */
  144608. /* #include <stdlib.h> */
  144609. /* #include <stdio.h> */
  144610. /* #include <string.h> */
  144611. /* #include "fts3_tokenizer.h" */
  144612. /*
  144613. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  144614. ** from the sqlite3 source file utf.c. If this file is compiled as part
  144615. ** of the amalgamation, they are not required.
  144616. */
  144617. #ifndef SQLITE_AMALGAMATION
  144618. static const unsigned char sqlite3Utf8Trans1[] = {
  144619. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  144620. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  144621. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  144622. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  144623. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  144624. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  144625. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  144626. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  144627. };
  144628. #define READ_UTF8(zIn, zTerm, c) \
  144629. c = *(zIn++); \
  144630. if( c>=0xc0 ){ \
  144631. c = sqlite3Utf8Trans1[c-0xc0]; \
  144632. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  144633. c = (c<<6) + (0x3f & *(zIn++)); \
  144634. } \
  144635. if( c<0x80 \
  144636. || (c&0xFFFFF800)==0xD800 \
  144637. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  144638. }
  144639. #define WRITE_UTF8(zOut, c) { \
  144640. if( c<0x00080 ){ \
  144641. *zOut++ = (u8)(c&0xFF); \
  144642. } \
  144643. else if( c<0x00800 ){ \
  144644. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  144645. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  144646. } \
  144647. else if( c<0x10000 ){ \
  144648. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  144649. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  144650. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  144651. }else{ \
  144652. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  144653. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  144654. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  144655. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  144656. } \
  144657. }
  144658. #endif /* ifndef SQLITE_AMALGAMATION */
  144659. typedef struct unicode_tokenizer unicode_tokenizer;
  144660. typedef struct unicode_cursor unicode_cursor;
  144661. struct unicode_tokenizer {
  144662. sqlite3_tokenizer base;
  144663. int bRemoveDiacritic;
  144664. int nException;
  144665. int *aiException;
  144666. };
  144667. struct unicode_cursor {
  144668. sqlite3_tokenizer_cursor base;
  144669. const unsigned char *aInput; /* Input text being tokenized */
  144670. int nInput; /* Size of aInput[] in bytes */
  144671. int iOff; /* Current offset within aInput[] */
  144672. int iToken; /* Index of next token to be returned */
  144673. char *zToken; /* storage for current token */
  144674. int nAlloc; /* space allocated at zToken */
  144675. };
  144676. /*
  144677. ** Destroy a tokenizer allocated by unicodeCreate().
  144678. */
  144679. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  144680. if( pTokenizer ){
  144681. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  144682. sqlite3_free(p->aiException);
  144683. sqlite3_free(p);
  144684. }
  144685. return SQLITE_OK;
  144686. }
  144687. /*
  144688. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  144689. ** statement has specified that the tokenizer for this table shall consider
  144690. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  144691. ** token characters (if bAlnum==1).
  144692. **
  144693. ** For each codepoint in the zIn/nIn string, this function checks if the
  144694. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  144695. ** If so, no action is taken. Otherwise, the codepoint is added to the
  144696. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  144697. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  144698. ** codepoints in the aiException[] array.
  144699. **
  144700. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  144701. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  144702. ** It is not possible to change the behavior of the tokenizer with respect
  144703. ** to these codepoints.
  144704. */
  144705. static int unicodeAddExceptions(
  144706. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  144707. int bAlnum, /* Replace Isalnum() return value with this */
  144708. const char *zIn, /* Array of characters to make exceptions */
  144709. int nIn /* Length of z in bytes */
  144710. ){
  144711. const unsigned char *z = (const unsigned char *)zIn;
  144712. const unsigned char *zTerm = &z[nIn];
  144713. int iCode;
  144714. int nEntry = 0;
  144715. assert( bAlnum==0 || bAlnum==1 );
  144716. while( z<zTerm ){
  144717. READ_UTF8(z, zTerm, iCode);
  144718. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  144719. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  144720. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  144721. ){
  144722. nEntry++;
  144723. }
  144724. }
  144725. if( nEntry ){
  144726. int *aNew; /* New aiException[] array */
  144727. int nNew; /* Number of valid entries in array aNew[] */
  144728. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  144729. if( aNew==0 ) return SQLITE_NOMEM;
  144730. nNew = p->nException;
  144731. z = (const unsigned char *)zIn;
  144732. while( z<zTerm ){
  144733. READ_UTF8(z, zTerm, iCode);
  144734. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  144735. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  144736. ){
  144737. int i, j;
  144738. for(i=0; i<nNew && aNew[i]<iCode; i++);
  144739. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  144740. aNew[i] = iCode;
  144741. nNew++;
  144742. }
  144743. }
  144744. p->aiException = aNew;
  144745. p->nException = nNew;
  144746. }
  144747. return SQLITE_OK;
  144748. }
  144749. /*
  144750. ** Return true if the p->aiException[] array contains the value iCode.
  144751. */
  144752. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  144753. if( p->nException>0 ){
  144754. int *a = p->aiException;
  144755. int iLo = 0;
  144756. int iHi = p->nException-1;
  144757. while( iHi>=iLo ){
  144758. int iTest = (iHi + iLo) / 2;
  144759. if( iCode==a[iTest] ){
  144760. return 1;
  144761. }else if( iCode>a[iTest] ){
  144762. iLo = iTest+1;
  144763. }else{
  144764. iHi = iTest-1;
  144765. }
  144766. }
  144767. }
  144768. return 0;
  144769. }
  144770. /*
  144771. ** Return true if, for the purposes of tokenization, codepoint iCode is
  144772. ** considered a token character (not a separator).
  144773. */
  144774. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  144775. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  144776. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  144777. }
  144778. /*
  144779. ** Create a new tokenizer instance.
  144780. */
  144781. static int unicodeCreate(
  144782. int nArg, /* Size of array argv[] */
  144783. const char * const *azArg, /* Tokenizer creation arguments */
  144784. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  144785. ){
  144786. unicode_tokenizer *pNew; /* New tokenizer object */
  144787. int i;
  144788. int rc = SQLITE_OK;
  144789. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  144790. if( pNew==NULL ) return SQLITE_NOMEM;
  144791. memset(pNew, 0, sizeof(unicode_tokenizer));
  144792. pNew->bRemoveDiacritic = 1;
  144793. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  144794. const char *z = azArg[i];
  144795. int n = (int)strlen(z);
  144796. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  144797. pNew->bRemoveDiacritic = 1;
  144798. }
  144799. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  144800. pNew->bRemoveDiacritic = 0;
  144801. }
  144802. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  144803. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  144804. }
  144805. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  144806. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  144807. }
  144808. else{
  144809. /* Unrecognized argument */
  144810. rc = SQLITE_ERROR;
  144811. }
  144812. }
  144813. if( rc!=SQLITE_OK ){
  144814. unicodeDestroy((sqlite3_tokenizer *)pNew);
  144815. pNew = 0;
  144816. }
  144817. *pp = (sqlite3_tokenizer *)pNew;
  144818. return rc;
  144819. }
  144820. /*
  144821. ** Prepare to begin tokenizing a particular string. The input
  144822. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  144823. ** used to incrementally tokenize this string is returned in
  144824. ** *ppCursor.
  144825. */
  144826. static int unicodeOpen(
  144827. sqlite3_tokenizer *p, /* The tokenizer */
  144828. const char *aInput, /* Input string */
  144829. int nInput, /* Size of string aInput in bytes */
  144830. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  144831. ){
  144832. unicode_cursor *pCsr;
  144833. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  144834. if( pCsr==0 ){
  144835. return SQLITE_NOMEM;
  144836. }
  144837. memset(pCsr, 0, sizeof(unicode_cursor));
  144838. pCsr->aInput = (const unsigned char *)aInput;
  144839. if( aInput==0 ){
  144840. pCsr->nInput = 0;
  144841. }else if( nInput<0 ){
  144842. pCsr->nInput = (int)strlen(aInput);
  144843. }else{
  144844. pCsr->nInput = nInput;
  144845. }
  144846. *pp = &pCsr->base;
  144847. UNUSED_PARAMETER(p);
  144848. return SQLITE_OK;
  144849. }
  144850. /*
  144851. ** Close a tokenization cursor previously opened by a call to
  144852. ** simpleOpen() above.
  144853. */
  144854. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  144855. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  144856. sqlite3_free(pCsr->zToken);
  144857. sqlite3_free(pCsr);
  144858. return SQLITE_OK;
  144859. }
  144860. /*
  144861. ** Extract the next token from a tokenization cursor. The cursor must
  144862. ** have been opened by a prior call to simpleOpen().
  144863. */
  144864. static int unicodeNext(
  144865. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  144866. const char **paToken, /* OUT: Token text */
  144867. int *pnToken, /* OUT: Number of bytes at *paToken */
  144868. int *piStart, /* OUT: Starting offset of token */
  144869. int *piEnd, /* OUT: Ending offset of token */
  144870. int *piPos /* OUT: Position integer of token */
  144871. ){
  144872. unicode_cursor *pCsr = (unicode_cursor *)pC;
  144873. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  144874. int iCode = 0;
  144875. char *zOut;
  144876. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  144877. const unsigned char *zStart = z;
  144878. const unsigned char *zEnd;
  144879. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  144880. /* Scan past any delimiter characters before the start of the next token.
  144881. ** Return SQLITE_DONE early if this takes us all the way to the end of
  144882. ** the input. */
  144883. while( z<zTerm ){
  144884. READ_UTF8(z, zTerm, iCode);
  144885. if( unicodeIsAlnum(p, iCode) ) break;
  144886. zStart = z;
  144887. }
  144888. if( zStart>=zTerm ) return SQLITE_DONE;
  144889. zOut = pCsr->zToken;
  144890. do {
  144891. int iOut;
  144892. /* Grow the output buffer if required. */
  144893. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  144894. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  144895. if( !zNew ) return SQLITE_NOMEM;
  144896. zOut = &zNew[zOut - pCsr->zToken];
  144897. pCsr->zToken = zNew;
  144898. pCsr->nAlloc += 64;
  144899. }
  144900. /* Write the folded case of the last character read to the output */
  144901. zEnd = z;
  144902. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  144903. if( iOut ){
  144904. WRITE_UTF8(zOut, iOut);
  144905. }
  144906. /* If the cursor is not at EOF, read the next character */
  144907. if( z>=zTerm ) break;
  144908. READ_UTF8(z, zTerm, iCode);
  144909. }while( unicodeIsAlnum(p, iCode)
  144910. || sqlite3FtsUnicodeIsdiacritic(iCode)
  144911. );
  144912. /* Set the output variables and return. */
  144913. pCsr->iOff = (int)(z - pCsr->aInput);
  144914. *paToken = pCsr->zToken;
  144915. *pnToken = (int)(zOut - pCsr->zToken);
  144916. *piStart = (int)(zStart - pCsr->aInput);
  144917. *piEnd = (int)(zEnd - pCsr->aInput);
  144918. *piPos = pCsr->iToken++;
  144919. return SQLITE_OK;
  144920. }
  144921. /*
  144922. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  144923. ** structure for the unicode tokenizer.
  144924. */
  144925. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  144926. static const sqlite3_tokenizer_module module = {
  144927. 0,
  144928. unicodeCreate,
  144929. unicodeDestroy,
  144930. unicodeOpen,
  144931. unicodeClose,
  144932. unicodeNext,
  144933. 0,
  144934. };
  144935. *ppModule = &module;
  144936. }
  144937. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  144938. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  144939. /************** End of fts3_unicode.c ****************************************/
  144940. /************** Begin file fts3_unicode2.c ***********************************/
  144941. /*
  144942. ** 2012 May 25
  144943. **
  144944. ** The author disclaims copyright to this source code. In place of
  144945. ** a legal notice, here is a blessing:
  144946. **
  144947. ** May you do good and not evil.
  144948. ** May you find forgiveness for yourself and forgive others.
  144949. ** May you share freely, never taking more than you give.
  144950. **
  144951. ******************************************************************************
  144952. */
  144953. /*
  144954. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  144955. */
  144956. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  144957. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  144958. /* #include <assert.h> */
  144959. /*
  144960. ** Return true if the argument corresponds to a unicode codepoint
  144961. ** classified as either a letter or a number. Otherwise false.
  144962. **
  144963. ** The results are undefined if the value passed to this function
  144964. ** is less than zero.
  144965. */
  144966. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  144967. /* Each unsigned integer in the following array corresponds to a contiguous
  144968. ** range of unicode codepoints that are not either letters or numbers (i.e.
  144969. ** codepoints for which this function should return 0).
  144970. **
  144971. ** The most significant 22 bits in each 32-bit value contain the first
  144972. ** codepoint in the range. The least significant 10 bits are used to store
  144973. ** the size of the range (always at least 1). In other words, the value
  144974. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  144975. ** C. It is not possible to represent a range larger than 1023 codepoints
  144976. ** using this format.
  144977. */
  144978. static const unsigned int aEntry[] = {
  144979. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  144980. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  144981. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  144982. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  144983. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  144984. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  144985. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  144986. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  144987. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  144988. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  144989. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  144990. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  144991. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  144992. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  144993. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  144994. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  144995. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  144996. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  144997. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  144998. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  144999. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  145000. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  145001. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  145002. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  145003. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  145004. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  145005. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  145006. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  145007. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  145008. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  145009. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  145010. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  145011. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  145012. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  145013. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  145014. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  145015. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  145016. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  145017. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  145018. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  145019. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  145020. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  145021. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  145022. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  145023. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  145024. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  145025. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  145026. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  145027. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  145028. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  145029. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  145030. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  145031. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  145032. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  145033. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  145034. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  145035. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  145036. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  145037. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  145038. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  145039. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  145040. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  145041. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  145042. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  145043. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  145044. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  145045. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  145046. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  145047. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  145048. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  145049. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  145050. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  145051. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  145052. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  145053. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  145054. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  145055. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  145056. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  145057. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  145058. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  145059. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  145060. 0x380400F0,
  145061. };
  145062. static const unsigned int aAscii[4] = {
  145063. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  145064. };
  145065. if( c<128 ){
  145066. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  145067. }else if( c<(1<<22) ){
  145068. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  145069. int iRes = 0;
  145070. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  145071. int iLo = 0;
  145072. while( iHi>=iLo ){
  145073. int iTest = (iHi + iLo) / 2;
  145074. if( key >= aEntry[iTest] ){
  145075. iRes = iTest;
  145076. iLo = iTest+1;
  145077. }else{
  145078. iHi = iTest-1;
  145079. }
  145080. }
  145081. assert( aEntry[0]<key );
  145082. assert( key>=aEntry[iRes] );
  145083. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  145084. }
  145085. return 1;
  145086. }
  145087. /*
  145088. ** If the argument is a codepoint corresponding to a lowercase letter
  145089. ** in the ASCII range with a diacritic added, return the codepoint
  145090. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  145091. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  145092. ** E"). The resuls of passing a codepoint that corresponds to an
  145093. ** uppercase letter are undefined.
  145094. */
  145095. static int remove_diacritic(int c){
  145096. unsigned short aDia[] = {
  145097. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  145098. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  145099. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  145100. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  145101. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  145102. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  145103. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  145104. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  145105. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  145106. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  145107. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  145108. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  145109. 62924, 63050, 63082, 63274, 63390,
  145110. };
  145111. char aChar[] = {
  145112. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  145113. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  145114. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  145115. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  145116. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  145117. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  145118. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  145119. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  145120. 'e', 'i', 'o', 'u', 'y',
  145121. };
  145122. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  145123. int iRes = 0;
  145124. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  145125. int iLo = 0;
  145126. while( iHi>=iLo ){
  145127. int iTest = (iHi + iLo) / 2;
  145128. if( key >= aDia[iTest] ){
  145129. iRes = iTest;
  145130. iLo = iTest+1;
  145131. }else{
  145132. iHi = iTest-1;
  145133. }
  145134. }
  145135. assert( key>=aDia[iRes] );
  145136. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  145137. }
  145138. /*
  145139. ** Return true if the argument interpreted as a unicode codepoint
  145140. ** is a diacritical modifier character.
  145141. */
  145142. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  145143. unsigned int mask0 = 0x08029FDF;
  145144. unsigned int mask1 = 0x000361F8;
  145145. if( c<768 || c>817 ) return 0;
  145146. return (c < 768+32) ?
  145147. (mask0 & (1 << (c-768))) :
  145148. (mask1 & (1 << (c-768-32)));
  145149. }
  145150. /*
  145151. ** Interpret the argument as a unicode codepoint. If the codepoint
  145152. ** is an upper case character that has a lower case equivalent,
  145153. ** return the codepoint corresponding to the lower case version.
  145154. ** Otherwise, return a copy of the argument.
  145155. **
  145156. ** The results are undefined if the value passed to this function
  145157. ** is less than zero.
  145158. */
  145159. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  145160. /* Each entry in the following array defines a rule for folding a range
  145161. ** of codepoints to lower case. The rule applies to a range of nRange
  145162. ** codepoints starting at codepoint iCode.
  145163. **
  145164. ** If the least significant bit in flags is clear, then the rule applies
  145165. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  145166. ** need to be folded). Or, if it is set, then the rule only applies to
  145167. ** every second codepoint in the range, starting with codepoint C.
  145168. **
  145169. ** The 7 most significant bits in flags are an index into the aiOff[]
  145170. ** array. If a specific codepoint C does require folding, then its lower
  145171. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  145172. **
  145173. ** The contents of this array are generated by parsing the CaseFolding.txt
  145174. ** file distributed as part of the "Unicode Character Database". See
  145175. ** http://www.unicode.org for details.
  145176. */
  145177. static const struct TableEntry {
  145178. unsigned short iCode;
  145179. unsigned char flags;
  145180. unsigned char nRange;
  145181. } aEntry[] = {
  145182. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  145183. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  145184. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  145185. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  145186. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  145187. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  145188. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  145189. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  145190. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  145191. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  145192. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  145193. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  145194. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  145195. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  145196. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  145197. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  145198. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  145199. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  145200. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  145201. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  145202. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  145203. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  145204. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  145205. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  145206. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  145207. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  145208. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  145209. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  145210. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  145211. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  145212. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  145213. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  145214. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  145215. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  145216. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  145217. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  145218. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  145219. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  145220. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  145221. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  145222. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  145223. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  145224. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  145225. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  145226. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  145227. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  145228. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  145229. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  145230. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  145231. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  145232. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  145233. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  145234. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  145235. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  145236. {65313, 14, 26},
  145237. };
  145238. static const unsigned short aiOff[] = {
  145239. 1, 2, 8, 15, 16, 26, 28, 32,
  145240. 37, 38, 40, 48, 63, 64, 69, 71,
  145241. 79, 80, 116, 202, 203, 205, 206, 207,
  145242. 209, 210, 211, 213, 214, 217, 218, 219,
  145243. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  145244. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  145245. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  145246. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  145247. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  145248. 65514, 65521, 65527, 65528, 65529,
  145249. };
  145250. int ret = c;
  145251. assert( c>=0 );
  145252. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  145253. if( c<128 ){
  145254. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  145255. }else if( c<65536 ){
  145256. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  145257. int iLo = 0;
  145258. int iRes = -1;
  145259. while( iHi>=iLo ){
  145260. int iTest = (iHi + iLo) / 2;
  145261. int cmp = (c - aEntry[iTest].iCode);
  145262. if( cmp>=0 ){
  145263. iRes = iTest;
  145264. iLo = iTest+1;
  145265. }else{
  145266. iHi = iTest-1;
  145267. }
  145268. }
  145269. assert( iRes<0 || c>=aEntry[iRes].iCode );
  145270. if( iRes>=0 ){
  145271. const struct TableEntry *p = &aEntry[iRes];
  145272. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  145273. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  145274. assert( ret>0 );
  145275. }
  145276. }
  145277. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  145278. }
  145279. else if( c>=66560 && c<66600 ){
  145280. ret = c + 40;
  145281. }
  145282. return ret;
  145283. }
  145284. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  145285. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  145286. /************** End of fts3_unicode2.c ***************************************/
  145287. /************** Begin file rtree.c *******************************************/
  145288. /*
  145289. ** 2001 September 15
  145290. **
  145291. ** The author disclaims copyright to this source code. In place of
  145292. ** a legal notice, here is a blessing:
  145293. **
  145294. ** May you do good and not evil.
  145295. ** May you find forgiveness for yourself and forgive others.
  145296. ** May you share freely, never taking more than you give.
  145297. **
  145298. *************************************************************************
  145299. ** This file contains code for implementations of the r-tree and r*-tree
  145300. ** algorithms packaged as an SQLite virtual table module.
  145301. */
  145302. /*
  145303. ** Database Format of R-Tree Tables
  145304. ** --------------------------------
  145305. **
  145306. ** The data structure for a single virtual r-tree table is stored in three
  145307. ** native SQLite tables declared as follows. In each case, the '%' character
  145308. ** in the table name is replaced with the user-supplied name of the r-tree
  145309. ** table.
  145310. **
  145311. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  145312. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  145313. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  145314. **
  145315. ** The data for each node of the r-tree structure is stored in the %_node
  145316. ** table. For each node that is not the root node of the r-tree, there is
  145317. ** an entry in the %_parent table associating the node with its parent.
  145318. ** And for each row of data in the table, there is an entry in the %_rowid
  145319. ** table that maps from the entries rowid to the id of the node that it
  145320. ** is stored on.
  145321. **
  145322. ** The root node of an r-tree always exists, even if the r-tree table is
  145323. ** empty. The nodeno of the root node is always 1. All other nodes in the
  145324. ** table must be the same size as the root node. The content of each node
  145325. ** is formatted as follows:
  145326. **
  145327. ** 1. If the node is the root node (node 1), then the first 2 bytes
  145328. ** of the node contain the tree depth as a big-endian integer.
  145329. ** For non-root nodes, the first 2 bytes are left unused.
  145330. **
  145331. ** 2. The next 2 bytes contain the number of entries currently
  145332. ** stored in the node.
  145333. **
  145334. ** 3. The remainder of the node contains the node entries. Each entry
  145335. ** consists of a single 8-byte integer followed by an even number
  145336. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  145337. ** of a record. For internal nodes it is the node number of a
  145338. ** child page.
  145339. */
  145340. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  145341. #ifndef SQLITE_CORE
  145342. /* #include "sqlite3ext.h" */
  145343. SQLITE_EXTENSION_INIT1
  145344. #else
  145345. /* #include "sqlite3.h" */
  145346. #endif
  145347. /* #include <string.h> */
  145348. /* #include <assert.h> */
  145349. /* #include <stdio.h> */
  145350. #ifndef SQLITE_AMALGAMATION
  145351. #include "sqlite3rtree.h"
  145352. typedef sqlite3_int64 i64;
  145353. typedef unsigned char u8;
  145354. typedef unsigned short u16;
  145355. typedef unsigned int u32;
  145356. #endif
  145357. /* The following macro is used to suppress compiler warnings.
  145358. */
  145359. #ifndef UNUSED_PARAMETER
  145360. # define UNUSED_PARAMETER(x) (void)(x)
  145361. #endif
  145362. typedef struct Rtree Rtree;
  145363. typedef struct RtreeCursor RtreeCursor;
  145364. typedef struct RtreeNode RtreeNode;
  145365. typedef struct RtreeCell RtreeCell;
  145366. typedef struct RtreeConstraint RtreeConstraint;
  145367. typedef struct RtreeMatchArg RtreeMatchArg;
  145368. typedef struct RtreeGeomCallback RtreeGeomCallback;
  145369. typedef union RtreeCoord RtreeCoord;
  145370. typedef struct RtreeSearchPoint RtreeSearchPoint;
  145371. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  145372. #define RTREE_MAX_DIMENSIONS 5
  145373. /* Size of hash table Rtree.aHash. This hash table is not expected to
  145374. ** ever contain very many entries, so a fixed number of buckets is
  145375. ** used.
  145376. */
  145377. #define HASHSIZE 97
  145378. /* The xBestIndex method of this virtual table requires an estimate of
  145379. ** the number of rows in the virtual table to calculate the costs of
  145380. ** various strategies. If possible, this estimate is loaded from the
  145381. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  145382. ** Otherwise, if no sqlite_stat1 entry is available, use
  145383. ** RTREE_DEFAULT_ROWEST.
  145384. */
  145385. #define RTREE_DEFAULT_ROWEST 1048576
  145386. #define RTREE_MIN_ROWEST 100
  145387. /*
  145388. ** An rtree virtual-table object.
  145389. */
  145390. struct Rtree {
  145391. sqlite3_vtab base; /* Base class. Must be first */
  145392. sqlite3 *db; /* Host database connection */
  145393. int iNodeSize; /* Size in bytes of each node in the node table */
  145394. u8 nDim; /* Number of dimensions */
  145395. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  145396. u8 nBytesPerCell; /* Bytes consumed per cell */
  145397. int iDepth; /* Current depth of the r-tree structure */
  145398. char *zDb; /* Name of database containing r-tree table */
  145399. char *zName; /* Name of r-tree table */
  145400. int nBusy; /* Current number of users of this structure */
  145401. i64 nRowEst; /* Estimated number of rows in this table */
  145402. /* List of nodes removed during a CondenseTree operation. List is
  145403. ** linked together via the pointer normally used for hash chains -
  145404. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  145405. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  145406. */
  145407. RtreeNode *pDeleted;
  145408. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  145409. /* Statements to read/write/delete a record from xxx_node */
  145410. sqlite3_stmt *pReadNode;
  145411. sqlite3_stmt *pWriteNode;
  145412. sqlite3_stmt *pDeleteNode;
  145413. /* Statements to read/write/delete a record from xxx_rowid */
  145414. sqlite3_stmt *pReadRowid;
  145415. sqlite3_stmt *pWriteRowid;
  145416. sqlite3_stmt *pDeleteRowid;
  145417. /* Statements to read/write/delete a record from xxx_parent */
  145418. sqlite3_stmt *pReadParent;
  145419. sqlite3_stmt *pWriteParent;
  145420. sqlite3_stmt *pDeleteParent;
  145421. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  145422. };
  145423. /* Possible values for Rtree.eCoordType: */
  145424. #define RTREE_COORD_REAL32 0
  145425. #define RTREE_COORD_INT32 1
  145426. /*
  145427. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  145428. ** only deal with integer coordinates. No floating point operations
  145429. ** will be done.
  145430. */
  145431. #ifdef SQLITE_RTREE_INT_ONLY
  145432. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  145433. typedef int RtreeValue; /* Low accuracy coordinate */
  145434. # define RTREE_ZERO 0
  145435. #else
  145436. typedef double RtreeDValue; /* High accuracy coordinate */
  145437. typedef float RtreeValue; /* Low accuracy coordinate */
  145438. # define RTREE_ZERO 0.0
  145439. #endif
  145440. /*
  145441. ** When doing a search of an r-tree, instances of the following structure
  145442. ** record intermediate results from the tree walk.
  145443. **
  145444. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  145445. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  145446. ** the id is of the parent node and the cell that RtreeSearchPoint
  145447. ** represents is the iCell-th entry in the parent node.
  145448. */
  145449. struct RtreeSearchPoint {
  145450. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  145451. sqlite3_int64 id; /* Node ID */
  145452. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  145453. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  145454. u8 iCell; /* Cell index within the node */
  145455. };
  145456. /*
  145457. ** The minimum number of cells allowed for a node is a third of the
  145458. ** maximum. In Gutman's notation:
  145459. **
  145460. ** m = M/3
  145461. **
  145462. ** If an R*-tree "Reinsert" operation is required, the same number of
  145463. ** cells are removed from the overfull node and reinserted into the tree.
  145464. */
  145465. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  145466. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  145467. #define RTREE_MAXCELLS 51
  145468. /*
  145469. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  145470. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  145471. ** Therefore all non-root nodes must contain at least 3 entries. Since
  145472. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  145473. ** 40 or less.
  145474. */
  145475. #define RTREE_MAX_DEPTH 40
  145476. /*
  145477. ** Number of entries in the cursor RtreeNode cache. The first entry is
  145478. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  145479. ** entries cache the RtreeNode for the first elements of the priority queue.
  145480. */
  145481. #define RTREE_CACHE_SZ 5
  145482. /*
  145483. ** An rtree cursor object.
  145484. */
  145485. struct RtreeCursor {
  145486. sqlite3_vtab_cursor base; /* Base class. Must be first */
  145487. u8 atEOF; /* True if at end of search */
  145488. u8 bPoint; /* True if sPoint is valid */
  145489. int iStrategy; /* Copy of idxNum search parameter */
  145490. int nConstraint; /* Number of entries in aConstraint */
  145491. RtreeConstraint *aConstraint; /* Search constraints. */
  145492. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  145493. int nPoint; /* Number of slots used in aPoint[] */
  145494. int mxLevel; /* iLevel value for root of the tree */
  145495. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  145496. RtreeSearchPoint sPoint; /* Cached next search point */
  145497. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  145498. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  145499. };
  145500. /* Return the Rtree of a RtreeCursor */
  145501. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  145502. /*
  145503. ** A coordinate can be either a floating point number or a integer. All
  145504. ** coordinates within a single R-Tree are always of the same time.
  145505. */
  145506. union RtreeCoord {
  145507. RtreeValue f; /* Floating point value */
  145508. int i; /* Integer value */
  145509. u32 u; /* Unsigned for byte-order conversions */
  145510. };
  145511. /*
  145512. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  145513. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  145514. ** variable pRtree points to the Rtree structure associated with the
  145515. ** RtreeCoord.
  145516. */
  145517. #ifdef SQLITE_RTREE_INT_ONLY
  145518. # define DCOORD(coord) ((RtreeDValue)coord.i)
  145519. #else
  145520. # define DCOORD(coord) ( \
  145521. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  145522. ((double)coord.f) : \
  145523. ((double)coord.i) \
  145524. )
  145525. #endif
  145526. /*
  145527. ** A search constraint.
  145528. */
  145529. struct RtreeConstraint {
  145530. int iCoord; /* Index of constrained coordinate */
  145531. int op; /* Constraining operation */
  145532. union {
  145533. RtreeDValue rValue; /* Constraint value. */
  145534. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  145535. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  145536. } u;
  145537. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  145538. };
  145539. /* Possible values for RtreeConstraint.op */
  145540. #define RTREE_EQ 0x41 /* A */
  145541. #define RTREE_LE 0x42 /* B */
  145542. #define RTREE_LT 0x43 /* C */
  145543. #define RTREE_GE 0x44 /* D */
  145544. #define RTREE_GT 0x45 /* E */
  145545. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  145546. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  145547. /*
  145548. ** An rtree structure node.
  145549. */
  145550. struct RtreeNode {
  145551. RtreeNode *pParent; /* Parent node */
  145552. i64 iNode; /* The node number */
  145553. int nRef; /* Number of references to this node */
  145554. int isDirty; /* True if the node needs to be written to disk */
  145555. u8 *zData; /* Content of the node, as should be on disk */
  145556. RtreeNode *pNext; /* Next node in this hash collision chain */
  145557. };
  145558. /* Return the number of cells in a node */
  145559. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  145560. /*
  145561. ** A single cell from a node, deserialized
  145562. */
  145563. struct RtreeCell {
  145564. i64 iRowid; /* Node or entry ID */
  145565. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  145566. };
  145567. /*
  145568. ** This object becomes the sqlite3_user_data() for the SQL functions
  145569. ** that are created by sqlite3_rtree_geometry_callback() and
  145570. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  145571. ** operators in order to constrain a search.
  145572. **
  145573. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  145574. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  145575. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  145576. ** sqlite3_rtree_query_callback().
  145577. **
  145578. ** This object is deleted automatically by the destructor mechanism in
  145579. ** sqlite3_create_function_v2().
  145580. */
  145581. struct RtreeGeomCallback {
  145582. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  145583. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  145584. void (*xDestructor)(void*);
  145585. void *pContext;
  145586. };
  145587. /*
  145588. ** Value for the first field of every RtreeMatchArg object. The MATCH
  145589. ** operator tests that the first field of a blob operand matches this
  145590. ** value to avoid operating on invalid blobs (which could cause a segfault).
  145591. */
  145592. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  145593. /*
  145594. ** An instance of this structure (in the form of a BLOB) is returned by
  145595. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  145596. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  145597. ** operand to the MATCH operator of an R-Tree.
  145598. */
  145599. struct RtreeMatchArg {
  145600. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  145601. RtreeGeomCallback cb; /* Info about the callback functions */
  145602. int nParam; /* Number of parameters to the SQL function */
  145603. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  145604. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  145605. };
  145606. #ifndef MAX
  145607. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  145608. #endif
  145609. #ifndef MIN
  145610. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  145611. #endif
  145612. /*
  145613. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  145614. ** 64 bit integer. The deserialized value is returned.
  145615. */
  145616. static int readInt16(u8 *p){
  145617. return (p[0]<<8) + p[1];
  145618. }
  145619. static void readCoord(u8 *p, RtreeCoord *pCoord){
  145620. pCoord->u = (
  145621. (((u32)p[0]) << 24) +
  145622. (((u32)p[1]) << 16) +
  145623. (((u32)p[2]) << 8) +
  145624. (((u32)p[3]) << 0)
  145625. );
  145626. }
  145627. static i64 readInt64(u8 *p){
  145628. return (
  145629. (((i64)p[0]) << 56) +
  145630. (((i64)p[1]) << 48) +
  145631. (((i64)p[2]) << 40) +
  145632. (((i64)p[3]) << 32) +
  145633. (((i64)p[4]) << 24) +
  145634. (((i64)p[5]) << 16) +
  145635. (((i64)p[6]) << 8) +
  145636. (((i64)p[7]) << 0)
  145637. );
  145638. }
  145639. /*
  145640. ** Functions to serialize a 16 bit integer, 32 bit real number and
  145641. ** 64 bit integer. The value returned is the number of bytes written
  145642. ** to the argument buffer (always 2, 4 and 8 respectively).
  145643. */
  145644. static int writeInt16(u8 *p, int i){
  145645. p[0] = (i>> 8)&0xFF;
  145646. p[1] = (i>> 0)&0xFF;
  145647. return 2;
  145648. }
  145649. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  145650. u32 i;
  145651. assert( sizeof(RtreeCoord)==4 );
  145652. assert( sizeof(u32)==4 );
  145653. i = pCoord->u;
  145654. p[0] = (i>>24)&0xFF;
  145655. p[1] = (i>>16)&0xFF;
  145656. p[2] = (i>> 8)&0xFF;
  145657. p[3] = (i>> 0)&0xFF;
  145658. return 4;
  145659. }
  145660. static int writeInt64(u8 *p, i64 i){
  145661. p[0] = (i>>56)&0xFF;
  145662. p[1] = (i>>48)&0xFF;
  145663. p[2] = (i>>40)&0xFF;
  145664. p[3] = (i>>32)&0xFF;
  145665. p[4] = (i>>24)&0xFF;
  145666. p[5] = (i>>16)&0xFF;
  145667. p[6] = (i>> 8)&0xFF;
  145668. p[7] = (i>> 0)&0xFF;
  145669. return 8;
  145670. }
  145671. /*
  145672. ** Increment the reference count of node p.
  145673. */
  145674. static void nodeReference(RtreeNode *p){
  145675. if( p ){
  145676. p->nRef++;
  145677. }
  145678. }
  145679. /*
  145680. ** Clear the content of node p (set all bytes to 0x00).
  145681. */
  145682. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  145683. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  145684. p->isDirty = 1;
  145685. }
  145686. /*
  145687. ** Given a node number iNode, return the corresponding key to use
  145688. ** in the Rtree.aHash table.
  145689. */
  145690. static int nodeHash(i64 iNode){
  145691. return iNode % HASHSIZE;
  145692. }
  145693. /*
  145694. ** Search the node hash table for node iNode. If found, return a pointer
  145695. ** to it. Otherwise, return 0.
  145696. */
  145697. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  145698. RtreeNode *p;
  145699. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  145700. return p;
  145701. }
  145702. /*
  145703. ** Add node pNode to the node hash table.
  145704. */
  145705. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  145706. int iHash;
  145707. assert( pNode->pNext==0 );
  145708. iHash = nodeHash(pNode->iNode);
  145709. pNode->pNext = pRtree->aHash[iHash];
  145710. pRtree->aHash[iHash] = pNode;
  145711. }
  145712. /*
  145713. ** Remove node pNode from the node hash table.
  145714. */
  145715. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  145716. RtreeNode **pp;
  145717. if( pNode->iNode!=0 ){
  145718. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  145719. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  145720. *pp = pNode->pNext;
  145721. pNode->pNext = 0;
  145722. }
  145723. }
  145724. /*
  145725. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  145726. ** indicating that node has not yet been assigned a node number. It is
  145727. ** assigned a node number when nodeWrite() is called to write the
  145728. ** node contents out to the database.
  145729. */
  145730. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  145731. RtreeNode *pNode;
  145732. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  145733. if( pNode ){
  145734. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  145735. pNode->zData = (u8 *)&pNode[1];
  145736. pNode->nRef = 1;
  145737. pNode->pParent = pParent;
  145738. pNode->isDirty = 1;
  145739. nodeReference(pParent);
  145740. }
  145741. return pNode;
  145742. }
  145743. /*
  145744. ** Obtain a reference to an r-tree node.
  145745. */
  145746. static int nodeAcquire(
  145747. Rtree *pRtree, /* R-tree structure */
  145748. i64 iNode, /* Node number to load */
  145749. RtreeNode *pParent, /* Either the parent node or NULL */
  145750. RtreeNode **ppNode /* OUT: Acquired node */
  145751. ){
  145752. int rc;
  145753. int rc2 = SQLITE_OK;
  145754. RtreeNode *pNode;
  145755. /* Check if the requested node is already in the hash table. If so,
  145756. ** increase its reference count and return it.
  145757. */
  145758. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  145759. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  145760. if( pParent && !pNode->pParent ){
  145761. nodeReference(pParent);
  145762. pNode->pParent = pParent;
  145763. }
  145764. pNode->nRef++;
  145765. *ppNode = pNode;
  145766. return SQLITE_OK;
  145767. }
  145768. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  145769. rc = sqlite3_step(pRtree->pReadNode);
  145770. if( rc==SQLITE_ROW ){
  145771. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  145772. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  145773. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  145774. if( !pNode ){
  145775. rc2 = SQLITE_NOMEM;
  145776. }else{
  145777. pNode->pParent = pParent;
  145778. pNode->zData = (u8 *)&pNode[1];
  145779. pNode->nRef = 1;
  145780. pNode->iNode = iNode;
  145781. pNode->isDirty = 0;
  145782. pNode->pNext = 0;
  145783. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  145784. nodeReference(pParent);
  145785. }
  145786. }
  145787. }
  145788. rc = sqlite3_reset(pRtree->pReadNode);
  145789. if( rc==SQLITE_OK ) rc = rc2;
  145790. /* If the root node was just loaded, set pRtree->iDepth to the height
  145791. ** of the r-tree structure. A height of zero means all data is stored on
  145792. ** the root node. A height of one means the children of the root node
  145793. ** are the leaves, and so on. If the depth as specified on the root node
  145794. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  145795. */
  145796. if( pNode && iNode==1 ){
  145797. pRtree->iDepth = readInt16(pNode->zData);
  145798. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  145799. rc = SQLITE_CORRUPT_VTAB;
  145800. }
  145801. }
  145802. /* If no error has occurred so far, check if the "number of entries"
  145803. ** field on the node is too large. If so, set the return code to
  145804. ** SQLITE_CORRUPT_VTAB.
  145805. */
  145806. if( pNode && rc==SQLITE_OK ){
  145807. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  145808. rc = SQLITE_CORRUPT_VTAB;
  145809. }
  145810. }
  145811. if( rc==SQLITE_OK ){
  145812. if( pNode!=0 ){
  145813. nodeHashInsert(pRtree, pNode);
  145814. }else{
  145815. rc = SQLITE_CORRUPT_VTAB;
  145816. }
  145817. *ppNode = pNode;
  145818. }else{
  145819. sqlite3_free(pNode);
  145820. *ppNode = 0;
  145821. }
  145822. return rc;
  145823. }
  145824. /*
  145825. ** Overwrite cell iCell of node pNode with the contents of pCell.
  145826. */
  145827. static void nodeOverwriteCell(
  145828. Rtree *pRtree, /* The overall R-Tree */
  145829. RtreeNode *pNode, /* The node into which the cell is to be written */
  145830. RtreeCell *pCell, /* The cell to write */
  145831. int iCell /* Index into pNode into which pCell is written */
  145832. ){
  145833. int ii;
  145834. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  145835. p += writeInt64(p, pCell->iRowid);
  145836. for(ii=0; ii<(pRtree->nDim*2); ii++){
  145837. p += writeCoord(p, &pCell->aCoord[ii]);
  145838. }
  145839. pNode->isDirty = 1;
  145840. }
  145841. /*
  145842. ** Remove the cell with index iCell from node pNode.
  145843. */
  145844. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  145845. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  145846. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  145847. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  145848. memmove(pDst, pSrc, nByte);
  145849. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  145850. pNode->isDirty = 1;
  145851. }
  145852. /*
  145853. ** Insert the contents of cell pCell into node pNode. If the insert
  145854. ** is successful, return SQLITE_OK.
  145855. **
  145856. ** If there is not enough free space in pNode, return SQLITE_FULL.
  145857. */
  145858. static int nodeInsertCell(
  145859. Rtree *pRtree, /* The overall R-Tree */
  145860. RtreeNode *pNode, /* Write new cell into this node */
  145861. RtreeCell *pCell /* The cell to be inserted */
  145862. ){
  145863. int nCell; /* Current number of cells in pNode */
  145864. int nMaxCell; /* Maximum number of cells for pNode */
  145865. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  145866. nCell = NCELL(pNode);
  145867. assert( nCell<=nMaxCell );
  145868. if( nCell<nMaxCell ){
  145869. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  145870. writeInt16(&pNode->zData[2], nCell+1);
  145871. pNode->isDirty = 1;
  145872. }
  145873. return (nCell==nMaxCell);
  145874. }
  145875. /*
  145876. ** If the node is dirty, write it out to the database.
  145877. */
  145878. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  145879. int rc = SQLITE_OK;
  145880. if( pNode->isDirty ){
  145881. sqlite3_stmt *p = pRtree->pWriteNode;
  145882. if( pNode->iNode ){
  145883. sqlite3_bind_int64(p, 1, pNode->iNode);
  145884. }else{
  145885. sqlite3_bind_null(p, 1);
  145886. }
  145887. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  145888. sqlite3_step(p);
  145889. pNode->isDirty = 0;
  145890. rc = sqlite3_reset(p);
  145891. if( pNode->iNode==0 && rc==SQLITE_OK ){
  145892. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  145893. nodeHashInsert(pRtree, pNode);
  145894. }
  145895. }
  145896. return rc;
  145897. }
  145898. /*
  145899. ** Release a reference to a node. If the node is dirty and the reference
  145900. ** count drops to zero, the node data is written to the database.
  145901. */
  145902. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  145903. int rc = SQLITE_OK;
  145904. if( pNode ){
  145905. assert( pNode->nRef>0 );
  145906. pNode->nRef--;
  145907. if( pNode->nRef==0 ){
  145908. if( pNode->iNode==1 ){
  145909. pRtree->iDepth = -1;
  145910. }
  145911. if( pNode->pParent ){
  145912. rc = nodeRelease(pRtree, pNode->pParent);
  145913. }
  145914. if( rc==SQLITE_OK ){
  145915. rc = nodeWrite(pRtree, pNode);
  145916. }
  145917. nodeHashDelete(pRtree, pNode);
  145918. sqlite3_free(pNode);
  145919. }
  145920. }
  145921. return rc;
  145922. }
  145923. /*
  145924. ** Return the 64-bit integer value associated with cell iCell of
  145925. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  145926. ** an internal node, then the 64-bit integer is a child page number.
  145927. */
  145928. static i64 nodeGetRowid(
  145929. Rtree *pRtree, /* The overall R-Tree */
  145930. RtreeNode *pNode, /* The node from which to extract the ID */
  145931. int iCell /* The cell index from which to extract the ID */
  145932. ){
  145933. assert( iCell<NCELL(pNode) );
  145934. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  145935. }
  145936. /*
  145937. ** Return coordinate iCoord from cell iCell in node pNode.
  145938. */
  145939. static void nodeGetCoord(
  145940. Rtree *pRtree, /* The overall R-Tree */
  145941. RtreeNode *pNode, /* The node from which to extract a coordinate */
  145942. int iCell, /* The index of the cell within the node */
  145943. int iCoord, /* Which coordinate to extract */
  145944. RtreeCoord *pCoord /* OUT: Space to write result to */
  145945. ){
  145946. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  145947. }
  145948. /*
  145949. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  145950. ** to by pCell with the results.
  145951. */
  145952. static void nodeGetCell(
  145953. Rtree *pRtree, /* The overall R-Tree */
  145954. RtreeNode *pNode, /* The node containing the cell to be read */
  145955. int iCell, /* Index of the cell within the node */
  145956. RtreeCell *pCell /* OUT: Write the cell contents here */
  145957. ){
  145958. u8 *pData;
  145959. RtreeCoord *pCoord;
  145960. int ii;
  145961. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  145962. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  145963. pCoord = pCell->aCoord;
  145964. for(ii=0; ii<pRtree->nDim*2; ii++){
  145965. readCoord(&pData[ii*4], &pCoord[ii]);
  145966. }
  145967. }
  145968. /* Forward declaration for the function that does the work of
  145969. ** the virtual table module xCreate() and xConnect() methods.
  145970. */
  145971. static int rtreeInit(
  145972. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  145973. );
  145974. /*
  145975. ** Rtree virtual table module xCreate method.
  145976. */
  145977. static int rtreeCreate(
  145978. sqlite3 *db,
  145979. void *pAux,
  145980. int argc, const char *const*argv,
  145981. sqlite3_vtab **ppVtab,
  145982. char **pzErr
  145983. ){
  145984. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  145985. }
  145986. /*
  145987. ** Rtree virtual table module xConnect method.
  145988. */
  145989. static int rtreeConnect(
  145990. sqlite3 *db,
  145991. void *pAux,
  145992. int argc, const char *const*argv,
  145993. sqlite3_vtab **ppVtab,
  145994. char **pzErr
  145995. ){
  145996. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  145997. }
  145998. /*
  145999. ** Increment the r-tree reference count.
  146000. */
  146001. static void rtreeReference(Rtree *pRtree){
  146002. pRtree->nBusy++;
  146003. }
  146004. /*
  146005. ** Decrement the r-tree reference count. When the reference count reaches
  146006. ** zero the structure is deleted.
  146007. */
  146008. static void rtreeRelease(Rtree *pRtree){
  146009. pRtree->nBusy--;
  146010. if( pRtree->nBusy==0 ){
  146011. sqlite3_finalize(pRtree->pReadNode);
  146012. sqlite3_finalize(pRtree->pWriteNode);
  146013. sqlite3_finalize(pRtree->pDeleteNode);
  146014. sqlite3_finalize(pRtree->pReadRowid);
  146015. sqlite3_finalize(pRtree->pWriteRowid);
  146016. sqlite3_finalize(pRtree->pDeleteRowid);
  146017. sqlite3_finalize(pRtree->pReadParent);
  146018. sqlite3_finalize(pRtree->pWriteParent);
  146019. sqlite3_finalize(pRtree->pDeleteParent);
  146020. sqlite3_free(pRtree);
  146021. }
  146022. }
  146023. /*
  146024. ** Rtree virtual table module xDisconnect method.
  146025. */
  146026. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  146027. rtreeRelease((Rtree *)pVtab);
  146028. return SQLITE_OK;
  146029. }
  146030. /*
  146031. ** Rtree virtual table module xDestroy method.
  146032. */
  146033. static int rtreeDestroy(sqlite3_vtab *pVtab){
  146034. Rtree *pRtree = (Rtree *)pVtab;
  146035. int rc;
  146036. char *zCreate = sqlite3_mprintf(
  146037. "DROP TABLE '%q'.'%q_node';"
  146038. "DROP TABLE '%q'.'%q_rowid';"
  146039. "DROP TABLE '%q'.'%q_parent';",
  146040. pRtree->zDb, pRtree->zName,
  146041. pRtree->zDb, pRtree->zName,
  146042. pRtree->zDb, pRtree->zName
  146043. );
  146044. if( !zCreate ){
  146045. rc = SQLITE_NOMEM;
  146046. }else{
  146047. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  146048. sqlite3_free(zCreate);
  146049. }
  146050. if( rc==SQLITE_OK ){
  146051. rtreeRelease(pRtree);
  146052. }
  146053. return rc;
  146054. }
  146055. /*
  146056. ** Rtree virtual table module xOpen method.
  146057. */
  146058. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  146059. int rc = SQLITE_NOMEM;
  146060. RtreeCursor *pCsr;
  146061. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  146062. if( pCsr ){
  146063. memset(pCsr, 0, sizeof(RtreeCursor));
  146064. pCsr->base.pVtab = pVTab;
  146065. rc = SQLITE_OK;
  146066. }
  146067. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  146068. return rc;
  146069. }
  146070. /*
  146071. ** Free the RtreeCursor.aConstraint[] array and its contents.
  146072. */
  146073. static void freeCursorConstraints(RtreeCursor *pCsr){
  146074. if( pCsr->aConstraint ){
  146075. int i; /* Used to iterate through constraint array */
  146076. for(i=0; i<pCsr->nConstraint; i++){
  146077. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  146078. if( pInfo ){
  146079. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  146080. sqlite3_free(pInfo);
  146081. }
  146082. }
  146083. sqlite3_free(pCsr->aConstraint);
  146084. pCsr->aConstraint = 0;
  146085. }
  146086. }
  146087. /*
  146088. ** Rtree virtual table module xClose method.
  146089. */
  146090. static int rtreeClose(sqlite3_vtab_cursor *cur){
  146091. Rtree *pRtree = (Rtree *)(cur->pVtab);
  146092. int ii;
  146093. RtreeCursor *pCsr = (RtreeCursor *)cur;
  146094. freeCursorConstraints(pCsr);
  146095. sqlite3_free(pCsr->aPoint);
  146096. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  146097. sqlite3_free(pCsr);
  146098. return SQLITE_OK;
  146099. }
  146100. /*
  146101. ** Rtree virtual table module xEof method.
  146102. **
  146103. ** Return non-zero if the cursor does not currently point to a valid
  146104. ** record (i.e if the scan has finished), or zero otherwise.
  146105. */
  146106. static int rtreeEof(sqlite3_vtab_cursor *cur){
  146107. RtreeCursor *pCsr = (RtreeCursor *)cur;
  146108. return pCsr->atEOF;
  146109. }
  146110. /*
  146111. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  146112. ** The on-disk format is big-endian and needs to be converted for little-
  146113. ** endian platforms. The on-disk record stores integer coordinates if
  146114. ** eInt is true and it stores 32-bit floating point records if eInt is
  146115. ** false. a[] is the four bytes of the on-disk record to be decoded.
  146116. ** Store the results in "r".
  146117. **
  146118. ** There are three versions of this macro, one each for little-endian and
  146119. ** big-endian processors and a third generic implementation. The endian-
  146120. ** specific implementations are much faster and are preferred if the
  146121. ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
  146122. ** macro is part of sqliteInt.h and hence the endian-specific
  146123. ** implementation will only be used if this module is compiled as part
  146124. ** of the amalgamation.
  146125. */
  146126. #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
  146127. #define RTREE_DECODE_COORD(eInt, a, r) { \
  146128. RtreeCoord c; /* Coordinate decoded */ \
  146129. memcpy(&c.u,a,4); \
  146130. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  146131. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  146132. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  146133. }
  146134. #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
  146135. #define RTREE_DECODE_COORD(eInt, a, r) { \
  146136. RtreeCoord c; /* Coordinate decoded */ \
  146137. memcpy(&c.u,a,4); \
  146138. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  146139. }
  146140. #else
  146141. #define RTREE_DECODE_COORD(eInt, a, r) { \
  146142. RtreeCoord c; /* Coordinate decoded */ \
  146143. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  146144. +((u32)a[2]<<8) + a[3]; \
  146145. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  146146. }
  146147. #endif
  146148. /*
  146149. ** Check the RTree node or entry given by pCellData and p against the MATCH
  146150. ** constraint pConstraint.
  146151. */
  146152. static int rtreeCallbackConstraint(
  146153. RtreeConstraint *pConstraint, /* The constraint to test */
  146154. int eInt, /* True if RTree holding integer coordinates */
  146155. u8 *pCellData, /* Raw cell content */
  146156. RtreeSearchPoint *pSearch, /* Container of this cell */
  146157. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  146158. int *peWithin /* OUT: visibility of the cell */
  146159. ){
  146160. int i; /* Loop counter */
  146161. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  146162. int nCoord = pInfo->nCoord; /* No. of coordinates */
  146163. int rc; /* Callback return code */
  146164. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  146165. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  146166. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  146167. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  146168. pInfo->iRowid = readInt64(pCellData);
  146169. }
  146170. pCellData += 8;
  146171. for(i=0; i<nCoord; i++, pCellData += 4){
  146172. RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
  146173. }
  146174. if( pConstraint->op==RTREE_MATCH ){
  146175. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  146176. nCoord, aCoord, &i);
  146177. if( i==0 ) *peWithin = NOT_WITHIN;
  146178. *prScore = RTREE_ZERO;
  146179. }else{
  146180. pInfo->aCoord = aCoord;
  146181. pInfo->iLevel = pSearch->iLevel - 1;
  146182. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  146183. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  146184. rc = pConstraint->u.xQueryFunc(pInfo);
  146185. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  146186. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  146187. *prScore = pInfo->rScore;
  146188. }
  146189. }
  146190. return rc;
  146191. }
  146192. /*
  146193. ** Check the internal RTree node given by pCellData against constraint p.
  146194. ** If this constraint cannot be satisfied by any child within the node,
  146195. ** set *peWithin to NOT_WITHIN.
  146196. */
  146197. static void rtreeNonleafConstraint(
  146198. RtreeConstraint *p, /* The constraint to test */
  146199. int eInt, /* True if RTree holds integer coordinates */
  146200. u8 *pCellData, /* Raw cell content as appears on disk */
  146201. int *peWithin /* Adjust downward, as appropriate */
  146202. ){
  146203. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  146204. /* p->iCoord might point to either a lower or upper bound coordinate
  146205. ** in a coordinate pair. But make pCellData point to the lower bound.
  146206. */
  146207. pCellData += 8 + 4*(p->iCoord&0xfe);
  146208. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  146209. || p->op==RTREE_GT || p->op==RTREE_EQ );
  146210. switch( p->op ){
  146211. case RTREE_LE:
  146212. case RTREE_LT:
  146213. case RTREE_EQ:
  146214. RTREE_DECODE_COORD(eInt, pCellData, val);
  146215. /* val now holds the lower bound of the coordinate pair */
  146216. if( p->u.rValue>=val ) return;
  146217. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  146218. /* Fall through for the RTREE_EQ case */
  146219. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  146220. pCellData += 4;
  146221. RTREE_DECODE_COORD(eInt, pCellData, val);
  146222. /* val now holds the upper bound of the coordinate pair */
  146223. if( p->u.rValue<=val ) return;
  146224. }
  146225. *peWithin = NOT_WITHIN;
  146226. }
  146227. /*
  146228. ** Check the leaf RTree cell given by pCellData against constraint p.
  146229. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  146230. ** If the constraint is satisfied, leave *peWithin unchanged.
  146231. **
  146232. ** The constraint is of the form: xN op $val
  146233. **
  146234. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  146235. ** pCellData. $val is given by p->u.rValue.
  146236. */
  146237. static void rtreeLeafConstraint(
  146238. RtreeConstraint *p, /* The constraint to test */
  146239. int eInt, /* True if RTree holds integer coordinates */
  146240. u8 *pCellData, /* Raw cell content as appears on disk */
  146241. int *peWithin /* Adjust downward, as appropriate */
  146242. ){
  146243. RtreeDValue xN; /* Coordinate value converted to a double */
  146244. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  146245. || p->op==RTREE_GT || p->op==RTREE_EQ );
  146246. pCellData += 8 + p->iCoord*4;
  146247. RTREE_DECODE_COORD(eInt, pCellData, xN);
  146248. switch( p->op ){
  146249. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  146250. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  146251. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  146252. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  146253. default: if( xN == p->u.rValue ) return; break;
  146254. }
  146255. *peWithin = NOT_WITHIN;
  146256. }
  146257. /*
  146258. ** One of the cells in node pNode is guaranteed to have a 64-bit
  146259. ** integer value equal to iRowid. Return the index of this cell.
  146260. */
  146261. static int nodeRowidIndex(
  146262. Rtree *pRtree,
  146263. RtreeNode *pNode,
  146264. i64 iRowid,
  146265. int *piIndex
  146266. ){
  146267. int ii;
  146268. int nCell = NCELL(pNode);
  146269. assert( nCell<200 );
  146270. for(ii=0; ii<nCell; ii++){
  146271. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  146272. *piIndex = ii;
  146273. return SQLITE_OK;
  146274. }
  146275. }
  146276. return SQLITE_CORRUPT_VTAB;
  146277. }
  146278. /*
  146279. ** Return the index of the cell containing a pointer to node pNode
  146280. ** in its parent. If pNode is the root node, return -1.
  146281. */
  146282. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  146283. RtreeNode *pParent = pNode->pParent;
  146284. if( pParent ){
  146285. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  146286. }
  146287. *piIndex = -1;
  146288. return SQLITE_OK;
  146289. }
  146290. /*
  146291. ** Compare two search points. Return negative, zero, or positive if the first
  146292. ** is less than, equal to, or greater than the second.
  146293. **
  146294. ** The rScore is the primary key. Smaller rScore values come first.
  146295. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  146296. ** iLevel values coming first. In this way, if rScore is the same for all
  146297. ** SearchPoints, then iLevel becomes the deciding factor and the result
  146298. ** is a depth-first search, which is the desired default behavior.
  146299. */
  146300. static int rtreeSearchPointCompare(
  146301. const RtreeSearchPoint *pA,
  146302. const RtreeSearchPoint *pB
  146303. ){
  146304. if( pA->rScore<pB->rScore ) return -1;
  146305. if( pA->rScore>pB->rScore ) return +1;
  146306. if( pA->iLevel<pB->iLevel ) return -1;
  146307. if( pA->iLevel>pB->iLevel ) return +1;
  146308. return 0;
  146309. }
  146310. /*
  146311. ** Interchange to search points in a cursor.
  146312. */
  146313. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  146314. RtreeSearchPoint t = p->aPoint[i];
  146315. assert( i<j );
  146316. p->aPoint[i] = p->aPoint[j];
  146317. p->aPoint[j] = t;
  146318. i++; j++;
  146319. if( i<RTREE_CACHE_SZ ){
  146320. if( j>=RTREE_CACHE_SZ ){
  146321. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  146322. p->aNode[i] = 0;
  146323. }else{
  146324. RtreeNode *pTemp = p->aNode[i];
  146325. p->aNode[i] = p->aNode[j];
  146326. p->aNode[j] = pTemp;
  146327. }
  146328. }
  146329. }
  146330. /*
  146331. ** Return the search point with the lowest current score.
  146332. */
  146333. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  146334. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  146335. }
  146336. /*
  146337. ** Get the RtreeNode for the search point with the lowest score.
  146338. */
  146339. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  146340. sqlite3_int64 id;
  146341. int ii = 1 - pCur->bPoint;
  146342. assert( ii==0 || ii==1 );
  146343. assert( pCur->bPoint || pCur->nPoint );
  146344. if( pCur->aNode[ii]==0 ){
  146345. assert( pRC!=0 );
  146346. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  146347. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  146348. }
  146349. return pCur->aNode[ii];
  146350. }
  146351. /*
  146352. ** Push a new element onto the priority queue
  146353. */
  146354. static RtreeSearchPoint *rtreeEnqueue(
  146355. RtreeCursor *pCur, /* The cursor */
  146356. RtreeDValue rScore, /* Score for the new search point */
  146357. u8 iLevel /* Level for the new search point */
  146358. ){
  146359. int i, j;
  146360. RtreeSearchPoint *pNew;
  146361. if( pCur->nPoint>=pCur->nPointAlloc ){
  146362. int nNew = pCur->nPointAlloc*2 + 8;
  146363. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  146364. if( pNew==0 ) return 0;
  146365. pCur->aPoint = pNew;
  146366. pCur->nPointAlloc = nNew;
  146367. }
  146368. i = pCur->nPoint++;
  146369. pNew = pCur->aPoint + i;
  146370. pNew->rScore = rScore;
  146371. pNew->iLevel = iLevel;
  146372. assert( iLevel<=RTREE_MAX_DEPTH );
  146373. while( i>0 ){
  146374. RtreeSearchPoint *pParent;
  146375. j = (i-1)/2;
  146376. pParent = pCur->aPoint + j;
  146377. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  146378. rtreeSearchPointSwap(pCur, j, i);
  146379. i = j;
  146380. pNew = pParent;
  146381. }
  146382. return pNew;
  146383. }
  146384. /*
  146385. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  146386. ** NULL if malloc fails.
  146387. */
  146388. static RtreeSearchPoint *rtreeSearchPointNew(
  146389. RtreeCursor *pCur, /* The cursor */
  146390. RtreeDValue rScore, /* Score for the new search point */
  146391. u8 iLevel /* Level for the new search point */
  146392. ){
  146393. RtreeSearchPoint *pNew, *pFirst;
  146394. pFirst = rtreeSearchPointFirst(pCur);
  146395. pCur->anQueue[iLevel]++;
  146396. if( pFirst==0
  146397. || pFirst->rScore>rScore
  146398. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  146399. ){
  146400. if( pCur->bPoint ){
  146401. int ii;
  146402. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  146403. if( pNew==0 ) return 0;
  146404. ii = (int)(pNew - pCur->aPoint) + 1;
  146405. if( ii<RTREE_CACHE_SZ ){
  146406. assert( pCur->aNode[ii]==0 );
  146407. pCur->aNode[ii] = pCur->aNode[0];
  146408. }else{
  146409. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  146410. }
  146411. pCur->aNode[0] = 0;
  146412. *pNew = pCur->sPoint;
  146413. }
  146414. pCur->sPoint.rScore = rScore;
  146415. pCur->sPoint.iLevel = iLevel;
  146416. pCur->bPoint = 1;
  146417. return &pCur->sPoint;
  146418. }else{
  146419. return rtreeEnqueue(pCur, rScore, iLevel);
  146420. }
  146421. }
  146422. #if 0
  146423. /* Tracing routines for the RtreeSearchPoint queue */
  146424. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  146425. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  146426. printf(" %d.%05lld.%02d %g %d",
  146427. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  146428. );
  146429. idx++;
  146430. if( idx<RTREE_CACHE_SZ ){
  146431. printf(" %p\n", pCur->aNode[idx]);
  146432. }else{
  146433. printf("\n");
  146434. }
  146435. }
  146436. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  146437. int ii;
  146438. printf("=== %9s ", zPrefix);
  146439. if( pCur->bPoint ){
  146440. tracePoint(&pCur->sPoint, -1, pCur);
  146441. }
  146442. for(ii=0; ii<pCur->nPoint; ii++){
  146443. if( ii>0 || pCur->bPoint ) printf(" ");
  146444. tracePoint(&pCur->aPoint[ii], ii, pCur);
  146445. }
  146446. }
  146447. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  146448. #else
  146449. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  146450. #endif
  146451. /* Remove the search point with the lowest current score.
  146452. */
  146453. static void rtreeSearchPointPop(RtreeCursor *p){
  146454. int i, j, k, n;
  146455. i = 1 - p->bPoint;
  146456. assert( i==0 || i==1 );
  146457. if( p->aNode[i] ){
  146458. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  146459. p->aNode[i] = 0;
  146460. }
  146461. if( p->bPoint ){
  146462. p->anQueue[p->sPoint.iLevel]--;
  146463. p->bPoint = 0;
  146464. }else if( p->nPoint ){
  146465. p->anQueue[p->aPoint[0].iLevel]--;
  146466. n = --p->nPoint;
  146467. p->aPoint[0] = p->aPoint[n];
  146468. if( n<RTREE_CACHE_SZ-1 ){
  146469. p->aNode[1] = p->aNode[n+1];
  146470. p->aNode[n+1] = 0;
  146471. }
  146472. i = 0;
  146473. while( (j = i*2+1)<n ){
  146474. k = j+1;
  146475. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  146476. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  146477. rtreeSearchPointSwap(p, i, k);
  146478. i = k;
  146479. }else{
  146480. break;
  146481. }
  146482. }else{
  146483. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  146484. rtreeSearchPointSwap(p, i, j);
  146485. i = j;
  146486. }else{
  146487. break;
  146488. }
  146489. }
  146490. }
  146491. }
  146492. }
  146493. /*
  146494. ** Continue the search on cursor pCur until the front of the queue
  146495. ** contains an entry suitable for returning as a result-set row,
  146496. ** or until the RtreeSearchPoint queue is empty, indicating that the
  146497. ** query has completed.
  146498. */
  146499. static int rtreeStepToLeaf(RtreeCursor *pCur){
  146500. RtreeSearchPoint *p;
  146501. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  146502. RtreeNode *pNode;
  146503. int eWithin;
  146504. int rc = SQLITE_OK;
  146505. int nCell;
  146506. int nConstraint = pCur->nConstraint;
  146507. int ii;
  146508. int eInt;
  146509. RtreeSearchPoint x;
  146510. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  146511. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  146512. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  146513. if( rc ) return rc;
  146514. nCell = NCELL(pNode);
  146515. assert( nCell<200 );
  146516. while( p->iCell<nCell ){
  146517. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  146518. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  146519. eWithin = FULLY_WITHIN;
  146520. for(ii=0; ii<nConstraint; ii++){
  146521. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  146522. if( pConstraint->op>=RTREE_MATCH ){
  146523. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  146524. &rScore, &eWithin);
  146525. if( rc ) return rc;
  146526. }else if( p->iLevel==1 ){
  146527. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  146528. }else{
  146529. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  146530. }
  146531. if( eWithin==NOT_WITHIN ) break;
  146532. }
  146533. p->iCell++;
  146534. if( eWithin==NOT_WITHIN ) continue;
  146535. x.iLevel = p->iLevel - 1;
  146536. if( x.iLevel ){
  146537. x.id = readInt64(pCellData);
  146538. x.iCell = 0;
  146539. }else{
  146540. x.id = p->id;
  146541. x.iCell = p->iCell - 1;
  146542. }
  146543. if( p->iCell>=nCell ){
  146544. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  146545. rtreeSearchPointPop(pCur);
  146546. }
  146547. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  146548. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  146549. if( p==0 ) return SQLITE_NOMEM;
  146550. p->eWithin = eWithin;
  146551. p->id = x.id;
  146552. p->iCell = x.iCell;
  146553. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  146554. break;
  146555. }
  146556. if( p->iCell>=nCell ){
  146557. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  146558. rtreeSearchPointPop(pCur);
  146559. }
  146560. }
  146561. pCur->atEOF = p==0;
  146562. return SQLITE_OK;
  146563. }
  146564. /*
  146565. ** Rtree virtual table module xNext method.
  146566. */
  146567. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  146568. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  146569. int rc = SQLITE_OK;
  146570. /* Move to the next entry that matches the configured constraints. */
  146571. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  146572. rtreeSearchPointPop(pCsr);
  146573. rc = rtreeStepToLeaf(pCsr);
  146574. return rc;
  146575. }
  146576. /*
  146577. ** Rtree virtual table module xRowid method.
  146578. */
  146579. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  146580. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  146581. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  146582. int rc = SQLITE_OK;
  146583. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  146584. if( rc==SQLITE_OK && p ){
  146585. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  146586. }
  146587. return rc;
  146588. }
  146589. /*
  146590. ** Rtree virtual table module xColumn method.
  146591. */
  146592. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  146593. Rtree *pRtree = (Rtree *)cur->pVtab;
  146594. RtreeCursor *pCsr = (RtreeCursor *)cur;
  146595. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  146596. RtreeCoord c;
  146597. int rc = SQLITE_OK;
  146598. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  146599. if( rc ) return rc;
  146600. if( p==0 ) return SQLITE_OK;
  146601. if( i==0 ){
  146602. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  146603. }else{
  146604. if( rc ) return rc;
  146605. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  146606. #ifndef SQLITE_RTREE_INT_ONLY
  146607. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  146608. sqlite3_result_double(ctx, c.f);
  146609. }else
  146610. #endif
  146611. {
  146612. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  146613. sqlite3_result_int(ctx, c.i);
  146614. }
  146615. }
  146616. return SQLITE_OK;
  146617. }
  146618. /*
  146619. ** Use nodeAcquire() to obtain the leaf node containing the record with
  146620. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  146621. ** return SQLITE_OK. If there is no such record in the table, set
  146622. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  146623. ** to zero and return an SQLite error code.
  146624. */
  146625. static int findLeafNode(
  146626. Rtree *pRtree, /* RTree to search */
  146627. i64 iRowid, /* The rowid searching for */
  146628. RtreeNode **ppLeaf, /* Write the node here */
  146629. sqlite3_int64 *piNode /* Write the node-id here */
  146630. ){
  146631. int rc;
  146632. *ppLeaf = 0;
  146633. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  146634. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  146635. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  146636. if( piNode ) *piNode = iNode;
  146637. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  146638. sqlite3_reset(pRtree->pReadRowid);
  146639. }else{
  146640. rc = sqlite3_reset(pRtree->pReadRowid);
  146641. }
  146642. return rc;
  146643. }
  146644. /*
  146645. ** This function is called to configure the RtreeConstraint object passed
  146646. ** as the second argument for a MATCH constraint. The value passed as the
  146647. ** first argument to this function is the right-hand operand to the MATCH
  146648. ** operator.
  146649. */
  146650. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  146651. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  146652. sqlite3_rtree_query_info *pInfo; /* Callback information */
  146653. int nBlob; /* Size of the geometry function blob */
  146654. int nExpected; /* Expected size of the BLOB */
  146655. /* Check that value is actually a blob. */
  146656. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  146657. /* Check that the blob is roughly the right size. */
  146658. nBlob = sqlite3_value_bytes(pValue);
  146659. if( nBlob<(int)sizeof(RtreeMatchArg) ){
  146660. return SQLITE_ERROR;
  146661. }
  146662. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  146663. if( !pInfo ) return SQLITE_NOMEM;
  146664. memset(pInfo, 0, sizeof(*pInfo));
  146665. pBlob = (RtreeMatchArg*)&pInfo[1];
  146666. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  146667. nExpected = (int)(sizeof(RtreeMatchArg) +
  146668. pBlob->nParam*sizeof(sqlite3_value*) +
  146669. (pBlob->nParam-1)*sizeof(RtreeDValue));
  146670. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  146671. sqlite3_free(pInfo);
  146672. return SQLITE_ERROR;
  146673. }
  146674. pInfo->pContext = pBlob->cb.pContext;
  146675. pInfo->nParam = pBlob->nParam;
  146676. pInfo->aParam = pBlob->aParam;
  146677. pInfo->apSqlParam = pBlob->apSqlParam;
  146678. if( pBlob->cb.xGeom ){
  146679. pCons->u.xGeom = pBlob->cb.xGeom;
  146680. }else{
  146681. pCons->op = RTREE_QUERY;
  146682. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  146683. }
  146684. pCons->pInfo = pInfo;
  146685. return SQLITE_OK;
  146686. }
  146687. /*
  146688. ** Rtree virtual table module xFilter method.
  146689. */
  146690. static int rtreeFilter(
  146691. sqlite3_vtab_cursor *pVtabCursor,
  146692. int idxNum, const char *idxStr,
  146693. int argc, sqlite3_value **argv
  146694. ){
  146695. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  146696. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  146697. RtreeNode *pRoot = 0;
  146698. int ii;
  146699. int rc = SQLITE_OK;
  146700. int iCell = 0;
  146701. rtreeReference(pRtree);
  146702. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  146703. freeCursorConstraints(pCsr);
  146704. sqlite3_free(pCsr->aPoint);
  146705. memset(pCsr, 0, sizeof(RtreeCursor));
  146706. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  146707. pCsr->iStrategy = idxNum;
  146708. if( idxNum==1 ){
  146709. /* Special case - lookup by rowid. */
  146710. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  146711. RtreeSearchPoint *p; /* Search point for the the leaf */
  146712. i64 iRowid = sqlite3_value_int64(argv[0]);
  146713. i64 iNode = 0;
  146714. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  146715. if( rc==SQLITE_OK && pLeaf!=0 ){
  146716. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  146717. assert( p!=0 ); /* Always returns pCsr->sPoint */
  146718. pCsr->aNode[0] = pLeaf;
  146719. p->id = iNode;
  146720. p->eWithin = PARTLY_WITHIN;
  146721. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  146722. p->iCell = iCell;
  146723. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  146724. }else{
  146725. pCsr->atEOF = 1;
  146726. }
  146727. }else{
  146728. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  146729. ** with the configured constraints.
  146730. */
  146731. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  146732. if( rc==SQLITE_OK && argc>0 ){
  146733. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  146734. pCsr->nConstraint = argc;
  146735. if( !pCsr->aConstraint ){
  146736. rc = SQLITE_NOMEM;
  146737. }else{
  146738. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  146739. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  146740. assert( (idxStr==0 && argc==0)
  146741. || (idxStr && (int)strlen(idxStr)==argc*2) );
  146742. for(ii=0; ii<argc; ii++){
  146743. RtreeConstraint *p = &pCsr->aConstraint[ii];
  146744. p->op = idxStr[ii*2];
  146745. p->iCoord = idxStr[ii*2+1]-'0';
  146746. if( p->op>=RTREE_MATCH ){
  146747. /* A MATCH operator. The right-hand-side must be a blob that
  146748. ** can be cast into an RtreeMatchArg object. One created using
  146749. ** an sqlite3_rtree_geometry_callback() SQL user function.
  146750. */
  146751. rc = deserializeGeometry(argv[ii], p);
  146752. if( rc!=SQLITE_OK ){
  146753. break;
  146754. }
  146755. p->pInfo->nCoord = pRtree->nDim*2;
  146756. p->pInfo->anQueue = pCsr->anQueue;
  146757. p->pInfo->mxLevel = pRtree->iDepth + 1;
  146758. }else{
  146759. #ifdef SQLITE_RTREE_INT_ONLY
  146760. p->u.rValue = sqlite3_value_int64(argv[ii]);
  146761. #else
  146762. p->u.rValue = sqlite3_value_double(argv[ii]);
  146763. #endif
  146764. }
  146765. }
  146766. }
  146767. }
  146768. if( rc==SQLITE_OK ){
  146769. RtreeSearchPoint *pNew;
  146770. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
  146771. if( pNew==0 ) return SQLITE_NOMEM;
  146772. pNew->id = 1;
  146773. pNew->iCell = 0;
  146774. pNew->eWithin = PARTLY_WITHIN;
  146775. assert( pCsr->bPoint==1 );
  146776. pCsr->aNode[0] = pRoot;
  146777. pRoot = 0;
  146778. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  146779. rc = rtreeStepToLeaf(pCsr);
  146780. }
  146781. }
  146782. nodeRelease(pRtree, pRoot);
  146783. rtreeRelease(pRtree);
  146784. return rc;
  146785. }
  146786. /*
  146787. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  146788. ** extension is currently being used by a version of SQLite too old to
  146789. ** support estimatedRows. In that case this function is a no-op.
  146790. */
  146791. static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  146792. #if SQLITE_VERSION_NUMBER>=3008002
  146793. if( sqlite3_libversion_number()>=3008002 ){
  146794. pIdxInfo->estimatedRows = nRow;
  146795. }
  146796. #endif
  146797. }
  146798. /*
  146799. ** Rtree virtual table module xBestIndex method. There are three
  146800. ** table scan strategies to choose from (in order from most to
  146801. ** least desirable):
  146802. **
  146803. ** idxNum idxStr Strategy
  146804. ** ------------------------------------------------
  146805. ** 1 Unused Direct lookup by rowid.
  146806. ** 2 See below R-tree query or full-table scan.
  146807. ** ------------------------------------------------
  146808. **
  146809. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  146810. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  146811. ** constraint used. The first two bytes of idxStr correspond to
  146812. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  146813. ** (argvIndex==1) etc.
  146814. **
  146815. ** The first of each pair of bytes in idxStr identifies the constraint
  146816. ** operator as follows:
  146817. **
  146818. ** Operator Byte Value
  146819. ** ----------------------
  146820. ** = 0x41 ('A')
  146821. ** <= 0x42 ('B')
  146822. ** < 0x43 ('C')
  146823. ** >= 0x44 ('D')
  146824. ** > 0x45 ('E')
  146825. ** MATCH 0x46 ('F')
  146826. ** ----------------------
  146827. **
  146828. ** The second of each pair of bytes identifies the coordinate column
  146829. ** to which the constraint applies. The leftmost coordinate column
  146830. ** is 'a', the second from the left 'b' etc.
  146831. */
  146832. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  146833. Rtree *pRtree = (Rtree*)tab;
  146834. int rc = SQLITE_OK;
  146835. int ii;
  146836. int bMatch = 0; /* True if there exists a MATCH constraint */
  146837. i64 nRow; /* Estimated rows returned by this scan */
  146838. int iIdx = 0;
  146839. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  146840. memset(zIdxStr, 0, sizeof(zIdxStr));
  146841. /* Check if there exists a MATCH constraint - even an unusable one. If there
  146842. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  146843. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  146844. ** possible. */
  146845. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  146846. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  146847. bMatch = 1;
  146848. }
  146849. }
  146850. assert( pIdxInfo->idxStr==0 );
  146851. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  146852. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  146853. if( bMatch==0 && p->usable
  146854. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  146855. ){
  146856. /* We have an equality constraint on the rowid. Use strategy 1. */
  146857. int jj;
  146858. for(jj=0; jj<ii; jj++){
  146859. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  146860. pIdxInfo->aConstraintUsage[jj].omit = 0;
  146861. }
  146862. pIdxInfo->idxNum = 1;
  146863. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  146864. pIdxInfo->aConstraintUsage[jj].omit = 1;
  146865. /* This strategy involves a two rowid lookups on an B-Tree structures
  146866. ** and then a linear search of an R-Tree node. This should be
  146867. ** considered almost as quick as a direct rowid lookup (for which
  146868. ** sqlite uses an internal cost of 0.0). It is expected to return
  146869. ** a single row.
  146870. */
  146871. pIdxInfo->estimatedCost = 30.0;
  146872. setEstimatedRows(pIdxInfo, 1);
  146873. return SQLITE_OK;
  146874. }
  146875. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  146876. u8 op;
  146877. switch( p->op ){
  146878. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  146879. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  146880. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  146881. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  146882. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  146883. default:
  146884. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  146885. op = RTREE_MATCH;
  146886. break;
  146887. }
  146888. zIdxStr[iIdx++] = op;
  146889. zIdxStr[iIdx++] = p->iColumn - 1 + '0';
  146890. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  146891. pIdxInfo->aConstraintUsage[ii].omit = 1;
  146892. }
  146893. }
  146894. pIdxInfo->idxNum = 2;
  146895. pIdxInfo->needToFreeIdxStr = 1;
  146896. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  146897. return SQLITE_NOMEM;
  146898. }
  146899. nRow = pRtree->nRowEst / (iIdx + 1);
  146900. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  146901. setEstimatedRows(pIdxInfo, nRow);
  146902. return rc;
  146903. }
  146904. /*
  146905. ** Return the N-dimensional volumn of the cell stored in *p.
  146906. */
  146907. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  146908. RtreeDValue area = (RtreeDValue)1;
  146909. int ii;
  146910. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  146911. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  146912. }
  146913. return area;
  146914. }
  146915. /*
  146916. ** Return the margin length of cell p. The margin length is the sum
  146917. ** of the objects size in each dimension.
  146918. */
  146919. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  146920. RtreeDValue margin = (RtreeDValue)0;
  146921. int ii;
  146922. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  146923. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  146924. }
  146925. return margin;
  146926. }
  146927. /*
  146928. ** Store the union of cells p1 and p2 in p1.
  146929. */
  146930. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  146931. int ii;
  146932. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  146933. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  146934. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  146935. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  146936. }
  146937. }else{
  146938. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  146939. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  146940. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  146941. }
  146942. }
  146943. }
  146944. /*
  146945. ** Return true if the area covered by p2 is a subset of the area covered
  146946. ** by p1. False otherwise.
  146947. */
  146948. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  146949. int ii;
  146950. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  146951. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  146952. RtreeCoord *a1 = &p1->aCoord[ii];
  146953. RtreeCoord *a2 = &p2->aCoord[ii];
  146954. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  146955. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  146956. ){
  146957. return 0;
  146958. }
  146959. }
  146960. return 1;
  146961. }
  146962. /*
  146963. ** Return the amount cell p would grow by if it were unioned with pCell.
  146964. */
  146965. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  146966. RtreeDValue area;
  146967. RtreeCell cell;
  146968. memcpy(&cell, p, sizeof(RtreeCell));
  146969. area = cellArea(pRtree, &cell);
  146970. cellUnion(pRtree, &cell, pCell);
  146971. return (cellArea(pRtree, &cell)-area);
  146972. }
  146973. static RtreeDValue cellOverlap(
  146974. Rtree *pRtree,
  146975. RtreeCell *p,
  146976. RtreeCell *aCell,
  146977. int nCell
  146978. ){
  146979. int ii;
  146980. RtreeDValue overlap = RTREE_ZERO;
  146981. for(ii=0; ii<nCell; ii++){
  146982. int jj;
  146983. RtreeDValue o = (RtreeDValue)1;
  146984. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  146985. RtreeDValue x1, x2;
  146986. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  146987. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  146988. if( x2<x1 ){
  146989. o = (RtreeDValue)0;
  146990. break;
  146991. }else{
  146992. o = o * (x2-x1);
  146993. }
  146994. }
  146995. overlap += o;
  146996. }
  146997. return overlap;
  146998. }
  146999. /*
  147000. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  147001. ** ChooseSubTree in r*tree terminology.
  147002. */
  147003. static int ChooseLeaf(
  147004. Rtree *pRtree, /* Rtree table */
  147005. RtreeCell *pCell, /* Cell to insert into rtree */
  147006. int iHeight, /* Height of sub-tree rooted at pCell */
  147007. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  147008. ){
  147009. int rc;
  147010. int ii;
  147011. RtreeNode *pNode;
  147012. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  147013. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  147014. int iCell;
  147015. sqlite3_int64 iBest = 0;
  147016. RtreeDValue fMinGrowth = RTREE_ZERO;
  147017. RtreeDValue fMinArea = RTREE_ZERO;
  147018. int nCell = NCELL(pNode);
  147019. RtreeCell cell;
  147020. RtreeNode *pChild;
  147021. RtreeCell *aCell = 0;
  147022. /* Select the child node which will be enlarged the least if pCell
  147023. ** is inserted into it. Resolve ties by choosing the entry with
  147024. ** the smallest area.
  147025. */
  147026. for(iCell=0; iCell<nCell; iCell++){
  147027. int bBest = 0;
  147028. RtreeDValue growth;
  147029. RtreeDValue area;
  147030. nodeGetCell(pRtree, pNode, iCell, &cell);
  147031. growth = cellGrowth(pRtree, &cell, pCell);
  147032. area = cellArea(pRtree, &cell);
  147033. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  147034. bBest = 1;
  147035. }
  147036. if( bBest ){
  147037. fMinGrowth = growth;
  147038. fMinArea = area;
  147039. iBest = cell.iRowid;
  147040. }
  147041. }
  147042. sqlite3_free(aCell);
  147043. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  147044. nodeRelease(pRtree, pNode);
  147045. pNode = pChild;
  147046. }
  147047. *ppLeaf = pNode;
  147048. return rc;
  147049. }
  147050. /*
  147051. ** A cell with the same content as pCell has just been inserted into
  147052. ** the node pNode. This function updates the bounding box cells in
  147053. ** all ancestor elements.
  147054. */
  147055. static int AdjustTree(
  147056. Rtree *pRtree, /* Rtree table */
  147057. RtreeNode *pNode, /* Adjust ancestry of this node. */
  147058. RtreeCell *pCell /* This cell was just inserted */
  147059. ){
  147060. RtreeNode *p = pNode;
  147061. while( p->pParent ){
  147062. RtreeNode *pParent = p->pParent;
  147063. RtreeCell cell;
  147064. int iCell;
  147065. if( nodeParentIndex(pRtree, p, &iCell) ){
  147066. return SQLITE_CORRUPT_VTAB;
  147067. }
  147068. nodeGetCell(pRtree, pParent, iCell, &cell);
  147069. if( !cellContains(pRtree, &cell, pCell) ){
  147070. cellUnion(pRtree, &cell, pCell);
  147071. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  147072. }
  147073. p = pParent;
  147074. }
  147075. return SQLITE_OK;
  147076. }
  147077. /*
  147078. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  147079. */
  147080. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  147081. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  147082. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  147083. sqlite3_step(pRtree->pWriteRowid);
  147084. return sqlite3_reset(pRtree->pWriteRowid);
  147085. }
  147086. /*
  147087. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  147088. */
  147089. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  147090. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  147091. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  147092. sqlite3_step(pRtree->pWriteParent);
  147093. return sqlite3_reset(pRtree->pWriteParent);
  147094. }
  147095. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  147096. /*
  147097. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  147098. ** nIdx. The aIdx array contains the set of integers from 0 to
  147099. ** (nIdx-1) in no particular order. This function sorts the values
  147100. ** in aIdx according to the indexed values in aDistance. For
  147101. ** example, assuming the inputs:
  147102. **
  147103. ** aIdx = { 0, 1, 2, 3 }
  147104. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  147105. **
  147106. ** this function sets the aIdx array to contain:
  147107. **
  147108. ** aIdx = { 0, 1, 2, 3 }
  147109. **
  147110. ** The aSpare array is used as temporary working space by the
  147111. ** sorting algorithm.
  147112. */
  147113. static void SortByDistance(
  147114. int *aIdx,
  147115. int nIdx,
  147116. RtreeDValue *aDistance,
  147117. int *aSpare
  147118. ){
  147119. if( nIdx>1 ){
  147120. int iLeft = 0;
  147121. int iRight = 0;
  147122. int nLeft = nIdx/2;
  147123. int nRight = nIdx-nLeft;
  147124. int *aLeft = aIdx;
  147125. int *aRight = &aIdx[nLeft];
  147126. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  147127. SortByDistance(aRight, nRight, aDistance, aSpare);
  147128. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  147129. aLeft = aSpare;
  147130. while( iLeft<nLeft || iRight<nRight ){
  147131. if( iLeft==nLeft ){
  147132. aIdx[iLeft+iRight] = aRight[iRight];
  147133. iRight++;
  147134. }else if( iRight==nRight ){
  147135. aIdx[iLeft+iRight] = aLeft[iLeft];
  147136. iLeft++;
  147137. }else{
  147138. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  147139. RtreeDValue fRight = aDistance[aRight[iRight]];
  147140. if( fLeft<fRight ){
  147141. aIdx[iLeft+iRight] = aLeft[iLeft];
  147142. iLeft++;
  147143. }else{
  147144. aIdx[iLeft+iRight] = aRight[iRight];
  147145. iRight++;
  147146. }
  147147. }
  147148. }
  147149. #if 0
  147150. /* Check that the sort worked */
  147151. {
  147152. int jj;
  147153. for(jj=1; jj<nIdx; jj++){
  147154. RtreeDValue left = aDistance[aIdx[jj-1]];
  147155. RtreeDValue right = aDistance[aIdx[jj]];
  147156. assert( left<=right );
  147157. }
  147158. }
  147159. #endif
  147160. }
  147161. }
  147162. /*
  147163. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  147164. ** nIdx. The aIdx array contains the set of integers from 0 to
  147165. ** (nIdx-1) in no particular order. This function sorts the values
  147166. ** in aIdx according to dimension iDim of the cells in aCell. The
  147167. ** minimum value of dimension iDim is considered first, the
  147168. ** maximum used to break ties.
  147169. **
  147170. ** The aSpare array is used as temporary working space by the
  147171. ** sorting algorithm.
  147172. */
  147173. static void SortByDimension(
  147174. Rtree *pRtree,
  147175. int *aIdx,
  147176. int nIdx,
  147177. int iDim,
  147178. RtreeCell *aCell,
  147179. int *aSpare
  147180. ){
  147181. if( nIdx>1 ){
  147182. int iLeft = 0;
  147183. int iRight = 0;
  147184. int nLeft = nIdx/2;
  147185. int nRight = nIdx-nLeft;
  147186. int *aLeft = aIdx;
  147187. int *aRight = &aIdx[nLeft];
  147188. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  147189. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  147190. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  147191. aLeft = aSpare;
  147192. while( iLeft<nLeft || iRight<nRight ){
  147193. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  147194. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  147195. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  147196. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  147197. if( (iLeft!=nLeft) && ((iRight==nRight)
  147198. || (xleft1<xright1)
  147199. || (xleft1==xright1 && xleft2<xright2)
  147200. )){
  147201. aIdx[iLeft+iRight] = aLeft[iLeft];
  147202. iLeft++;
  147203. }else{
  147204. aIdx[iLeft+iRight] = aRight[iRight];
  147205. iRight++;
  147206. }
  147207. }
  147208. #if 0
  147209. /* Check that the sort worked */
  147210. {
  147211. int jj;
  147212. for(jj=1; jj<nIdx; jj++){
  147213. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  147214. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  147215. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  147216. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  147217. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  147218. }
  147219. }
  147220. #endif
  147221. }
  147222. }
  147223. /*
  147224. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  147225. */
  147226. static int splitNodeStartree(
  147227. Rtree *pRtree,
  147228. RtreeCell *aCell,
  147229. int nCell,
  147230. RtreeNode *pLeft,
  147231. RtreeNode *pRight,
  147232. RtreeCell *pBboxLeft,
  147233. RtreeCell *pBboxRight
  147234. ){
  147235. int **aaSorted;
  147236. int *aSpare;
  147237. int ii;
  147238. int iBestDim = 0;
  147239. int iBestSplit = 0;
  147240. RtreeDValue fBestMargin = RTREE_ZERO;
  147241. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  147242. aaSorted = (int **)sqlite3_malloc(nByte);
  147243. if( !aaSorted ){
  147244. return SQLITE_NOMEM;
  147245. }
  147246. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  147247. memset(aaSorted, 0, nByte);
  147248. for(ii=0; ii<pRtree->nDim; ii++){
  147249. int jj;
  147250. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  147251. for(jj=0; jj<nCell; jj++){
  147252. aaSorted[ii][jj] = jj;
  147253. }
  147254. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  147255. }
  147256. for(ii=0; ii<pRtree->nDim; ii++){
  147257. RtreeDValue margin = RTREE_ZERO;
  147258. RtreeDValue fBestOverlap = RTREE_ZERO;
  147259. RtreeDValue fBestArea = RTREE_ZERO;
  147260. int iBestLeft = 0;
  147261. int nLeft;
  147262. for(
  147263. nLeft=RTREE_MINCELLS(pRtree);
  147264. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  147265. nLeft++
  147266. ){
  147267. RtreeCell left;
  147268. RtreeCell right;
  147269. int kk;
  147270. RtreeDValue overlap;
  147271. RtreeDValue area;
  147272. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  147273. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  147274. for(kk=1; kk<(nCell-1); kk++){
  147275. if( kk<nLeft ){
  147276. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  147277. }else{
  147278. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  147279. }
  147280. }
  147281. margin += cellMargin(pRtree, &left);
  147282. margin += cellMargin(pRtree, &right);
  147283. overlap = cellOverlap(pRtree, &left, &right, 1);
  147284. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  147285. if( (nLeft==RTREE_MINCELLS(pRtree))
  147286. || (overlap<fBestOverlap)
  147287. || (overlap==fBestOverlap && area<fBestArea)
  147288. ){
  147289. iBestLeft = nLeft;
  147290. fBestOverlap = overlap;
  147291. fBestArea = area;
  147292. }
  147293. }
  147294. if( ii==0 || margin<fBestMargin ){
  147295. iBestDim = ii;
  147296. fBestMargin = margin;
  147297. iBestSplit = iBestLeft;
  147298. }
  147299. }
  147300. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  147301. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  147302. for(ii=0; ii<nCell; ii++){
  147303. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  147304. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  147305. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  147306. nodeInsertCell(pRtree, pTarget, pCell);
  147307. cellUnion(pRtree, pBbox, pCell);
  147308. }
  147309. sqlite3_free(aaSorted);
  147310. return SQLITE_OK;
  147311. }
  147312. static int updateMapping(
  147313. Rtree *pRtree,
  147314. i64 iRowid,
  147315. RtreeNode *pNode,
  147316. int iHeight
  147317. ){
  147318. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  147319. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  147320. if( iHeight>0 ){
  147321. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  147322. if( pChild ){
  147323. nodeRelease(pRtree, pChild->pParent);
  147324. nodeReference(pNode);
  147325. pChild->pParent = pNode;
  147326. }
  147327. }
  147328. return xSetMapping(pRtree, iRowid, pNode->iNode);
  147329. }
  147330. static int SplitNode(
  147331. Rtree *pRtree,
  147332. RtreeNode *pNode,
  147333. RtreeCell *pCell,
  147334. int iHeight
  147335. ){
  147336. int i;
  147337. int newCellIsRight = 0;
  147338. int rc = SQLITE_OK;
  147339. int nCell = NCELL(pNode);
  147340. RtreeCell *aCell;
  147341. int *aiUsed;
  147342. RtreeNode *pLeft = 0;
  147343. RtreeNode *pRight = 0;
  147344. RtreeCell leftbbox;
  147345. RtreeCell rightbbox;
  147346. /* Allocate an array and populate it with a copy of pCell and
  147347. ** all cells from node pLeft. Then zero the original node.
  147348. */
  147349. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  147350. if( !aCell ){
  147351. rc = SQLITE_NOMEM;
  147352. goto splitnode_out;
  147353. }
  147354. aiUsed = (int *)&aCell[nCell+1];
  147355. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  147356. for(i=0; i<nCell; i++){
  147357. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  147358. }
  147359. nodeZero(pRtree, pNode);
  147360. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  147361. nCell++;
  147362. if( pNode->iNode==1 ){
  147363. pRight = nodeNew(pRtree, pNode);
  147364. pLeft = nodeNew(pRtree, pNode);
  147365. pRtree->iDepth++;
  147366. pNode->isDirty = 1;
  147367. writeInt16(pNode->zData, pRtree->iDepth);
  147368. }else{
  147369. pLeft = pNode;
  147370. pRight = nodeNew(pRtree, pLeft->pParent);
  147371. nodeReference(pLeft);
  147372. }
  147373. if( !pLeft || !pRight ){
  147374. rc = SQLITE_NOMEM;
  147375. goto splitnode_out;
  147376. }
  147377. memset(pLeft->zData, 0, pRtree->iNodeSize);
  147378. memset(pRight->zData, 0, pRtree->iNodeSize);
  147379. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  147380. &leftbbox, &rightbbox);
  147381. if( rc!=SQLITE_OK ){
  147382. goto splitnode_out;
  147383. }
  147384. /* Ensure both child nodes have node numbers assigned to them by calling
  147385. ** nodeWrite(). Node pRight always needs a node number, as it was created
  147386. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  147387. ** In this case avoid the all to nodeWrite().
  147388. */
  147389. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  147390. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  147391. ){
  147392. goto splitnode_out;
  147393. }
  147394. rightbbox.iRowid = pRight->iNode;
  147395. leftbbox.iRowid = pLeft->iNode;
  147396. if( pNode->iNode==1 ){
  147397. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  147398. if( rc!=SQLITE_OK ){
  147399. goto splitnode_out;
  147400. }
  147401. }else{
  147402. RtreeNode *pParent = pLeft->pParent;
  147403. int iCell;
  147404. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  147405. if( rc==SQLITE_OK ){
  147406. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  147407. rc = AdjustTree(pRtree, pParent, &leftbbox);
  147408. }
  147409. if( rc!=SQLITE_OK ){
  147410. goto splitnode_out;
  147411. }
  147412. }
  147413. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  147414. goto splitnode_out;
  147415. }
  147416. for(i=0; i<NCELL(pRight); i++){
  147417. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  147418. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  147419. if( iRowid==pCell->iRowid ){
  147420. newCellIsRight = 1;
  147421. }
  147422. if( rc!=SQLITE_OK ){
  147423. goto splitnode_out;
  147424. }
  147425. }
  147426. if( pNode->iNode==1 ){
  147427. for(i=0; i<NCELL(pLeft); i++){
  147428. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  147429. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  147430. if( rc!=SQLITE_OK ){
  147431. goto splitnode_out;
  147432. }
  147433. }
  147434. }else if( newCellIsRight==0 ){
  147435. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  147436. }
  147437. if( rc==SQLITE_OK ){
  147438. rc = nodeRelease(pRtree, pRight);
  147439. pRight = 0;
  147440. }
  147441. if( rc==SQLITE_OK ){
  147442. rc = nodeRelease(pRtree, pLeft);
  147443. pLeft = 0;
  147444. }
  147445. splitnode_out:
  147446. nodeRelease(pRtree, pRight);
  147447. nodeRelease(pRtree, pLeft);
  147448. sqlite3_free(aCell);
  147449. return rc;
  147450. }
  147451. /*
  147452. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  147453. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  147454. ** the pLeaf->pParent chain all the way up to the root node.
  147455. **
  147456. ** This operation is required when a row is deleted (or updated - an update
  147457. ** is implemented as a delete followed by an insert). SQLite provides the
  147458. ** rowid of the row to delete, which can be used to find the leaf on which
  147459. ** the entry resides (argument pLeaf). Once the leaf is located, this
  147460. ** function is called to determine its ancestry.
  147461. */
  147462. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  147463. int rc = SQLITE_OK;
  147464. RtreeNode *pChild = pLeaf;
  147465. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  147466. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  147467. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  147468. rc = sqlite3_step(pRtree->pReadParent);
  147469. if( rc==SQLITE_ROW ){
  147470. RtreeNode *pTest; /* Used to test for reference loops */
  147471. i64 iNode; /* Node number of parent node */
  147472. /* Before setting pChild->pParent, test that we are not creating a
  147473. ** loop of references (as we would if, say, pChild==pParent). We don't
  147474. ** want to do this as it leads to a memory leak when trying to delete
  147475. ** the referenced counted node structures.
  147476. */
  147477. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  147478. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  147479. if( !pTest ){
  147480. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  147481. }
  147482. }
  147483. rc = sqlite3_reset(pRtree->pReadParent);
  147484. if( rc==SQLITE_OK ) rc = rc2;
  147485. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  147486. pChild = pChild->pParent;
  147487. }
  147488. return rc;
  147489. }
  147490. static int deleteCell(Rtree *, RtreeNode *, int, int);
  147491. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  147492. int rc;
  147493. int rc2;
  147494. RtreeNode *pParent = 0;
  147495. int iCell;
  147496. assert( pNode->nRef==1 );
  147497. /* Remove the entry in the parent cell. */
  147498. rc = nodeParentIndex(pRtree, pNode, &iCell);
  147499. if( rc==SQLITE_OK ){
  147500. pParent = pNode->pParent;
  147501. pNode->pParent = 0;
  147502. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  147503. }
  147504. rc2 = nodeRelease(pRtree, pParent);
  147505. if( rc==SQLITE_OK ){
  147506. rc = rc2;
  147507. }
  147508. if( rc!=SQLITE_OK ){
  147509. return rc;
  147510. }
  147511. /* Remove the xxx_node entry. */
  147512. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  147513. sqlite3_step(pRtree->pDeleteNode);
  147514. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  147515. return rc;
  147516. }
  147517. /* Remove the xxx_parent entry. */
  147518. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  147519. sqlite3_step(pRtree->pDeleteParent);
  147520. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  147521. return rc;
  147522. }
  147523. /* Remove the node from the in-memory hash table and link it into
  147524. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  147525. */
  147526. nodeHashDelete(pRtree, pNode);
  147527. pNode->iNode = iHeight;
  147528. pNode->pNext = pRtree->pDeleted;
  147529. pNode->nRef++;
  147530. pRtree->pDeleted = pNode;
  147531. return SQLITE_OK;
  147532. }
  147533. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  147534. RtreeNode *pParent = pNode->pParent;
  147535. int rc = SQLITE_OK;
  147536. if( pParent ){
  147537. int ii;
  147538. int nCell = NCELL(pNode);
  147539. RtreeCell box; /* Bounding box for pNode */
  147540. nodeGetCell(pRtree, pNode, 0, &box);
  147541. for(ii=1; ii<nCell; ii++){
  147542. RtreeCell cell;
  147543. nodeGetCell(pRtree, pNode, ii, &cell);
  147544. cellUnion(pRtree, &box, &cell);
  147545. }
  147546. box.iRowid = pNode->iNode;
  147547. rc = nodeParentIndex(pRtree, pNode, &ii);
  147548. if( rc==SQLITE_OK ){
  147549. nodeOverwriteCell(pRtree, pParent, &box, ii);
  147550. rc = fixBoundingBox(pRtree, pParent);
  147551. }
  147552. }
  147553. return rc;
  147554. }
  147555. /*
  147556. ** Delete the cell at index iCell of node pNode. After removing the
  147557. ** cell, adjust the r-tree data structure if required.
  147558. */
  147559. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  147560. RtreeNode *pParent;
  147561. int rc;
  147562. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  147563. return rc;
  147564. }
  147565. /* Remove the cell from the node. This call just moves bytes around
  147566. ** the in-memory node image, so it cannot fail.
  147567. */
  147568. nodeDeleteCell(pRtree, pNode, iCell);
  147569. /* If the node is not the tree root and now has less than the minimum
  147570. ** number of cells, remove it from the tree. Otherwise, update the
  147571. ** cell in the parent node so that it tightly contains the updated
  147572. ** node.
  147573. */
  147574. pParent = pNode->pParent;
  147575. assert( pParent || pNode->iNode==1 );
  147576. if( pParent ){
  147577. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  147578. rc = removeNode(pRtree, pNode, iHeight);
  147579. }else{
  147580. rc = fixBoundingBox(pRtree, pNode);
  147581. }
  147582. }
  147583. return rc;
  147584. }
  147585. static int Reinsert(
  147586. Rtree *pRtree,
  147587. RtreeNode *pNode,
  147588. RtreeCell *pCell,
  147589. int iHeight
  147590. ){
  147591. int *aOrder;
  147592. int *aSpare;
  147593. RtreeCell *aCell;
  147594. RtreeDValue *aDistance;
  147595. int nCell;
  147596. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  147597. int iDim;
  147598. int ii;
  147599. int rc = SQLITE_OK;
  147600. int n;
  147601. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  147602. nCell = NCELL(pNode)+1;
  147603. n = (nCell+1)&(~1);
  147604. /* Allocate the buffers used by this operation. The allocation is
  147605. ** relinquished before this function returns.
  147606. */
  147607. aCell = (RtreeCell *)sqlite3_malloc(n * (
  147608. sizeof(RtreeCell) + /* aCell array */
  147609. sizeof(int) + /* aOrder array */
  147610. sizeof(int) + /* aSpare array */
  147611. sizeof(RtreeDValue) /* aDistance array */
  147612. ));
  147613. if( !aCell ){
  147614. return SQLITE_NOMEM;
  147615. }
  147616. aOrder = (int *)&aCell[n];
  147617. aSpare = (int *)&aOrder[n];
  147618. aDistance = (RtreeDValue *)&aSpare[n];
  147619. for(ii=0; ii<nCell; ii++){
  147620. if( ii==(nCell-1) ){
  147621. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  147622. }else{
  147623. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  147624. }
  147625. aOrder[ii] = ii;
  147626. for(iDim=0; iDim<pRtree->nDim; iDim++){
  147627. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  147628. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  147629. }
  147630. }
  147631. for(iDim=0; iDim<pRtree->nDim; iDim++){
  147632. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  147633. }
  147634. for(ii=0; ii<nCell; ii++){
  147635. aDistance[ii] = RTREE_ZERO;
  147636. for(iDim=0; iDim<pRtree->nDim; iDim++){
  147637. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  147638. DCOORD(aCell[ii].aCoord[iDim*2]));
  147639. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  147640. }
  147641. }
  147642. SortByDistance(aOrder, nCell, aDistance, aSpare);
  147643. nodeZero(pRtree, pNode);
  147644. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  147645. RtreeCell *p = &aCell[aOrder[ii]];
  147646. nodeInsertCell(pRtree, pNode, p);
  147647. if( p->iRowid==pCell->iRowid ){
  147648. if( iHeight==0 ){
  147649. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  147650. }else{
  147651. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  147652. }
  147653. }
  147654. }
  147655. if( rc==SQLITE_OK ){
  147656. rc = fixBoundingBox(pRtree, pNode);
  147657. }
  147658. for(; rc==SQLITE_OK && ii<nCell; ii++){
  147659. /* Find a node to store this cell in. pNode->iNode currently contains
  147660. ** the height of the sub-tree headed by the cell.
  147661. */
  147662. RtreeNode *pInsert;
  147663. RtreeCell *p = &aCell[aOrder[ii]];
  147664. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  147665. if( rc==SQLITE_OK ){
  147666. int rc2;
  147667. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  147668. rc2 = nodeRelease(pRtree, pInsert);
  147669. if( rc==SQLITE_OK ){
  147670. rc = rc2;
  147671. }
  147672. }
  147673. }
  147674. sqlite3_free(aCell);
  147675. return rc;
  147676. }
  147677. /*
  147678. ** Insert cell pCell into node pNode. Node pNode is the head of a
  147679. ** subtree iHeight high (leaf nodes have iHeight==0).
  147680. */
  147681. static int rtreeInsertCell(
  147682. Rtree *pRtree,
  147683. RtreeNode *pNode,
  147684. RtreeCell *pCell,
  147685. int iHeight
  147686. ){
  147687. int rc = SQLITE_OK;
  147688. if( iHeight>0 ){
  147689. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  147690. if( pChild ){
  147691. nodeRelease(pRtree, pChild->pParent);
  147692. nodeReference(pNode);
  147693. pChild->pParent = pNode;
  147694. }
  147695. }
  147696. if( nodeInsertCell(pRtree, pNode, pCell) ){
  147697. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  147698. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  147699. }else{
  147700. pRtree->iReinsertHeight = iHeight;
  147701. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  147702. }
  147703. }else{
  147704. rc = AdjustTree(pRtree, pNode, pCell);
  147705. if( rc==SQLITE_OK ){
  147706. if( iHeight==0 ){
  147707. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  147708. }else{
  147709. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  147710. }
  147711. }
  147712. }
  147713. return rc;
  147714. }
  147715. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  147716. int ii;
  147717. int rc = SQLITE_OK;
  147718. int nCell = NCELL(pNode);
  147719. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  147720. RtreeNode *pInsert;
  147721. RtreeCell cell;
  147722. nodeGetCell(pRtree, pNode, ii, &cell);
  147723. /* Find a node to store this cell in. pNode->iNode currently contains
  147724. ** the height of the sub-tree headed by the cell.
  147725. */
  147726. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  147727. if( rc==SQLITE_OK ){
  147728. int rc2;
  147729. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  147730. rc2 = nodeRelease(pRtree, pInsert);
  147731. if( rc==SQLITE_OK ){
  147732. rc = rc2;
  147733. }
  147734. }
  147735. }
  147736. return rc;
  147737. }
  147738. /*
  147739. ** Select a currently unused rowid for a new r-tree record.
  147740. */
  147741. static int newRowid(Rtree *pRtree, i64 *piRowid){
  147742. int rc;
  147743. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  147744. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  147745. sqlite3_step(pRtree->pWriteRowid);
  147746. rc = sqlite3_reset(pRtree->pWriteRowid);
  147747. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  147748. return rc;
  147749. }
  147750. /*
  147751. ** Remove the entry with rowid=iDelete from the r-tree structure.
  147752. */
  147753. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  147754. int rc; /* Return code */
  147755. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  147756. int iCell; /* Index of iDelete cell in pLeaf */
  147757. RtreeNode *pRoot; /* Root node of rtree structure */
  147758. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  147759. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  147760. /* Obtain a reference to the leaf node that contains the entry
  147761. ** about to be deleted.
  147762. */
  147763. if( rc==SQLITE_OK ){
  147764. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  147765. }
  147766. /* Delete the cell in question from the leaf node. */
  147767. if( rc==SQLITE_OK ){
  147768. int rc2;
  147769. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  147770. if( rc==SQLITE_OK ){
  147771. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  147772. }
  147773. rc2 = nodeRelease(pRtree, pLeaf);
  147774. if( rc==SQLITE_OK ){
  147775. rc = rc2;
  147776. }
  147777. }
  147778. /* Delete the corresponding entry in the <rtree>_rowid table. */
  147779. if( rc==SQLITE_OK ){
  147780. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  147781. sqlite3_step(pRtree->pDeleteRowid);
  147782. rc = sqlite3_reset(pRtree->pDeleteRowid);
  147783. }
  147784. /* Check if the root node now has exactly one child. If so, remove
  147785. ** it, schedule the contents of the child for reinsertion and
  147786. ** reduce the tree height by one.
  147787. **
  147788. ** This is equivalent to copying the contents of the child into
  147789. ** the root node (the operation that Gutman's paper says to perform
  147790. ** in this scenario).
  147791. */
  147792. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  147793. int rc2;
  147794. RtreeNode *pChild;
  147795. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  147796. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  147797. if( rc==SQLITE_OK ){
  147798. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  147799. }
  147800. rc2 = nodeRelease(pRtree, pChild);
  147801. if( rc==SQLITE_OK ) rc = rc2;
  147802. if( rc==SQLITE_OK ){
  147803. pRtree->iDepth--;
  147804. writeInt16(pRoot->zData, pRtree->iDepth);
  147805. pRoot->isDirty = 1;
  147806. }
  147807. }
  147808. /* Re-insert the contents of any underfull nodes removed from the tree. */
  147809. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  147810. if( rc==SQLITE_OK ){
  147811. rc = reinsertNodeContent(pRtree, pLeaf);
  147812. }
  147813. pRtree->pDeleted = pLeaf->pNext;
  147814. sqlite3_free(pLeaf);
  147815. }
  147816. /* Release the reference to the root node. */
  147817. if( rc==SQLITE_OK ){
  147818. rc = nodeRelease(pRtree, pRoot);
  147819. }else{
  147820. nodeRelease(pRtree, pRoot);
  147821. }
  147822. return rc;
  147823. }
  147824. /*
  147825. ** Rounding constants for float->double conversion.
  147826. */
  147827. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  147828. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  147829. #if !defined(SQLITE_RTREE_INT_ONLY)
  147830. /*
  147831. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  147832. ** while taking care to round toward negative or positive, respectively.
  147833. */
  147834. static RtreeValue rtreeValueDown(sqlite3_value *v){
  147835. double d = sqlite3_value_double(v);
  147836. float f = (float)d;
  147837. if( f>d ){
  147838. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  147839. }
  147840. return f;
  147841. }
  147842. static RtreeValue rtreeValueUp(sqlite3_value *v){
  147843. double d = sqlite3_value_double(v);
  147844. float f = (float)d;
  147845. if( f<d ){
  147846. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  147847. }
  147848. return f;
  147849. }
  147850. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  147851. /*
  147852. ** The xUpdate method for rtree module virtual tables.
  147853. */
  147854. static int rtreeUpdate(
  147855. sqlite3_vtab *pVtab,
  147856. int nData,
  147857. sqlite3_value **azData,
  147858. sqlite_int64 *pRowid
  147859. ){
  147860. Rtree *pRtree = (Rtree *)pVtab;
  147861. int rc = SQLITE_OK;
  147862. RtreeCell cell; /* New cell to insert if nData>1 */
  147863. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  147864. rtreeReference(pRtree);
  147865. assert(nData>=1);
  147866. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  147867. /* Constraint handling. A write operation on an r-tree table may return
  147868. ** SQLITE_CONSTRAINT for two reasons:
  147869. **
  147870. ** 1. A duplicate rowid value, or
  147871. ** 2. The supplied data violates the "x2>=x1" constraint.
  147872. **
  147873. ** In the first case, if the conflict-handling mode is REPLACE, then
  147874. ** the conflicting row can be removed before proceeding. In the second
  147875. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  147876. ** conflict-handling mode specified by the user.
  147877. */
  147878. if( nData>1 ){
  147879. int ii;
  147880. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  147881. **
  147882. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  147883. ** with "column" that are interpreted as table constraints.
  147884. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  147885. ** This problem was discovered after years of use, so we silently ignore
  147886. ** these kinds of misdeclared tables to avoid breaking any legacy.
  147887. */
  147888. assert( nData<=(pRtree->nDim*2 + 3) );
  147889. #ifndef SQLITE_RTREE_INT_ONLY
  147890. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  147891. for(ii=0; ii<nData-4; ii+=2){
  147892. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  147893. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  147894. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  147895. rc = SQLITE_CONSTRAINT;
  147896. goto constraint;
  147897. }
  147898. }
  147899. }else
  147900. #endif
  147901. {
  147902. for(ii=0; ii<nData-4; ii+=2){
  147903. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  147904. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  147905. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  147906. rc = SQLITE_CONSTRAINT;
  147907. goto constraint;
  147908. }
  147909. }
  147910. }
  147911. /* If a rowid value was supplied, check if it is already present in
  147912. ** the table. If so, the constraint has failed. */
  147913. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  147914. cell.iRowid = sqlite3_value_int64(azData[2]);
  147915. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  147916. || sqlite3_value_int64(azData[0])!=cell.iRowid
  147917. ){
  147918. int steprc;
  147919. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  147920. steprc = sqlite3_step(pRtree->pReadRowid);
  147921. rc = sqlite3_reset(pRtree->pReadRowid);
  147922. if( SQLITE_ROW==steprc ){
  147923. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  147924. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  147925. }else{
  147926. rc = SQLITE_CONSTRAINT;
  147927. goto constraint;
  147928. }
  147929. }
  147930. }
  147931. bHaveRowid = 1;
  147932. }
  147933. }
  147934. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  147935. ** record to delete from the r-tree table. The following block does
  147936. ** just that.
  147937. */
  147938. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  147939. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  147940. }
  147941. /* If the azData[] array contains more than one element, elements
  147942. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  147943. ** the r-tree structure.
  147944. */
  147945. if( rc==SQLITE_OK && nData>1 ){
  147946. /* Insert the new record into the r-tree */
  147947. RtreeNode *pLeaf = 0;
  147948. /* Figure out the rowid of the new row. */
  147949. if( bHaveRowid==0 ){
  147950. rc = newRowid(pRtree, &cell.iRowid);
  147951. }
  147952. *pRowid = cell.iRowid;
  147953. if( rc==SQLITE_OK ){
  147954. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  147955. }
  147956. if( rc==SQLITE_OK ){
  147957. int rc2;
  147958. pRtree->iReinsertHeight = -1;
  147959. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  147960. rc2 = nodeRelease(pRtree, pLeaf);
  147961. if( rc==SQLITE_OK ){
  147962. rc = rc2;
  147963. }
  147964. }
  147965. }
  147966. constraint:
  147967. rtreeRelease(pRtree);
  147968. return rc;
  147969. }
  147970. /*
  147971. ** The xRename method for rtree module virtual tables.
  147972. */
  147973. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  147974. Rtree *pRtree = (Rtree *)pVtab;
  147975. int rc = SQLITE_NOMEM;
  147976. char *zSql = sqlite3_mprintf(
  147977. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  147978. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  147979. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  147980. , pRtree->zDb, pRtree->zName, zNewName
  147981. , pRtree->zDb, pRtree->zName, zNewName
  147982. , pRtree->zDb, pRtree->zName, zNewName
  147983. );
  147984. if( zSql ){
  147985. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  147986. sqlite3_free(zSql);
  147987. }
  147988. return rc;
  147989. }
  147990. /*
  147991. ** This function populates the pRtree->nRowEst variable with an estimate
  147992. ** of the number of rows in the virtual table. If possible, this is based
  147993. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  147994. */
  147995. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  147996. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  147997. char *zSql;
  147998. sqlite3_stmt *p;
  147999. int rc;
  148000. i64 nRow = 0;
  148001. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  148002. if( zSql==0 ){
  148003. rc = SQLITE_NOMEM;
  148004. }else{
  148005. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  148006. if( rc==SQLITE_OK ){
  148007. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  148008. rc = sqlite3_finalize(p);
  148009. }else if( rc!=SQLITE_NOMEM ){
  148010. rc = SQLITE_OK;
  148011. }
  148012. if( rc==SQLITE_OK ){
  148013. if( nRow==0 ){
  148014. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  148015. }else{
  148016. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  148017. }
  148018. }
  148019. sqlite3_free(zSql);
  148020. }
  148021. return rc;
  148022. }
  148023. static sqlite3_module rtreeModule = {
  148024. 0, /* iVersion */
  148025. rtreeCreate, /* xCreate - create a table */
  148026. rtreeConnect, /* xConnect - connect to an existing table */
  148027. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  148028. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  148029. rtreeDestroy, /* xDestroy - Drop a table */
  148030. rtreeOpen, /* xOpen - open a cursor */
  148031. rtreeClose, /* xClose - close a cursor */
  148032. rtreeFilter, /* xFilter - configure scan constraints */
  148033. rtreeNext, /* xNext - advance a cursor */
  148034. rtreeEof, /* xEof */
  148035. rtreeColumn, /* xColumn - read data */
  148036. rtreeRowid, /* xRowid - read data */
  148037. rtreeUpdate, /* xUpdate - write data */
  148038. 0, /* xBegin - begin transaction */
  148039. 0, /* xSync - sync transaction */
  148040. 0, /* xCommit - commit transaction */
  148041. 0, /* xRollback - rollback transaction */
  148042. 0, /* xFindFunction - function overloading */
  148043. rtreeRename, /* xRename - rename the table */
  148044. 0, /* xSavepoint */
  148045. 0, /* xRelease */
  148046. 0 /* xRollbackTo */
  148047. };
  148048. static int rtreeSqlInit(
  148049. Rtree *pRtree,
  148050. sqlite3 *db,
  148051. const char *zDb,
  148052. const char *zPrefix,
  148053. int isCreate
  148054. ){
  148055. int rc = SQLITE_OK;
  148056. #define N_STATEMENT 9
  148057. static const char *azSql[N_STATEMENT] = {
  148058. /* Read and write the xxx_node table */
  148059. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  148060. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  148061. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  148062. /* Read and write the xxx_rowid table */
  148063. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  148064. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  148065. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  148066. /* Read and write the xxx_parent table */
  148067. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  148068. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  148069. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  148070. };
  148071. sqlite3_stmt **appStmt[N_STATEMENT];
  148072. int i;
  148073. pRtree->db = db;
  148074. if( isCreate ){
  148075. char *zCreate = sqlite3_mprintf(
  148076. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  148077. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  148078. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  148079. " parentnode INTEGER);"
  148080. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  148081. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  148082. );
  148083. if( !zCreate ){
  148084. return SQLITE_NOMEM;
  148085. }
  148086. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  148087. sqlite3_free(zCreate);
  148088. if( rc!=SQLITE_OK ){
  148089. return rc;
  148090. }
  148091. }
  148092. appStmt[0] = &pRtree->pReadNode;
  148093. appStmt[1] = &pRtree->pWriteNode;
  148094. appStmt[2] = &pRtree->pDeleteNode;
  148095. appStmt[3] = &pRtree->pReadRowid;
  148096. appStmt[4] = &pRtree->pWriteRowid;
  148097. appStmt[5] = &pRtree->pDeleteRowid;
  148098. appStmt[6] = &pRtree->pReadParent;
  148099. appStmt[7] = &pRtree->pWriteParent;
  148100. appStmt[8] = &pRtree->pDeleteParent;
  148101. rc = rtreeQueryStat1(db, pRtree);
  148102. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  148103. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  148104. if( zSql ){
  148105. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  148106. }else{
  148107. rc = SQLITE_NOMEM;
  148108. }
  148109. sqlite3_free(zSql);
  148110. }
  148111. return rc;
  148112. }
  148113. /*
  148114. ** The second argument to this function contains the text of an SQL statement
  148115. ** that returns a single integer value. The statement is compiled and executed
  148116. ** using database connection db. If successful, the integer value returned
  148117. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  148118. ** code is returned and the value of *piVal after returning is not defined.
  148119. */
  148120. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  148121. int rc = SQLITE_NOMEM;
  148122. if( zSql ){
  148123. sqlite3_stmt *pStmt = 0;
  148124. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  148125. if( rc==SQLITE_OK ){
  148126. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148127. *piVal = sqlite3_column_int(pStmt, 0);
  148128. }
  148129. rc = sqlite3_finalize(pStmt);
  148130. }
  148131. }
  148132. return rc;
  148133. }
  148134. /*
  148135. ** This function is called from within the xConnect() or xCreate() method to
  148136. ** determine the node-size used by the rtree table being created or connected
  148137. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  148138. ** Otherwise, an SQLite error code is returned.
  148139. **
  148140. ** If this function is being called as part of an xConnect(), then the rtree
  148141. ** table already exists. In this case the node-size is determined by inspecting
  148142. ** the root node of the tree.
  148143. **
  148144. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  148145. ** This ensures that each node is stored on a single database page. If the
  148146. ** database page-size is so large that more than RTREE_MAXCELLS entries
  148147. ** would fit in a single node, use a smaller node-size.
  148148. */
  148149. static int getNodeSize(
  148150. sqlite3 *db, /* Database handle */
  148151. Rtree *pRtree, /* Rtree handle */
  148152. int isCreate, /* True for xCreate, false for xConnect */
  148153. char **pzErr /* OUT: Error message, if any */
  148154. ){
  148155. int rc;
  148156. char *zSql;
  148157. if( isCreate ){
  148158. int iPageSize = 0;
  148159. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  148160. rc = getIntFromStmt(db, zSql, &iPageSize);
  148161. if( rc==SQLITE_OK ){
  148162. pRtree->iNodeSize = iPageSize-64;
  148163. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  148164. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  148165. }
  148166. }else{
  148167. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  148168. }
  148169. }else{
  148170. zSql = sqlite3_mprintf(
  148171. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  148172. pRtree->zDb, pRtree->zName
  148173. );
  148174. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  148175. if( rc!=SQLITE_OK ){
  148176. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  148177. }
  148178. }
  148179. sqlite3_free(zSql);
  148180. return rc;
  148181. }
  148182. /*
  148183. ** This function is the implementation of both the xConnect and xCreate
  148184. ** methods of the r-tree virtual table.
  148185. **
  148186. ** argv[0] -> module name
  148187. ** argv[1] -> database name
  148188. ** argv[2] -> table name
  148189. ** argv[...] -> column names...
  148190. */
  148191. static int rtreeInit(
  148192. sqlite3 *db, /* Database connection */
  148193. void *pAux, /* One of the RTREE_COORD_* constants */
  148194. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  148195. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  148196. char **pzErr, /* OUT: Error message, if any */
  148197. int isCreate /* True for xCreate, false for xConnect */
  148198. ){
  148199. int rc = SQLITE_OK;
  148200. Rtree *pRtree;
  148201. int nDb; /* Length of string argv[1] */
  148202. int nName; /* Length of string argv[2] */
  148203. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  148204. const char *aErrMsg[] = {
  148205. 0, /* 0 */
  148206. "Wrong number of columns for an rtree table", /* 1 */
  148207. "Too few columns for an rtree table", /* 2 */
  148208. "Too many columns for an rtree table" /* 3 */
  148209. };
  148210. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  148211. if( aErrMsg[iErr] ){
  148212. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  148213. return SQLITE_ERROR;
  148214. }
  148215. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  148216. /* Allocate the sqlite3_vtab structure */
  148217. nDb = (int)strlen(argv[1]);
  148218. nName = (int)strlen(argv[2]);
  148219. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  148220. if( !pRtree ){
  148221. return SQLITE_NOMEM;
  148222. }
  148223. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  148224. pRtree->nBusy = 1;
  148225. pRtree->base.pModule = &rtreeModule;
  148226. pRtree->zDb = (char *)&pRtree[1];
  148227. pRtree->zName = &pRtree->zDb[nDb+1];
  148228. pRtree->nDim = (argc-4)/2;
  148229. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  148230. pRtree->eCoordType = eCoordType;
  148231. memcpy(pRtree->zDb, argv[1], nDb);
  148232. memcpy(pRtree->zName, argv[2], nName);
  148233. /* Figure out the node size to use. */
  148234. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  148235. /* Create/Connect to the underlying relational database schema. If
  148236. ** that is successful, call sqlite3_declare_vtab() to configure
  148237. ** the r-tree table schema.
  148238. */
  148239. if( rc==SQLITE_OK ){
  148240. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  148241. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  148242. }else{
  148243. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  148244. char *zTmp;
  148245. int ii;
  148246. for(ii=4; zSql && ii<argc; ii++){
  148247. zTmp = zSql;
  148248. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  148249. sqlite3_free(zTmp);
  148250. }
  148251. if( zSql ){
  148252. zTmp = zSql;
  148253. zSql = sqlite3_mprintf("%s);", zTmp);
  148254. sqlite3_free(zTmp);
  148255. }
  148256. if( !zSql ){
  148257. rc = SQLITE_NOMEM;
  148258. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  148259. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  148260. }
  148261. sqlite3_free(zSql);
  148262. }
  148263. }
  148264. if( rc==SQLITE_OK ){
  148265. *ppVtab = (sqlite3_vtab *)pRtree;
  148266. }else{
  148267. assert( *ppVtab==0 );
  148268. assert( pRtree->nBusy==1 );
  148269. rtreeRelease(pRtree);
  148270. }
  148271. return rc;
  148272. }
  148273. /*
  148274. ** Implementation of a scalar function that decodes r-tree nodes to
  148275. ** human readable strings. This can be used for debugging and analysis.
  148276. **
  148277. ** The scalar function takes two arguments: (1) the number of dimensions
  148278. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  148279. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  148280. ** deserialize all nodes, a statement like:
  148281. **
  148282. ** SELECT rtreenode(2, data) FROM rt_node;
  148283. **
  148284. ** The human readable string takes the form of a Tcl list with one
  148285. ** entry for each cell in the r-tree node. Each entry is itself a
  148286. ** list, containing the 8-byte rowid/pageno followed by the
  148287. ** <num-dimension>*2 coordinates.
  148288. */
  148289. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  148290. char *zText = 0;
  148291. RtreeNode node;
  148292. Rtree tree;
  148293. int ii;
  148294. UNUSED_PARAMETER(nArg);
  148295. memset(&node, 0, sizeof(RtreeNode));
  148296. memset(&tree, 0, sizeof(Rtree));
  148297. tree.nDim = sqlite3_value_int(apArg[0]);
  148298. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  148299. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  148300. for(ii=0; ii<NCELL(&node); ii++){
  148301. char zCell[512];
  148302. int nCell = 0;
  148303. RtreeCell cell;
  148304. int jj;
  148305. nodeGetCell(&tree, &node, ii, &cell);
  148306. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  148307. nCell = (int)strlen(zCell);
  148308. for(jj=0; jj<tree.nDim*2; jj++){
  148309. #ifndef SQLITE_RTREE_INT_ONLY
  148310. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  148311. (double)cell.aCoord[jj].f);
  148312. #else
  148313. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  148314. cell.aCoord[jj].i);
  148315. #endif
  148316. nCell = (int)strlen(zCell);
  148317. }
  148318. if( zText ){
  148319. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  148320. sqlite3_free(zText);
  148321. zText = zTextNew;
  148322. }else{
  148323. zText = sqlite3_mprintf("{%s}", zCell);
  148324. }
  148325. }
  148326. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  148327. }
  148328. /* This routine implements an SQL function that returns the "depth" parameter
  148329. ** from the front of a blob that is an r-tree node. For example:
  148330. **
  148331. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  148332. **
  148333. ** The depth value is 0 for all nodes other than the root node, and the root
  148334. ** node always has nodeno=1, so the example above is the primary use for this
  148335. ** routine. This routine is intended for testing and analysis only.
  148336. */
  148337. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  148338. UNUSED_PARAMETER(nArg);
  148339. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  148340. || sqlite3_value_bytes(apArg[0])<2
  148341. ){
  148342. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  148343. }else{
  148344. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  148345. sqlite3_result_int(ctx, readInt16(zBlob));
  148346. }
  148347. }
  148348. /*
  148349. ** Register the r-tree module with database handle db. This creates the
  148350. ** virtual table module "rtree" and the debugging/analysis scalar
  148351. ** function "rtreenode".
  148352. */
  148353. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  148354. const int utf8 = SQLITE_UTF8;
  148355. int rc;
  148356. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  148357. if( rc==SQLITE_OK ){
  148358. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  148359. }
  148360. if( rc==SQLITE_OK ){
  148361. #ifdef SQLITE_RTREE_INT_ONLY
  148362. void *c = (void *)RTREE_COORD_INT32;
  148363. #else
  148364. void *c = (void *)RTREE_COORD_REAL32;
  148365. #endif
  148366. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  148367. }
  148368. if( rc==SQLITE_OK ){
  148369. void *c = (void *)RTREE_COORD_INT32;
  148370. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  148371. }
  148372. return rc;
  148373. }
  148374. /*
  148375. ** This routine deletes the RtreeGeomCallback object that was attached
  148376. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  148377. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  148378. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  148379. ** the corresponding SQL function is deleted.
  148380. */
  148381. static void rtreeFreeCallback(void *p){
  148382. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  148383. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  148384. sqlite3_free(p);
  148385. }
  148386. /*
  148387. ** This routine frees the BLOB that is returned by geomCallback().
  148388. */
  148389. static void rtreeMatchArgFree(void *pArg){
  148390. int i;
  148391. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  148392. for(i=0; i<p->nParam; i++){
  148393. sqlite3_value_free(p->apSqlParam[i]);
  148394. }
  148395. sqlite3_free(p);
  148396. }
  148397. /*
  148398. ** Each call to sqlite3_rtree_geometry_callback() or
  148399. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  148400. ** scalar function that is implemented by this routine.
  148401. **
  148402. ** All this function does is construct an RtreeMatchArg object that
  148403. ** contains the geometry-checking callback routines and a list of
  148404. ** parameters to this function, then return that RtreeMatchArg object
  148405. ** as a BLOB.
  148406. **
  148407. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  148408. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  148409. ** out which elements of the R-Tree should be returned by the query.
  148410. */
  148411. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  148412. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  148413. RtreeMatchArg *pBlob;
  148414. int nBlob;
  148415. int memErr = 0;
  148416. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  148417. + nArg*sizeof(sqlite3_value*);
  148418. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  148419. if( !pBlob ){
  148420. sqlite3_result_error_nomem(ctx);
  148421. }else{
  148422. int i;
  148423. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  148424. pBlob->cb = pGeomCtx[0];
  148425. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  148426. pBlob->nParam = nArg;
  148427. for(i=0; i<nArg; i++){
  148428. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  148429. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  148430. #ifdef SQLITE_RTREE_INT_ONLY
  148431. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  148432. #else
  148433. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  148434. #endif
  148435. }
  148436. if( memErr ){
  148437. sqlite3_result_error_nomem(ctx);
  148438. rtreeMatchArgFree(pBlob);
  148439. }else{
  148440. sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
  148441. }
  148442. }
  148443. }
  148444. /*
  148445. ** Register a new geometry function for use with the r-tree MATCH operator.
  148446. */
  148447. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  148448. sqlite3 *db, /* Register SQL function on this connection */
  148449. const char *zGeom, /* Name of the new SQL function */
  148450. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  148451. void *pContext /* Extra data associated with the callback */
  148452. ){
  148453. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  148454. /* Allocate and populate the context object. */
  148455. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  148456. if( !pGeomCtx ) return SQLITE_NOMEM;
  148457. pGeomCtx->xGeom = xGeom;
  148458. pGeomCtx->xQueryFunc = 0;
  148459. pGeomCtx->xDestructor = 0;
  148460. pGeomCtx->pContext = pContext;
  148461. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  148462. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  148463. );
  148464. }
  148465. /*
  148466. ** Register a new 2nd-generation geometry function for use with the
  148467. ** r-tree MATCH operator.
  148468. */
  148469. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  148470. sqlite3 *db, /* Register SQL function on this connection */
  148471. const char *zQueryFunc, /* Name of new SQL function */
  148472. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  148473. void *pContext, /* Extra data passed into the callback */
  148474. void (*xDestructor)(void*) /* Destructor for the extra data */
  148475. ){
  148476. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  148477. /* Allocate and populate the context object. */
  148478. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  148479. if( !pGeomCtx ) return SQLITE_NOMEM;
  148480. pGeomCtx->xGeom = 0;
  148481. pGeomCtx->xQueryFunc = xQueryFunc;
  148482. pGeomCtx->xDestructor = xDestructor;
  148483. pGeomCtx->pContext = pContext;
  148484. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  148485. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  148486. );
  148487. }
  148488. #if !SQLITE_CORE
  148489. #ifdef _WIN32
  148490. __declspec(dllexport)
  148491. #endif
  148492. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
  148493. sqlite3 *db,
  148494. char **pzErrMsg,
  148495. const sqlite3_api_routines *pApi
  148496. ){
  148497. SQLITE_EXTENSION_INIT2(pApi)
  148498. return sqlite3RtreeInit(db);
  148499. }
  148500. #endif
  148501. #endif
  148502. /************** End of rtree.c ***********************************************/
  148503. /************** Begin file icu.c *********************************************/
  148504. /*
  148505. ** 2007 May 6
  148506. **
  148507. ** The author disclaims copyright to this source code. In place of
  148508. ** a legal notice, here is a blessing:
  148509. **
  148510. ** May you do good and not evil.
  148511. ** May you find forgiveness for yourself and forgive others.
  148512. ** May you share freely, never taking more than you give.
  148513. **
  148514. *************************************************************************
  148515. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  148516. **
  148517. ** This file implements an integration between the ICU library
  148518. ** ("International Components for Unicode", an open-source library
  148519. ** for handling unicode data) and SQLite. The integration uses
  148520. ** ICU to provide the following to SQLite:
  148521. **
  148522. ** * An implementation of the SQL regexp() function (and hence REGEXP
  148523. ** operator) using the ICU uregex_XX() APIs.
  148524. **
  148525. ** * Implementations of the SQL scalar upper() and lower() functions
  148526. ** for case mapping.
  148527. **
  148528. ** * Integration of ICU and SQLite collation sequences.
  148529. **
  148530. ** * An implementation of the LIKE operator that uses ICU to
  148531. ** provide case-independent matching.
  148532. */
  148533. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  148534. /* Include ICU headers */
  148535. #include <unicode/utypes.h>
  148536. #include <unicode/uregex.h>
  148537. #include <unicode/ustring.h>
  148538. #include <unicode/ucol.h>
  148539. /* #include <assert.h> */
  148540. #ifndef SQLITE_CORE
  148541. /* #include "sqlite3ext.h" */
  148542. SQLITE_EXTENSION_INIT1
  148543. #else
  148544. /* #include "sqlite3.h" */
  148545. #endif
  148546. /*
  148547. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  148548. ** operator.
  148549. */
  148550. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  148551. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  148552. #endif
  148553. /*
  148554. ** Version of sqlite3_free() that is always a function, never a macro.
  148555. */
  148556. static void xFree(void *p){
  148557. sqlite3_free(p);
  148558. }
  148559. /*
  148560. ** Compare two UTF-8 strings for equality where the first string is
  148561. ** a "LIKE" expression. Return true (1) if they are the same and
  148562. ** false (0) if they are different.
  148563. */
  148564. static int icuLikeCompare(
  148565. const uint8_t *zPattern, /* LIKE pattern */
  148566. const uint8_t *zString, /* The UTF-8 string to compare against */
  148567. const UChar32 uEsc /* The escape character */
  148568. ){
  148569. static const int MATCH_ONE = (UChar32)'_';
  148570. static const int MATCH_ALL = (UChar32)'%';
  148571. int iPattern = 0; /* Current byte index in zPattern */
  148572. int iString = 0; /* Current byte index in zString */
  148573. int prevEscape = 0; /* True if the previous character was uEsc */
  148574. while( zPattern[iPattern]!=0 ){
  148575. /* Read (and consume) the next character from the input pattern. */
  148576. UChar32 uPattern;
  148577. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  148578. /* There are now 4 possibilities:
  148579. **
  148580. ** 1. uPattern is an unescaped match-all character "%",
  148581. ** 2. uPattern is an unescaped match-one character "_",
  148582. ** 3. uPattern is an unescaped escape character, or
  148583. ** 4. uPattern is to be handled as an ordinary character
  148584. */
  148585. if( !prevEscape && uPattern==MATCH_ALL ){
  148586. /* Case 1. */
  148587. uint8_t c;
  148588. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  148589. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  148590. ** test string.
  148591. */
  148592. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  148593. if( c==MATCH_ONE ){
  148594. if( zString[iString]==0 ) return 0;
  148595. U8_FWD_1_UNSAFE(zString, iString);
  148596. }
  148597. iPattern++;
  148598. }
  148599. if( zPattern[iPattern]==0 ) return 1;
  148600. while( zString[iString] ){
  148601. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  148602. return 1;
  148603. }
  148604. U8_FWD_1_UNSAFE(zString, iString);
  148605. }
  148606. return 0;
  148607. }else if( !prevEscape && uPattern==MATCH_ONE ){
  148608. /* Case 2. */
  148609. if( zString[iString]==0 ) return 0;
  148610. U8_FWD_1_UNSAFE(zString, iString);
  148611. }else if( !prevEscape && uPattern==uEsc){
  148612. /* Case 3. */
  148613. prevEscape = 1;
  148614. }else{
  148615. /* Case 4. */
  148616. UChar32 uString;
  148617. U8_NEXT_UNSAFE(zString, iString, uString);
  148618. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  148619. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  148620. if( uString!=uPattern ){
  148621. return 0;
  148622. }
  148623. prevEscape = 0;
  148624. }
  148625. }
  148626. return zString[iString]==0;
  148627. }
  148628. /*
  148629. ** Implementation of the like() SQL function. This function implements
  148630. ** the build-in LIKE operator. The first argument to the function is the
  148631. ** pattern and the second argument is the string. So, the SQL statements:
  148632. **
  148633. ** A LIKE B
  148634. **
  148635. ** is implemented as like(B, A). If there is an escape character E,
  148636. **
  148637. ** A LIKE B ESCAPE E
  148638. **
  148639. ** is mapped to like(B, A, E).
  148640. */
  148641. static void icuLikeFunc(
  148642. sqlite3_context *context,
  148643. int argc,
  148644. sqlite3_value **argv
  148645. ){
  148646. const unsigned char *zA = sqlite3_value_text(argv[0]);
  148647. const unsigned char *zB = sqlite3_value_text(argv[1]);
  148648. UChar32 uEsc = 0;
  148649. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  148650. ** of deep recursion and N*N behavior in patternCompare().
  148651. */
  148652. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  148653. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  148654. return;
  148655. }
  148656. if( argc==3 ){
  148657. /* The escape character string must consist of a single UTF-8 character.
  148658. ** Otherwise, return an error.
  148659. */
  148660. int nE= sqlite3_value_bytes(argv[2]);
  148661. const unsigned char *zE = sqlite3_value_text(argv[2]);
  148662. int i = 0;
  148663. if( zE==0 ) return;
  148664. U8_NEXT(zE, i, nE, uEsc);
  148665. if( i!=nE){
  148666. sqlite3_result_error(context,
  148667. "ESCAPE expression must be a single character", -1);
  148668. return;
  148669. }
  148670. }
  148671. if( zA && zB ){
  148672. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  148673. }
  148674. }
  148675. /*
  148676. ** This function is called when an ICU function called from within
  148677. ** the implementation of an SQL scalar function returns an error.
  148678. **
  148679. ** The scalar function context passed as the first argument is
  148680. ** loaded with an error message based on the following two args.
  148681. */
  148682. static void icuFunctionError(
  148683. sqlite3_context *pCtx, /* SQLite scalar function context */
  148684. const char *zName, /* Name of ICU function that failed */
  148685. UErrorCode e /* Error code returned by ICU function */
  148686. ){
  148687. char zBuf[128];
  148688. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  148689. zBuf[127] = '\0';
  148690. sqlite3_result_error(pCtx, zBuf, -1);
  148691. }
  148692. /*
  148693. ** Function to delete compiled regexp objects. Registered as
  148694. ** a destructor function with sqlite3_set_auxdata().
  148695. */
  148696. static void icuRegexpDelete(void *p){
  148697. URegularExpression *pExpr = (URegularExpression *)p;
  148698. uregex_close(pExpr);
  148699. }
  148700. /*
  148701. ** Implementation of SQLite REGEXP operator. This scalar function takes
  148702. ** two arguments. The first is a regular expression pattern to compile
  148703. ** the second is a string to match against that pattern. If either
  148704. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  148705. ** is 1 if the string matches the pattern, or 0 otherwise.
  148706. **
  148707. ** SQLite maps the regexp() function to the regexp() operator such
  148708. ** that the following two are equivalent:
  148709. **
  148710. ** zString REGEXP zPattern
  148711. ** regexp(zPattern, zString)
  148712. **
  148713. ** Uses the following ICU regexp APIs:
  148714. **
  148715. ** uregex_open()
  148716. ** uregex_matches()
  148717. ** uregex_close()
  148718. */
  148719. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  148720. UErrorCode status = U_ZERO_ERROR;
  148721. URegularExpression *pExpr;
  148722. UBool res;
  148723. const UChar *zString = sqlite3_value_text16(apArg[1]);
  148724. (void)nArg; /* Unused parameter */
  148725. /* If the left hand side of the regexp operator is NULL,
  148726. ** then the result is also NULL.
  148727. */
  148728. if( !zString ){
  148729. return;
  148730. }
  148731. pExpr = sqlite3_get_auxdata(p, 0);
  148732. if( !pExpr ){
  148733. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  148734. if( !zPattern ){
  148735. return;
  148736. }
  148737. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  148738. if( U_SUCCESS(status) ){
  148739. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  148740. }else{
  148741. assert(!pExpr);
  148742. icuFunctionError(p, "uregex_open", status);
  148743. return;
  148744. }
  148745. }
  148746. /* Configure the text that the regular expression operates on. */
  148747. uregex_setText(pExpr, zString, -1, &status);
  148748. if( !U_SUCCESS(status) ){
  148749. icuFunctionError(p, "uregex_setText", status);
  148750. return;
  148751. }
  148752. /* Attempt the match */
  148753. res = uregex_matches(pExpr, 0, &status);
  148754. if( !U_SUCCESS(status) ){
  148755. icuFunctionError(p, "uregex_matches", status);
  148756. return;
  148757. }
  148758. /* Set the text that the regular expression operates on to a NULL
  148759. ** pointer. This is not really necessary, but it is tidier than
  148760. ** leaving the regular expression object configured with an invalid
  148761. ** pointer after this function returns.
  148762. */
  148763. uregex_setText(pExpr, 0, 0, &status);
  148764. /* Return 1 or 0. */
  148765. sqlite3_result_int(p, res ? 1 : 0);
  148766. }
  148767. /*
  148768. ** Implementations of scalar functions for case mapping - upper() and
  148769. ** lower(). Function upper() converts its input to upper-case (ABC).
  148770. ** Function lower() converts to lower-case (abc).
  148771. **
  148772. ** ICU provides two types of case mapping, "general" case mapping and
  148773. ** "language specific". Refer to ICU documentation for the differences
  148774. ** between the two.
  148775. **
  148776. ** To utilise "general" case mapping, the upper() or lower() scalar
  148777. ** functions are invoked with one argument:
  148778. **
  148779. ** upper('ABC') -> 'abc'
  148780. ** lower('abc') -> 'ABC'
  148781. **
  148782. ** To access ICU "language specific" case mapping, upper() or lower()
  148783. ** should be invoked with two arguments. The second argument is the name
  148784. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  148785. ** as the second argument is the same as invoking the 1 argument version
  148786. ** of upper() or lower().
  148787. **
  148788. ** lower('I', 'en_us') -> 'i'
  148789. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  148790. **
  148791. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  148792. */
  148793. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  148794. const UChar *zInput;
  148795. UChar *zOutput;
  148796. int nInput;
  148797. int nOutput;
  148798. UErrorCode status = U_ZERO_ERROR;
  148799. const char *zLocale = 0;
  148800. assert(nArg==1 || nArg==2);
  148801. if( nArg==2 ){
  148802. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  148803. }
  148804. zInput = sqlite3_value_text16(apArg[0]);
  148805. if( !zInput ){
  148806. return;
  148807. }
  148808. nInput = sqlite3_value_bytes16(apArg[0]);
  148809. nOutput = nInput * 2 + 2;
  148810. zOutput = sqlite3_malloc(nOutput);
  148811. if( !zOutput ){
  148812. return;
  148813. }
  148814. if( sqlite3_user_data(p) ){
  148815. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  148816. }else{
  148817. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  148818. }
  148819. if( !U_SUCCESS(status) ){
  148820. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  148821. return;
  148822. }
  148823. sqlite3_result_text16(p, zOutput, -1, xFree);
  148824. }
  148825. /*
  148826. ** Collation sequence destructor function. The pCtx argument points to
  148827. ** a UCollator structure previously allocated using ucol_open().
  148828. */
  148829. static void icuCollationDel(void *pCtx){
  148830. UCollator *p = (UCollator *)pCtx;
  148831. ucol_close(p);
  148832. }
  148833. /*
  148834. ** Collation sequence comparison function. The pCtx argument points to
  148835. ** a UCollator structure previously allocated using ucol_open().
  148836. */
  148837. static int icuCollationColl(
  148838. void *pCtx,
  148839. int nLeft,
  148840. const void *zLeft,
  148841. int nRight,
  148842. const void *zRight
  148843. ){
  148844. UCollationResult res;
  148845. UCollator *p = (UCollator *)pCtx;
  148846. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  148847. switch( res ){
  148848. case UCOL_LESS: return -1;
  148849. case UCOL_GREATER: return +1;
  148850. case UCOL_EQUAL: return 0;
  148851. }
  148852. assert(!"Unexpected return value from ucol_strcoll()");
  148853. return 0;
  148854. }
  148855. /*
  148856. ** Implementation of the scalar function icu_load_collation().
  148857. **
  148858. ** This scalar function is used to add ICU collation based collation
  148859. ** types to an SQLite database connection. It is intended to be called
  148860. ** as follows:
  148861. **
  148862. ** SELECT icu_load_collation(<locale>, <collation-name>);
  148863. **
  148864. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  148865. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  148866. ** collation sequence to create.
  148867. */
  148868. static void icuLoadCollation(
  148869. sqlite3_context *p,
  148870. int nArg,
  148871. sqlite3_value **apArg
  148872. ){
  148873. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  148874. UErrorCode status = U_ZERO_ERROR;
  148875. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  148876. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  148877. UCollator *pUCollator; /* ICU library collation object */
  148878. int rc; /* Return code from sqlite3_create_collation_x() */
  148879. assert(nArg==2);
  148880. (void)nArg; /* Unused parameter */
  148881. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  148882. zName = (const char *)sqlite3_value_text(apArg[1]);
  148883. if( !zLocale || !zName ){
  148884. return;
  148885. }
  148886. pUCollator = ucol_open(zLocale, &status);
  148887. if( !U_SUCCESS(status) ){
  148888. icuFunctionError(p, "ucol_open", status);
  148889. return;
  148890. }
  148891. assert(p);
  148892. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  148893. icuCollationColl, icuCollationDel
  148894. );
  148895. if( rc!=SQLITE_OK ){
  148896. ucol_close(pUCollator);
  148897. sqlite3_result_error(p, "Error registering collation function", -1);
  148898. }
  148899. }
  148900. /*
  148901. ** Register the ICU extension functions with database db.
  148902. */
  148903. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  148904. struct IcuScalar {
  148905. const char *zName; /* Function name */
  148906. int nArg; /* Number of arguments */
  148907. int enc; /* Optimal text encoding */
  148908. void *pContext; /* sqlite3_user_data() context */
  148909. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  148910. } scalars[] = {
  148911. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  148912. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  148913. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  148914. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  148915. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  148916. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  148917. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  148918. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  148919. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  148920. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  148921. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  148922. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  148923. };
  148924. int rc = SQLITE_OK;
  148925. int i;
  148926. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  148927. struct IcuScalar *p = &scalars[i];
  148928. rc = sqlite3_create_function(
  148929. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  148930. );
  148931. }
  148932. return rc;
  148933. }
  148934. #if !SQLITE_CORE
  148935. #ifdef _WIN32
  148936. __declspec(dllexport)
  148937. #endif
  148938. SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
  148939. sqlite3 *db,
  148940. char **pzErrMsg,
  148941. const sqlite3_api_routines *pApi
  148942. ){
  148943. SQLITE_EXTENSION_INIT2(pApi)
  148944. return sqlite3IcuInit(db);
  148945. }
  148946. #endif
  148947. #endif
  148948. /************** End of icu.c *************************************************/
  148949. /************** Begin file fts3_icu.c ****************************************/
  148950. /*
  148951. ** 2007 June 22
  148952. **
  148953. ** The author disclaims copyright to this source code. In place of
  148954. ** a legal notice, here is a blessing:
  148955. **
  148956. ** May you do good and not evil.
  148957. ** May you find forgiveness for yourself and forgive others.
  148958. ** May you share freely, never taking more than you give.
  148959. **
  148960. *************************************************************************
  148961. ** This file implements a tokenizer for fts3 based on the ICU library.
  148962. */
  148963. /* #include "fts3Int.h" */
  148964. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  148965. #ifdef SQLITE_ENABLE_ICU
  148966. /* #include <assert.h> */
  148967. /* #include <string.h> */
  148968. /* #include "fts3_tokenizer.h" */
  148969. #include <unicode/ubrk.h>
  148970. /* #include <unicode/ucol.h> */
  148971. /* #include <unicode/ustring.h> */
  148972. #include <unicode/utf16.h>
  148973. typedef struct IcuTokenizer IcuTokenizer;
  148974. typedef struct IcuCursor IcuCursor;
  148975. struct IcuTokenizer {
  148976. sqlite3_tokenizer base;
  148977. char *zLocale;
  148978. };
  148979. struct IcuCursor {
  148980. sqlite3_tokenizer_cursor base;
  148981. UBreakIterator *pIter; /* ICU break-iterator object */
  148982. int nChar; /* Number of UChar elements in pInput */
  148983. UChar *aChar; /* Copy of input using utf-16 encoding */
  148984. int *aOffset; /* Offsets of each character in utf-8 input */
  148985. int nBuffer;
  148986. char *zBuffer;
  148987. int iToken;
  148988. };
  148989. /*
  148990. ** Create a new tokenizer instance.
  148991. */
  148992. static int icuCreate(
  148993. int argc, /* Number of entries in argv[] */
  148994. const char * const *argv, /* Tokenizer creation arguments */
  148995. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  148996. ){
  148997. IcuTokenizer *p;
  148998. int n = 0;
  148999. if( argc>0 ){
  149000. n = strlen(argv[0])+1;
  149001. }
  149002. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  149003. if( !p ){
  149004. return SQLITE_NOMEM;
  149005. }
  149006. memset(p, 0, sizeof(IcuTokenizer));
  149007. if( n ){
  149008. p->zLocale = (char *)&p[1];
  149009. memcpy(p->zLocale, argv[0], n);
  149010. }
  149011. *ppTokenizer = (sqlite3_tokenizer *)p;
  149012. return SQLITE_OK;
  149013. }
  149014. /*
  149015. ** Destroy a tokenizer
  149016. */
  149017. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  149018. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  149019. sqlite3_free(p);
  149020. return SQLITE_OK;
  149021. }
  149022. /*
  149023. ** Prepare to begin tokenizing a particular string. The input
  149024. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  149025. ** used to incrementally tokenize this string is returned in
  149026. ** *ppCursor.
  149027. */
  149028. static int icuOpen(
  149029. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  149030. const char *zInput, /* Input string */
  149031. int nInput, /* Length of zInput in bytes */
  149032. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  149033. ){
  149034. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  149035. IcuCursor *pCsr;
  149036. const int32_t opt = U_FOLD_CASE_DEFAULT;
  149037. UErrorCode status = U_ZERO_ERROR;
  149038. int nChar;
  149039. UChar32 c;
  149040. int iInput = 0;
  149041. int iOut = 0;
  149042. *ppCursor = 0;
  149043. if( zInput==0 ){
  149044. nInput = 0;
  149045. zInput = "";
  149046. }else if( nInput<0 ){
  149047. nInput = strlen(zInput);
  149048. }
  149049. nChar = nInput+1;
  149050. pCsr = (IcuCursor *)sqlite3_malloc(
  149051. sizeof(IcuCursor) + /* IcuCursor */
  149052. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  149053. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  149054. );
  149055. if( !pCsr ){
  149056. return SQLITE_NOMEM;
  149057. }
  149058. memset(pCsr, 0, sizeof(IcuCursor));
  149059. pCsr->aChar = (UChar *)&pCsr[1];
  149060. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  149061. pCsr->aOffset[iOut] = iInput;
  149062. U8_NEXT(zInput, iInput, nInput, c);
  149063. while( c>0 ){
  149064. int isError = 0;
  149065. c = u_foldCase(c, opt);
  149066. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  149067. if( isError ){
  149068. sqlite3_free(pCsr);
  149069. return SQLITE_ERROR;
  149070. }
  149071. pCsr->aOffset[iOut] = iInput;
  149072. if( iInput<nInput ){
  149073. U8_NEXT(zInput, iInput, nInput, c);
  149074. }else{
  149075. c = 0;
  149076. }
  149077. }
  149078. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  149079. if( !U_SUCCESS(status) ){
  149080. sqlite3_free(pCsr);
  149081. return SQLITE_ERROR;
  149082. }
  149083. pCsr->nChar = iOut;
  149084. ubrk_first(pCsr->pIter);
  149085. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  149086. return SQLITE_OK;
  149087. }
  149088. /*
  149089. ** Close a tokenization cursor previously opened by a call to icuOpen().
  149090. */
  149091. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  149092. IcuCursor *pCsr = (IcuCursor *)pCursor;
  149093. ubrk_close(pCsr->pIter);
  149094. sqlite3_free(pCsr->zBuffer);
  149095. sqlite3_free(pCsr);
  149096. return SQLITE_OK;
  149097. }
  149098. /*
  149099. ** Extract the next token from a tokenization cursor.
  149100. */
  149101. static int icuNext(
  149102. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  149103. const char **ppToken, /* OUT: *ppToken is the token text */
  149104. int *pnBytes, /* OUT: Number of bytes in token */
  149105. int *piStartOffset, /* OUT: Starting offset of token */
  149106. int *piEndOffset, /* OUT: Ending offset of token */
  149107. int *piPosition /* OUT: Position integer of token */
  149108. ){
  149109. IcuCursor *pCsr = (IcuCursor *)pCursor;
  149110. int iStart = 0;
  149111. int iEnd = 0;
  149112. int nByte = 0;
  149113. while( iStart==iEnd ){
  149114. UChar32 c;
  149115. iStart = ubrk_current(pCsr->pIter);
  149116. iEnd = ubrk_next(pCsr->pIter);
  149117. if( iEnd==UBRK_DONE ){
  149118. return SQLITE_DONE;
  149119. }
  149120. while( iStart<iEnd ){
  149121. int iWhite = iStart;
  149122. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  149123. if( u_isspace(c) ){
  149124. iStart = iWhite;
  149125. }else{
  149126. break;
  149127. }
  149128. }
  149129. assert(iStart<=iEnd);
  149130. }
  149131. do {
  149132. UErrorCode status = U_ZERO_ERROR;
  149133. if( nByte ){
  149134. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  149135. if( !zNew ){
  149136. return SQLITE_NOMEM;
  149137. }
  149138. pCsr->zBuffer = zNew;
  149139. pCsr->nBuffer = nByte;
  149140. }
  149141. u_strToUTF8(
  149142. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  149143. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  149144. &status /* Output success/failure */
  149145. );
  149146. } while( nByte>pCsr->nBuffer );
  149147. *ppToken = pCsr->zBuffer;
  149148. *pnBytes = nByte;
  149149. *piStartOffset = pCsr->aOffset[iStart];
  149150. *piEndOffset = pCsr->aOffset[iEnd];
  149151. *piPosition = pCsr->iToken++;
  149152. return SQLITE_OK;
  149153. }
  149154. /*
  149155. ** The set of routines that implement the simple tokenizer
  149156. */
  149157. static const sqlite3_tokenizer_module icuTokenizerModule = {
  149158. 0, /* iVersion */
  149159. icuCreate, /* xCreate */
  149160. icuDestroy, /* xCreate */
  149161. icuOpen, /* xOpen */
  149162. icuClose, /* xClose */
  149163. icuNext, /* xNext */
  149164. 0, /* xLanguageid */
  149165. };
  149166. /*
  149167. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  149168. */
  149169. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  149170. sqlite3_tokenizer_module const**ppModule
  149171. ){
  149172. *ppModule = &icuTokenizerModule;
  149173. }
  149174. #endif /* defined(SQLITE_ENABLE_ICU) */
  149175. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  149176. /************** End of fts3_icu.c ********************************************/
  149177. /************** Begin file sqlite3rbu.c **************************************/
  149178. /*
  149179. ** 2014 August 30
  149180. **
  149181. ** The author disclaims copyright to this source code. In place of
  149182. ** a legal notice, here is a blessing:
  149183. **
  149184. ** May you do good and not evil.
  149185. ** May you find forgiveness for yourself and forgive others.
  149186. ** May you share freely, never taking more than you give.
  149187. **
  149188. *************************************************************************
  149189. **
  149190. **
  149191. ** OVERVIEW
  149192. **
  149193. ** The RBU extension requires that the RBU update be packaged as an
  149194. ** SQLite database. The tables it expects to find are described in
  149195. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  149196. ** that the user wishes to write to, a corresponding data_xyz table is
  149197. ** created in the RBU database and populated with one row for each row to
  149198. ** update, insert or delete from the target table.
  149199. **
  149200. ** The update proceeds in three stages:
  149201. **
  149202. ** 1) The database is updated. The modified database pages are written
  149203. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  149204. ** that it is named "<database>-oal" instead of "<database>-wal".
  149205. ** Because regular SQLite clients do not look for file named
  149206. ** "<database>-oal", they go on using the original database in
  149207. ** rollback mode while the *-oal file is being generated.
  149208. **
  149209. ** During this stage RBU does not update the database by writing
  149210. ** directly to the target tables. Instead it creates "imposter"
  149211. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  149212. ** to update each b-tree individually. All updates required by each
  149213. ** b-tree are completed before moving on to the next, and all
  149214. ** updates are done in sorted key order.
  149215. **
  149216. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  149217. ** location using a call to rename(2). Before doing this the RBU
  149218. ** module takes an EXCLUSIVE lock on the database file, ensuring
  149219. ** that there are no other active readers.
  149220. **
  149221. ** Once the EXCLUSIVE lock is released, any other database readers
  149222. ** detect the new *-wal file and read the database in wal mode. At
  149223. ** this point they see the new version of the database - including
  149224. ** the updates made as part of the RBU update.
  149225. **
  149226. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  149227. ** as a regular database checkpoint, except that a single frame is
  149228. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  149229. ** handle is closed before the entire *-wal file is checkpointed,
  149230. ** the checkpoint progress is saved in the RBU database and the
  149231. ** checkpoint can be resumed by another RBU client at some point in
  149232. ** the future.
  149233. **
  149234. ** POTENTIAL PROBLEMS
  149235. **
  149236. ** The rename() call might not be portable. And RBU is not currently
  149237. ** syncing the directory after renaming the file.
  149238. **
  149239. ** When state is saved, any commit to the *-oal file and the commit to
  149240. ** the RBU update database are not atomic. So if the power fails at the
  149241. ** wrong moment they might get out of sync. As the main database will be
  149242. ** committed before the RBU update database this will likely either just
  149243. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  149244. ** constraint violations).
  149245. **
  149246. ** If some client does modify the target database mid RBU update, or some
  149247. ** other error occurs, the RBU extension will keep throwing errors. It's
  149248. ** not really clear how to get out of this state. The system could just
  149249. ** by delete the RBU update database and *-oal file and have the device
  149250. ** download the update again and start over.
  149251. **
  149252. ** At present, for an UPDATE, both the new.* and old.* records are
  149253. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  149254. ** fields are collected. This means we're probably writing a lot more
  149255. ** data to disk when saving the state of an ongoing update to the RBU
  149256. ** update database than is strictly necessary.
  149257. **
  149258. */
  149259. /* #include <assert.h> */
  149260. /* #include <string.h> */
  149261. /* #include <stdio.h> */
  149262. /* #include "sqlite3.h" */
  149263. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  149264. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  149265. /************** Begin file sqlite3rbu.h **************************************/
  149266. /*
  149267. ** 2014 August 30
  149268. **
  149269. ** The author disclaims copyright to this source code. In place of
  149270. ** a legal notice, here is a blessing:
  149271. **
  149272. ** May you do good and not evil.
  149273. ** May you find forgiveness for yourself and forgive others.
  149274. ** May you share freely, never taking more than you give.
  149275. **
  149276. *************************************************************************
  149277. **
  149278. ** This file contains the public interface for the RBU extension.
  149279. */
  149280. /*
  149281. ** SUMMARY
  149282. **
  149283. ** Writing a transaction containing a large number of operations on
  149284. ** b-tree indexes that are collectively larger than the available cache
  149285. ** memory can be very inefficient.
  149286. **
  149287. ** The problem is that in order to update a b-tree, the leaf page (at least)
  149288. ** containing the entry being inserted or deleted must be modified. If the
  149289. ** working set of leaves is larger than the available cache memory, then a
  149290. ** single leaf that is modified more than once as part of the transaction
  149291. ** may be loaded from or written to the persistent media multiple times.
  149292. ** Additionally, because the index updates are likely to be applied in
  149293. ** random order, access to pages within the database is also likely to be in
  149294. ** random order, which is itself quite inefficient.
  149295. **
  149296. ** One way to improve the situation is to sort the operations on each index
  149297. ** by index key before applying them to the b-tree. This leads to an IO
  149298. ** pattern that resembles a single linear scan through the index b-tree,
  149299. ** and all but guarantees each modified leaf page is loaded and stored
  149300. ** exactly once. SQLite uses this trick to improve the performance of
  149301. ** CREATE INDEX commands. This extension allows it to be used to improve
  149302. ** the performance of large transactions on existing databases.
  149303. **
  149304. ** Additionally, this extension allows the work involved in writing the
  149305. ** large transaction to be broken down into sub-transactions performed
  149306. ** sequentially by separate processes. This is useful if the system cannot
  149307. ** guarantee that a single update process will run for long enough to apply
  149308. ** the entire update, for example because the update is being applied on a
  149309. ** mobile device that is frequently rebooted. Even after the writer process
  149310. ** has committed one or more sub-transactions, other database clients continue
  149311. ** to read from the original database snapshot. In other words, partially
  149312. ** applied transactions are not visible to other clients.
  149313. **
  149314. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  149315. ** transmitted via a wireless network to a mobile device. A transaction
  149316. ** applied using this extension is hence refered to as an "RBU update".
  149317. **
  149318. **
  149319. ** LIMITATIONS
  149320. **
  149321. ** An "RBU update" transaction is subject to the following limitations:
  149322. **
  149323. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  149324. ** only.
  149325. **
  149326. ** * INSERT statements may not use any default values.
  149327. **
  149328. ** * UPDATE and DELETE statements must identify their target rows by
  149329. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  149330. ** KEY fields may not be updated or deleted. If the table being written
  149331. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  149332. **
  149333. ** * UPDATE statements may not modify PRIMARY KEY columns.
  149334. **
  149335. ** * No triggers will be fired.
  149336. **
  149337. ** * No foreign key violations are detected or reported.
  149338. **
  149339. ** * CHECK constraints are not enforced.
  149340. **
  149341. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  149342. **
  149343. **
  149344. ** PREPARATION
  149345. **
  149346. ** An "RBU update" is stored as a separate SQLite database. A database
  149347. ** containing an RBU update is an "RBU database". For each table in the
  149348. ** target database to be updated, the RBU database should contain a table
  149349. ** named "data_<target name>" containing the same set of columns as the
  149350. ** target table, and one more - "rbu_control". The data_% table should
  149351. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  149352. ** the same type as the corresponding column in the target database.
  149353. ** The "rbu_control" column should have no type at all. For example, if
  149354. ** the target database contains:
  149355. **
  149356. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  149357. **
  149358. ** Then the RBU database should contain:
  149359. **
  149360. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  149361. **
  149362. ** The order of the columns in the data_% table does not matter.
  149363. **
  149364. ** Instead of a regular table, the RBU database may also contain virtual
  149365. ** tables or view named using the data_<target> naming scheme.
  149366. **
  149367. ** Instead of the plain data_<target> naming scheme, RBU database tables
  149368. ** may also be named data<integer>_<target>, where <integer> is any sequence
  149369. ** of zero or more numeric characters (0-9). This can be significant because
  149370. ** tables within the RBU database are always processed in order sorted by
  149371. ** name. By judicious selection of the the <integer> portion of the names
  149372. ** of the RBU tables the user can therefore control the order in which they
  149373. ** are processed. This can be useful, for example, to ensure that "external
  149374. ** content" FTS4 tables are updated before their underlying content tables.
  149375. **
  149376. ** If the target database table is a virtual table or a table that has no
  149377. ** PRIMARY KEY declaration, the data_% table must also contain a column
  149378. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  149379. ** key column - "rowid". Virtual tables for which the "rowid" column does
  149380. ** not function like a primary key value cannot be updated using RBU. For
  149381. ** example, if the target db contains either of the following:
  149382. **
  149383. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  149384. ** CREATE TABLE x1(a, b)
  149385. **
  149386. ** then the RBU database should contain:
  149387. **
  149388. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  149389. **
  149390. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  149391. ** target table must be present in the input table. For virtual tables,
  149392. ** hidden columns are optional - they are updated by RBU if present in
  149393. ** the input table, or not otherwise. For example, to write to an fts4
  149394. ** table with a hidden languageid column such as:
  149395. **
  149396. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  149397. **
  149398. ** Either of the following input table schemas may be used:
  149399. **
  149400. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  149401. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  149402. **
  149403. ** For each row to INSERT into the target database as part of the RBU
  149404. ** update, the corresponding data_% table should contain a single record
  149405. ** with the "rbu_control" column set to contain integer value 0. The
  149406. ** other columns should be set to the values that make up the new record
  149407. ** to insert.
  149408. **
  149409. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  149410. ** possible to insert a NULL value into the IPK column. Attempting to
  149411. ** do so results in an SQLITE_MISMATCH error.
  149412. **
  149413. ** For each row to DELETE from the target database as part of the RBU
  149414. ** update, the corresponding data_% table should contain a single record
  149415. ** with the "rbu_control" column set to contain integer value 1. The
  149416. ** real primary key values of the row to delete should be stored in the
  149417. ** corresponding columns of the data_% table. The values stored in the
  149418. ** other columns are not used.
  149419. **
  149420. ** For each row to UPDATE from the target database as part of the RBU
  149421. ** update, the corresponding data_% table should contain a single record
  149422. ** with the "rbu_control" column set to contain a value of type text.
  149423. ** The real primary key values identifying the row to update should be
  149424. ** stored in the corresponding columns of the data_% table row, as should
  149425. ** the new values of all columns being update. The text value in the
  149426. ** "rbu_control" column must contain the same number of characters as
  149427. ** there are columns in the target database table, and must consist entirely
  149428. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  149429. ** each column that is being updated, the corresponding character is set to
  149430. ** 'x'. For those that remain as they are, the corresponding character of the
  149431. ** rbu_control value should be set to '.'. For example, given the tables
  149432. ** above, the update statement:
  149433. **
  149434. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  149435. **
  149436. ** is represented by the data_t1 row created by:
  149437. **
  149438. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  149439. **
  149440. ** Instead of an 'x' character, characters of the rbu_control value specified
  149441. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  149442. ** target table with the value stored in the corresponding data_% column, the
  149443. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  149444. ** the target table column. rbu_delta() is invoked with two arguments - the
  149445. ** original value currently stored in the target table column and the
  149446. ** value specified in the data_xxx table.
  149447. **
  149448. ** For example, this row:
  149449. **
  149450. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  149451. **
  149452. ** is similar to an UPDATE statement such as:
  149453. **
  149454. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  149455. **
  149456. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  149457. ** ota_control string, the contents of the data_xxx table column is assumed
  149458. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  149459. ** format used by the fossil source-code management system. In this case
  149460. ** the existing value within the target database table must be of type BLOB.
  149461. ** It is replaced by the result of applying the specified fossil delta to
  149462. ** itself.
  149463. **
  149464. ** If the target database table is a virtual table or a table with no PRIMARY
  149465. ** KEY, the rbu_control value should not include a character corresponding
  149466. ** to the rbu_rowid value. For example, this:
  149467. **
  149468. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  149469. ** VALUES(NULL, 'usa', 12, '.x');
  149470. **
  149471. ** causes a result similar to:
  149472. **
  149473. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  149474. **
  149475. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  149476. ** However, RBU is more efficient if reading the rows in from each data_xxx
  149477. ** table in "rowid" order is roughly the same as reading them sorted by
  149478. ** the PRIMARY KEY of the corresponding target database table. In other
  149479. ** words, rows should be sorted using the destination table PRIMARY KEY
  149480. ** fields before they are inserted into the data_xxx tables.
  149481. **
  149482. ** USAGE
  149483. **
  149484. ** The API declared below allows an application to apply an RBU update
  149485. ** stored on disk to an existing target database. Essentially, the
  149486. ** application:
  149487. **
  149488. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  149489. **
  149490. ** 2) Registers any required virtual table modules with the database
  149491. ** handle returned by sqlite3rbu_db(). Also, if required, register
  149492. ** the rbu_delta() implementation.
  149493. **
  149494. ** 3) Calls the sqlite3rbu_step() function one or more times on
  149495. ** the new handle. Each call to sqlite3rbu_step() performs a single
  149496. ** b-tree operation, so thousands of calls may be required to apply
  149497. ** a complete update.
  149498. **
  149499. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  149500. ** sqlite3rbu_step() has been called enough times to completely
  149501. ** apply the update to the target database, then the RBU database
  149502. ** is marked as fully applied. Otherwise, the state of the RBU
  149503. ** update application is saved in the RBU database for later
  149504. ** resumption.
  149505. **
  149506. ** See comments below for more detail on APIs.
  149507. **
  149508. ** If an update is only partially applied to the target database by the
  149509. ** time sqlite3rbu_close() is called, various state information is saved
  149510. ** within the RBU database. This allows subsequent processes to automatically
  149511. ** resume the RBU update from where it left off.
  149512. **
  149513. ** To remove all RBU extension state information, returning an RBU database
  149514. ** to its original contents, it is sufficient to drop all tables that begin
  149515. ** with the prefix "rbu_"
  149516. **
  149517. ** DATABASE LOCKING
  149518. **
  149519. ** An RBU update may not be applied to a database in WAL mode. Attempting
  149520. ** to do so is an error (SQLITE_ERROR).
  149521. **
  149522. ** While an RBU handle is open, a SHARED lock may be held on the target
  149523. ** database file. This means it is possible for other clients to read the
  149524. ** database, but not to write it.
  149525. **
  149526. ** If an RBU update is started and then suspended before it is completed,
  149527. ** then an external client writes to the database, then attempting to resume
  149528. ** the suspended RBU update is also an error (SQLITE_BUSY).
  149529. */
  149530. #ifndef _SQLITE3RBU_H
  149531. #define _SQLITE3RBU_H
  149532. /* #include "sqlite3.h" ** Required for error code definitions ** */
  149533. #if 0
  149534. extern "C" {
  149535. #endif
  149536. typedef struct sqlite3rbu sqlite3rbu;
  149537. /*
  149538. ** Open an RBU handle.
  149539. **
  149540. ** Argument zTarget is the path to the target database. Argument zRbu is
  149541. ** the path to the RBU database. Each call to this function must be matched
  149542. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  149543. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  149544. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  149545. ** database URI, not a regular file name.
  149546. **
  149547. ** If the zState argument is passed a NULL value, the RBU extension stores
  149548. ** the current state of the update (how many rows have been updated, which
  149549. ** indexes are yet to be updated etc.) within the RBU database itself. This
  149550. ** can be convenient, as it means that the RBU application does not need to
  149551. ** organize removing a separate state file after the update is concluded.
  149552. ** Or, if zState is non-NULL, it must be a path to a database file in which
  149553. ** the RBU extension can store the state of the update.
  149554. **
  149555. ** When resuming an RBU update, the zState argument must be passed the same
  149556. ** value as when the RBU update was started.
  149557. **
  149558. ** Once the RBU update is finished, the RBU extension does not
  149559. ** automatically remove any zState database file, even if it created it.
  149560. **
  149561. ** By default, RBU uses the default VFS to access the files on disk. To
  149562. ** use a VFS other than the default, an SQLite "file:" URI containing a
  149563. ** "vfs=..." option may be passed as the zTarget option.
  149564. **
  149565. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  149566. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  149567. ** not work out of the box with zipvfs. Refer to the comment describing
  149568. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  149569. */
  149570. SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
  149571. const char *zTarget,
  149572. const char *zRbu,
  149573. const char *zState
  149574. );
  149575. /*
  149576. ** Internally, each RBU connection uses a separate SQLite database
  149577. ** connection to access the target and rbu update databases. This
  149578. ** API allows the application direct access to these database handles.
  149579. **
  149580. ** The first argument passed to this function must be a valid, open, RBU
  149581. ** handle. The second argument should be passed zero to access the target
  149582. ** database handle, or non-zero to access the rbu update database handle.
  149583. ** Accessing the underlying database handles may be useful in the
  149584. ** following scenarios:
  149585. **
  149586. ** * If any target tables are virtual tables, it may be necessary to
  149587. ** call sqlite3_create_module() on the target database handle to
  149588. ** register the required virtual table implementations.
  149589. **
  149590. ** * If the data_xxx tables in the RBU source database are virtual
  149591. ** tables, the application may need to call sqlite3_create_module() on
  149592. ** the rbu update db handle to any required virtual table
  149593. ** implementations.
  149594. **
  149595. ** * If the application uses the "rbu_delta()" feature described above,
  149596. ** it must use sqlite3_create_function() or similar to register the
  149597. ** rbu_delta() implementation with the target database handle.
  149598. **
  149599. ** If an error has occurred, either while opening or stepping the RBU object,
  149600. ** this function may return NULL. The error code and message may be collected
  149601. ** when sqlite3rbu_close() is called.
  149602. **
  149603. ** Database handles returned by this function remain valid until the next
  149604. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  149605. */
  149606. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
  149607. /*
  149608. ** Do some work towards applying the RBU update to the target db.
  149609. **
  149610. ** Return SQLITE_DONE if the update has been completely applied, or
  149611. ** SQLITE_OK if no error occurs but there remains work to do to apply
  149612. ** the RBU update. If an error does occur, some other error code is
  149613. ** returned.
  149614. **
  149615. ** Once a call to sqlite3rbu_step() has returned a value other than
  149616. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  149617. ** that immediately return the same value.
  149618. */
  149619. SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
  149620. /*
  149621. ** Force RBU to save its state to disk.
  149622. **
  149623. ** If a power failure or application crash occurs during an update, following
  149624. ** system recovery RBU may resume the update from the point at which the state
  149625. ** was last saved. In other words, from the most recent successful call to
  149626. ** sqlite3rbu_close() or this function.
  149627. **
  149628. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  149629. */
  149630. SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *pRbu);
  149631. /*
  149632. ** Close an RBU handle.
  149633. **
  149634. ** If the RBU update has been completely applied, mark the RBU database
  149635. ** as fully applied. Otherwise, assuming no error has occurred, save the
  149636. ** current state of the RBU update appliation to the RBU database.
  149637. **
  149638. ** If an error has already occurred as part of an sqlite3rbu_step()
  149639. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  149640. ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
  149641. ** point to a buffer containing a utf-8 formatted English language error
  149642. ** message. It is the responsibility of the caller to eventually free any
  149643. ** such buffer using sqlite3_free().
  149644. **
  149645. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  149646. ** update has been partially applied, or SQLITE_DONE if it has been
  149647. ** completely applied.
  149648. */
  149649. SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  149650. /*
  149651. ** Return the total number of key-value operations (inserts, deletes or
  149652. ** updates) that have been performed on the target database since the
  149653. ** current RBU update was started.
  149654. */
  149655. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
  149656. /*
  149657. ** Create an RBU VFS named zName that accesses the underlying file-system
  149658. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  149659. ** then the new RBU VFS uses the default system VFS to access the file-system.
  149660. ** The new object is registered as a non-default VFS with SQLite before
  149661. ** returning.
  149662. **
  149663. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  149664. ** object is created and deleted automatically by RBU.
  149665. **
  149666. ** The exception is for applications that also use zipvfs. In this case,
  149667. ** the custom VFS must be explicitly created by the user before the RBU
  149668. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  149669. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  149670. ** (for example multiplexor) to access the file-system. For example,
  149671. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  149672. ** multiplexor (error checking omitted):
  149673. **
  149674. ** // Create a VFS named "multiplex" (not the default).
  149675. ** sqlite3_multiplex_initialize(0, 0);
  149676. **
  149677. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  149678. ** // second argument were replaced with NULL, the "rbu" VFS would
  149679. ** // access the file-system via the system default VFS, bypassing the
  149680. ** // multiplexor.
  149681. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  149682. **
  149683. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  149684. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  149685. **
  149686. ** // Make zipvfs the default VFS.
  149687. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  149688. **
  149689. ** Because the default VFS created above includes a RBU functionality, it
  149690. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  149691. ** that does not include the RBU layer results in an error.
  149692. **
  149693. ** The overhead of adding the "rbu" VFS to the system is negligible for
  149694. ** non-RBU users. There is no harm in an application accessing the
  149695. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  149696. ** occasionally.
  149697. */
  149698. SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  149699. /*
  149700. ** Deregister and destroy an RBU vfs created by an earlier call to
  149701. ** sqlite3rbu_create_vfs().
  149702. **
  149703. ** VFS objects are not reference counted. If a VFS object is destroyed
  149704. ** before all database handles that use it have been closed, the results
  149705. ** are undefined.
  149706. */
  149707. SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
  149708. #if 0
  149709. } /* end of the 'extern "C"' block */
  149710. #endif
  149711. #endif /* _SQLITE3RBU_H */
  149712. /************** End of sqlite3rbu.h ******************************************/
  149713. /************** Continuing where we left off in sqlite3rbu.c *****************/
  149714. #if defined(_WIN32_WCE)
  149715. /* #include "windows.h" */
  149716. #endif
  149717. /* Maximum number of prepared UPDATE statements held by this module */
  149718. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  149719. /*
  149720. ** Swap two objects of type TYPE.
  149721. */
  149722. #if !defined(SQLITE_AMALGAMATION)
  149723. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  149724. #endif
  149725. /*
  149726. ** The rbu_state table is used to save the state of a partially applied
  149727. ** update so that it can be resumed later. The table consists of integer
  149728. ** keys mapped to values as follows:
  149729. **
  149730. ** RBU_STATE_STAGE:
  149731. ** May be set to integer values 1, 2, 4 or 5. As follows:
  149732. ** 1: the *-rbu file is currently under construction.
  149733. ** 2: the *-rbu file has been constructed, but not yet moved
  149734. ** to the *-wal path.
  149735. ** 4: the checkpoint is underway.
  149736. ** 5: the rbu update has been checkpointed.
  149737. **
  149738. ** RBU_STATE_TBL:
  149739. ** Only valid if STAGE==1. The target database name of the table
  149740. ** currently being written.
  149741. **
  149742. ** RBU_STATE_IDX:
  149743. ** Only valid if STAGE==1. The target database name of the index
  149744. ** currently being written, or NULL if the main table is currently being
  149745. ** updated.
  149746. **
  149747. ** RBU_STATE_ROW:
  149748. ** Only valid if STAGE==1. Number of rows already processed for the current
  149749. ** table/index.
  149750. **
  149751. ** RBU_STATE_PROGRESS:
  149752. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  149753. ** rbu update.
  149754. **
  149755. ** RBU_STATE_CKPT:
  149756. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  149757. ** header created by recovering the *-wal file. This is used to detect
  149758. ** cases when another client appends frames to the *-wal file in the
  149759. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  149760. ** be continued if this happens).
  149761. **
  149762. ** RBU_STATE_COOKIE:
  149763. ** Valid if STAGE==1. The current change-counter cookie value in the
  149764. ** target db file.
  149765. **
  149766. ** RBU_STATE_OALSZ:
  149767. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  149768. */
  149769. #define RBU_STATE_STAGE 1
  149770. #define RBU_STATE_TBL 2
  149771. #define RBU_STATE_IDX 3
  149772. #define RBU_STATE_ROW 4
  149773. #define RBU_STATE_PROGRESS 5
  149774. #define RBU_STATE_CKPT 6
  149775. #define RBU_STATE_COOKIE 7
  149776. #define RBU_STATE_OALSZ 8
  149777. #define RBU_STAGE_OAL 1
  149778. #define RBU_STAGE_MOVE 2
  149779. #define RBU_STAGE_CAPTURE 3
  149780. #define RBU_STAGE_CKPT 4
  149781. #define RBU_STAGE_DONE 5
  149782. #define RBU_CREATE_STATE \
  149783. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  149784. typedef struct RbuFrame RbuFrame;
  149785. typedef struct RbuObjIter RbuObjIter;
  149786. typedef struct RbuState RbuState;
  149787. typedef struct rbu_vfs rbu_vfs;
  149788. typedef struct rbu_file rbu_file;
  149789. typedef struct RbuUpdateStmt RbuUpdateStmt;
  149790. #if !defined(SQLITE_AMALGAMATION)
  149791. typedef unsigned int u32;
  149792. typedef unsigned char u8;
  149793. typedef sqlite3_int64 i64;
  149794. #endif
  149795. /*
  149796. ** These values must match the values defined in wal.c for the equivalent
  149797. ** locks. These are not magic numbers as they are part of the SQLite file
  149798. ** format.
  149799. */
  149800. #define WAL_LOCK_WRITE 0
  149801. #define WAL_LOCK_CKPT 1
  149802. #define WAL_LOCK_READ0 3
  149803. /*
  149804. ** A structure to store values read from the rbu_state table in memory.
  149805. */
  149806. struct RbuState {
  149807. int eStage;
  149808. char *zTbl;
  149809. char *zIdx;
  149810. i64 iWalCksum;
  149811. int nRow;
  149812. i64 nProgress;
  149813. u32 iCookie;
  149814. i64 iOalSz;
  149815. };
  149816. struct RbuUpdateStmt {
  149817. char *zMask; /* Copy of update mask used with pUpdate */
  149818. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  149819. RbuUpdateStmt *pNext;
  149820. };
  149821. /*
  149822. ** An iterator of this type is used to iterate through all objects in
  149823. ** the target database that require updating. For each such table, the
  149824. ** iterator visits, in order:
  149825. **
  149826. ** * the table itself,
  149827. ** * each index of the table (zero or more points to visit), and
  149828. ** * a special "cleanup table" state.
  149829. **
  149830. ** abIndexed:
  149831. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  149832. ** it points to an array of flags nTblCol elements in size. The flag is
  149833. ** set for each column that is either a part of the PK or a part of an
  149834. ** index. Or clear otherwise.
  149835. **
  149836. */
  149837. struct RbuObjIter {
  149838. sqlite3_stmt *pTblIter; /* Iterate through tables */
  149839. sqlite3_stmt *pIdxIter; /* Index iterator */
  149840. int nTblCol; /* Size of azTblCol[] array */
  149841. char **azTblCol; /* Array of unquoted target column names */
  149842. char **azTblType; /* Array of target column types */
  149843. int *aiSrcOrder; /* src table col -> target table col */
  149844. u8 *abTblPk; /* Array of flags, set on target PK columns */
  149845. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  149846. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  149847. int eType; /* Table type - an RBU_PK_XXX value */
  149848. /* Output variables. zTbl==0 implies EOF. */
  149849. int bCleanup; /* True in "cleanup" state */
  149850. const char *zTbl; /* Name of target db table */
  149851. const char *zDataTbl; /* Name of rbu db table (or null) */
  149852. const char *zIdx; /* Name of target db index (or null) */
  149853. int iTnum; /* Root page of current object */
  149854. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  149855. int bUnique; /* Current index is unique */
  149856. /* Statements created by rbuObjIterPrepareAll() */
  149857. int nCol; /* Number of columns in current object */
  149858. sqlite3_stmt *pSelect; /* Source data */
  149859. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  149860. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  149861. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  149862. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  149863. RbuUpdateStmt *pRbuUpdate;
  149864. };
  149865. /*
  149866. ** Values for RbuObjIter.eType
  149867. **
  149868. ** 0: Table does not exist (error)
  149869. ** 1: Table has an implicit rowid.
  149870. ** 2: Table has an explicit IPK column.
  149871. ** 3: Table has an external PK index.
  149872. ** 4: Table is WITHOUT ROWID.
  149873. ** 5: Table is a virtual table.
  149874. */
  149875. #define RBU_PK_NOTABLE 0
  149876. #define RBU_PK_NONE 1
  149877. #define RBU_PK_IPK 2
  149878. #define RBU_PK_EXTERNAL 3
  149879. #define RBU_PK_WITHOUT_ROWID 4
  149880. #define RBU_PK_VTAB 5
  149881. /*
  149882. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  149883. ** one of the following operations.
  149884. */
  149885. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  149886. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  149887. #define RBU_IDX_DELETE 3 /* Delete a row from an aux. index b-tree */
  149888. #define RBU_IDX_INSERT 4 /* Insert on an aux. index b-tree */
  149889. #define RBU_UPDATE 5 /* Update a row in a main table b-tree */
  149890. /*
  149891. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  149892. ** file should be copied to page iDbPage of the database file.
  149893. */
  149894. struct RbuFrame {
  149895. u32 iDbPage;
  149896. u32 iWalFrame;
  149897. };
  149898. /*
  149899. ** RBU handle.
  149900. */
  149901. struct sqlite3rbu {
  149902. int eStage; /* Value of RBU_STATE_STAGE field */
  149903. sqlite3 *dbMain; /* target database handle */
  149904. sqlite3 *dbRbu; /* rbu database handle */
  149905. char *zTarget; /* Path to target db */
  149906. char *zRbu; /* Path to rbu db */
  149907. char *zState; /* Path to state db (or NULL if zRbu) */
  149908. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  149909. int rc; /* Value returned by last rbu_step() call */
  149910. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  149911. int nStep; /* Rows processed for current object */
  149912. int nProgress; /* Rows processed for all objects */
  149913. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  149914. const char *zVfsName; /* Name of automatically created rbu vfs */
  149915. rbu_file *pTargetFd; /* File handle open on target db */
  149916. i64 iOalSz;
  149917. /* The following state variables are used as part of the incremental
  149918. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  149919. ** function rbuSetupCheckpoint() for details. */
  149920. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  149921. u32 mLock;
  149922. int nFrame; /* Entries in aFrame[] array */
  149923. int nFrameAlloc; /* Allocated size of aFrame[] array */
  149924. RbuFrame *aFrame;
  149925. int pgsz;
  149926. u8 *aBuf;
  149927. i64 iWalCksum;
  149928. };
  149929. /*
  149930. ** An rbu VFS is implemented using an instance of this structure.
  149931. */
  149932. struct rbu_vfs {
  149933. sqlite3_vfs base; /* rbu VFS shim methods */
  149934. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  149935. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  149936. rbu_file *pMain; /* Linked list of main db files */
  149937. };
  149938. /*
  149939. ** Each file opened by an rbu VFS is represented by an instance of
  149940. ** the following structure.
  149941. */
  149942. struct rbu_file {
  149943. sqlite3_file base; /* sqlite3_file methods */
  149944. sqlite3_file *pReal; /* Underlying file handle */
  149945. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  149946. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  149947. int openFlags; /* Flags this file was opened with */
  149948. u32 iCookie; /* Cookie value for main db files */
  149949. u8 iWriteVer; /* "write-version" value for main db files */
  149950. int nShm; /* Number of entries in apShm[] array */
  149951. char **apShm; /* Array of mmap'd *-shm regions */
  149952. char *zDel; /* Delete this when closing file */
  149953. const char *zWal; /* Wal filename for this main db file */
  149954. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  149955. rbu_file *pMainNext; /* Next MAIN_DB file */
  149956. };
  149957. /*************************************************************************
  149958. ** The following three functions, found below:
  149959. **
  149960. ** rbuDeltaGetInt()
  149961. ** rbuDeltaChecksum()
  149962. ** rbuDeltaApply()
  149963. **
  149964. ** are lifted from the fossil source code (http://fossil-scm.org). They
  149965. ** are used to implement the scalar SQL function rbu_fossil_delta().
  149966. */
  149967. /*
  149968. ** Read bytes from *pz and convert them into a positive integer. When
  149969. ** finished, leave *pz pointing to the first character past the end of
  149970. ** the integer. The *pLen parameter holds the length of the string
  149971. ** in *pz and is decremented once for each character in the integer.
  149972. */
  149973. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  149974. static const signed char zValue[] = {
  149975. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  149976. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  149977. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  149978. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  149979. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  149980. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  149981. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  149982. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  149983. };
  149984. unsigned int v = 0;
  149985. int c;
  149986. unsigned char *z = (unsigned char*)*pz;
  149987. unsigned char *zStart = z;
  149988. while( (c = zValue[0x7f&*(z++)])>=0 ){
  149989. v = (v<<6) + c;
  149990. }
  149991. z--;
  149992. *pLen -= z - zStart;
  149993. *pz = (char*)z;
  149994. return v;
  149995. }
  149996. /*
  149997. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  149998. */
  149999. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  150000. const unsigned char *z = (const unsigned char *)zIn;
  150001. unsigned sum0 = 0;
  150002. unsigned sum1 = 0;
  150003. unsigned sum2 = 0;
  150004. unsigned sum3 = 0;
  150005. while(N >= 16){
  150006. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  150007. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  150008. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  150009. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  150010. z += 16;
  150011. N -= 16;
  150012. }
  150013. while(N >= 4){
  150014. sum0 += z[0];
  150015. sum1 += z[1];
  150016. sum2 += z[2];
  150017. sum3 += z[3];
  150018. z += 4;
  150019. N -= 4;
  150020. }
  150021. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  150022. switch(N){
  150023. case 3: sum3 += (z[2] << 8);
  150024. case 2: sum3 += (z[1] << 16);
  150025. case 1: sum3 += (z[0] << 24);
  150026. default: ;
  150027. }
  150028. return sum3;
  150029. }
  150030. /*
  150031. ** Apply a delta.
  150032. **
  150033. ** The output buffer should be big enough to hold the whole output
  150034. ** file and a NUL terminator at the end. The delta_output_size()
  150035. ** routine will determine this size for you.
  150036. **
  150037. ** The delta string should be null-terminated. But the delta string
  150038. ** may contain embedded NUL characters (if the input and output are
  150039. ** binary files) so we also have to pass in the length of the delta in
  150040. ** the lenDelta parameter.
  150041. **
  150042. ** This function returns the size of the output file in bytes (excluding
  150043. ** the final NUL terminator character). Except, if the delta string is
  150044. ** malformed or intended for use with a source file other than zSrc,
  150045. ** then this routine returns -1.
  150046. **
  150047. ** Refer to the delta_create() documentation above for a description
  150048. ** of the delta file format.
  150049. */
  150050. static int rbuDeltaApply(
  150051. const char *zSrc, /* The source or pattern file */
  150052. int lenSrc, /* Length of the source file */
  150053. const char *zDelta, /* Delta to apply to the pattern */
  150054. int lenDelta, /* Length of the delta */
  150055. char *zOut /* Write the output into this preallocated buffer */
  150056. ){
  150057. unsigned int limit;
  150058. unsigned int total = 0;
  150059. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  150060. char *zOrigOut = zOut;
  150061. #endif
  150062. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  150063. if( *zDelta!='\n' ){
  150064. /* ERROR: size integer not terminated by "\n" */
  150065. return -1;
  150066. }
  150067. zDelta++; lenDelta--;
  150068. while( *zDelta && lenDelta>0 ){
  150069. unsigned int cnt, ofst;
  150070. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  150071. switch( zDelta[0] ){
  150072. case '@': {
  150073. zDelta++; lenDelta--;
  150074. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  150075. if( lenDelta>0 && zDelta[0]!=',' ){
  150076. /* ERROR: copy command not terminated by ',' */
  150077. return -1;
  150078. }
  150079. zDelta++; lenDelta--;
  150080. total += cnt;
  150081. if( total>limit ){
  150082. /* ERROR: copy exceeds output file size */
  150083. return -1;
  150084. }
  150085. if( (int)(ofst+cnt) > lenSrc ){
  150086. /* ERROR: copy extends past end of input */
  150087. return -1;
  150088. }
  150089. memcpy(zOut, &zSrc[ofst], cnt);
  150090. zOut += cnt;
  150091. break;
  150092. }
  150093. case ':': {
  150094. zDelta++; lenDelta--;
  150095. total += cnt;
  150096. if( total>limit ){
  150097. /* ERROR: insert command gives an output larger than predicted */
  150098. return -1;
  150099. }
  150100. if( (int)cnt>lenDelta ){
  150101. /* ERROR: insert count exceeds size of delta */
  150102. return -1;
  150103. }
  150104. memcpy(zOut, zDelta, cnt);
  150105. zOut += cnt;
  150106. zDelta += cnt;
  150107. lenDelta -= cnt;
  150108. break;
  150109. }
  150110. case ';': {
  150111. zDelta++; lenDelta--;
  150112. zOut[0] = 0;
  150113. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  150114. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  150115. /* ERROR: bad checksum */
  150116. return -1;
  150117. }
  150118. #endif
  150119. if( total!=limit ){
  150120. /* ERROR: generated size does not match predicted size */
  150121. return -1;
  150122. }
  150123. return total;
  150124. }
  150125. default: {
  150126. /* ERROR: unknown delta operator */
  150127. return -1;
  150128. }
  150129. }
  150130. }
  150131. /* ERROR: unterminated delta */
  150132. return -1;
  150133. }
  150134. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  150135. int size;
  150136. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  150137. if( *zDelta!='\n' ){
  150138. /* ERROR: size integer not terminated by "\n" */
  150139. return -1;
  150140. }
  150141. return size;
  150142. }
  150143. /*
  150144. ** End of code taken from fossil.
  150145. *************************************************************************/
  150146. /*
  150147. ** Implementation of SQL scalar function rbu_fossil_delta().
  150148. **
  150149. ** This function applies a fossil delta patch to a blob. Exactly two
  150150. ** arguments must be passed to this function. The first is the blob to
  150151. ** patch and the second the patch to apply. If no error occurs, this
  150152. ** function returns the patched blob.
  150153. */
  150154. static void rbuFossilDeltaFunc(
  150155. sqlite3_context *context,
  150156. int argc,
  150157. sqlite3_value **argv
  150158. ){
  150159. const char *aDelta;
  150160. int nDelta;
  150161. const char *aOrig;
  150162. int nOrig;
  150163. int nOut;
  150164. int nOut2;
  150165. char *aOut;
  150166. assert( argc==2 );
  150167. nOrig = sqlite3_value_bytes(argv[0]);
  150168. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  150169. nDelta = sqlite3_value_bytes(argv[1]);
  150170. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  150171. /* Figure out the size of the output */
  150172. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  150173. if( nOut<0 ){
  150174. sqlite3_result_error(context, "corrupt fossil delta", -1);
  150175. return;
  150176. }
  150177. aOut = sqlite3_malloc(nOut+1);
  150178. if( aOut==0 ){
  150179. sqlite3_result_error_nomem(context);
  150180. }else{
  150181. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  150182. if( nOut2!=nOut ){
  150183. sqlite3_result_error(context, "corrupt fossil delta", -1);
  150184. }else{
  150185. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  150186. }
  150187. }
  150188. }
  150189. /*
  150190. ** Prepare the SQL statement in buffer zSql against database handle db.
  150191. ** If successful, set *ppStmt to point to the new statement and return
  150192. ** SQLITE_OK.
  150193. **
  150194. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  150195. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  150196. ** point to a buffer containing an error message. It is the responsibility
  150197. ** of the caller to (eventually) free this buffer using sqlite3_free().
  150198. */
  150199. static int prepareAndCollectError(
  150200. sqlite3 *db,
  150201. sqlite3_stmt **ppStmt,
  150202. char **pzErrmsg,
  150203. const char *zSql
  150204. ){
  150205. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  150206. if( rc!=SQLITE_OK ){
  150207. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  150208. *ppStmt = 0;
  150209. }
  150210. return rc;
  150211. }
  150212. /*
  150213. ** Reset the SQL statement passed as the first argument. Return a copy
  150214. ** of the value returned by sqlite3_reset().
  150215. **
  150216. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  150217. ** containing an error message. It is the responsibility of the caller
  150218. ** to eventually free this buffer using sqlite3_free().
  150219. */
  150220. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  150221. int rc = sqlite3_reset(pStmt);
  150222. if( rc!=SQLITE_OK ){
  150223. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  150224. }
  150225. return rc;
  150226. }
  150227. /*
  150228. ** Unless it is NULL, argument zSql points to a buffer allocated using
  150229. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  150230. ** statement against database db and frees the buffer. If statement
  150231. ** compilation is successful, *ppStmt is set to point to the new statement
  150232. ** handle and SQLITE_OK is returned.
  150233. **
  150234. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  150235. ** returned. In this case, *pzErrmsg may also be set to point to an error
  150236. ** message. It is the responsibility of the caller to free this error message
  150237. ** buffer using sqlite3_free().
  150238. **
  150239. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  150240. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  150241. */
  150242. static int prepareFreeAndCollectError(
  150243. sqlite3 *db,
  150244. sqlite3_stmt **ppStmt,
  150245. char **pzErrmsg,
  150246. char *zSql
  150247. ){
  150248. int rc;
  150249. assert( *pzErrmsg==0 );
  150250. if( zSql==0 ){
  150251. rc = SQLITE_NOMEM;
  150252. *ppStmt = 0;
  150253. }else{
  150254. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  150255. sqlite3_free(zSql);
  150256. }
  150257. return rc;
  150258. }
  150259. /*
  150260. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  150261. ** by an earlier call to rbuObjIterCacheTableInfo().
  150262. */
  150263. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  150264. int i;
  150265. for(i=0; i<pIter->nTblCol; i++){
  150266. sqlite3_free(pIter->azTblCol[i]);
  150267. sqlite3_free(pIter->azTblType[i]);
  150268. }
  150269. sqlite3_free(pIter->azTblCol);
  150270. pIter->azTblCol = 0;
  150271. pIter->azTblType = 0;
  150272. pIter->aiSrcOrder = 0;
  150273. pIter->abTblPk = 0;
  150274. pIter->abNotNull = 0;
  150275. pIter->nTblCol = 0;
  150276. pIter->eType = 0; /* Invalid value */
  150277. }
  150278. /*
  150279. ** Finalize all statements and free all allocations that are specific to
  150280. ** the current object (table/index pair).
  150281. */
  150282. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  150283. RbuUpdateStmt *pUp;
  150284. sqlite3_finalize(pIter->pSelect);
  150285. sqlite3_finalize(pIter->pInsert);
  150286. sqlite3_finalize(pIter->pDelete);
  150287. sqlite3_finalize(pIter->pTmpInsert);
  150288. pUp = pIter->pRbuUpdate;
  150289. while( pUp ){
  150290. RbuUpdateStmt *pTmp = pUp->pNext;
  150291. sqlite3_finalize(pUp->pUpdate);
  150292. sqlite3_free(pUp);
  150293. pUp = pTmp;
  150294. }
  150295. pIter->pSelect = 0;
  150296. pIter->pInsert = 0;
  150297. pIter->pDelete = 0;
  150298. pIter->pRbuUpdate = 0;
  150299. pIter->pTmpInsert = 0;
  150300. pIter->nCol = 0;
  150301. }
  150302. /*
  150303. ** Clean up any resources allocated as part of the iterator object passed
  150304. ** as the only argument.
  150305. */
  150306. static void rbuObjIterFinalize(RbuObjIter *pIter){
  150307. rbuObjIterClearStatements(pIter);
  150308. sqlite3_finalize(pIter->pTblIter);
  150309. sqlite3_finalize(pIter->pIdxIter);
  150310. rbuObjIterFreeCols(pIter);
  150311. memset(pIter, 0, sizeof(RbuObjIter));
  150312. }
  150313. /*
  150314. ** Advance the iterator to the next position.
  150315. **
  150316. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  150317. ** pointing to the next entry. Otherwise, an error code and message is
  150318. ** left in the RBU handle passed as the first argument. A copy of the
  150319. ** error code is returned.
  150320. */
  150321. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  150322. int rc = p->rc;
  150323. if( rc==SQLITE_OK ){
  150324. /* Free any SQLite statements used while processing the previous object */
  150325. rbuObjIterClearStatements(pIter);
  150326. if( pIter->zIdx==0 ){
  150327. rc = sqlite3_exec(p->dbMain,
  150328. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  150329. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  150330. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  150331. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  150332. , 0, 0, &p->zErrmsg
  150333. );
  150334. }
  150335. if( rc==SQLITE_OK ){
  150336. if( pIter->bCleanup ){
  150337. rbuObjIterFreeCols(pIter);
  150338. pIter->bCleanup = 0;
  150339. rc = sqlite3_step(pIter->pTblIter);
  150340. if( rc!=SQLITE_ROW ){
  150341. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  150342. pIter->zTbl = 0;
  150343. }else{
  150344. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  150345. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  150346. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  150347. }
  150348. }else{
  150349. if( pIter->zIdx==0 ){
  150350. sqlite3_stmt *pIdx = pIter->pIdxIter;
  150351. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  150352. }
  150353. if( rc==SQLITE_OK ){
  150354. rc = sqlite3_step(pIter->pIdxIter);
  150355. if( rc!=SQLITE_ROW ){
  150356. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  150357. pIter->bCleanup = 1;
  150358. pIter->zIdx = 0;
  150359. }else{
  150360. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  150361. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  150362. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  150363. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  150364. }
  150365. }
  150366. }
  150367. }
  150368. }
  150369. if( rc!=SQLITE_OK ){
  150370. rbuObjIterFinalize(pIter);
  150371. p->rc = rc;
  150372. }
  150373. return rc;
  150374. }
  150375. /*
  150376. ** The implementation of the rbu_target_name() SQL function. This function
  150377. ** accepts one argument - the name of a table in the RBU database. If the
  150378. ** table name matches the pattern:
  150379. **
  150380. ** data[0-9]_<name>
  150381. **
  150382. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  150383. ** Otherwise, if the only argument does not match the above pattern, an SQL
  150384. ** NULL is returned.
  150385. **
  150386. ** "data_t1" -> "t1"
  150387. ** "data0123_t2" -> "t2"
  150388. ** "dataAB_t3" -> NULL
  150389. */
  150390. static void rbuTargetNameFunc(
  150391. sqlite3_context *context,
  150392. int argc,
  150393. sqlite3_value **argv
  150394. ){
  150395. const char *zIn;
  150396. assert( argc==1 );
  150397. zIn = (const char*)sqlite3_value_text(argv[0]);
  150398. if( zIn && strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  150399. int i;
  150400. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  150401. if( zIn[i]=='_' && zIn[i+1] ){
  150402. sqlite3_result_text(context, &zIn[i+1], -1, SQLITE_STATIC);
  150403. }
  150404. }
  150405. }
  150406. /*
  150407. ** Initialize the iterator structure passed as the second argument.
  150408. **
  150409. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  150410. ** pointing to the first entry. Otherwise, an error code and message is
  150411. ** left in the RBU handle passed as the first argument. A copy of the
  150412. ** error code is returned.
  150413. */
  150414. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  150415. int rc;
  150416. memset(pIter, 0, sizeof(RbuObjIter));
  150417. rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  150418. "SELECT rbu_target_name(name) AS target, name FROM sqlite_master "
  150419. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  150420. "ORDER BY name"
  150421. );
  150422. if( rc==SQLITE_OK ){
  150423. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  150424. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  150425. " FROM main.sqlite_master "
  150426. " WHERE type='index' AND tbl_name = ?"
  150427. );
  150428. }
  150429. pIter->bCleanup = 1;
  150430. p->rc = rc;
  150431. return rbuObjIterNext(p, pIter);
  150432. }
  150433. /*
  150434. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  150435. ** an error code is stored in the RBU handle passed as the first argument.
  150436. **
  150437. ** If an error has already occurred (p->rc is already set to something other
  150438. ** than SQLITE_OK), then this function returns NULL without modifying the
  150439. ** stored error code. In this case it still calls sqlite3_free() on any
  150440. ** printf() parameters associated with %z conversions.
  150441. */
  150442. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  150443. char *zSql = 0;
  150444. va_list ap;
  150445. va_start(ap, zFmt);
  150446. zSql = sqlite3_vmprintf(zFmt, ap);
  150447. if( p->rc==SQLITE_OK ){
  150448. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  150449. }else{
  150450. sqlite3_free(zSql);
  150451. zSql = 0;
  150452. }
  150453. va_end(ap);
  150454. return zSql;
  150455. }
  150456. /*
  150457. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  150458. ** arguments are the usual subsitution values. This function performs
  150459. ** the printf() style substitutions and executes the result as an SQL
  150460. ** statement on the RBU handles database.
  150461. **
  150462. ** If an error occurs, an error code and error message is stored in the
  150463. ** RBU handle. If an error has already occurred when this function is
  150464. ** called, it is a no-op.
  150465. */
  150466. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  150467. va_list ap;
  150468. char *zSql;
  150469. va_start(ap, zFmt);
  150470. zSql = sqlite3_vmprintf(zFmt, ap);
  150471. if( p->rc==SQLITE_OK ){
  150472. if( zSql==0 ){
  150473. p->rc = SQLITE_NOMEM;
  150474. }else{
  150475. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  150476. }
  150477. }
  150478. sqlite3_free(zSql);
  150479. va_end(ap);
  150480. return p->rc;
  150481. }
  150482. /*
  150483. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  150484. ** bytes.
  150485. **
  150486. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  150487. ** error code in the rbu handle passed as the first argument. Or, if an
  150488. ** error has already occurred when this function is called, return NULL
  150489. ** immediately without attempting the allocation or modifying the stored
  150490. ** error code.
  150491. */
  150492. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  150493. void *pRet = 0;
  150494. if( p->rc==SQLITE_OK ){
  150495. assert( nByte>0 );
  150496. pRet = sqlite3_malloc(nByte);
  150497. if( pRet==0 ){
  150498. p->rc = SQLITE_NOMEM;
  150499. }else{
  150500. memset(pRet, 0, nByte);
  150501. }
  150502. }
  150503. return pRet;
  150504. }
  150505. /*
  150506. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  150507. ** there is room for at least nCol elements. If an OOM occurs, store an
  150508. ** error code in the RBU handle passed as the first argument.
  150509. */
  150510. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  150511. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  150512. char **azNew;
  150513. azNew = (char**)rbuMalloc(p, nByte);
  150514. if( azNew ){
  150515. pIter->azTblCol = azNew;
  150516. pIter->azTblType = &azNew[nCol];
  150517. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  150518. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  150519. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  150520. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  150521. }
  150522. }
  150523. /*
  150524. ** The first argument must be a nul-terminated string. This function
  150525. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  150526. ** It is the responsibility of the caller to eventually free this memory
  150527. ** using sqlite3_free().
  150528. **
  150529. ** If an OOM condition is encountered when attempting to allocate memory,
  150530. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  150531. ** if the allocation succeeds, (*pRc) is left unchanged.
  150532. */
  150533. static char *rbuStrndup(const char *zStr, int *pRc){
  150534. char *zRet = 0;
  150535. assert( *pRc==SQLITE_OK );
  150536. if( zStr ){
  150537. int nCopy = strlen(zStr) + 1;
  150538. zRet = (char*)sqlite3_malloc(nCopy);
  150539. if( zRet ){
  150540. memcpy(zRet, zStr, nCopy);
  150541. }else{
  150542. *pRc = SQLITE_NOMEM;
  150543. }
  150544. }
  150545. return zRet;
  150546. }
  150547. /*
  150548. ** Finalize the statement passed as the second argument.
  150549. **
  150550. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  150551. ** rbu handle error code is not already set, set the error code and error
  150552. ** message accordingly.
  150553. */
  150554. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  150555. sqlite3 *db = sqlite3_db_handle(pStmt);
  150556. int rc = sqlite3_finalize(pStmt);
  150557. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  150558. p->rc = rc;
  150559. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  150560. }
  150561. }
  150562. /* Determine the type of a table.
  150563. **
  150564. ** peType is of type (int*), a pointer to an output parameter of type
  150565. ** (int). This call sets the output parameter as follows, depending
  150566. ** on the type of the table specified by parameters dbName and zTbl.
  150567. **
  150568. ** RBU_PK_NOTABLE: No such table.
  150569. ** RBU_PK_NONE: Table has an implicit rowid.
  150570. ** RBU_PK_IPK: Table has an explicit IPK column.
  150571. ** RBU_PK_EXTERNAL: Table has an external PK index.
  150572. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  150573. ** RBU_PK_VTAB: Table is a virtual table.
  150574. **
  150575. ** Argument *piPk is also of type (int*), and also points to an output
  150576. ** parameter. Unless the table has an external primary key index
  150577. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  150578. ** if the table does have an external primary key index, then *piPk
  150579. ** is set to the root page number of the primary key index before
  150580. ** returning.
  150581. **
  150582. ** ALGORITHM:
  150583. **
  150584. ** if( no entry exists in sqlite_master ){
  150585. ** return RBU_PK_NOTABLE
  150586. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  150587. ** return RBU_PK_VTAB
  150588. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  150589. ** if( the index that is the pk exists in sqlite_master ){
  150590. ** *piPK = rootpage of that index.
  150591. ** return RBU_PK_EXTERNAL
  150592. ** }else{
  150593. ** return RBU_PK_WITHOUT_ROWID
  150594. ** }
  150595. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  150596. ** return RBU_PK_IPK
  150597. ** }else{
  150598. ** return RBU_PK_NONE
  150599. ** }
  150600. */
  150601. static void rbuTableType(
  150602. sqlite3rbu *p,
  150603. const char *zTab,
  150604. int *peType,
  150605. int *piTnum,
  150606. int *piPk
  150607. ){
  150608. /*
  150609. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  150610. ** 1) PRAGMA index_list = ?
  150611. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  150612. ** 3) PRAGMA table_info = ?
  150613. */
  150614. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  150615. *peType = RBU_PK_NOTABLE;
  150616. *piPk = 0;
  150617. assert( p->rc==SQLITE_OK );
  150618. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  150619. sqlite3_mprintf(
  150620. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  150621. " FROM sqlite_master"
  150622. " WHERE name=%Q", zTab
  150623. ));
  150624. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  150625. /* Either an error, or no such table. */
  150626. goto rbuTableType_end;
  150627. }
  150628. if( sqlite3_column_int(aStmt[0], 0) ){
  150629. *peType = RBU_PK_VTAB; /* virtual table */
  150630. goto rbuTableType_end;
  150631. }
  150632. *piTnum = sqlite3_column_int(aStmt[0], 1);
  150633. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  150634. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  150635. );
  150636. if( p->rc ) goto rbuTableType_end;
  150637. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  150638. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  150639. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  150640. if( zOrig && zIdx && zOrig[0]=='p' ){
  150641. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  150642. sqlite3_mprintf(
  150643. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  150644. ));
  150645. if( p->rc==SQLITE_OK ){
  150646. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  150647. *piPk = sqlite3_column_int(aStmt[2], 0);
  150648. *peType = RBU_PK_EXTERNAL;
  150649. }else{
  150650. *peType = RBU_PK_WITHOUT_ROWID;
  150651. }
  150652. }
  150653. goto rbuTableType_end;
  150654. }
  150655. }
  150656. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  150657. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  150658. );
  150659. if( p->rc==SQLITE_OK ){
  150660. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  150661. if( sqlite3_column_int(aStmt[3],5)>0 ){
  150662. *peType = RBU_PK_IPK; /* explicit IPK column */
  150663. goto rbuTableType_end;
  150664. }
  150665. }
  150666. *peType = RBU_PK_NONE;
  150667. }
  150668. rbuTableType_end: {
  150669. unsigned int i;
  150670. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  150671. rbuFinalize(p, aStmt[i]);
  150672. }
  150673. }
  150674. }
  150675. /*
  150676. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  150677. ** the pIter->abIndexed[] array.
  150678. */
  150679. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  150680. sqlite3_stmt *pList = 0;
  150681. int bIndex = 0;
  150682. if( p->rc==SQLITE_OK ){
  150683. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  150684. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  150685. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  150686. );
  150687. }
  150688. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  150689. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  150690. sqlite3_stmt *pXInfo = 0;
  150691. if( zIdx==0 ) break;
  150692. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  150693. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  150694. );
  150695. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  150696. int iCid = sqlite3_column_int(pXInfo, 1);
  150697. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  150698. }
  150699. rbuFinalize(p, pXInfo);
  150700. bIndex = 1;
  150701. }
  150702. rbuFinalize(p, pList);
  150703. if( bIndex==0 ) pIter->abIndexed = 0;
  150704. }
  150705. /*
  150706. ** If they are not already populated, populate the pIter->azTblCol[],
  150707. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  150708. ** the table (not index) that the iterator currently points to.
  150709. **
  150710. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  150711. ** an error does occur, an error code and error message are also left in
  150712. ** the RBU handle.
  150713. */
  150714. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  150715. if( pIter->azTblCol==0 ){
  150716. sqlite3_stmt *pStmt = 0;
  150717. int nCol = 0;
  150718. int i; /* for() loop iterator variable */
  150719. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  150720. int iOrder = 0;
  150721. int iTnum = 0;
  150722. /* Figure out the type of table this step will deal with. */
  150723. assert( pIter->eType==0 );
  150724. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  150725. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  150726. p->rc = SQLITE_ERROR;
  150727. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  150728. }
  150729. if( p->rc ) return p->rc;
  150730. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  150731. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  150732. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  150733. || pIter->eType==RBU_PK_VTAB
  150734. );
  150735. /* Populate the azTblCol[] and nTblCol variables based on the columns
  150736. ** of the input table. Ignore any input table columns that begin with
  150737. ** "rbu_". */
  150738. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  150739. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  150740. );
  150741. if( p->rc==SQLITE_OK ){
  150742. nCol = sqlite3_column_count(pStmt);
  150743. rbuAllocateIterArrays(p, pIter, nCol);
  150744. }
  150745. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  150746. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  150747. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  150748. char *zCopy = rbuStrndup(zName, &p->rc);
  150749. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  150750. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  150751. }
  150752. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  150753. bRbuRowid = 1;
  150754. }
  150755. }
  150756. sqlite3_finalize(pStmt);
  150757. pStmt = 0;
  150758. if( p->rc==SQLITE_OK
  150759. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  150760. ){
  150761. p->rc = SQLITE_ERROR;
  150762. p->zErrmsg = sqlite3_mprintf(
  150763. "table %q %s rbu_rowid column", pIter->zDataTbl,
  150764. (bRbuRowid ? "may not have" : "requires")
  150765. );
  150766. }
  150767. /* Check that all non-HIDDEN columns in the destination table are also
  150768. ** present in the input table. Populate the abTblPk[], azTblType[] and
  150769. ** aiTblOrder[] arrays at the same time. */
  150770. if( p->rc==SQLITE_OK ){
  150771. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  150772. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  150773. );
  150774. }
  150775. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  150776. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  150777. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  150778. for(i=iOrder; i<pIter->nTblCol; i++){
  150779. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  150780. }
  150781. if( i==pIter->nTblCol ){
  150782. p->rc = SQLITE_ERROR;
  150783. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  150784. pIter->zDataTbl, zName
  150785. );
  150786. }else{
  150787. int iPk = sqlite3_column_int(pStmt, 5);
  150788. int bNotNull = sqlite3_column_int(pStmt, 3);
  150789. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  150790. if( i!=iOrder ){
  150791. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  150792. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  150793. }
  150794. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  150795. pIter->abTblPk[iOrder] = (iPk!=0);
  150796. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  150797. iOrder++;
  150798. }
  150799. }
  150800. rbuFinalize(p, pStmt);
  150801. rbuObjIterCacheIndexedCols(p, pIter);
  150802. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  150803. }
  150804. return p->rc;
  150805. }
  150806. /*
  150807. ** This function constructs and returns a pointer to a nul-terminated
  150808. ** string containing some SQL clause or list based on one or more of the
  150809. ** column names currently stored in the pIter->azTblCol[] array.
  150810. */
  150811. static char *rbuObjIterGetCollist(
  150812. sqlite3rbu *p, /* RBU object */
  150813. RbuObjIter *pIter /* Object iterator for column names */
  150814. ){
  150815. char *zList = 0;
  150816. const char *zSep = "";
  150817. int i;
  150818. for(i=0; i<pIter->nTblCol; i++){
  150819. const char *z = pIter->azTblCol[i];
  150820. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  150821. zSep = ", ";
  150822. }
  150823. return zList;
  150824. }
  150825. /*
  150826. ** This function is used to create a SELECT list (the list of SQL
  150827. ** expressions that follows a SELECT keyword) for a SELECT statement
  150828. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  150829. ** index object currently indicated by the iterator object passed as the
  150830. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  150831. ** to obtain the required information.
  150832. **
  150833. ** If the index is of the following form:
  150834. **
  150835. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  150836. **
  150837. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  150838. ** "ipk", the returned string is:
  150839. **
  150840. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  150841. **
  150842. ** As well as the returned string, three other malloc'd strings are
  150843. ** returned via output parameters. As follows:
  150844. **
  150845. ** pzImposterCols: ...
  150846. ** pzImposterPk: ...
  150847. ** pzWhere: ...
  150848. */
  150849. static char *rbuObjIterGetIndexCols(
  150850. sqlite3rbu *p, /* RBU object */
  150851. RbuObjIter *pIter, /* Object iterator for column names */
  150852. char **pzImposterCols, /* OUT: Columns for imposter table */
  150853. char **pzImposterPk, /* OUT: Imposter PK clause */
  150854. char **pzWhere, /* OUT: WHERE clause */
  150855. int *pnBind /* OUT: Trbul number of columns */
  150856. ){
  150857. int rc = p->rc; /* Error code */
  150858. int rc2; /* sqlite3_finalize() return code */
  150859. char *zRet = 0; /* String to return */
  150860. char *zImpCols = 0; /* String to return via *pzImposterCols */
  150861. char *zImpPK = 0; /* String to return via *pzImposterPK */
  150862. char *zWhere = 0; /* String to return via *pzWhere */
  150863. int nBind = 0; /* Value to return via *pnBind */
  150864. const char *zCom = ""; /* Set to ", " later on */
  150865. const char *zAnd = ""; /* Set to " AND " later on */
  150866. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  150867. if( rc==SQLITE_OK ){
  150868. assert( p->zErrmsg==0 );
  150869. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  150870. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  150871. );
  150872. }
  150873. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  150874. int iCid = sqlite3_column_int(pXInfo, 1);
  150875. int bDesc = sqlite3_column_int(pXInfo, 3);
  150876. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  150877. const char *zCol;
  150878. const char *zType;
  150879. if( iCid<0 ){
  150880. /* An integer primary key. If the table has an explicit IPK, use
  150881. ** its name. Otherwise, use "rbu_rowid". */
  150882. if( pIter->eType==RBU_PK_IPK ){
  150883. int i;
  150884. for(i=0; pIter->abTblPk[i]==0; i++);
  150885. assert( i<pIter->nTblCol );
  150886. zCol = pIter->azTblCol[i];
  150887. }else{
  150888. zCol = "rbu_rowid";
  150889. }
  150890. zType = "INTEGER";
  150891. }else{
  150892. zCol = pIter->azTblCol[iCid];
  150893. zType = pIter->azTblType[iCid];
  150894. }
  150895. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  150896. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  150897. const char *zOrder = (bDesc ? " DESC" : "");
  150898. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  150899. zImpPK, zCom, nBind, zCol, zOrder
  150900. );
  150901. }
  150902. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  150903. zImpCols, zCom, nBind, zCol, zType, zCollate
  150904. );
  150905. zWhere = sqlite3_mprintf(
  150906. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  150907. );
  150908. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  150909. zCom = ", ";
  150910. zAnd = " AND ";
  150911. nBind++;
  150912. }
  150913. rc2 = sqlite3_finalize(pXInfo);
  150914. if( rc==SQLITE_OK ) rc = rc2;
  150915. if( rc!=SQLITE_OK ){
  150916. sqlite3_free(zRet);
  150917. sqlite3_free(zImpCols);
  150918. sqlite3_free(zImpPK);
  150919. sqlite3_free(zWhere);
  150920. zRet = 0;
  150921. zImpCols = 0;
  150922. zImpPK = 0;
  150923. zWhere = 0;
  150924. p->rc = rc;
  150925. }
  150926. *pzImposterCols = zImpCols;
  150927. *pzImposterPk = zImpPK;
  150928. *pzWhere = zWhere;
  150929. *pnBind = nBind;
  150930. return zRet;
  150931. }
  150932. /*
  150933. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  150934. ** paramter is passed "old", return a string of the form:
  150935. **
  150936. ** "old.a, old.b, old.b"
  150937. **
  150938. ** With the column names escaped.
  150939. **
  150940. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  150941. ** the text ", old._rowid_" to the returned value.
  150942. */
  150943. static char *rbuObjIterGetOldlist(
  150944. sqlite3rbu *p,
  150945. RbuObjIter *pIter,
  150946. const char *zObj
  150947. ){
  150948. char *zList = 0;
  150949. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  150950. const char *zS = "";
  150951. int i;
  150952. for(i=0; i<pIter->nTblCol; i++){
  150953. if( pIter->abIndexed[i] ){
  150954. const char *zCol = pIter->azTblCol[i];
  150955. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  150956. }else{
  150957. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  150958. }
  150959. zS = ", ";
  150960. if( zList==0 ){
  150961. p->rc = SQLITE_NOMEM;
  150962. break;
  150963. }
  150964. }
  150965. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  150966. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  150967. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  150968. }
  150969. }
  150970. return zList;
  150971. }
  150972. /*
  150973. ** Return an expression that can be used in a WHERE clause to match the
  150974. ** primary key of the current table. For example, if the table is:
  150975. **
  150976. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  150977. **
  150978. ** Return the string:
  150979. **
  150980. ** "b = ?1 AND c = ?2"
  150981. */
  150982. static char *rbuObjIterGetWhere(
  150983. sqlite3rbu *p,
  150984. RbuObjIter *pIter
  150985. ){
  150986. char *zList = 0;
  150987. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  150988. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  150989. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  150990. const char *zSep = "";
  150991. int i;
  150992. for(i=0; i<pIter->nTblCol; i++){
  150993. if( pIter->abTblPk[i] ){
  150994. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  150995. zSep = " AND ";
  150996. }
  150997. }
  150998. zList = rbuMPrintf(p,
  150999. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  151000. );
  151001. }else{
  151002. const char *zSep = "";
  151003. int i;
  151004. for(i=0; i<pIter->nTblCol; i++){
  151005. if( pIter->abTblPk[i] ){
  151006. const char *zCol = pIter->azTblCol[i];
  151007. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  151008. zSep = " AND ";
  151009. }
  151010. }
  151011. }
  151012. return zList;
  151013. }
  151014. /*
  151015. ** The SELECT statement iterating through the keys for the current object
  151016. ** (p->objiter.pSelect) currently points to a valid row. However, there
  151017. ** is something wrong with the rbu_control value in the rbu_control value
  151018. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  151019. ** of the RBU handle to something reflecting this.
  151020. */
  151021. static void rbuBadControlError(sqlite3rbu *p){
  151022. p->rc = SQLITE_ERROR;
  151023. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  151024. }
  151025. /*
  151026. ** Return a nul-terminated string containing the comma separated list of
  151027. ** assignments that should be included following the "SET" keyword of
  151028. ** an UPDATE statement used to update the table object that the iterator
  151029. ** passed as the second argument currently points to if the rbu_control
  151030. ** column of the data_xxx table entry is set to zMask.
  151031. **
  151032. ** The memory for the returned string is obtained from sqlite3_malloc().
  151033. ** It is the responsibility of the caller to eventually free it using
  151034. ** sqlite3_free().
  151035. **
  151036. ** If an OOM error is encountered when allocating space for the new
  151037. ** string, an error code is left in the rbu handle passed as the first
  151038. ** argument and NULL is returned. Or, if an error has already occurred
  151039. ** when this function is called, NULL is returned immediately, without
  151040. ** attempting the allocation or modifying the stored error code.
  151041. */
  151042. static char *rbuObjIterGetSetlist(
  151043. sqlite3rbu *p,
  151044. RbuObjIter *pIter,
  151045. const char *zMask
  151046. ){
  151047. char *zList = 0;
  151048. if( p->rc==SQLITE_OK ){
  151049. int i;
  151050. if( (int)strlen(zMask)!=pIter->nTblCol ){
  151051. rbuBadControlError(p);
  151052. }else{
  151053. const char *zSep = "";
  151054. for(i=0; i<pIter->nTblCol; i++){
  151055. char c = zMask[pIter->aiSrcOrder[i]];
  151056. if( c=='x' ){
  151057. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  151058. zList, zSep, pIter->azTblCol[i], i+1
  151059. );
  151060. zSep = ", ";
  151061. }
  151062. else if( c=='d' ){
  151063. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  151064. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  151065. );
  151066. zSep = ", ";
  151067. }
  151068. else if( c=='f' ){
  151069. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  151070. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  151071. );
  151072. zSep = ", ";
  151073. }
  151074. }
  151075. }
  151076. }
  151077. return zList;
  151078. }
  151079. /*
  151080. ** Return a nul-terminated string consisting of nByte comma separated
  151081. ** "?" expressions. For example, if nByte is 3, return a pointer to
  151082. ** a buffer containing the string "?,?,?".
  151083. **
  151084. ** The memory for the returned string is obtained from sqlite3_malloc().
  151085. ** It is the responsibility of the caller to eventually free it using
  151086. ** sqlite3_free().
  151087. **
  151088. ** If an OOM error is encountered when allocating space for the new
  151089. ** string, an error code is left in the rbu handle passed as the first
  151090. ** argument and NULL is returned. Or, if an error has already occurred
  151091. ** when this function is called, NULL is returned immediately, without
  151092. ** attempting the allocation or modifying the stored error code.
  151093. */
  151094. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  151095. char *zRet = 0;
  151096. int nByte = nBind*2 + 1;
  151097. zRet = (char*)rbuMalloc(p, nByte);
  151098. if( zRet ){
  151099. int i;
  151100. for(i=0; i<nBind; i++){
  151101. zRet[i*2] = '?';
  151102. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  151103. }
  151104. }
  151105. return zRet;
  151106. }
  151107. /*
  151108. ** The iterator currently points to a table (not index) of type
  151109. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  151110. ** declaration for the corresponding imposter table. For example,
  151111. ** if the iterator points to a table created as:
  151112. **
  151113. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  151114. **
  151115. ** this function returns:
  151116. **
  151117. ** PRIMARY KEY("b", "a" DESC)
  151118. */
  151119. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  151120. char *z = 0;
  151121. assert( pIter->zIdx==0 );
  151122. if( p->rc==SQLITE_OK ){
  151123. const char *zSep = "PRIMARY KEY(";
  151124. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  151125. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  151126. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  151127. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  151128. );
  151129. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  151130. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  151131. if( zOrig && strcmp(zOrig, "pk")==0 ){
  151132. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  151133. if( zIdx ){
  151134. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  151135. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  151136. );
  151137. }
  151138. break;
  151139. }
  151140. }
  151141. rbuFinalize(p, pXList);
  151142. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  151143. if( sqlite3_column_int(pXInfo, 5) ){
  151144. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  151145. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  151146. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  151147. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  151148. zSep = ", ";
  151149. }
  151150. }
  151151. z = rbuMPrintf(p, "%z)", z);
  151152. rbuFinalize(p, pXInfo);
  151153. }
  151154. return z;
  151155. }
  151156. /*
  151157. ** This function creates the second imposter table used when writing to
  151158. ** a table b-tree where the table has an external primary key. If the
  151159. ** iterator passed as the second argument does not currently point to
  151160. ** a table (not index) with an external primary key, this function is a
  151161. ** no-op.
  151162. **
  151163. ** Assuming the iterator does point to a table with an external PK, this
  151164. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  151165. ** used to access that PK index. For example, if the target table is
  151166. ** declared as follows:
  151167. **
  151168. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  151169. **
  151170. ** then the imposter table schema is:
  151171. **
  151172. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  151173. **
  151174. */
  151175. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  151176. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  151177. int tnum = pIter->iPkTnum; /* Root page of PK index */
  151178. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  151179. const char *zIdx = 0; /* Name of PK index */
  151180. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  151181. const char *zComma = "";
  151182. char *zCols = 0; /* Used to build up list of table cols */
  151183. char *zPk = 0; /* Used to build up table PK declaration */
  151184. /* Figure out the name of the primary key index for the current table.
  151185. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  151186. ** zIdx to point to a nul-terminated string containing this name. */
  151187. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  151188. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  151189. );
  151190. if( p->rc==SQLITE_OK ){
  151191. sqlite3_bind_int(pQuery, 1, tnum);
  151192. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  151193. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  151194. }
  151195. }
  151196. if( zIdx ){
  151197. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  151198. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  151199. );
  151200. }
  151201. rbuFinalize(p, pQuery);
  151202. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  151203. int bKey = sqlite3_column_int(pXInfo, 5);
  151204. if( bKey ){
  151205. int iCid = sqlite3_column_int(pXInfo, 1);
  151206. int bDesc = sqlite3_column_int(pXInfo, 3);
  151207. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  151208. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
  151209. iCid, pIter->azTblType[iCid], zCollate
  151210. );
  151211. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  151212. zComma = ", ";
  151213. }
  151214. }
  151215. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  151216. rbuFinalize(p, pXInfo);
  151217. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  151218. rbuMPrintfExec(p, p->dbMain,
  151219. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  151220. zCols, zPk
  151221. );
  151222. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  151223. }
  151224. }
  151225. /*
  151226. ** If an error has already occurred when this function is called, it
  151227. ** immediately returns zero (without doing any work). Or, if an error
  151228. ** occurs during the execution of this function, it sets the error code
  151229. ** in the sqlite3rbu object indicated by the first argument and returns
  151230. ** zero.
  151231. **
  151232. ** The iterator passed as the second argument is guaranteed to point to
  151233. ** a table (not an index) when this function is called. This function
  151234. ** attempts to create any imposter table required to write to the main
  151235. ** table b-tree of the table before returning. Non-zero is returned if
  151236. ** an imposter table are created, or zero otherwise.
  151237. **
  151238. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  151239. ** virtual tables are written to directly. The imposter table has the
  151240. ** same schema as the actual target table (less any UNIQUE constraints).
  151241. ** More precisely, the "same schema" means the same columns, types,
  151242. ** collation sequences. For tables that do not have an external PRIMARY
  151243. ** KEY, it also means the same PRIMARY KEY declaration.
  151244. */
  151245. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  151246. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  151247. int tnum = pIter->iTnum;
  151248. const char *zComma = "";
  151249. char *zSql = 0;
  151250. int iCol;
  151251. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  151252. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  151253. const char *zPk = "";
  151254. const char *zCol = pIter->azTblCol[iCol];
  151255. const char *zColl = 0;
  151256. p->rc = sqlite3_table_column_metadata(
  151257. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  151258. );
  151259. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  151260. /* If the target table column is an "INTEGER PRIMARY KEY", add
  151261. ** "PRIMARY KEY" to the imposter table column declaration. */
  151262. zPk = "PRIMARY KEY ";
  151263. }
  151264. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
  151265. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  151266. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  151267. );
  151268. zComma = ", ";
  151269. }
  151270. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  151271. char *zPk = rbuWithoutRowidPK(p, pIter);
  151272. if( zPk ){
  151273. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  151274. }
  151275. }
  151276. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  151277. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  151278. pIter->zTbl, zSql,
  151279. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  151280. );
  151281. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  151282. }
  151283. }
  151284. /*
  151285. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  151286. ** Specifically a statement of the form:
  151287. **
  151288. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  151289. **
  151290. ** The number of bound variables is equal to the number of columns in
  151291. ** the target table, plus one (for the rbu_control column), plus one more
  151292. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  151293. ** virtual table.
  151294. */
  151295. static void rbuObjIterPrepareTmpInsert(
  151296. sqlite3rbu *p,
  151297. RbuObjIter *pIter,
  151298. const char *zCollist,
  151299. const char *zRbuRowid
  151300. ){
  151301. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  151302. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  151303. if( zBind ){
  151304. assert( pIter->pTmpInsert==0 );
  151305. p->rc = prepareFreeAndCollectError(
  151306. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  151307. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  151308. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  151309. ));
  151310. }
  151311. }
  151312. static void rbuTmpInsertFunc(
  151313. sqlite3_context *pCtx,
  151314. int nVal,
  151315. sqlite3_value **apVal
  151316. ){
  151317. sqlite3rbu *p = sqlite3_user_data(pCtx);
  151318. int rc = SQLITE_OK;
  151319. int i;
  151320. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  151321. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  151322. }
  151323. if( rc==SQLITE_OK ){
  151324. sqlite3_step(p->objiter.pTmpInsert);
  151325. rc = sqlite3_reset(p->objiter.pTmpInsert);
  151326. }
  151327. if( rc!=SQLITE_OK ){
  151328. sqlite3_result_error_code(pCtx, rc);
  151329. }
  151330. }
  151331. /*
  151332. ** Ensure that the SQLite statement handles required to update the
  151333. ** target database object currently indicated by the iterator passed
  151334. ** as the second argument are available.
  151335. */
  151336. static int rbuObjIterPrepareAll(
  151337. sqlite3rbu *p,
  151338. RbuObjIter *pIter,
  151339. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  151340. ){
  151341. assert( pIter->bCleanup==0 );
  151342. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  151343. const int tnum = pIter->iTnum;
  151344. char *zCollist = 0; /* List of indexed columns */
  151345. char **pz = &p->zErrmsg;
  151346. const char *zIdx = pIter->zIdx;
  151347. char *zLimit = 0;
  151348. if( nOffset ){
  151349. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  151350. if( !zLimit ) p->rc = SQLITE_NOMEM;
  151351. }
  151352. if( zIdx ){
  151353. const char *zTbl = pIter->zTbl;
  151354. char *zImposterCols = 0; /* Columns for imposter table */
  151355. char *zImposterPK = 0; /* Primary key declaration for imposter */
  151356. char *zWhere = 0; /* WHERE clause on PK columns */
  151357. char *zBind = 0;
  151358. int nBind = 0;
  151359. assert( pIter->eType!=RBU_PK_VTAB );
  151360. zCollist = rbuObjIterGetIndexCols(
  151361. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  151362. );
  151363. zBind = rbuObjIterGetBindlist(p, nBind);
  151364. /* Create the imposter table used to write to this index. */
  151365. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  151366. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  151367. rbuMPrintfExec(p, p->dbMain,
  151368. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  151369. zTbl, zImposterCols, zImposterPK
  151370. );
  151371. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  151372. /* Create the statement to insert index entries */
  151373. pIter->nCol = nBind;
  151374. if( p->rc==SQLITE_OK ){
  151375. p->rc = prepareFreeAndCollectError(
  151376. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  151377. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  151378. );
  151379. }
  151380. /* And to delete index entries */
  151381. if( p->rc==SQLITE_OK ){
  151382. p->rc = prepareFreeAndCollectError(
  151383. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  151384. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  151385. );
  151386. }
  151387. /* Create the SELECT statement to read keys in sorted order */
  151388. if( p->rc==SQLITE_OK ){
  151389. char *zSql;
  151390. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  151391. zSql = sqlite3_mprintf(
  151392. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  151393. zCollist, p->zStateDb, pIter->zDataTbl,
  151394. zCollist, zLimit
  151395. );
  151396. }else{
  151397. zSql = sqlite3_mprintf(
  151398. "SELECT %s, rbu_control FROM '%q' "
  151399. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  151400. "UNION ALL "
  151401. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  151402. "ORDER BY %s%s",
  151403. zCollist, pIter->zDataTbl,
  151404. zCollist, p->zStateDb, pIter->zDataTbl,
  151405. zCollist, zLimit
  151406. );
  151407. }
  151408. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  151409. }
  151410. sqlite3_free(zImposterCols);
  151411. sqlite3_free(zImposterPK);
  151412. sqlite3_free(zWhere);
  151413. sqlite3_free(zBind);
  151414. }else{
  151415. int bRbuRowid = (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE);
  151416. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  151417. const char *zWrite; /* Imposter table name */
  151418. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  151419. char *zWhere = rbuObjIterGetWhere(p, pIter);
  151420. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  151421. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  151422. zCollist = rbuObjIterGetCollist(p, pIter);
  151423. pIter->nCol = pIter->nTblCol;
  151424. /* Create the imposter table or tables (if required). */
  151425. rbuCreateImposterTable(p, pIter);
  151426. rbuCreateImposterTable2(p, pIter);
  151427. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  151428. /* Create the INSERT statement to write to the target PK b-tree */
  151429. if( p->rc==SQLITE_OK ){
  151430. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  151431. sqlite3_mprintf(
  151432. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  151433. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  151434. )
  151435. );
  151436. }
  151437. /* Create the DELETE statement to write to the target PK b-tree */
  151438. if( p->rc==SQLITE_OK ){
  151439. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  151440. sqlite3_mprintf(
  151441. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  151442. )
  151443. );
  151444. }
  151445. if( pIter->abIndexed ){
  151446. const char *zRbuRowid = "";
  151447. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  151448. zRbuRowid = ", rbu_rowid";
  151449. }
  151450. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  151451. rbuMPrintfExec(p, p->dbRbu,
  151452. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  151453. "SELECT *%s FROM '%q' WHERE 0;"
  151454. , p->zStateDb, pIter->zDataTbl
  151455. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  151456. , pIter->zDataTbl
  151457. );
  151458. rbuMPrintfExec(p, p->dbMain,
  151459. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  151460. "BEGIN "
  151461. " SELECT rbu_tmp_insert(2, %s);"
  151462. "END;"
  151463. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  151464. "BEGIN "
  151465. " SELECT rbu_tmp_insert(2, %s);"
  151466. "END;"
  151467. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  151468. "BEGIN "
  151469. " SELECT rbu_tmp_insert(3, %s);"
  151470. "END;",
  151471. zWrite, zTbl, zOldlist,
  151472. zWrite, zTbl, zOldlist,
  151473. zWrite, zTbl, zNewlist
  151474. );
  151475. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  151476. rbuMPrintfExec(p, p->dbMain,
  151477. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  151478. "BEGIN "
  151479. " SELECT rbu_tmp_insert(0, %s);"
  151480. "END;",
  151481. zWrite, zTbl, zNewlist
  151482. );
  151483. }
  151484. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  151485. }
  151486. /* Create the SELECT statement to read keys from data_xxx */
  151487. if( p->rc==SQLITE_OK ){
  151488. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  151489. sqlite3_mprintf(
  151490. "SELECT %s, rbu_control%s FROM '%q'%s",
  151491. zCollist, (bRbuRowid ? ", rbu_rowid" : ""),
  151492. pIter->zDataTbl, zLimit
  151493. )
  151494. );
  151495. }
  151496. sqlite3_free(zWhere);
  151497. sqlite3_free(zOldlist);
  151498. sqlite3_free(zNewlist);
  151499. sqlite3_free(zBindings);
  151500. }
  151501. sqlite3_free(zCollist);
  151502. sqlite3_free(zLimit);
  151503. }
  151504. return p->rc;
  151505. }
  151506. /*
  151507. ** Set output variable *ppStmt to point to an UPDATE statement that may
  151508. ** be used to update the imposter table for the main table b-tree of the
  151509. ** table object that pIter currently points to, assuming that the
  151510. ** rbu_control column of the data_xyz table contains zMask.
  151511. **
  151512. ** If the zMask string does not specify any columns to update, then this
  151513. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  151514. */
  151515. static int rbuGetUpdateStmt(
  151516. sqlite3rbu *p, /* RBU handle */
  151517. RbuObjIter *pIter, /* Object iterator */
  151518. const char *zMask, /* rbu_control value ('x.x.') */
  151519. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  151520. ){
  151521. RbuUpdateStmt **pp;
  151522. RbuUpdateStmt *pUp = 0;
  151523. int nUp = 0;
  151524. /* In case an error occurs */
  151525. *ppStmt = 0;
  151526. /* Search for an existing statement. If one is found, shift it to the front
  151527. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  151528. ** to the number of statements currently in the cache and pUp to the
  151529. ** last object in the list. */
  151530. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  151531. pUp = *pp;
  151532. if( strcmp(pUp->zMask, zMask)==0 ){
  151533. *pp = pUp->pNext;
  151534. pUp->pNext = pIter->pRbuUpdate;
  151535. pIter->pRbuUpdate = pUp;
  151536. *ppStmt = pUp->pUpdate;
  151537. return SQLITE_OK;
  151538. }
  151539. nUp++;
  151540. }
  151541. assert( pUp==0 || pUp->pNext==0 );
  151542. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  151543. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  151544. *pp = 0;
  151545. sqlite3_finalize(pUp->pUpdate);
  151546. pUp->pUpdate = 0;
  151547. }else{
  151548. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  151549. }
  151550. if( pUp ){
  151551. char *zWhere = rbuObjIterGetWhere(p, pIter);
  151552. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  151553. char *zUpdate = 0;
  151554. pUp->zMask = (char*)&pUp[1];
  151555. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  151556. pUp->pNext = pIter->pRbuUpdate;
  151557. pIter->pRbuUpdate = pUp;
  151558. if( zSet ){
  151559. const char *zPrefix = "";
  151560. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  151561. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  151562. zPrefix, pIter->zTbl, zSet, zWhere
  151563. );
  151564. p->rc = prepareFreeAndCollectError(
  151565. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  151566. );
  151567. *ppStmt = pUp->pUpdate;
  151568. }
  151569. sqlite3_free(zWhere);
  151570. sqlite3_free(zSet);
  151571. }
  151572. return p->rc;
  151573. }
  151574. static sqlite3 *rbuOpenDbhandle(sqlite3rbu *p, const char *zName){
  151575. sqlite3 *db = 0;
  151576. if( p->rc==SQLITE_OK ){
  151577. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  151578. p->rc = sqlite3_open_v2(zName, &db, flags, p->zVfsName);
  151579. if( p->rc ){
  151580. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  151581. sqlite3_close(db);
  151582. db = 0;
  151583. }
  151584. }
  151585. return db;
  151586. }
  151587. /*
  151588. ** Open the database handle and attach the RBU database as "rbu". If an
  151589. ** error occurs, leave an error code and message in the RBU handle.
  151590. */
  151591. static void rbuOpenDatabase(sqlite3rbu *p){
  151592. assert( p->rc==SQLITE_OK );
  151593. assert( p->dbMain==0 && p->dbRbu==0 );
  151594. p->eStage = 0;
  151595. p->dbMain = rbuOpenDbhandle(p, p->zTarget);
  151596. p->dbRbu = rbuOpenDbhandle(p, p->zRbu);
  151597. /* If using separate RBU and state databases, attach the state database to
  151598. ** the RBU db handle now. */
  151599. if( p->zState ){
  151600. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  151601. memcpy(p->zStateDb, "stat", 4);
  151602. }else{
  151603. memcpy(p->zStateDb, "main", 4);
  151604. }
  151605. if( p->rc==SQLITE_OK ){
  151606. p->rc = sqlite3_create_function(p->dbMain,
  151607. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  151608. );
  151609. }
  151610. if( p->rc==SQLITE_OK ){
  151611. p->rc = sqlite3_create_function(p->dbMain,
  151612. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  151613. );
  151614. }
  151615. if( p->rc==SQLITE_OK ){
  151616. p->rc = sqlite3_create_function(p->dbRbu,
  151617. "rbu_target_name", 1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  151618. );
  151619. }
  151620. if( p->rc==SQLITE_OK ){
  151621. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  151622. }
  151623. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  151624. /* Mark the database file just opened as an RBU target database. If
  151625. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  151626. ** This is an error. */
  151627. if( p->rc==SQLITE_OK ){
  151628. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  151629. }
  151630. if( p->rc==SQLITE_NOTFOUND ){
  151631. p->rc = SQLITE_ERROR;
  151632. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  151633. }
  151634. }
  151635. /*
  151636. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  151637. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  151638. **
  151639. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  151640. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  151641. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  151642. ** three characters, then shorten the suffix on z[] to be the last three
  151643. ** characters of the original suffix.
  151644. **
  151645. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  151646. ** do the suffix shortening regardless of URI parameter.
  151647. **
  151648. ** Examples:
  151649. **
  151650. ** test.db-journal => test.nal
  151651. ** test.db-wal => test.wal
  151652. ** test.db-shm => test.shm
  151653. ** test.db-mj7f3319fa => test.9fa
  151654. */
  151655. static void rbuFileSuffix3(const char *zBase, char *z){
  151656. #ifdef SQLITE_ENABLE_8_3_NAMES
  151657. #if SQLITE_ENABLE_8_3_NAMES<2
  151658. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  151659. #endif
  151660. {
  151661. int i, sz;
  151662. sz = sqlite3Strlen30(z);
  151663. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  151664. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  151665. }
  151666. #endif
  151667. }
  151668. /*
  151669. ** Return the current wal-index header checksum for the target database
  151670. ** as a 64-bit integer.
  151671. **
  151672. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  151673. ** blob starting at byte offset 40.
  151674. */
  151675. static i64 rbuShmChecksum(sqlite3rbu *p){
  151676. i64 iRet = 0;
  151677. if( p->rc==SQLITE_OK ){
  151678. sqlite3_file *pDb = p->pTargetFd->pReal;
  151679. u32 volatile *ptr;
  151680. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  151681. if( p->rc==SQLITE_OK ){
  151682. iRet = ((i64)ptr[10] << 32) + ptr[11];
  151683. }
  151684. }
  151685. return iRet;
  151686. }
  151687. /*
  151688. ** This function is called as part of initializing or reinitializing an
  151689. ** incremental checkpoint.
  151690. **
  151691. ** It populates the sqlite3rbu.aFrame[] array with the set of
  151692. ** (wal frame -> db page) copy operations required to checkpoint the
  151693. ** current wal file, and obtains the set of shm locks required to safely
  151694. ** perform the copy operations directly on the file-system.
  151695. **
  151696. ** If argument pState is not NULL, then the incremental checkpoint is
  151697. ** being resumed. In this case, if the checksum of the wal-index-header
  151698. ** following recovery is not the same as the checksum saved in the RbuState
  151699. ** object, then the rbu handle is set to DONE state. This occurs if some
  151700. ** other client appends a transaction to the wal file in the middle of
  151701. ** an incremental checkpoint.
  151702. */
  151703. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  151704. /* If pState is NULL, then the wal file may not have been opened and
  151705. ** recovered. Running a read-statement here to ensure that doing so
  151706. ** does not interfere with the "capture" process below. */
  151707. if( pState==0 ){
  151708. p->eStage = 0;
  151709. if( p->rc==SQLITE_OK ){
  151710. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  151711. }
  151712. }
  151713. /* Assuming no error has occurred, run a "restart" checkpoint with the
  151714. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  151715. ** special behaviour in the rbu VFS:
  151716. **
  151717. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  151718. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  151719. ** proceed with running a passive checkpoint instead of failing).
  151720. **
  151721. ** * Attempts to read from the *-wal file or write to the database file
  151722. ** do not perform any IO. Instead, the frame/page combinations that
  151723. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  151724. ** array.
  151725. **
  151726. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  151727. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  151728. ** no-ops. These locks will not be released until the connection
  151729. ** is closed.
  151730. **
  151731. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  151732. ** error.
  151733. **
  151734. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  151735. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  151736. ** array populated with a set of (frame -> page) mappings. Because the
  151737. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  151738. ** data from the wal file into the database file according to the
  151739. ** contents of aFrame[].
  151740. */
  151741. if( p->rc==SQLITE_OK ){
  151742. int rc2;
  151743. p->eStage = RBU_STAGE_CAPTURE;
  151744. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  151745. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  151746. }
  151747. if( p->rc==SQLITE_OK ){
  151748. p->eStage = RBU_STAGE_CKPT;
  151749. p->nStep = (pState ? pState->nRow : 0);
  151750. p->aBuf = rbuMalloc(p, p->pgsz);
  151751. p->iWalCksum = rbuShmChecksum(p);
  151752. }
  151753. if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
  151754. p->rc = SQLITE_DONE;
  151755. p->eStage = RBU_STAGE_DONE;
  151756. }
  151757. }
  151758. /*
  151759. ** Called when iAmt bytes are read from offset iOff of the wal file while
  151760. ** the rbu object is in capture mode. Record the frame number of the frame
  151761. ** being read in the aFrame[] array.
  151762. */
  151763. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  151764. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  151765. u32 iFrame;
  151766. if( pRbu->mLock!=mReq ){
  151767. pRbu->rc = SQLITE_BUSY;
  151768. return SQLITE_INTERNAL;
  151769. }
  151770. pRbu->pgsz = iAmt;
  151771. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  151772. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  151773. RbuFrame *aNew;
  151774. aNew = (RbuFrame*)sqlite3_realloc(pRbu->aFrame, nNew * sizeof(RbuFrame));
  151775. if( aNew==0 ) return SQLITE_NOMEM;
  151776. pRbu->aFrame = aNew;
  151777. pRbu->nFrameAlloc = nNew;
  151778. }
  151779. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  151780. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  151781. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  151782. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  151783. pRbu->nFrame++;
  151784. return SQLITE_OK;
  151785. }
  151786. /*
  151787. ** Called when a page of data is written to offset iOff of the database
  151788. ** file while the rbu handle is in capture mode. Record the page number
  151789. ** of the page being written in the aFrame[] array.
  151790. */
  151791. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  151792. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  151793. return SQLITE_OK;
  151794. }
  151795. /*
  151796. ** This is called as part of an incremental checkpoint operation. Copy
  151797. ** a single frame of data from the wal file into the database file, as
  151798. ** indicated by the RbuFrame object.
  151799. */
  151800. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  151801. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  151802. sqlite3_file *pDb = p->pTargetFd->pReal;
  151803. i64 iOff;
  151804. assert( p->rc==SQLITE_OK );
  151805. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  151806. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  151807. if( p->rc ) return;
  151808. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  151809. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  151810. }
  151811. /*
  151812. ** Take an EXCLUSIVE lock on the database file.
  151813. */
  151814. static void rbuLockDatabase(sqlite3rbu *p){
  151815. sqlite3_file *pReal = p->pTargetFd->pReal;
  151816. assert( p->rc==SQLITE_OK );
  151817. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  151818. if( p->rc==SQLITE_OK ){
  151819. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  151820. }
  151821. }
  151822. #if defined(_WIN32_WCE)
  151823. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  151824. int nChar;
  151825. LPWSTR zWideFilename;
  151826. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  151827. if( nChar==0 ){
  151828. return 0;
  151829. }
  151830. zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
  151831. if( zWideFilename==0 ){
  151832. return 0;
  151833. }
  151834. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  151835. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  151836. nChar);
  151837. if( nChar==0 ){
  151838. sqlite3_free(zWideFilename);
  151839. zWideFilename = 0;
  151840. }
  151841. return zWideFilename;
  151842. }
  151843. #endif
  151844. /*
  151845. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  151846. ** on the database file. This proc moves the *-oal file to the *-wal path,
  151847. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  151848. ** If an error occurs, leave an error code and error message in the rbu
  151849. ** handle.
  151850. */
  151851. static void rbuMoveOalFile(sqlite3rbu *p){
  151852. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  151853. char *zWal = sqlite3_mprintf("%s-wal", zBase);
  151854. char *zOal = sqlite3_mprintf("%s-oal", zBase);
  151855. assert( p->eStage==RBU_STAGE_MOVE );
  151856. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  151857. if( zWal==0 || zOal==0 ){
  151858. p->rc = SQLITE_NOMEM;
  151859. }else{
  151860. /* Move the *-oal file to *-wal. At this point connection p->db is
  151861. ** holding a SHARED lock on the target database file (because it is
  151862. ** in WAL mode). So no other connection may be writing the db.
  151863. **
  151864. ** In order to ensure that there are no database readers, an EXCLUSIVE
  151865. ** lock is obtained here before the *-oal is moved to *-wal.
  151866. */
  151867. rbuLockDatabase(p);
  151868. if( p->rc==SQLITE_OK ){
  151869. rbuFileSuffix3(zBase, zWal);
  151870. rbuFileSuffix3(zBase, zOal);
  151871. /* Re-open the databases. */
  151872. rbuObjIterFinalize(&p->objiter);
  151873. sqlite3_close(p->dbMain);
  151874. sqlite3_close(p->dbRbu);
  151875. p->dbMain = 0;
  151876. p->dbRbu = 0;
  151877. #if defined(_WIN32_WCE)
  151878. {
  151879. LPWSTR zWideOal;
  151880. LPWSTR zWideWal;
  151881. zWideOal = rbuWinUtf8ToUnicode(zOal);
  151882. if( zWideOal ){
  151883. zWideWal = rbuWinUtf8ToUnicode(zWal);
  151884. if( zWideWal ){
  151885. if( MoveFileW(zWideOal, zWideWal) ){
  151886. p->rc = SQLITE_OK;
  151887. }else{
  151888. p->rc = SQLITE_IOERR;
  151889. }
  151890. sqlite3_free(zWideWal);
  151891. }else{
  151892. p->rc = SQLITE_IOERR_NOMEM;
  151893. }
  151894. sqlite3_free(zWideOal);
  151895. }else{
  151896. p->rc = SQLITE_IOERR_NOMEM;
  151897. }
  151898. }
  151899. #else
  151900. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  151901. #endif
  151902. if( p->rc==SQLITE_OK ){
  151903. rbuOpenDatabase(p);
  151904. rbuSetupCheckpoint(p, 0);
  151905. }
  151906. }
  151907. }
  151908. sqlite3_free(zWal);
  151909. sqlite3_free(zOal);
  151910. }
  151911. /*
  151912. ** The SELECT statement iterating through the keys for the current object
  151913. ** (p->objiter.pSelect) currently points to a valid row. This function
  151914. ** determines the type of operation requested by this row and returns
  151915. ** one of the following values to indicate the result:
  151916. **
  151917. ** * RBU_INSERT
  151918. ** * RBU_DELETE
  151919. ** * RBU_IDX_DELETE
  151920. ** * RBU_UPDATE
  151921. **
  151922. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  151923. ** point to the text value indicating the columns to update.
  151924. **
  151925. ** If the rbu_control field contains an invalid value, an error code and
  151926. ** message are left in the RBU handle and zero returned.
  151927. */
  151928. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  151929. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  151930. int res = 0; /* Return value */
  151931. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  151932. case SQLITE_INTEGER: {
  151933. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  151934. if( iVal==0 ){
  151935. res = RBU_INSERT;
  151936. }else if( iVal==1 ){
  151937. res = RBU_DELETE;
  151938. }else if( iVal==2 ){
  151939. res = RBU_IDX_DELETE;
  151940. }else if( iVal==3 ){
  151941. res = RBU_IDX_INSERT;
  151942. }
  151943. break;
  151944. }
  151945. case SQLITE_TEXT: {
  151946. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  151947. if( z==0 ){
  151948. p->rc = SQLITE_NOMEM;
  151949. }else{
  151950. *pzMask = (const char*)z;
  151951. }
  151952. res = RBU_UPDATE;
  151953. break;
  151954. }
  151955. default:
  151956. break;
  151957. }
  151958. if( res==0 ){
  151959. rbuBadControlError(p);
  151960. }
  151961. return res;
  151962. }
  151963. #ifdef SQLITE_DEBUG
  151964. /*
  151965. ** Assert that column iCol of statement pStmt is named zName.
  151966. */
  151967. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  151968. const char *zCol = sqlite3_column_name(pStmt, iCol);
  151969. assert( 0==sqlite3_stricmp(zName, zCol) );
  151970. }
  151971. #else
  151972. # define assertColumnName(x,y,z)
  151973. #endif
  151974. /*
  151975. ** This function does the work for an sqlite3rbu_step() call.
  151976. **
  151977. ** The object-iterator (p->objiter) currently points to a valid object,
  151978. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  151979. ** input row. Perform whatever processing is required and return.
  151980. **
  151981. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  151982. ** and message is left in the RBU handle and a copy of the error code
  151983. ** returned.
  151984. */
  151985. static int rbuStep(sqlite3rbu *p){
  151986. RbuObjIter *pIter = &p->objiter;
  151987. const char *zMask = 0;
  151988. int i;
  151989. int eType = rbuStepType(p, &zMask);
  151990. if( eType ){
  151991. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  151992. if( pIter->zIdx==0 && eType==RBU_IDX_DELETE ){
  151993. rbuBadControlError(p);
  151994. }
  151995. else if(
  151996. eType==RBU_INSERT
  151997. || eType==RBU_DELETE
  151998. || eType==RBU_IDX_DELETE
  151999. || eType==RBU_IDX_INSERT
  152000. ){
  152001. sqlite3_value *pVal;
  152002. sqlite3_stmt *pWriter;
  152003. assert( eType!=RBU_UPDATE );
  152004. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  152005. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  152006. pWriter = pIter->pDelete;
  152007. }else{
  152008. pWriter = pIter->pInsert;
  152009. }
  152010. for(i=0; i<pIter->nCol; i++){
  152011. /* If this is an INSERT into a table b-tree and the table has an
  152012. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  152013. ** to write a NULL into the IPK column. That is not permitted. */
  152014. if( eType==RBU_INSERT
  152015. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  152016. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  152017. ){
  152018. p->rc = SQLITE_MISMATCH;
  152019. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  152020. goto step_out;
  152021. }
  152022. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  152023. continue;
  152024. }
  152025. pVal = sqlite3_column_value(pIter->pSelect, i);
  152026. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  152027. if( p->rc ) goto step_out;
  152028. }
  152029. if( pIter->zIdx==0
  152030. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  152031. ){
  152032. /* For a virtual table, or a table with no primary key, the
  152033. ** SELECT statement is:
  152034. **
  152035. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  152036. **
  152037. ** Hence column_value(pIter->nCol+1).
  152038. */
  152039. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  152040. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  152041. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  152042. }
  152043. if( p->rc==SQLITE_OK ){
  152044. sqlite3_step(pWriter);
  152045. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  152046. }
  152047. }else{
  152048. sqlite3_value *pVal;
  152049. sqlite3_stmt *pUpdate = 0;
  152050. assert( eType==RBU_UPDATE );
  152051. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  152052. if( pUpdate ){
  152053. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  152054. char c = zMask[pIter->aiSrcOrder[i]];
  152055. pVal = sqlite3_column_value(pIter->pSelect, i);
  152056. if( pIter->abTblPk[i] || c!='.' ){
  152057. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  152058. }
  152059. }
  152060. if( p->rc==SQLITE_OK
  152061. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  152062. ){
  152063. /* Bind the rbu_rowid value to column _rowid_ */
  152064. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  152065. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  152066. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  152067. }
  152068. if( p->rc==SQLITE_OK ){
  152069. sqlite3_step(pUpdate);
  152070. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  152071. }
  152072. }
  152073. }
  152074. }
  152075. step_out:
  152076. return p->rc;
  152077. }
  152078. /*
  152079. ** Increment the schema cookie of the main database opened by p->dbMain.
  152080. */
  152081. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  152082. if( p->rc==SQLITE_OK ){
  152083. int iCookie = 1000000;
  152084. sqlite3_stmt *pStmt;
  152085. p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  152086. "PRAGMA schema_version"
  152087. );
  152088. if( p->rc==SQLITE_OK ){
  152089. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  152090. ** is already a transaction open, so the prepared statement cannot
  152091. ** throw an SQLITE_SCHEMA exception. The only database page the
  152092. ** statement reads is page 1, which is guaranteed to be in the cache.
  152093. ** And no memory allocations are required. */
  152094. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  152095. iCookie = sqlite3_column_int(pStmt, 0);
  152096. }
  152097. rbuFinalize(p, pStmt);
  152098. }
  152099. if( p->rc==SQLITE_OK ){
  152100. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  152101. }
  152102. }
  152103. }
  152104. /*
  152105. ** Update the contents of the rbu_state table within the rbu database. The
  152106. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  152107. ** are determined by inspecting the rbu handle passed as the first argument.
  152108. */
  152109. static void rbuSaveState(sqlite3rbu *p, int eStage){
  152110. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  152111. sqlite3_stmt *pInsert = 0;
  152112. int rc;
  152113. assert( p->zErrmsg==0 );
  152114. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  152115. sqlite3_mprintf(
  152116. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  152117. "(%d, %d), "
  152118. "(%d, %Q), "
  152119. "(%d, %Q), "
  152120. "(%d, %d), "
  152121. "(%d, %d), "
  152122. "(%d, %lld), "
  152123. "(%d, %lld), "
  152124. "(%d, %lld) ",
  152125. p->zStateDb,
  152126. RBU_STATE_STAGE, eStage,
  152127. RBU_STATE_TBL, p->objiter.zTbl,
  152128. RBU_STATE_IDX, p->objiter.zIdx,
  152129. RBU_STATE_ROW, p->nStep,
  152130. RBU_STATE_PROGRESS, p->nProgress,
  152131. RBU_STATE_CKPT, p->iWalCksum,
  152132. RBU_STATE_COOKIE, (i64)p->pTargetFd->iCookie,
  152133. RBU_STATE_OALSZ, p->iOalSz
  152134. )
  152135. );
  152136. assert( pInsert==0 || rc==SQLITE_OK );
  152137. if( rc==SQLITE_OK ){
  152138. sqlite3_step(pInsert);
  152139. rc = sqlite3_finalize(pInsert);
  152140. }
  152141. if( rc!=SQLITE_OK ) p->rc = rc;
  152142. }
  152143. }
  152144. /*
  152145. ** Step the RBU object.
  152146. */
  152147. SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
  152148. if( p ){
  152149. switch( p->eStage ){
  152150. case RBU_STAGE_OAL: {
  152151. RbuObjIter *pIter = &p->objiter;
  152152. while( p->rc==SQLITE_OK && pIter->zTbl ){
  152153. if( pIter->bCleanup ){
  152154. /* Clean up the rbu_tmp_xxx table for the previous table. It
  152155. ** cannot be dropped as there are currently active SQL statements.
  152156. ** But the contents can be deleted. */
  152157. if( pIter->abIndexed ){
  152158. rbuMPrintfExec(p, p->dbRbu,
  152159. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  152160. );
  152161. }
  152162. }else{
  152163. rbuObjIterPrepareAll(p, pIter, 0);
  152164. /* Advance to the next row to process. */
  152165. if( p->rc==SQLITE_OK ){
  152166. int rc = sqlite3_step(pIter->pSelect);
  152167. if( rc==SQLITE_ROW ){
  152168. p->nProgress++;
  152169. p->nStep++;
  152170. return rbuStep(p);
  152171. }
  152172. p->rc = sqlite3_reset(pIter->pSelect);
  152173. p->nStep = 0;
  152174. }
  152175. }
  152176. rbuObjIterNext(p, pIter);
  152177. }
  152178. if( p->rc==SQLITE_OK ){
  152179. assert( pIter->zTbl==0 );
  152180. rbuSaveState(p, RBU_STAGE_MOVE);
  152181. rbuIncrSchemaCookie(p);
  152182. if( p->rc==SQLITE_OK ){
  152183. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  152184. }
  152185. if( p->rc==SQLITE_OK ){
  152186. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  152187. }
  152188. p->eStage = RBU_STAGE_MOVE;
  152189. }
  152190. break;
  152191. }
  152192. case RBU_STAGE_MOVE: {
  152193. if( p->rc==SQLITE_OK ){
  152194. rbuMoveOalFile(p);
  152195. p->nProgress++;
  152196. }
  152197. break;
  152198. }
  152199. case RBU_STAGE_CKPT: {
  152200. if( p->rc==SQLITE_OK ){
  152201. if( p->nStep>=p->nFrame ){
  152202. sqlite3_file *pDb = p->pTargetFd->pReal;
  152203. /* Sync the db file */
  152204. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  152205. /* Update nBackfill */
  152206. if( p->rc==SQLITE_OK ){
  152207. void volatile *ptr;
  152208. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  152209. if( p->rc==SQLITE_OK ){
  152210. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  152211. }
  152212. }
  152213. if( p->rc==SQLITE_OK ){
  152214. p->eStage = RBU_STAGE_DONE;
  152215. p->rc = SQLITE_DONE;
  152216. }
  152217. }else{
  152218. RbuFrame *pFrame = &p->aFrame[p->nStep];
  152219. rbuCheckpointFrame(p, pFrame);
  152220. p->nStep++;
  152221. }
  152222. p->nProgress++;
  152223. }
  152224. break;
  152225. }
  152226. default:
  152227. break;
  152228. }
  152229. return p->rc;
  152230. }else{
  152231. return SQLITE_NOMEM;
  152232. }
  152233. }
  152234. /*
  152235. ** Free an RbuState object allocated by rbuLoadState().
  152236. */
  152237. static void rbuFreeState(RbuState *p){
  152238. if( p ){
  152239. sqlite3_free(p->zTbl);
  152240. sqlite3_free(p->zIdx);
  152241. sqlite3_free(p);
  152242. }
  152243. }
  152244. /*
  152245. ** Allocate an RbuState object and load the contents of the rbu_state
  152246. ** table into it. Return a pointer to the new object. It is the
  152247. ** responsibility of the caller to eventually free the object using
  152248. ** sqlite3_free().
  152249. **
  152250. ** If an error occurs, leave an error code and message in the rbu handle
  152251. ** and return NULL.
  152252. */
  152253. static RbuState *rbuLoadState(sqlite3rbu *p){
  152254. RbuState *pRet = 0;
  152255. sqlite3_stmt *pStmt = 0;
  152256. int rc;
  152257. int rc2;
  152258. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  152259. if( pRet==0 ) return 0;
  152260. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  152261. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  152262. );
  152263. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  152264. switch( sqlite3_column_int(pStmt, 0) ){
  152265. case RBU_STATE_STAGE:
  152266. pRet->eStage = sqlite3_column_int(pStmt, 1);
  152267. if( pRet->eStage!=RBU_STAGE_OAL
  152268. && pRet->eStage!=RBU_STAGE_MOVE
  152269. && pRet->eStage!=RBU_STAGE_CKPT
  152270. ){
  152271. p->rc = SQLITE_CORRUPT;
  152272. }
  152273. break;
  152274. case RBU_STATE_TBL:
  152275. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  152276. break;
  152277. case RBU_STATE_IDX:
  152278. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  152279. break;
  152280. case RBU_STATE_ROW:
  152281. pRet->nRow = sqlite3_column_int(pStmt, 1);
  152282. break;
  152283. case RBU_STATE_PROGRESS:
  152284. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  152285. break;
  152286. case RBU_STATE_CKPT:
  152287. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  152288. break;
  152289. case RBU_STATE_COOKIE:
  152290. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  152291. break;
  152292. case RBU_STATE_OALSZ:
  152293. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  152294. break;
  152295. default:
  152296. rc = SQLITE_CORRUPT;
  152297. break;
  152298. }
  152299. }
  152300. rc2 = sqlite3_finalize(pStmt);
  152301. if( rc==SQLITE_OK ) rc = rc2;
  152302. p->rc = rc;
  152303. return pRet;
  152304. }
  152305. /*
  152306. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  152307. ** otherwise. Either or both argument may be NULL. Two NULL values are
  152308. ** considered equal, and NULL is considered distinct from all other values.
  152309. */
  152310. static int rbuStrCompare(const char *z1, const char *z2){
  152311. if( z1==0 && z2==0 ) return 0;
  152312. if( z1==0 || z2==0 ) return 1;
  152313. return (sqlite3_stricmp(z1, z2)!=0);
  152314. }
  152315. /*
  152316. ** This function is called as part of sqlite3rbu_open() when initializing
  152317. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  152318. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  152319. ** things so that the next call to sqlite3rbu_step() continues on from
  152320. ** where the previous rbu handle left off.
  152321. **
  152322. ** If an error occurs, an error code and error message are left in the
  152323. ** rbu handle passed as the first argument.
  152324. */
  152325. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  152326. assert( p->rc==SQLITE_OK );
  152327. if( pState->zTbl ){
  152328. RbuObjIter *pIter = &p->objiter;
  152329. int rc = SQLITE_OK;
  152330. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  152331. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  152332. || rbuStrCompare(pIter->zTbl, pState->zTbl)
  152333. )){
  152334. rc = rbuObjIterNext(p, pIter);
  152335. }
  152336. if( rc==SQLITE_OK && !pIter->zTbl ){
  152337. rc = SQLITE_ERROR;
  152338. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  152339. }
  152340. if( rc==SQLITE_OK ){
  152341. p->nStep = pState->nRow;
  152342. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  152343. }
  152344. p->rc = rc;
  152345. }
  152346. }
  152347. /*
  152348. ** If there is a "*-oal" file in the file-system corresponding to the
  152349. ** target database in the file-system, delete it. If an error occurs,
  152350. ** leave an error code and error message in the rbu handle.
  152351. */
  152352. static void rbuDeleteOalFile(sqlite3rbu *p){
  152353. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  152354. if( zOal ){
  152355. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  152356. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  152357. pVfs->xDelete(pVfs, zOal, 0);
  152358. sqlite3_free(zOal);
  152359. }
  152360. }
  152361. /*
  152362. ** Allocate a private rbu VFS for the rbu handle passed as the only
  152363. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  152364. ** specified a URI with a vfs=? option in place of a target database
  152365. ** file name.
  152366. */
  152367. static void rbuCreateVfs(sqlite3rbu *p){
  152368. int rnd;
  152369. char zRnd[64];
  152370. assert( p->rc==SQLITE_OK );
  152371. sqlite3_randomness(sizeof(int), (void*)&rnd);
  152372. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  152373. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  152374. if( p->rc==SQLITE_OK ){
  152375. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  152376. assert( pVfs );
  152377. p->zVfsName = pVfs->zName;
  152378. }
  152379. }
  152380. /*
  152381. ** Destroy the private VFS created for the rbu handle passed as the only
  152382. ** argument by an earlier call to rbuCreateVfs().
  152383. */
  152384. static void rbuDeleteVfs(sqlite3rbu *p){
  152385. if( p->zVfsName ){
  152386. sqlite3rbu_destroy_vfs(p->zVfsName);
  152387. p->zVfsName = 0;
  152388. }
  152389. }
  152390. /*
  152391. ** Open and return a new RBU handle.
  152392. */
  152393. SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
  152394. const char *zTarget,
  152395. const char *zRbu,
  152396. const char *zState
  152397. ){
  152398. sqlite3rbu *p;
  152399. int nTarget = strlen(zTarget);
  152400. int nRbu = strlen(zRbu);
  152401. int nState = zState ? strlen(zState) : 0;
  152402. p = (sqlite3rbu*)sqlite3_malloc(sizeof(sqlite3rbu)+nTarget+1+nRbu+1+nState+1);
  152403. if( p ){
  152404. RbuState *pState = 0;
  152405. /* Create the custom VFS. */
  152406. memset(p, 0, sizeof(sqlite3rbu));
  152407. rbuCreateVfs(p);
  152408. /* Open the target database */
  152409. if( p->rc==SQLITE_OK ){
  152410. p->zTarget = (char*)&p[1];
  152411. memcpy(p->zTarget, zTarget, nTarget+1);
  152412. p->zRbu = &p->zTarget[nTarget+1];
  152413. memcpy(p->zRbu, zRbu, nRbu+1);
  152414. if( zState ){
  152415. p->zState = &p->zRbu[nRbu+1];
  152416. memcpy(p->zState, zState, nState+1);
  152417. }
  152418. rbuOpenDatabase(p);
  152419. }
  152420. /* If it has not already been created, create the rbu_state table */
  152421. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  152422. if( p->rc==SQLITE_OK ){
  152423. pState = rbuLoadState(p);
  152424. assert( pState || p->rc!=SQLITE_OK );
  152425. if( p->rc==SQLITE_OK ){
  152426. if( pState->eStage==0 ){
  152427. rbuDeleteOalFile(p);
  152428. p->eStage = RBU_STAGE_OAL;
  152429. }else{
  152430. p->eStage = pState->eStage;
  152431. }
  152432. p->nProgress = pState->nProgress;
  152433. p->iOalSz = pState->iOalSz;
  152434. }
  152435. }
  152436. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  152437. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  152438. if( p->eStage==RBU_STAGE_OAL ){
  152439. p->rc = SQLITE_ERROR;
  152440. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  152441. }else if( p->eStage==RBU_STAGE_MOVE ){
  152442. p->eStage = RBU_STAGE_CKPT;
  152443. p->nStep = 0;
  152444. }
  152445. }
  152446. if( p->rc==SQLITE_OK
  152447. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  152448. && pState->eStage!=0 && p->pTargetFd->iCookie!=pState->iCookie
  152449. ){
  152450. /* At this point (pTargetFd->iCookie) contains the value of the
  152451. ** change-counter cookie (the thing that gets incremented when a
  152452. ** transaction is committed in rollback mode) currently stored on
  152453. ** page 1 of the database file. */
  152454. p->rc = SQLITE_BUSY;
  152455. p->zErrmsg = sqlite3_mprintf("database modified during rbu update");
  152456. }
  152457. if( p->rc==SQLITE_OK ){
  152458. if( p->eStage==RBU_STAGE_OAL ){
  152459. sqlite3 *db = p->dbMain;
  152460. /* Open transactions both databases. The *-oal file is opened or
  152461. ** created at this point. */
  152462. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  152463. if( p->rc==SQLITE_OK ){
  152464. p->rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  152465. }
  152466. /* Check if the main database is a zipvfs db. If it is, set the upper
  152467. ** level pager to use "journal_mode=off". This prevents it from
  152468. ** generating a large journal using a temp file. */
  152469. if( p->rc==SQLITE_OK ){
  152470. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  152471. if( frc==SQLITE_OK ){
  152472. p->rc = sqlite3_exec(db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  152473. }
  152474. }
  152475. /* Point the object iterator at the first object */
  152476. if( p->rc==SQLITE_OK ){
  152477. p->rc = rbuObjIterFirst(p, &p->objiter);
  152478. }
  152479. /* If the RBU database contains no data_xxx tables, declare the RBU
  152480. ** update finished. */
  152481. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  152482. p->rc = SQLITE_DONE;
  152483. }
  152484. if( p->rc==SQLITE_OK ){
  152485. rbuSetupOal(p, pState);
  152486. }
  152487. }else if( p->eStage==RBU_STAGE_MOVE ){
  152488. /* no-op */
  152489. }else if( p->eStage==RBU_STAGE_CKPT ){
  152490. rbuSetupCheckpoint(p, pState);
  152491. }else if( p->eStage==RBU_STAGE_DONE ){
  152492. p->rc = SQLITE_DONE;
  152493. }else{
  152494. p->rc = SQLITE_CORRUPT;
  152495. }
  152496. }
  152497. rbuFreeState(pState);
  152498. }
  152499. return p;
  152500. }
  152501. /*
  152502. ** Return the database handle used by pRbu.
  152503. */
  152504. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  152505. sqlite3 *db = 0;
  152506. if( pRbu ){
  152507. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  152508. }
  152509. return db;
  152510. }
  152511. /*
  152512. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  152513. ** then edit any error message string so as to remove all occurrences of
  152514. ** the pattern "rbu_imp_[0-9]*".
  152515. */
  152516. static void rbuEditErrmsg(sqlite3rbu *p){
  152517. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  152518. int i;
  152519. int nErrmsg = strlen(p->zErrmsg);
  152520. for(i=0; i<(nErrmsg-8); i++){
  152521. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  152522. int nDel = 8;
  152523. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  152524. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  152525. nErrmsg -= nDel;
  152526. }
  152527. }
  152528. }
  152529. }
  152530. /*
  152531. ** Close the RBU handle.
  152532. */
  152533. SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  152534. int rc;
  152535. if( p ){
  152536. /* Commit the transaction to the *-oal file. */
  152537. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  152538. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  152539. }
  152540. rbuSaveState(p, p->eStage);
  152541. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  152542. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  152543. }
  152544. /* Close any open statement handles. */
  152545. rbuObjIterFinalize(&p->objiter);
  152546. /* Close the open database handle and VFS object. */
  152547. sqlite3_close(p->dbMain);
  152548. sqlite3_close(p->dbRbu);
  152549. rbuDeleteVfs(p);
  152550. sqlite3_free(p->aBuf);
  152551. sqlite3_free(p->aFrame);
  152552. rbuEditErrmsg(p);
  152553. rc = p->rc;
  152554. *pzErrmsg = p->zErrmsg;
  152555. sqlite3_free(p);
  152556. }else{
  152557. rc = SQLITE_NOMEM;
  152558. *pzErrmsg = 0;
  152559. }
  152560. return rc;
  152561. }
  152562. /*
  152563. ** Return the total number of key-value operations (inserts, deletes or
  152564. ** updates) that have been performed on the target database since the
  152565. ** current RBU update was started.
  152566. */
  152567. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
  152568. return pRbu->nProgress;
  152569. }
  152570. SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *p){
  152571. int rc = p->rc;
  152572. if( rc==SQLITE_DONE ) return SQLITE_OK;
  152573. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  152574. if( p->eStage==RBU_STAGE_OAL ){
  152575. assert( rc!=SQLITE_DONE );
  152576. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  152577. }
  152578. p->rc = rc;
  152579. rbuSaveState(p, p->eStage);
  152580. rc = p->rc;
  152581. if( p->eStage==RBU_STAGE_OAL ){
  152582. assert( rc!=SQLITE_DONE );
  152583. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  152584. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  152585. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  152586. }
  152587. p->rc = rc;
  152588. return rc;
  152589. }
  152590. /**************************************************************************
  152591. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  152592. ** of a standard VFS in the following ways:
  152593. **
  152594. ** 1. Whenever the first page of a main database file is read or
  152595. ** written, the value of the change-counter cookie is stored in
  152596. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  152597. ** database header field is stored in rbu_file.iWriteVer. This ensures
  152598. ** that the values are always trustworthy within an open transaction.
  152599. **
  152600. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  152601. ** member variable of the associated database file descriptor is set
  152602. ** to point to the new file. A mutex protected linked list of all main
  152603. ** db fds opened using a particular RBU VFS is maintained at
  152604. ** rbu_vfs.pMain to facilitate this.
  152605. **
  152606. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  152607. ** object can be marked as the target database of an RBU update. This
  152608. ** turns on the following extra special behaviour:
  152609. **
  152610. ** 3a. If xAccess() is called to check if there exists a *-wal file
  152611. ** associated with an RBU target database currently in RBU_STAGE_OAL
  152612. ** stage (preparing the *-oal file), the following special handling
  152613. ** applies:
  152614. **
  152615. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  152616. ** target database may not be in wal mode already.
  152617. **
  152618. ** * if the *-wal file does not exist, set the output parameter to
  152619. ** non-zero (to tell SQLite that it does exist) anyway.
  152620. **
  152621. ** Then, when xOpen() is called to open the *-wal file associated with
  152622. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  152623. ** file, the rbu vfs opens the corresponding *-oal file instead.
  152624. **
  152625. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  152626. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  152627. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  152628. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  152629. ** because assert() statements in some VFS implementations fail if
  152630. ** xShmLock() is called before xShmMap().
  152631. **
  152632. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  152633. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  152634. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  152635. ** from automatically checkpointing a *-wal (or *-oal) file from within
  152636. ** sqlite3_close().
  152637. **
  152638. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  152639. ** all xWrite() calls on the target database file perform no IO.
  152640. ** Instead the frame and page numbers that would be read and written
  152641. ** are recorded. Additionally, successful attempts to obtain exclusive
  152642. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  152643. ** database file are recorded. xShmLock() calls to unlock the same
  152644. ** locks are no-ops (so that once obtained, these locks are never
  152645. ** relinquished). Finally, calls to xSync() on the target database
  152646. ** file fail with SQLITE_INTERNAL errors.
  152647. */
  152648. static void rbuUnlockShm(rbu_file *p){
  152649. if( p->pRbu ){
  152650. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  152651. int i;
  152652. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  152653. if( (1<<i) & p->pRbu->mLock ){
  152654. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  152655. }
  152656. }
  152657. p->pRbu->mLock = 0;
  152658. }
  152659. }
  152660. /*
  152661. ** Close an rbu file.
  152662. */
  152663. static int rbuVfsClose(sqlite3_file *pFile){
  152664. rbu_file *p = (rbu_file*)pFile;
  152665. int rc;
  152666. int i;
  152667. /* Free the contents of the apShm[] array. And the array itself. */
  152668. for(i=0; i<p->nShm; i++){
  152669. sqlite3_free(p->apShm[i]);
  152670. }
  152671. sqlite3_free(p->apShm);
  152672. p->apShm = 0;
  152673. sqlite3_free(p->zDel);
  152674. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  152675. rbu_file **pp;
  152676. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  152677. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  152678. *pp = p->pMainNext;
  152679. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  152680. rbuUnlockShm(p);
  152681. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  152682. }
  152683. /* Close the underlying file handle */
  152684. rc = p->pReal->pMethods->xClose(p->pReal);
  152685. return rc;
  152686. }
  152687. /*
  152688. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  152689. ** passed as the only argument.
  152690. */
  152691. static u32 rbuGetU32(u8 *aBuf){
  152692. return ((u32)aBuf[0] << 24)
  152693. + ((u32)aBuf[1] << 16)
  152694. + ((u32)aBuf[2] << 8)
  152695. + ((u32)aBuf[3]);
  152696. }
  152697. /*
  152698. ** Read data from an rbuVfs-file.
  152699. */
  152700. static int rbuVfsRead(
  152701. sqlite3_file *pFile,
  152702. void *zBuf,
  152703. int iAmt,
  152704. sqlite_int64 iOfst
  152705. ){
  152706. rbu_file *p = (rbu_file*)pFile;
  152707. sqlite3rbu *pRbu = p->pRbu;
  152708. int rc;
  152709. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  152710. assert( p->openFlags & SQLITE_OPEN_WAL );
  152711. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  152712. }else{
  152713. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  152714. && (p->openFlags & SQLITE_OPEN_WAL)
  152715. && iOfst>=pRbu->iOalSz
  152716. ){
  152717. rc = SQLITE_OK;
  152718. memset(zBuf, 0, iAmt);
  152719. }else{
  152720. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  152721. }
  152722. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  152723. /* These look like magic numbers. But they are stable, as they are part
  152724. ** of the definition of the SQLite file format, which may not change. */
  152725. u8 *pBuf = (u8*)zBuf;
  152726. p->iCookie = rbuGetU32(&pBuf[24]);
  152727. p->iWriteVer = pBuf[19];
  152728. }
  152729. }
  152730. return rc;
  152731. }
  152732. /*
  152733. ** Write data to an rbuVfs-file.
  152734. */
  152735. static int rbuVfsWrite(
  152736. sqlite3_file *pFile,
  152737. const void *zBuf,
  152738. int iAmt,
  152739. sqlite_int64 iOfst
  152740. ){
  152741. rbu_file *p = (rbu_file*)pFile;
  152742. sqlite3rbu *pRbu = p->pRbu;
  152743. int rc;
  152744. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  152745. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  152746. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  152747. }else{
  152748. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  152749. && (p->openFlags & SQLITE_OPEN_WAL)
  152750. && iOfst>=pRbu->iOalSz
  152751. ){
  152752. pRbu->iOalSz = iAmt + iOfst;
  152753. }
  152754. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  152755. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  152756. /* These look like magic numbers. But they are stable, as they are part
  152757. ** of the definition of the SQLite file format, which may not change. */
  152758. u8 *pBuf = (u8*)zBuf;
  152759. p->iCookie = rbuGetU32(&pBuf[24]);
  152760. p->iWriteVer = pBuf[19];
  152761. }
  152762. }
  152763. return rc;
  152764. }
  152765. /*
  152766. ** Truncate an rbuVfs-file.
  152767. */
  152768. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  152769. rbu_file *p = (rbu_file*)pFile;
  152770. return p->pReal->pMethods->xTruncate(p->pReal, size);
  152771. }
  152772. /*
  152773. ** Sync an rbuVfs-file.
  152774. */
  152775. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  152776. rbu_file *p = (rbu_file *)pFile;
  152777. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  152778. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  152779. return SQLITE_INTERNAL;
  152780. }
  152781. return SQLITE_OK;
  152782. }
  152783. return p->pReal->pMethods->xSync(p->pReal, flags);
  152784. }
  152785. /*
  152786. ** Return the current file-size of an rbuVfs-file.
  152787. */
  152788. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  152789. rbu_file *p = (rbu_file *)pFile;
  152790. return p->pReal->pMethods->xFileSize(p->pReal, pSize);
  152791. }
  152792. /*
  152793. ** Lock an rbuVfs-file.
  152794. */
  152795. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  152796. rbu_file *p = (rbu_file*)pFile;
  152797. sqlite3rbu *pRbu = p->pRbu;
  152798. int rc = SQLITE_OK;
  152799. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  152800. if( pRbu && eLock==SQLITE_LOCK_EXCLUSIVE && pRbu->eStage!=RBU_STAGE_DONE ){
  152801. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  152802. ** prevents it from checkpointing the database from sqlite3_close(). */
  152803. rc = SQLITE_BUSY;
  152804. }else{
  152805. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  152806. }
  152807. return rc;
  152808. }
  152809. /*
  152810. ** Unlock an rbuVfs-file.
  152811. */
  152812. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  152813. rbu_file *p = (rbu_file *)pFile;
  152814. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  152815. }
  152816. /*
  152817. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  152818. */
  152819. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  152820. rbu_file *p = (rbu_file *)pFile;
  152821. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  152822. }
  152823. /*
  152824. ** File control method. For custom operations on an rbuVfs-file.
  152825. */
  152826. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  152827. rbu_file *p = (rbu_file *)pFile;
  152828. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  152829. int rc;
  152830. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  152831. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  152832. );
  152833. if( op==SQLITE_FCNTL_RBU ){
  152834. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  152835. /* First try to find another RBU vfs lower down in the vfs stack. If
  152836. ** one is found, this vfs will operate in pass-through mode. The lower
  152837. ** level vfs will do the special RBU handling. */
  152838. rc = xControl(p->pReal, op, pArg);
  152839. if( rc==SQLITE_NOTFOUND ){
  152840. /* Now search for a zipvfs instance lower down in the VFS stack. If
  152841. ** one is found, this is an error. */
  152842. void *dummy = 0;
  152843. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  152844. if( rc==SQLITE_OK ){
  152845. rc = SQLITE_ERROR;
  152846. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  152847. }else if( rc==SQLITE_NOTFOUND ){
  152848. pRbu->pTargetFd = p;
  152849. p->pRbu = pRbu;
  152850. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  152851. rc = SQLITE_OK;
  152852. }
  152853. }
  152854. return rc;
  152855. }
  152856. rc = xControl(p->pReal, op, pArg);
  152857. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  152858. rbu_vfs *pRbuVfs = p->pRbuVfs;
  152859. char *zIn = *(char**)pArg;
  152860. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  152861. *(char**)pArg = zOut;
  152862. if( zOut==0 ) rc = SQLITE_NOMEM;
  152863. }
  152864. return rc;
  152865. }
  152866. /*
  152867. ** Return the sector-size in bytes for an rbuVfs-file.
  152868. */
  152869. static int rbuVfsSectorSize(sqlite3_file *pFile){
  152870. rbu_file *p = (rbu_file *)pFile;
  152871. return p->pReal->pMethods->xSectorSize(p->pReal);
  152872. }
  152873. /*
  152874. ** Return the device characteristic flags supported by an rbuVfs-file.
  152875. */
  152876. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  152877. rbu_file *p = (rbu_file *)pFile;
  152878. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  152879. }
  152880. /*
  152881. ** Take or release a shared-memory lock.
  152882. */
  152883. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  152884. rbu_file *p = (rbu_file*)pFile;
  152885. sqlite3rbu *pRbu = p->pRbu;
  152886. int rc = SQLITE_OK;
  152887. #ifdef SQLITE_AMALGAMATION
  152888. assert( WAL_CKPT_LOCK==1 );
  152889. #endif
  152890. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  152891. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  152892. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  152893. ** taking this lock also prevents any checkpoints from occurring.
  152894. ** todo: really, it's not clear why this might occur, as
  152895. ** wal_autocheckpoint ought to be turned off. */
  152896. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  152897. }else{
  152898. int bCapture = 0;
  152899. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  152900. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  152901. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  152902. ){
  152903. bCapture = 1;
  152904. }
  152905. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  152906. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  152907. if( bCapture && rc==SQLITE_OK ){
  152908. pRbu->mLock |= (1 << ofst);
  152909. }
  152910. }
  152911. }
  152912. return rc;
  152913. }
  152914. /*
  152915. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  152916. */
  152917. static int rbuVfsShmMap(
  152918. sqlite3_file *pFile,
  152919. int iRegion,
  152920. int szRegion,
  152921. int isWrite,
  152922. void volatile **pp
  152923. ){
  152924. rbu_file *p = (rbu_file*)pFile;
  152925. int rc = SQLITE_OK;
  152926. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  152927. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  152928. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  152929. ** instead of a file on disk. */
  152930. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  152931. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  152932. if( iRegion<=p->nShm ){
  152933. int nByte = (iRegion+1) * sizeof(char*);
  152934. char **apNew = (char**)sqlite3_realloc(p->apShm, nByte);
  152935. if( apNew==0 ){
  152936. rc = SQLITE_NOMEM;
  152937. }else{
  152938. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  152939. p->apShm = apNew;
  152940. p->nShm = iRegion+1;
  152941. }
  152942. }
  152943. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  152944. char *pNew = (char*)sqlite3_malloc(szRegion);
  152945. if( pNew==0 ){
  152946. rc = SQLITE_NOMEM;
  152947. }else{
  152948. memset(pNew, 0, szRegion);
  152949. p->apShm[iRegion] = pNew;
  152950. }
  152951. }
  152952. if( rc==SQLITE_OK ){
  152953. *pp = p->apShm[iRegion];
  152954. }else{
  152955. *pp = 0;
  152956. }
  152957. }else{
  152958. assert( p->apShm==0 );
  152959. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  152960. }
  152961. return rc;
  152962. }
  152963. /*
  152964. ** Memory barrier.
  152965. */
  152966. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  152967. rbu_file *p = (rbu_file *)pFile;
  152968. p->pReal->pMethods->xShmBarrier(p->pReal);
  152969. }
  152970. /*
  152971. ** The xShmUnmap method.
  152972. */
  152973. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  152974. rbu_file *p = (rbu_file*)pFile;
  152975. int rc = SQLITE_OK;
  152976. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  152977. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  152978. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  152979. /* no-op */
  152980. }else{
  152981. /* Release the checkpointer and writer locks */
  152982. rbuUnlockShm(p);
  152983. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  152984. }
  152985. return rc;
  152986. }
  152987. /*
  152988. ** Given that zWal points to a buffer containing a wal file name passed to
  152989. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  152990. ** file-handle opened by the same database connection on the corresponding
  152991. ** database file.
  152992. */
  152993. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  152994. rbu_file *pDb;
  152995. sqlite3_mutex_enter(pRbuVfs->mutex);
  152996. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext);
  152997. sqlite3_mutex_leave(pRbuVfs->mutex);
  152998. return pDb;
  152999. }
  153000. /*
  153001. ** Open an rbu file handle.
  153002. */
  153003. static int rbuVfsOpen(
  153004. sqlite3_vfs *pVfs,
  153005. const char *zName,
  153006. sqlite3_file *pFile,
  153007. int flags,
  153008. int *pOutFlags
  153009. ){
  153010. static sqlite3_io_methods rbuvfs_io_methods = {
  153011. 2, /* iVersion */
  153012. rbuVfsClose, /* xClose */
  153013. rbuVfsRead, /* xRead */
  153014. rbuVfsWrite, /* xWrite */
  153015. rbuVfsTruncate, /* xTruncate */
  153016. rbuVfsSync, /* xSync */
  153017. rbuVfsFileSize, /* xFileSize */
  153018. rbuVfsLock, /* xLock */
  153019. rbuVfsUnlock, /* xUnlock */
  153020. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  153021. rbuVfsFileControl, /* xFileControl */
  153022. rbuVfsSectorSize, /* xSectorSize */
  153023. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  153024. rbuVfsShmMap, /* xShmMap */
  153025. rbuVfsShmLock, /* xShmLock */
  153026. rbuVfsShmBarrier, /* xShmBarrier */
  153027. rbuVfsShmUnmap, /* xShmUnmap */
  153028. 0, 0 /* xFetch, xUnfetch */
  153029. };
  153030. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  153031. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  153032. rbu_file *pFd = (rbu_file *)pFile;
  153033. int rc = SQLITE_OK;
  153034. const char *zOpen = zName;
  153035. memset(pFd, 0, sizeof(rbu_file));
  153036. pFd->pReal = (sqlite3_file*)&pFd[1];
  153037. pFd->pRbuVfs = pRbuVfs;
  153038. pFd->openFlags = flags;
  153039. if( zName ){
  153040. if( flags & SQLITE_OPEN_MAIN_DB ){
  153041. /* A main database has just been opened. The following block sets
  153042. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  153043. ** the name of the *-wal file this db connection will use. SQLite
  153044. ** happens to pass a pointer to this buffer when using xAccess()
  153045. ** or xOpen() to operate on the *-wal file. */
  153046. int n = strlen(zName);
  153047. const char *z = &zName[n];
  153048. if( flags & SQLITE_OPEN_URI ){
  153049. int odd = 0;
  153050. while( 1 ){
  153051. if( z[0]==0 ){
  153052. odd = 1 - odd;
  153053. if( odd && z[1]==0 ) break;
  153054. }
  153055. z++;
  153056. }
  153057. z += 2;
  153058. }else{
  153059. while( *z==0 ) z++;
  153060. }
  153061. z += (n + 8 + 1);
  153062. pFd->zWal = z;
  153063. }
  153064. else if( flags & SQLITE_OPEN_WAL ){
  153065. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  153066. if( pDb ){
  153067. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  153068. /* This call is to open a *-wal file. Intead, open the *-oal. This
  153069. ** code ensures that the string passed to xOpen() is terminated by a
  153070. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  153071. ** parameter from it. */
  153072. int nCopy = strlen(zName);
  153073. char *zCopy = sqlite3_malloc(nCopy+2);
  153074. if( zCopy ){
  153075. memcpy(zCopy, zName, nCopy);
  153076. zCopy[nCopy-3] = 'o';
  153077. zCopy[nCopy] = '\0';
  153078. zCopy[nCopy+1] = '\0';
  153079. zOpen = (const char*)(pFd->zDel = zCopy);
  153080. }else{
  153081. rc = SQLITE_NOMEM;
  153082. }
  153083. pFd->pRbu = pDb->pRbu;
  153084. }
  153085. pDb->pWalFd = pFd;
  153086. }
  153087. }
  153088. }
  153089. if( rc==SQLITE_OK ){
  153090. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, flags, pOutFlags);
  153091. }
  153092. if( pFd->pReal->pMethods ){
  153093. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  153094. ** pointer and, if the file is a main database file, link it into the
  153095. ** mutex protected linked list of all such files. */
  153096. pFile->pMethods = &rbuvfs_io_methods;
  153097. if( flags & SQLITE_OPEN_MAIN_DB ){
  153098. sqlite3_mutex_enter(pRbuVfs->mutex);
  153099. pFd->pMainNext = pRbuVfs->pMain;
  153100. pRbuVfs->pMain = pFd;
  153101. sqlite3_mutex_leave(pRbuVfs->mutex);
  153102. }
  153103. }else{
  153104. sqlite3_free(pFd->zDel);
  153105. }
  153106. return rc;
  153107. }
  153108. /*
  153109. ** Delete the file located at zPath.
  153110. */
  153111. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  153112. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153113. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  153114. }
  153115. /*
  153116. ** Test for access permissions. Return true if the requested permission
  153117. ** is available, or false otherwise.
  153118. */
  153119. static int rbuVfsAccess(
  153120. sqlite3_vfs *pVfs,
  153121. const char *zPath,
  153122. int flags,
  153123. int *pResOut
  153124. ){
  153125. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  153126. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  153127. int rc;
  153128. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  153129. /* If this call is to check if a *-wal file associated with an RBU target
  153130. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  153131. ** the following special handling is activated:
  153132. **
  153133. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  153134. ** ensures that the RBU extension never tries to update a database
  153135. ** in wal mode, even if the first page of the database file has
  153136. ** been damaged.
  153137. **
  153138. ** b) if the *-wal file does not exist, claim that it does anyway,
  153139. ** causing SQLite to call xOpen() to open it. This call will also
  153140. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  153141. ** file opened instead.
  153142. */
  153143. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  153144. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  153145. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  153146. if( *pResOut ){
  153147. rc = SQLITE_CANTOPEN;
  153148. }else{
  153149. *pResOut = 1;
  153150. }
  153151. }
  153152. }
  153153. return rc;
  153154. }
  153155. /*
  153156. ** Populate buffer zOut with the full canonical pathname corresponding
  153157. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  153158. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  153159. */
  153160. static int rbuVfsFullPathname(
  153161. sqlite3_vfs *pVfs,
  153162. const char *zPath,
  153163. int nOut,
  153164. char *zOut
  153165. ){
  153166. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153167. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  153168. }
  153169. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  153170. /*
  153171. ** Open the dynamic library located at zPath and return a handle.
  153172. */
  153173. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  153174. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153175. return pRealVfs->xDlOpen(pRealVfs, zPath);
  153176. }
  153177. /*
  153178. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  153179. ** utf-8 string describing the most recent error encountered associated
  153180. ** with dynamic libraries.
  153181. */
  153182. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  153183. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153184. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  153185. }
  153186. /*
  153187. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  153188. */
  153189. static void (*rbuVfsDlSym(
  153190. sqlite3_vfs *pVfs,
  153191. void *pArg,
  153192. const char *zSym
  153193. ))(void){
  153194. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153195. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  153196. }
  153197. /*
  153198. ** Close the dynamic library handle pHandle.
  153199. */
  153200. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  153201. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153202. pRealVfs->xDlClose(pRealVfs, pHandle);
  153203. }
  153204. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  153205. /*
  153206. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  153207. ** random data.
  153208. */
  153209. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  153210. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153211. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  153212. }
  153213. /*
  153214. ** Sleep for nMicro microseconds. Return the number of microseconds
  153215. ** actually slept.
  153216. */
  153217. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  153218. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153219. return pRealVfs->xSleep(pRealVfs, nMicro);
  153220. }
  153221. /*
  153222. ** Return the current time as a Julian Day number in *pTimeOut.
  153223. */
  153224. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  153225. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  153226. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  153227. }
  153228. /*
  153229. ** No-op.
  153230. */
  153231. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  153232. return 0;
  153233. }
  153234. /*
  153235. ** Deregister and destroy an RBU vfs created by an earlier call to
  153236. ** sqlite3rbu_create_vfs().
  153237. */
  153238. SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
  153239. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  153240. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  153241. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  153242. sqlite3_vfs_unregister(pVfs);
  153243. sqlite3_free(pVfs);
  153244. }
  153245. }
  153246. /*
  153247. ** Create an RBU VFS named zName that accesses the underlying file-system
  153248. ** via existing VFS zParent. The new object is registered as a non-default
  153249. ** VFS with SQLite before returning.
  153250. */
  153251. SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  153252. /* Template for VFS */
  153253. static sqlite3_vfs vfs_template = {
  153254. 1, /* iVersion */
  153255. 0, /* szOsFile */
  153256. 0, /* mxPathname */
  153257. 0, /* pNext */
  153258. 0, /* zName */
  153259. 0, /* pAppData */
  153260. rbuVfsOpen, /* xOpen */
  153261. rbuVfsDelete, /* xDelete */
  153262. rbuVfsAccess, /* xAccess */
  153263. rbuVfsFullPathname, /* xFullPathname */
  153264. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  153265. rbuVfsDlOpen, /* xDlOpen */
  153266. rbuVfsDlError, /* xDlError */
  153267. rbuVfsDlSym, /* xDlSym */
  153268. rbuVfsDlClose, /* xDlClose */
  153269. #else
  153270. 0, 0, 0, 0,
  153271. #endif
  153272. rbuVfsRandomness, /* xRandomness */
  153273. rbuVfsSleep, /* xSleep */
  153274. rbuVfsCurrentTime, /* xCurrentTime */
  153275. rbuVfsGetLastError, /* xGetLastError */
  153276. 0, /* xCurrentTimeInt64 (version 2) */
  153277. 0, 0, 0 /* Unimplemented version 3 methods */
  153278. };
  153279. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  153280. int nName;
  153281. int rc = SQLITE_OK;
  153282. int nByte;
  153283. nName = strlen(zName);
  153284. nByte = sizeof(rbu_vfs) + nName + 1;
  153285. pNew = (rbu_vfs*)sqlite3_malloc(nByte);
  153286. if( pNew==0 ){
  153287. rc = SQLITE_NOMEM;
  153288. }else{
  153289. sqlite3_vfs *pParent; /* Parent VFS */
  153290. memset(pNew, 0, nByte);
  153291. pParent = sqlite3_vfs_find(zParent);
  153292. if( pParent==0 ){
  153293. rc = SQLITE_NOTFOUND;
  153294. }else{
  153295. char *zSpace;
  153296. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  153297. pNew->base.mxPathname = pParent->mxPathname;
  153298. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  153299. pNew->pRealVfs = pParent;
  153300. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  153301. memcpy(zSpace, zName, nName);
  153302. /* Allocate the mutex and register the new VFS (not as the default) */
  153303. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  153304. if( pNew->mutex==0 ){
  153305. rc = SQLITE_NOMEM;
  153306. }else{
  153307. rc = sqlite3_vfs_register(&pNew->base, 0);
  153308. }
  153309. }
  153310. if( rc!=SQLITE_OK ){
  153311. sqlite3_mutex_free(pNew->mutex);
  153312. sqlite3_free(pNew);
  153313. }
  153314. }
  153315. return rc;
  153316. }
  153317. /**************************************************************************/
  153318. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  153319. /************** End of sqlite3rbu.c ******************************************/
  153320. /************** Begin file dbstat.c ******************************************/
  153321. /*
  153322. ** 2010 July 12
  153323. **
  153324. ** The author disclaims copyright to this source code. In place of
  153325. ** a legal notice, here is a blessing:
  153326. **
  153327. ** May you do good and not evil.
  153328. ** May you find forgiveness for yourself and forgive others.
  153329. ** May you share freely, never taking more than you give.
  153330. **
  153331. ******************************************************************************
  153332. **
  153333. ** This file contains an implementation of the "dbstat" virtual table.
  153334. **
  153335. ** The dbstat virtual table is used to extract low-level formatting
  153336. ** information from an SQLite database in order to implement the
  153337. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  153338. ** for an example implementation.
  153339. **
  153340. ** Additional information is available on the "dbstat.html" page of the
  153341. ** official SQLite documentation.
  153342. */
  153343. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  153344. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  153345. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  153346. /*
  153347. ** Page paths:
  153348. **
  153349. ** The value of the 'path' column describes the path taken from the
  153350. ** root-node of the b-tree structure to each page. The value of the
  153351. ** root-node path is '/'.
  153352. **
  153353. ** The value of the path for the left-most child page of the root of
  153354. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  153355. ** so the pages to the left have smaller keys than the pages to the right.)
  153356. ** The next to left-most child of the root page is
  153357. ** '/001', and so on, each sibling page identified by a 3-digit hex
  153358. ** value. The children of the 451st left-most sibling have paths such
  153359. ** as '/1c2/000/, '/1c2/001/' etc.
  153360. **
  153361. ** Overflow pages are specified by appending a '+' character and a
  153362. ** six-digit hexadecimal value to the path to the cell they are linked
  153363. ** from. For example, the three overflow pages in a chain linked from
  153364. ** the left-most cell of the 450th child of the root page are identified
  153365. ** by the paths:
  153366. **
  153367. ** '/1c2/000+000000' // First page in overflow chain
  153368. ** '/1c2/000+000001' // Second page in overflow chain
  153369. ** '/1c2/000+000002' // Third page in overflow chain
  153370. **
  153371. ** If the paths are sorted using the BINARY collation sequence, then
  153372. ** the overflow pages associated with a cell will appear earlier in the
  153373. ** sort-order than its child page:
  153374. **
  153375. ** '/1c2/000/' // Left-most child of 451st child of root
  153376. */
  153377. #define VTAB_SCHEMA \
  153378. "CREATE TABLE xx( " \
  153379. " name STRING, /* Name of table or index */" \
  153380. " path INTEGER, /* Path to page from root */" \
  153381. " pageno INTEGER, /* Page number */" \
  153382. " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" \
  153383. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  153384. " payload INTEGER, /* Bytes of payload on this page */" \
  153385. " unused INTEGER, /* Bytes of unused space on this page */" \
  153386. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  153387. " pgoffset INTEGER, /* Offset of page in file */" \
  153388. " pgsize INTEGER, /* Size of the page */" \
  153389. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  153390. ");"
  153391. typedef struct StatTable StatTable;
  153392. typedef struct StatCursor StatCursor;
  153393. typedef struct StatPage StatPage;
  153394. typedef struct StatCell StatCell;
  153395. struct StatCell {
  153396. int nLocal; /* Bytes of local payload */
  153397. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  153398. int nOvfl; /* Entries in aOvfl[] */
  153399. u32 *aOvfl; /* Array of overflow page numbers */
  153400. int nLastOvfl; /* Bytes of payload on final overflow page */
  153401. int iOvfl; /* Iterates through aOvfl[] */
  153402. };
  153403. struct StatPage {
  153404. u32 iPgno;
  153405. DbPage *pPg;
  153406. int iCell;
  153407. char *zPath; /* Path to this page */
  153408. /* Variables populated by statDecodePage(): */
  153409. u8 flags; /* Copy of flags byte */
  153410. int nCell; /* Number of cells on page */
  153411. int nUnused; /* Number of unused bytes on page */
  153412. StatCell *aCell; /* Array of parsed cells */
  153413. u32 iRightChildPg; /* Right-child page number (or 0) */
  153414. int nMxPayload; /* Largest payload of any cell on this page */
  153415. };
  153416. struct StatCursor {
  153417. sqlite3_vtab_cursor base;
  153418. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  153419. int isEof; /* After pStmt has returned SQLITE_DONE */
  153420. int iDb; /* Schema used for this query */
  153421. StatPage aPage[32];
  153422. int iPage; /* Current entry in aPage[] */
  153423. /* Values to return. */
  153424. char *zName; /* Value of 'name' column */
  153425. char *zPath; /* Value of 'path' column */
  153426. u32 iPageno; /* Value of 'pageno' column */
  153427. char *zPagetype; /* Value of 'pagetype' column */
  153428. int nCell; /* Value of 'ncell' column */
  153429. int nPayload; /* Value of 'payload' column */
  153430. int nUnused; /* Value of 'unused' column */
  153431. int nMxPayload; /* Value of 'mx_payload' column */
  153432. i64 iOffset; /* Value of 'pgOffset' column */
  153433. int szPage; /* Value of 'pgSize' column */
  153434. };
  153435. struct StatTable {
  153436. sqlite3_vtab base;
  153437. sqlite3 *db;
  153438. int iDb; /* Index of database to analyze */
  153439. };
  153440. #ifndef get2byte
  153441. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  153442. #endif
  153443. /*
  153444. ** Connect to or create a statvfs virtual table.
  153445. */
  153446. static int statConnect(
  153447. sqlite3 *db,
  153448. void *pAux,
  153449. int argc, const char *const*argv,
  153450. sqlite3_vtab **ppVtab,
  153451. char **pzErr
  153452. ){
  153453. StatTable *pTab = 0;
  153454. int rc = SQLITE_OK;
  153455. int iDb;
  153456. if( argc>=4 ){
  153457. iDb = sqlite3FindDbName(db, argv[3]);
  153458. if( iDb<0 ){
  153459. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  153460. return SQLITE_ERROR;
  153461. }
  153462. }else{
  153463. iDb = 0;
  153464. }
  153465. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  153466. if( rc==SQLITE_OK ){
  153467. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  153468. if( pTab==0 ) rc = SQLITE_NOMEM;
  153469. }
  153470. assert( rc==SQLITE_OK || pTab==0 );
  153471. if( rc==SQLITE_OK ){
  153472. memset(pTab, 0, sizeof(StatTable));
  153473. pTab->db = db;
  153474. pTab->iDb = iDb;
  153475. }
  153476. *ppVtab = (sqlite3_vtab*)pTab;
  153477. return rc;
  153478. }
  153479. /*
  153480. ** Disconnect from or destroy a statvfs virtual table.
  153481. */
  153482. static int statDisconnect(sqlite3_vtab *pVtab){
  153483. sqlite3_free(pVtab);
  153484. return SQLITE_OK;
  153485. }
  153486. /*
  153487. ** There is no "best-index". This virtual table always does a linear
  153488. ** scan. However, a schema=? constraint should cause this table to
  153489. ** operate on a different database schema, so check for it.
  153490. **
  153491. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  153492. */
  153493. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  153494. int i;
  153495. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  153496. /* Look for a valid schema=? constraint. If found, change the idxNum to
  153497. ** 1 and request the value of that constraint be sent to xFilter. And
  153498. ** lower the cost estimate to encourage the constrained version to be
  153499. ** used.
  153500. */
  153501. for(i=0; i<pIdxInfo->nConstraint; i++){
  153502. if( pIdxInfo->aConstraint[i].usable==0 ) continue;
  153503. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  153504. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  153505. pIdxInfo->idxNum = 1;
  153506. pIdxInfo->estimatedCost = 1.0;
  153507. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  153508. pIdxInfo->aConstraintUsage[i].omit = 1;
  153509. break;
  153510. }
  153511. /* Records are always returned in ascending order of (name, path).
  153512. ** If this will satisfy the client, set the orderByConsumed flag so that
  153513. ** SQLite does not do an external sort.
  153514. */
  153515. if( ( pIdxInfo->nOrderBy==1
  153516. && pIdxInfo->aOrderBy[0].iColumn==0
  153517. && pIdxInfo->aOrderBy[0].desc==0
  153518. ) ||
  153519. ( pIdxInfo->nOrderBy==2
  153520. && pIdxInfo->aOrderBy[0].iColumn==0
  153521. && pIdxInfo->aOrderBy[0].desc==0
  153522. && pIdxInfo->aOrderBy[1].iColumn==1
  153523. && pIdxInfo->aOrderBy[1].desc==0
  153524. )
  153525. ){
  153526. pIdxInfo->orderByConsumed = 1;
  153527. }
  153528. return SQLITE_OK;
  153529. }
  153530. /*
  153531. ** Open a new statvfs cursor.
  153532. */
  153533. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  153534. StatTable *pTab = (StatTable *)pVTab;
  153535. StatCursor *pCsr;
  153536. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  153537. if( pCsr==0 ){
  153538. return SQLITE_NOMEM;
  153539. }else{
  153540. memset(pCsr, 0, sizeof(StatCursor));
  153541. pCsr->base.pVtab = pVTab;
  153542. pCsr->iDb = pTab->iDb;
  153543. }
  153544. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  153545. return SQLITE_OK;
  153546. }
  153547. static void statClearPage(StatPage *p){
  153548. int i;
  153549. if( p->aCell ){
  153550. for(i=0; i<p->nCell; i++){
  153551. sqlite3_free(p->aCell[i].aOvfl);
  153552. }
  153553. sqlite3_free(p->aCell);
  153554. }
  153555. sqlite3PagerUnref(p->pPg);
  153556. sqlite3_free(p->zPath);
  153557. memset(p, 0, sizeof(StatPage));
  153558. }
  153559. static void statResetCsr(StatCursor *pCsr){
  153560. int i;
  153561. sqlite3_reset(pCsr->pStmt);
  153562. for(i=0; i<ArraySize(pCsr->aPage); i++){
  153563. statClearPage(&pCsr->aPage[i]);
  153564. }
  153565. pCsr->iPage = 0;
  153566. sqlite3_free(pCsr->zPath);
  153567. pCsr->zPath = 0;
  153568. pCsr->isEof = 0;
  153569. }
  153570. /*
  153571. ** Close a statvfs cursor.
  153572. */
  153573. static int statClose(sqlite3_vtab_cursor *pCursor){
  153574. StatCursor *pCsr = (StatCursor *)pCursor;
  153575. statResetCsr(pCsr);
  153576. sqlite3_finalize(pCsr->pStmt);
  153577. sqlite3_free(pCsr);
  153578. return SQLITE_OK;
  153579. }
  153580. static void getLocalPayload(
  153581. int nUsable, /* Usable bytes per page */
  153582. u8 flags, /* Page flags */
  153583. int nTotal, /* Total record (payload) size */
  153584. int *pnLocal /* OUT: Bytes stored locally */
  153585. ){
  153586. int nLocal;
  153587. int nMinLocal;
  153588. int nMaxLocal;
  153589. if( flags==0x0D ){ /* Table leaf node */
  153590. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  153591. nMaxLocal = nUsable - 35;
  153592. }else{ /* Index interior and leaf nodes */
  153593. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  153594. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  153595. }
  153596. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  153597. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  153598. *pnLocal = nLocal;
  153599. }
  153600. static int statDecodePage(Btree *pBt, StatPage *p){
  153601. int nUnused;
  153602. int iOff;
  153603. int nHdr;
  153604. int isLeaf;
  153605. int szPage;
  153606. u8 *aData = sqlite3PagerGetData(p->pPg);
  153607. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  153608. p->flags = aHdr[0];
  153609. p->nCell = get2byte(&aHdr[3]);
  153610. p->nMxPayload = 0;
  153611. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  153612. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  153613. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  153614. nUnused += (int)aHdr[7];
  153615. iOff = get2byte(&aHdr[1]);
  153616. while( iOff ){
  153617. nUnused += get2byte(&aData[iOff+2]);
  153618. iOff = get2byte(&aData[iOff]);
  153619. }
  153620. p->nUnused = nUnused;
  153621. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  153622. szPage = sqlite3BtreeGetPageSize(pBt);
  153623. if( p->nCell ){
  153624. int i; /* Used to iterate through cells */
  153625. int nUsable; /* Usable bytes per page */
  153626. sqlite3BtreeEnter(pBt);
  153627. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  153628. sqlite3BtreeLeave(pBt);
  153629. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  153630. if( p->aCell==0 ) return SQLITE_NOMEM;
  153631. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  153632. for(i=0; i<p->nCell; i++){
  153633. StatCell *pCell = &p->aCell[i];
  153634. iOff = get2byte(&aData[nHdr+i*2]);
  153635. if( !isLeaf ){
  153636. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  153637. iOff += 4;
  153638. }
  153639. if( p->flags==0x05 ){
  153640. /* A table interior node. nPayload==0. */
  153641. }else{
  153642. u32 nPayload; /* Bytes of payload total (local+overflow) */
  153643. int nLocal; /* Bytes of payload stored locally */
  153644. iOff += getVarint32(&aData[iOff], nPayload);
  153645. if( p->flags==0x0D ){
  153646. u64 dummy;
  153647. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  153648. }
  153649. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  153650. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  153651. pCell->nLocal = nLocal;
  153652. assert( nLocal>=0 );
  153653. assert( nPayload>=(u32)nLocal );
  153654. assert( nLocal<=(nUsable-35) );
  153655. if( nPayload>(u32)nLocal ){
  153656. int j;
  153657. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  153658. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  153659. pCell->nOvfl = nOvfl;
  153660. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  153661. if( pCell->aOvfl==0 ) return SQLITE_NOMEM;
  153662. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  153663. for(j=1; j<nOvfl; j++){
  153664. int rc;
  153665. u32 iPrev = pCell->aOvfl[j-1];
  153666. DbPage *pPg = 0;
  153667. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  153668. if( rc!=SQLITE_OK ){
  153669. assert( pPg==0 );
  153670. return rc;
  153671. }
  153672. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  153673. sqlite3PagerUnref(pPg);
  153674. }
  153675. }
  153676. }
  153677. }
  153678. }
  153679. return SQLITE_OK;
  153680. }
  153681. /*
  153682. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  153683. ** the current value of pCsr->iPageno.
  153684. */
  153685. static void statSizeAndOffset(StatCursor *pCsr){
  153686. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  153687. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  153688. Pager *pPager = sqlite3BtreePager(pBt);
  153689. sqlite3_file *fd;
  153690. sqlite3_int64 x[2];
  153691. /* The default page size and offset */
  153692. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  153693. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  153694. /* If connected to a ZIPVFS backend, override the page size and
  153695. ** offset with actual values obtained from ZIPVFS.
  153696. */
  153697. fd = sqlite3PagerFile(pPager);
  153698. x[0] = pCsr->iPageno;
  153699. if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  153700. pCsr->iOffset = x[0];
  153701. pCsr->szPage = (int)x[1];
  153702. }
  153703. }
  153704. /*
  153705. ** Move a statvfs cursor to the next entry in the file.
  153706. */
  153707. static int statNext(sqlite3_vtab_cursor *pCursor){
  153708. int rc;
  153709. int nPayload;
  153710. char *z;
  153711. StatCursor *pCsr = (StatCursor *)pCursor;
  153712. StatTable *pTab = (StatTable *)pCursor->pVtab;
  153713. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  153714. Pager *pPager = sqlite3BtreePager(pBt);
  153715. sqlite3_free(pCsr->zPath);
  153716. pCsr->zPath = 0;
  153717. statNextRestart:
  153718. if( pCsr->aPage[0].pPg==0 ){
  153719. rc = sqlite3_step(pCsr->pStmt);
  153720. if( rc==SQLITE_ROW ){
  153721. int nPage;
  153722. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  153723. sqlite3PagerPagecount(pPager, &nPage);
  153724. if( nPage==0 ){
  153725. pCsr->isEof = 1;
  153726. return sqlite3_reset(pCsr->pStmt);
  153727. }
  153728. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  153729. pCsr->aPage[0].iPgno = iRoot;
  153730. pCsr->aPage[0].iCell = 0;
  153731. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  153732. pCsr->iPage = 0;
  153733. if( z==0 ) rc = SQLITE_NOMEM;
  153734. }else{
  153735. pCsr->isEof = 1;
  153736. return sqlite3_reset(pCsr->pStmt);
  153737. }
  153738. }else{
  153739. /* Page p itself has already been visited. */
  153740. StatPage *p = &pCsr->aPage[pCsr->iPage];
  153741. while( p->iCell<p->nCell ){
  153742. StatCell *pCell = &p->aCell[p->iCell];
  153743. if( pCell->iOvfl<pCell->nOvfl ){
  153744. int nUsable;
  153745. sqlite3BtreeEnter(pBt);
  153746. nUsable = sqlite3BtreeGetPageSize(pBt) -
  153747. sqlite3BtreeGetReserveNoMutex(pBt);
  153748. sqlite3BtreeLeave(pBt);
  153749. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  153750. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  153751. pCsr->zPagetype = "overflow";
  153752. pCsr->nCell = 0;
  153753. pCsr->nMxPayload = 0;
  153754. pCsr->zPath = z = sqlite3_mprintf(
  153755. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  153756. );
  153757. if( pCell->iOvfl<pCell->nOvfl-1 ){
  153758. pCsr->nUnused = 0;
  153759. pCsr->nPayload = nUsable - 4;
  153760. }else{
  153761. pCsr->nPayload = pCell->nLastOvfl;
  153762. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  153763. }
  153764. pCell->iOvfl++;
  153765. statSizeAndOffset(pCsr);
  153766. return z==0 ? SQLITE_NOMEM : SQLITE_OK;
  153767. }
  153768. if( p->iRightChildPg ) break;
  153769. p->iCell++;
  153770. }
  153771. if( !p->iRightChildPg || p->iCell>p->nCell ){
  153772. statClearPage(p);
  153773. if( pCsr->iPage==0 ) return statNext(pCursor);
  153774. pCsr->iPage--;
  153775. goto statNextRestart; /* Tail recursion */
  153776. }
  153777. pCsr->iPage++;
  153778. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  153779. if( p->iCell==p->nCell ){
  153780. p[1].iPgno = p->iRightChildPg;
  153781. }else{
  153782. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  153783. }
  153784. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  153785. p[1].iCell = 0;
  153786. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  153787. p->iCell++;
  153788. if( z==0 ) rc = SQLITE_NOMEM;
  153789. }
  153790. /* Populate the StatCursor fields with the values to be returned
  153791. ** by the xColumn() and xRowid() methods.
  153792. */
  153793. if( rc==SQLITE_OK ){
  153794. int i;
  153795. StatPage *p = &pCsr->aPage[pCsr->iPage];
  153796. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  153797. pCsr->iPageno = p->iPgno;
  153798. rc = statDecodePage(pBt, p);
  153799. if( rc==SQLITE_OK ){
  153800. statSizeAndOffset(pCsr);
  153801. switch( p->flags ){
  153802. case 0x05: /* table internal */
  153803. case 0x02: /* index internal */
  153804. pCsr->zPagetype = "internal";
  153805. break;
  153806. case 0x0D: /* table leaf */
  153807. case 0x0A: /* index leaf */
  153808. pCsr->zPagetype = "leaf";
  153809. break;
  153810. default:
  153811. pCsr->zPagetype = "corrupted";
  153812. break;
  153813. }
  153814. pCsr->nCell = p->nCell;
  153815. pCsr->nUnused = p->nUnused;
  153816. pCsr->nMxPayload = p->nMxPayload;
  153817. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  153818. if( z==0 ) rc = SQLITE_NOMEM;
  153819. nPayload = 0;
  153820. for(i=0; i<p->nCell; i++){
  153821. nPayload += p->aCell[i].nLocal;
  153822. }
  153823. pCsr->nPayload = nPayload;
  153824. }
  153825. }
  153826. return rc;
  153827. }
  153828. static int statEof(sqlite3_vtab_cursor *pCursor){
  153829. StatCursor *pCsr = (StatCursor *)pCursor;
  153830. return pCsr->isEof;
  153831. }
  153832. static int statFilter(
  153833. sqlite3_vtab_cursor *pCursor,
  153834. int idxNum, const char *idxStr,
  153835. int argc, sqlite3_value **argv
  153836. ){
  153837. StatCursor *pCsr = (StatCursor *)pCursor;
  153838. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  153839. char *zSql;
  153840. int rc = SQLITE_OK;
  153841. char *zMaster;
  153842. if( idxNum==1 ){
  153843. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  153844. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  153845. if( pCsr->iDb<0 ){
  153846. sqlite3_free(pCursor->pVtab->zErrMsg);
  153847. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  153848. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  153849. }
  153850. }else{
  153851. pCsr->iDb = pTab->iDb;
  153852. }
  153853. statResetCsr(pCsr);
  153854. sqlite3_finalize(pCsr->pStmt);
  153855. pCsr->pStmt = 0;
  153856. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  153857. zSql = sqlite3_mprintf(
  153858. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  153859. " UNION ALL "
  153860. "SELECT name, rootpage, type"
  153861. " FROM \"%w\".%s WHERE rootpage!=0"
  153862. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
  153863. if( zSql==0 ){
  153864. return SQLITE_NOMEM;
  153865. }else{
  153866. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  153867. sqlite3_free(zSql);
  153868. }
  153869. if( rc==SQLITE_OK ){
  153870. rc = statNext(pCursor);
  153871. }
  153872. return rc;
  153873. }
  153874. static int statColumn(
  153875. sqlite3_vtab_cursor *pCursor,
  153876. sqlite3_context *ctx,
  153877. int i
  153878. ){
  153879. StatCursor *pCsr = (StatCursor *)pCursor;
  153880. switch( i ){
  153881. case 0: /* name */
  153882. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  153883. break;
  153884. case 1: /* path */
  153885. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  153886. break;
  153887. case 2: /* pageno */
  153888. sqlite3_result_int64(ctx, pCsr->iPageno);
  153889. break;
  153890. case 3: /* pagetype */
  153891. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  153892. break;
  153893. case 4: /* ncell */
  153894. sqlite3_result_int(ctx, pCsr->nCell);
  153895. break;
  153896. case 5: /* payload */
  153897. sqlite3_result_int(ctx, pCsr->nPayload);
  153898. break;
  153899. case 6: /* unused */
  153900. sqlite3_result_int(ctx, pCsr->nUnused);
  153901. break;
  153902. case 7: /* mx_payload */
  153903. sqlite3_result_int(ctx, pCsr->nMxPayload);
  153904. break;
  153905. case 8: /* pgoffset */
  153906. sqlite3_result_int64(ctx, pCsr->iOffset);
  153907. break;
  153908. case 9: /* pgsize */
  153909. sqlite3_result_int(ctx, pCsr->szPage);
  153910. break;
  153911. default: { /* schema */
  153912. sqlite3 *db = sqlite3_context_db_handle(ctx);
  153913. int iDb = pCsr->iDb;
  153914. sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
  153915. break;
  153916. }
  153917. }
  153918. return SQLITE_OK;
  153919. }
  153920. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  153921. StatCursor *pCsr = (StatCursor *)pCursor;
  153922. *pRowid = pCsr->iPageno;
  153923. return SQLITE_OK;
  153924. }
  153925. /*
  153926. ** Invoke this routine to register the "dbstat" virtual table module
  153927. */
  153928. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  153929. static sqlite3_module dbstat_module = {
  153930. 0, /* iVersion */
  153931. statConnect, /* xCreate */
  153932. statConnect, /* xConnect */
  153933. statBestIndex, /* xBestIndex */
  153934. statDisconnect, /* xDisconnect */
  153935. statDisconnect, /* xDestroy */
  153936. statOpen, /* xOpen - open a cursor */
  153937. statClose, /* xClose - close a cursor */
  153938. statFilter, /* xFilter - configure scan constraints */
  153939. statNext, /* xNext - advance a cursor */
  153940. statEof, /* xEof - check for end of scan */
  153941. statColumn, /* xColumn - read data */
  153942. statRowid, /* xRowid - read data */
  153943. 0, /* xUpdate */
  153944. 0, /* xBegin */
  153945. 0, /* xSync */
  153946. 0, /* xCommit */
  153947. 0, /* xRollback */
  153948. 0, /* xFindMethod */
  153949. 0, /* xRename */
  153950. };
  153951. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  153952. }
  153953. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  153954. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  153955. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  153956. /************** End of dbstat.c **********************************************/
  153957. /************** Begin file json1.c *******************************************/
  153958. /*
  153959. ** 2015-08-12
  153960. **
  153961. ** The author disclaims copyright to this source code. In place of
  153962. ** a legal notice, here is a blessing:
  153963. **
  153964. ** May you do good and not evil.
  153965. ** May you find forgiveness for yourself and forgive others.
  153966. ** May you share freely, never taking more than you give.
  153967. **
  153968. ******************************************************************************
  153969. **
  153970. ** This SQLite extension implements JSON functions. The interface is
  153971. ** modeled after MySQL JSON functions:
  153972. **
  153973. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  153974. **
  153975. ** For the time being, all JSON is stored as pure text. (We might add
  153976. ** a JSONB type in the future which stores a binary encoding of JSON in
  153977. ** a BLOB, but there is no support for JSONB in the current implementation.
  153978. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  153979. ** how JSONB might improve on that.)
  153980. */
  153981. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  153982. #if !defined(_SQLITEINT_H_)
  153983. /* #include "sqlite3ext.h" */
  153984. #endif
  153985. SQLITE_EXTENSION_INIT1
  153986. /* #include <assert.h> */
  153987. /* #include <string.h> */
  153988. /* #include <stdlib.h> */
  153989. /* #include <stdarg.h> */
  153990. #define UNUSED_PARAM(X) (void)(X)
  153991. #ifndef LARGEST_INT64
  153992. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  153993. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  153994. #endif
  153995. /*
  153996. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  153997. ** to pass signed char values.
  153998. */
  153999. #ifdef sqlite3Isdigit
  154000. /* Use the SQLite core versions if this routine is part of the
  154001. ** SQLite amalgamation */
  154002. # define safe_isdigit(x) sqlite3Isdigit(x)
  154003. # define safe_isalnum(x) sqlite3Isalnum(x)
  154004. #else
  154005. /* Use the standard library for separate compilation */
  154006. #include <ctype.h> /* amalgamator: keep */
  154007. # define safe_isdigit(x) isdigit((unsigned char)(x))
  154008. # define safe_isalnum(x) isalnum((unsigned char)(x))
  154009. #endif
  154010. /*
  154011. ** Growing our own isspace() routine this way is twice as fast as
  154012. ** the library isspace() function, resulting in a 7% overall performance
  154013. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  154014. */
  154015. static const char jsonIsSpace[] = {
  154016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  154017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154018. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  154032. };
  154033. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  154034. #ifndef SQLITE_AMALGAMATION
  154035. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  154036. ** but the definitions need to be repeated for separate compilation. */
  154037. typedef sqlite3_uint64 u64;
  154038. typedef unsigned int u32;
  154039. typedef unsigned char u8;
  154040. #endif
  154041. /* Objects */
  154042. typedef struct JsonString JsonString;
  154043. typedef struct JsonNode JsonNode;
  154044. typedef struct JsonParse JsonParse;
  154045. /* An instance of this object represents a JSON string
  154046. ** under construction. Really, this is a generic string accumulator
  154047. ** that can be and is used to create strings other than JSON.
  154048. */
  154049. struct JsonString {
  154050. sqlite3_context *pCtx; /* Function context - put error messages here */
  154051. char *zBuf; /* Append JSON content here */
  154052. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  154053. u64 nUsed; /* Bytes of zBuf[] currently used */
  154054. u8 bStatic; /* True if zBuf is static space */
  154055. u8 bErr; /* True if an error has been encountered */
  154056. char zSpace[100]; /* Initial static space */
  154057. };
  154058. /* JSON type values
  154059. */
  154060. #define JSON_NULL 0
  154061. #define JSON_TRUE 1
  154062. #define JSON_FALSE 2
  154063. #define JSON_INT 3
  154064. #define JSON_REAL 4
  154065. #define JSON_STRING 5
  154066. #define JSON_ARRAY 6
  154067. #define JSON_OBJECT 7
  154068. /* The "subtype" set for JSON values */
  154069. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  154070. /*
  154071. ** Names of the various JSON types:
  154072. */
  154073. static const char * const jsonType[] = {
  154074. "null", "true", "false", "integer", "real", "text", "array", "object"
  154075. };
  154076. /* Bit values for the JsonNode.jnFlag field
  154077. */
  154078. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  154079. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  154080. #define JNODE_REMOVE 0x04 /* Do not output */
  154081. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
  154082. #define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
  154083. #define JNODE_LABEL 0x20 /* Is a label of an object */
  154084. /* A single node of parsed JSON
  154085. */
  154086. struct JsonNode {
  154087. u8 eType; /* One of the JSON_ type values */
  154088. u8 jnFlags; /* JNODE flags */
  154089. u8 iVal; /* Replacement value when JNODE_REPLACE */
  154090. u32 n; /* Bytes of content, or number of sub-nodes */
  154091. union {
  154092. const char *zJContent; /* Content for INT, REAL, and STRING */
  154093. u32 iAppend; /* More terms for ARRAY and OBJECT */
  154094. u32 iKey; /* Key for ARRAY objects in json_tree() */
  154095. } u;
  154096. };
  154097. /* A completely parsed JSON string
  154098. */
  154099. struct JsonParse {
  154100. u32 nNode; /* Number of slots of aNode[] used */
  154101. u32 nAlloc; /* Number of slots of aNode[] allocated */
  154102. JsonNode *aNode; /* Array of nodes containing the parse */
  154103. const char *zJson; /* Original JSON string */
  154104. u32 *aUp; /* Index of parent of each node */
  154105. u8 oom; /* Set to true if out of memory */
  154106. u8 nErr; /* Number of errors seen */
  154107. };
  154108. /**************************************************************************
  154109. ** Utility routines for dealing with JsonString objects
  154110. **************************************************************************/
  154111. /* Set the JsonString object to an empty string
  154112. */
  154113. static void jsonZero(JsonString *p){
  154114. p->zBuf = p->zSpace;
  154115. p->nAlloc = sizeof(p->zSpace);
  154116. p->nUsed = 0;
  154117. p->bStatic = 1;
  154118. }
  154119. /* Initialize the JsonString object
  154120. */
  154121. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  154122. p->pCtx = pCtx;
  154123. p->bErr = 0;
  154124. jsonZero(p);
  154125. }
  154126. /* Free all allocated memory and reset the JsonString object back to its
  154127. ** initial state.
  154128. */
  154129. static void jsonReset(JsonString *p){
  154130. if( !p->bStatic ) sqlite3_free(p->zBuf);
  154131. jsonZero(p);
  154132. }
  154133. /* Report an out-of-memory (OOM) condition
  154134. */
  154135. static void jsonOom(JsonString *p){
  154136. p->bErr = 1;
  154137. sqlite3_result_error_nomem(p->pCtx);
  154138. jsonReset(p);
  154139. }
  154140. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  154141. ** Return zero on success. Return non-zero on an OOM error
  154142. */
  154143. static int jsonGrow(JsonString *p, u32 N){
  154144. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  154145. char *zNew;
  154146. if( p->bStatic ){
  154147. if( p->bErr ) return 1;
  154148. zNew = sqlite3_malloc64(nTotal);
  154149. if( zNew==0 ){
  154150. jsonOom(p);
  154151. return SQLITE_NOMEM;
  154152. }
  154153. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  154154. p->zBuf = zNew;
  154155. p->bStatic = 0;
  154156. }else{
  154157. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  154158. if( zNew==0 ){
  154159. jsonOom(p);
  154160. return SQLITE_NOMEM;
  154161. }
  154162. p->zBuf = zNew;
  154163. }
  154164. p->nAlloc = nTotal;
  154165. return SQLITE_OK;
  154166. }
  154167. /* Append N bytes from zIn onto the end of the JsonString string.
  154168. */
  154169. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  154170. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  154171. memcpy(p->zBuf+p->nUsed, zIn, N);
  154172. p->nUsed += N;
  154173. }
  154174. /* Append formatted text (not to exceed N bytes) to the JsonString.
  154175. */
  154176. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  154177. va_list ap;
  154178. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  154179. va_start(ap, zFormat);
  154180. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  154181. va_end(ap);
  154182. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  154183. }
  154184. /* Append a single character
  154185. */
  154186. static void jsonAppendChar(JsonString *p, char c){
  154187. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  154188. p->zBuf[p->nUsed++] = c;
  154189. }
  154190. /* Append a comma separator to the output buffer, if the previous
  154191. ** character is not '[' or '{'.
  154192. */
  154193. static void jsonAppendSeparator(JsonString *p){
  154194. char c;
  154195. if( p->nUsed==0 ) return;
  154196. c = p->zBuf[p->nUsed-1];
  154197. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  154198. }
  154199. /* Append the N-byte string in zIn to the end of the JsonString string
  154200. ** under construction. Enclose the string in "..." and escape
  154201. ** any double-quotes or backslash characters contained within the
  154202. ** string.
  154203. */
  154204. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  154205. u32 i;
  154206. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  154207. p->zBuf[p->nUsed++] = '"';
  154208. for(i=0; i<N; i++){
  154209. char c = zIn[i];
  154210. if( c=='"' || c=='\\' ){
  154211. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  154212. p->zBuf[p->nUsed++] = '\\';
  154213. }
  154214. p->zBuf[p->nUsed++] = c;
  154215. }
  154216. p->zBuf[p->nUsed++] = '"';
  154217. assert( p->nUsed<p->nAlloc );
  154218. }
  154219. /*
  154220. ** Append a function parameter value to the JSON string under
  154221. ** construction.
  154222. */
  154223. static void jsonAppendValue(
  154224. JsonString *p, /* Append to this JSON string */
  154225. sqlite3_value *pValue /* Value to append */
  154226. ){
  154227. switch( sqlite3_value_type(pValue) ){
  154228. case SQLITE_NULL: {
  154229. jsonAppendRaw(p, "null", 4);
  154230. break;
  154231. }
  154232. case SQLITE_INTEGER:
  154233. case SQLITE_FLOAT: {
  154234. const char *z = (const char*)sqlite3_value_text(pValue);
  154235. u32 n = (u32)sqlite3_value_bytes(pValue);
  154236. jsonAppendRaw(p, z, n);
  154237. break;
  154238. }
  154239. case SQLITE_TEXT: {
  154240. const char *z = (const char*)sqlite3_value_text(pValue);
  154241. u32 n = (u32)sqlite3_value_bytes(pValue);
  154242. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  154243. jsonAppendRaw(p, z, n);
  154244. }else{
  154245. jsonAppendString(p, z, n);
  154246. }
  154247. break;
  154248. }
  154249. default: {
  154250. if( p->bErr==0 ){
  154251. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  154252. p->bErr = 1;
  154253. jsonReset(p);
  154254. }
  154255. break;
  154256. }
  154257. }
  154258. }
  154259. /* Make the JSON in p the result of the SQL function.
  154260. */
  154261. static void jsonResult(JsonString *p){
  154262. if( p->bErr==0 ){
  154263. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  154264. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  154265. SQLITE_UTF8);
  154266. jsonZero(p);
  154267. }
  154268. assert( p->bStatic );
  154269. }
  154270. /**************************************************************************
  154271. ** Utility routines for dealing with JsonNode and JsonParse objects
  154272. **************************************************************************/
  154273. /*
  154274. ** Return the number of consecutive JsonNode slots need to represent
  154275. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  154276. ** OBJECT types, the number might be larger.
  154277. **
  154278. ** Appended elements are not counted. The value returned is the number
  154279. ** by which the JsonNode counter should increment in order to go to the
  154280. ** next peer value.
  154281. */
  154282. static u32 jsonNodeSize(JsonNode *pNode){
  154283. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  154284. }
  154285. /*
  154286. ** Reclaim all memory allocated by a JsonParse object. But do not
  154287. ** delete the JsonParse object itself.
  154288. */
  154289. static void jsonParseReset(JsonParse *pParse){
  154290. sqlite3_free(pParse->aNode);
  154291. pParse->aNode = 0;
  154292. pParse->nNode = 0;
  154293. pParse->nAlloc = 0;
  154294. sqlite3_free(pParse->aUp);
  154295. pParse->aUp = 0;
  154296. }
  154297. /*
  154298. ** Convert the JsonNode pNode into a pure JSON string and
  154299. ** append to pOut. Subsubstructure is also included. Return
  154300. ** the number of JsonNode objects that are encoded.
  154301. */
  154302. static void jsonRenderNode(
  154303. JsonNode *pNode, /* The node to render */
  154304. JsonString *pOut, /* Write JSON here */
  154305. sqlite3_value **aReplace /* Replacement values */
  154306. ){
  154307. switch( pNode->eType ){
  154308. default: {
  154309. assert( pNode->eType==JSON_NULL );
  154310. jsonAppendRaw(pOut, "null", 4);
  154311. break;
  154312. }
  154313. case JSON_TRUE: {
  154314. jsonAppendRaw(pOut, "true", 4);
  154315. break;
  154316. }
  154317. case JSON_FALSE: {
  154318. jsonAppendRaw(pOut, "false", 5);
  154319. break;
  154320. }
  154321. case JSON_STRING: {
  154322. if( pNode->jnFlags & JNODE_RAW ){
  154323. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  154324. break;
  154325. }
  154326. /* Fall through into the next case */
  154327. }
  154328. case JSON_REAL:
  154329. case JSON_INT: {
  154330. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  154331. break;
  154332. }
  154333. case JSON_ARRAY: {
  154334. u32 j = 1;
  154335. jsonAppendChar(pOut, '[');
  154336. for(;;){
  154337. while( j<=pNode->n ){
  154338. if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
  154339. if( pNode[j].jnFlags & JNODE_REPLACE ){
  154340. jsonAppendSeparator(pOut);
  154341. jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
  154342. }
  154343. }else{
  154344. jsonAppendSeparator(pOut);
  154345. jsonRenderNode(&pNode[j], pOut, aReplace);
  154346. }
  154347. j += jsonNodeSize(&pNode[j]);
  154348. }
  154349. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  154350. pNode = &pNode[pNode->u.iAppend];
  154351. j = 1;
  154352. }
  154353. jsonAppendChar(pOut, ']');
  154354. break;
  154355. }
  154356. case JSON_OBJECT: {
  154357. u32 j = 1;
  154358. jsonAppendChar(pOut, '{');
  154359. for(;;){
  154360. while( j<=pNode->n ){
  154361. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  154362. jsonAppendSeparator(pOut);
  154363. jsonRenderNode(&pNode[j], pOut, aReplace);
  154364. jsonAppendChar(pOut, ':');
  154365. if( pNode[j+1].jnFlags & JNODE_REPLACE ){
  154366. jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
  154367. }else{
  154368. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  154369. }
  154370. }
  154371. j += 1 + jsonNodeSize(&pNode[j+1]);
  154372. }
  154373. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  154374. pNode = &pNode[pNode->u.iAppend];
  154375. j = 1;
  154376. }
  154377. jsonAppendChar(pOut, '}');
  154378. break;
  154379. }
  154380. }
  154381. }
  154382. /*
  154383. ** Return a JsonNode and all its descendents as a JSON string.
  154384. */
  154385. static void jsonReturnJson(
  154386. JsonNode *pNode, /* Node to return */
  154387. sqlite3_context *pCtx, /* Return value for this function */
  154388. sqlite3_value **aReplace /* Array of replacement values */
  154389. ){
  154390. JsonString s;
  154391. jsonInit(&s, pCtx);
  154392. jsonRenderNode(pNode, &s, aReplace);
  154393. jsonResult(&s);
  154394. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  154395. }
  154396. /*
  154397. ** Make the JsonNode the return value of the function.
  154398. */
  154399. static void jsonReturn(
  154400. JsonNode *pNode, /* Node to return */
  154401. sqlite3_context *pCtx, /* Return value for this function */
  154402. sqlite3_value **aReplace /* Array of replacement values */
  154403. ){
  154404. switch( pNode->eType ){
  154405. default: {
  154406. assert( pNode->eType==JSON_NULL );
  154407. sqlite3_result_null(pCtx);
  154408. break;
  154409. }
  154410. case JSON_TRUE: {
  154411. sqlite3_result_int(pCtx, 1);
  154412. break;
  154413. }
  154414. case JSON_FALSE: {
  154415. sqlite3_result_int(pCtx, 0);
  154416. break;
  154417. }
  154418. case JSON_INT: {
  154419. sqlite3_int64 i = 0;
  154420. const char *z = pNode->u.zJContent;
  154421. if( z[0]=='-' ){ z++; }
  154422. while( z[0]>='0' && z[0]<='9' ){
  154423. unsigned v = *(z++) - '0';
  154424. if( i>=LARGEST_INT64/10 ){
  154425. if( i>LARGEST_INT64/10 ) goto int_as_real;
  154426. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  154427. if( v==9 ) goto int_as_real;
  154428. if( v==8 ){
  154429. if( pNode->u.zJContent[0]=='-' ){
  154430. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  154431. goto int_done;
  154432. }else{
  154433. goto int_as_real;
  154434. }
  154435. }
  154436. }
  154437. i = i*10 + v;
  154438. }
  154439. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  154440. sqlite3_result_int64(pCtx, i);
  154441. int_done:
  154442. break;
  154443. int_as_real: /* fall through to real */;
  154444. }
  154445. case JSON_REAL: {
  154446. double r;
  154447. #ifdef SQLITE_AMALGAMATION
  154448. const char *z = pNode->u.zJContent;
  154449. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  154450. #else
  154451. r = strtod(pNode->u.zJContent, 0);
  154452. #endif
  154453. sqlite3_result_double(pCtx, r);
  154454. break;
  154455. }
  154456. case JSON_STRING: {
  154457. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  154458. ** json_insert() and json_replace() and those routines do not
  154459. ** call jsonReturn() */
  154460. if( pNode->jnFlags & JNODE_RAW ){
  154461. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  154462. SQLITE_TRANSIENT);
  154463. }else
  154464. #endif
  154465. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  154466. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  154467. /* JSON formatted without any backslash-escapes */
  154468. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  154469. SQLITE_TRANSIENT);
  154470. }else{
  154471. /* Translate JSON formatted string into raw text */
  154472. u32 i;
  154473. u32 n = pNode->n;
  154474. const char *z = pNode->u.zJContent;
  154475. char *zOut;
  154476. u32 j;
  154477. zOut = sqlite3_malloc( n+1 );
  154478. if( zOut==0 ){
  154479. sqlite3_result_error_nomem(pCtx);
  154480. break;
  154481. }
  154482. for(i=1, j=0; i<n-1; i++){
  154483. char c = z[i];
  154484. if( c!='\\' ){
  154485. zOut[j++] = c;
  154486. }else{
  154487. c = z[++i];
  154488. if( c=='u' ){
  154489. u32 v = 0, k;
  154490. for(k=0; k<4 && i<n-2; i++, k++){
  154491. c = z[i+1];
  154492. if( c>='0' && c<='9' ) v = v*16 + c - '0';
  154493. else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
  154494. else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
  154495. else break;
  154496. }
  154497. if( v==0 ) break;
  154498. if( v<=0x7f ){
  154499. zOut[j++] = (char)v;
  154500. }else if( v<=0x7ff ){
  154501. zOut[j++] = (char)(0xc0 | (v>>6));
  154502. zOut[j++] = 0x80 | (v&0x3f);
  154503. }else{
  154504. zOut[j++] = (char)(0xe0 | (v>>12));
  154505. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  154506. zOut[j++] = 0x80 | (v&0x3f);
  154507. }
  154508. }else{
  154509. if( c=='b' ){
  154510. c = '\b';
  154511. }else if( c=='f' ){
  154512. c = '\f';
  154513. }else if( c=='n' ){
  154514. c = '\n';
  154515. }else if( c=='r' ){
  154516. c = '\r';
  154517. }else if( c=='t' ){
  154518. c = '\t';
  154519. }
  154520. zOut[j++] = c;
  154521. }
  154522. }
  154523. }
  154524. zOut[j] = 0;
  154525. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  154526. }
  154527. break;
  154528. }
  154529. case JSON_ARRAY:
  154530. case JSON_OBJECT: {
  154531. jsonReturnJson(pNode, pCtx, aReplace);
  154532. break;
  154533. }
  154534. }
  154535. }
  154536. /* Forward reference */
  154537. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  154538. /*
  154539. ** A macro to hint to the compiler that a function should not be
  154540. ** inlined.
  154541. */
  154542. #if defined(__GNUC__)
  154543. # define JSON_NOINLINE __attribute__((noinline))
  154544. #elif defined(_MSC_VER) && _MSC_VER>=1310
  154545. # define JSON_NOINLINE __declspec(noinline)
  154546. #else
  154547. # define JSON_NOINLINE
  154548. #endif
  154549. static JSON_NOINLINE int jsonParseAddNodeExpand(
  154550. JsonParse *pParse, /* Append the node to this object */
  154551. u32 eType, /* Node type */
  154552. u32 n, /* Content size or sub-node count */
  154553. const char *zContent /* Content */
  154554. ){
  154555. u32 nNew;
  154556. JsonNode *pNew;
  154557. assert( pParse->nNode>=pParse->nAlloc );
  154558. if( pParse->oom ) return -1;
  154559. nNew = pParse->nAlloc*2 + 10;
  154560. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  154561. if( pNew==0 ){
  154562. pParse->oom = 1;
  154563. return -1;
  154564. }
  154565. pParse->nAlloc = nNew;
  154566. pParse->aNode = pNew;
  154567. assert( pParse->nNode<pParse->nAlloc );
  154568. return jsonParseAddNode(pParse, eType, n, zContent);
  154569. }
  154570. /*
  154571. ** Create a new JsonNode instance based on the arguments and append that
  154572. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  154573. ** new node, or -1 if a memory allocation fails.
  154574. */
  154575. static int jsonParseAddNode(
  154576. JsonParse *pParse, /* Append the node to this object */
  154577. u32 eType, /* Node type */
  154578. u32 n, /* Content size or sub-node count */
  154579. const char *zContent /* Content */
  154580. ){
  154581. JsonNode *p;
  154582. if( pParse->nNode>=pParse->nAlloc ){
  154583. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  154584. }
  154585. p = &pParse->aNode[pParse->nNode];
  154586. p->eType = (u8)eType;
  154587. p->jnFlags = 0;
  154588. p->iVal = 0;
  154589. p->n = n;
  154590. p->u.zJContent = zContent;
  154591. return pParse->nNode++;
  154592. }
  154593. /*
  154594. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  154595. ** index of the first character past the end of the value parsed.
  154596. **
  154597. ** Return negative for a syntax error. Special cases: return -2 if the
  154598. ** first non-whitespace character is '}' and return -3 if the first
  154599. ** non-whitespace character is ']'.
  154600. */
  154601. static int jsonParseValue(JsonParse *pParse, u32 i){
  154602. char c;
  154603. u32 j;
  154604. int iThis;
  154605. int x;
  154606. JsonNode *pNode;
  154607. while( safe_isspace(pParse->zJson[i]) ){ i++; }
  154608. if( (c = pParse->zJson[i])=='{' ){
  154609. /* Parse object */
  154610. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  154611. if( iThis<0 ) return -1;
  154612. for(j=i+1;;j++){
  154613. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  154614. x = jsonParseValue(pParse, j);
  154615. if( x<0 ){
  154616. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  154617. return -1;
  154618. }
  154619. if( pParse->oom ) return -1;
  154620. pNode = &pParse->aNode[pParse->nNode-1];
  154621. if( pNode->eType!=JSON_STRING ) return -1;
  154622. pNode->jnFlags |= JNODE_LABEL;
  154623. j = x;
  154624. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  154625. if( pParse->zJson[j]!=':' ) return -1;
  154626. j++;
  154627. x = jsonParseValue(pParse, j);
  154628. if( x<0 ) return -1;
  154629. j = x;
  154630. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  154631. c = pParse->zJson[j];
  154632. if( c==',' ) continue;
  154633. if( c!='}' ) return -1;
  154634. break;
  154635. }
  154636. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  154637. return j+1;
  154638. }else if( c=='[' ){
  154639. /* Parse array */
  154640. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  154641. if( iThis<0 ) return -1;
  154642. for(j=i+1;;j++){
  154643. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  154644. x = jsonParseValue(pParse, j);
  154645. if( x<0 ){
  154646. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  154647. return -1;
  154648. }
  154649. j = x;
  154650. while( safe_isspace(pParse->zJson[j]) ){ j++; }
  154651. c = pParse->zJson[j];
  154652. if( c==',' ) continue;
  154653. if( c!=']' ) return -1;
  154654. break;
  154655. }
  154656. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  154657. return j+1;
  154658. }else if( c=='"' ){
  154659. /* Parse string */
  154660. u8 jnFlags = 0;
  154661. j = i+1;
  154662. for(;;){
  154663. c = pParse->zJson[j];
  154664. if( c==0 ) return -1;
  154665. if( c=='\\' ){
  154666. c = pParse->zJson[++j];
  154667. if( c==0 ) return -1;
  154668. jnFlags = JNODE_ESCAPE;
  154669. }else if( c=='"' ){
  154670. break;
  154671. }
  154672. j++;
  154673. }
  154674. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
  154675. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  154676. return j+1;
  154677. }else if( c=='n'
  154678. && strncmp(pParse->zJson+i,"null",4)==0
  154679. && !safe_isalnum(pParse->zJson[i+4]) ){
  154680. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  154681. return i+4;
  154682. }else if( c=='t'
  154683. && strncmp(pParse->zJson+i,"true",4)==0
  154684. && !safe_isalnum(pParse->zJson[i+4]) ){
  154685. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  154686. return i+4;
  154687. }else if( c=='f'
  154688. && strncmp(pParse->zJson+i,"false",5)==0
  154689. && !safe_isalnum(pParse->zJson[i+5]) ){
  154690. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  154691. return i+5;
  154692. }else if( c=='-' || (c>='0' && c<='9') ){
  154693. /* Parse number */
  154694. u8 seenDP = 0;
  154695. u8 seenE = 0;
  154696. j = i+1;
  154697. for(;; j++){
  154698. c = pParse->zJson[j];
  154699. if( c>='0' && c<='9' ) continue;
  154700. if( c=='.' ){
  154701. if( pParse->zJson[j-1]=='-' ) return -1;
  154702. if( seenDP ) return -1;
  154703. seenDP = 1;
  154704. continue;
  154705. }
  154706. if( c=='e' || c=='E' ){
  154707. if( pParse->zJson[j-1]<'0' ) return -1;
  154708. if( seenE ) return -1;
  154709. seenDP = seenE = 1;
  154710. c = pParse->zJson[j+1];
  154711. if( c=='+' || c=='-' ){
  154712. j++;
  154713. c = pParse->zJson[j+1];
  154714. }
  154715. if( c<'0' || c>'9' ) return -1;
  154716. continue;
  154717. }
  154718. break;
  154719. }
  154720. if( pParse->zJson[j-1]<'0' ) return -1;
  154721. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  154722. j - i, &pParse->zJson[i]);
  154723. return j;
  154724. }else if( c=='}' ){
  154725. return -2; /* End of {...} */
  154726. }else if( c==']' ){
  154727. return -3; /* End of [...] */
  154728. }else if( c==0 ){
  154729. return 0; /* End of file */
  154730. }else{
  154731. return -1; /* Syntax error */
  154732. }
  154733. }
  154734. /*
  154735. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  154736. ** are any errors. If an error occurs, free all memory associated with
  154737. ** pParse.
  154738. **
  154739. ** pParse is uninitialized when this routine is called.
  154740. */
  154741. static int jsonParse(
  154742. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  154743. sqlite3_context *pCtx, /* Report errors here */
  154744. const char *zJson /* Input JSON text to be parsed */
  154745. ){
  154746. int i;
  154747. memset(pParse, 0, sizeof(*pParse));
  154748. if( zJson==0 ) return 1;
  154749. pParse->zJson = zJson;
  154750. i = jsonParseValue(pParse, 0);
  154751. if( pParse->oom ) i = -1;
  154752. if( i>0 ){
  154753. while( safe_isspace(zJson[i]) ) i++;
  154754. if( zJson[i] ) i = -1;
  154755. }
  154756. if( i<=0 ){
  154757. if( pCtx!=0 ){
  154758. if( pParse->oom ){
  154759. sqlite3_result_error_nomem(pCtx);
  154760. }else{
  154761. sqlite3_result_error(pCtx, "malformed JSON", -1);
  154762. }
  154763. }
  154764. jsonParseReset(pParse);
  154765. return 1;
  154766. }
  154767. return 0;
  154768. }
  154769. /* Mark node i of pParse as being a child of iParent. Call recursively
  154770. ** to fill in all the descendants of node i.
  154771. */
  154772. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  154773. JsonNode *pNode = &pParse->aNode[i];
  154774. u32 j;
  154775. pParse->aUp[i] = iParent;
  154776. switch( pNode->eType ){
  154777. case JSON_ARRAY: {
  154778. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  154779. jsonParseFillInParentage(pParse, i+j, i);
  154780. }
  154781. break;
  154782. }
  154783. case JSON_OBJECT: {
  154784. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  154785. pParse->aUp[i+j] = i;
  154786. jsonParseFillInParentage(pParse, i+j+1, i);
  154787. }
  154788. break;
  154789. }
  154790. default: {
  154791. break;
  154792. }
  154793. }
  154794. }
  154795. /*
  154796. ** Compute the parentage of all nodes in a completed parse.
  154797. */
  154798. static int jsonParseFindParents(JsonParse *pParse){
  154799. u32 *aUp;
  154800. assert( pParse->aUp==0 );
  154801. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  154802. if( aUp==0 ){
  154803. pParse->oom = 1;
  154804. return SQLITE_NOMEM;
  154805. }
  154806. jsonParseFillInParentage(pParse, 0, 0);
  154807. return SQLITE_OK;
  154808. }
  154809. /*
  154810. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  154811. ** a match.
  154812. */
  154813. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  154814. if( pNode->jnFlags & JNODE_RAW ){
  154815. if( pNode->n!=nKey ) return 0;
  154816. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  154817. }else{
  154818. if( pNode->n!=nKey+2 ) return 0;
  154819. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  154820. }
  154821. }
  154822. /* forward declaration */
  154823. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  154824. /*
  154825. ** Search along zPath to find the node specified. Return a pointer
  154826. ** to that node, or NULL if zPath is malformed or if there is no such
  154827. ** node.
  154828. **
  154829. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  154830. ** possible to do so and if no existing node corresponds to zPath. If
  154831. ** new nodes are appended *pApnd is set to 1.
  154832. */
  154833. static JsonNode *jsonLookupStep(
  154834. JsonParse *pParse, /* The JSON to search */
  154835. u32 iRoot, /* Begin the search at this node */
  154836. const char *zPath, /* The path to search */
  154837. int *pApnd, /* Append nodes to complete path if not NULL */
  154838. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  154839. ){
  154840. u32 i, j, nKey;
  154841. const char *zKey;
  154842. JsonNode *pRoot = &pParse->aNode[iRoot];
  154843. if( zPath[0]==0 ) return pRoot;
  154844. if( zPath[0]=='.' ){
  154845. if( pRoot->eType!=JSON_OBJECT ) return 0;
  154846. zPath++;
  154847. if( zPath[0]=='"' ){
  154848. zKey = zPath + 1;
  154849. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  154850. nKey = i-1;
  154851. if( zPath[i] ){
  154852. i++;
  154853. }else{
  154854. *pzErr = zPath;
  154855. return 0;
  154856. }
  154857. }else{
  154858. zKey = zPath;
  154859. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  154860. nKey = i;
  154861. }
  154862. if( nKey==0 ){
  154863. *pzErr = zPath;
  154864. return 0;
  154865. }
  154866. j = 1;
  154867. for(;;){
  154868. while( j<=pRoot->n ){
  154869. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  154870. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  154871. }
  154872. j++;
  154873. j += jsonNodeSize(&pRoot[j]);
  154874. }
  154875. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  154876. iRoot += pRoot->u.iAppend;
  154877. pRoot = &pParse->aNode[iRoot];
  154878. j = 1;
  154879. }
  154880. if( pApnd ){
  154881. u32 iStart, iLabel;
  154882. JsonNode *pNode;
  154883. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  154884. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  154885. zPath += i;
  154886. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  154887. if( pParse->oom ) return 0;
  154888. if( pNode ){
  154889. pRoot = &pParse->aNode[iRoot];
  154890. pRoot->u.iAppend = iStart - iRoot;
  154891. pRoot->jnFlags |= JNODE_APPEND;
  154892. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  154893. }
  154894. return pNode;
  154895. }
  154896. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  154897. if( pRoot->eType!=JSON_ARRAY ) return 0;
  154898. i = 0;
  154899. j = 1;
  154900. while( safe_isdigit(zPath[j]) ){
  154901. i = i*10 + zPath[j] - '0';
  154902. j++;
  154903. }
  154904. if( zPath[j]!=']' ){
  154905. *pzErr = zPath;
  154906. return 0;
  154907. }
  154908. zPath += j + 1;
  154909. j = 1;
  154910. for(;;){
  154911. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  154912. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  154913. j += jsonNodeSize(&pRoot[j]);
  154914. }
  154915. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  154916. iRoot += pRoot->u.iAppend;
  154917. pRoot = &pParse->aNode[iRoot];
  154918. j = 1;
  154919. }
  154920. if( j<=pRoot->n ){
  154921. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  154922. }
  154923. if( i==0 && pApnd ){
  154924. u32 iStart;
  154925. JsonNode *pNode;
  154926. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  154927. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  154928. if( pParse->oom ) return 0;
  154929. if( pNode ){
  154930. pRoot = &pParse->aNode[iRoot];
  154931. pRoot->u.iAppend = iStart - iRoot;
  154932. pRoot->jnFlags |= JNODE_APPEND;
  154933. }
  154934. return pNode;
  154935. }
  154936. }else{
  154937. *pzErr = zPath;
  154938. }
  154939. return 0;
  154940. }
  154941. /*
  154942. ** Append content to pParse that will complete zPath. Return a pointer
  154943. ** to the inserted node, or return NULL if the append fails.
  154944. */
  154945. static JsonNode *jsonLookupAppend(
  154946. JsonParse *pParse, /* Append content to the JSON parse */
  154947. const char *zPath, /* Description of content to append */
  154948. int *pApnd, /* Set this flag to 1 */
  154949. const char **pzErr /* Make this point to any syntax error */
  154950. ){
  154951. *pApnd = 1;
  154952. if( zPath[0]==0 ){
  154953. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  154954. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  154955. }
  154956. if( zPath[0]=='.' ){
  154957. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  154958. }else if( strncmp(zPath,"[0]",3)==0 ){
  154959. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  154960. }else{
  154961. return 0;
  154962. }
  154963. if( pParse->oom ) return 0;
  154964. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  154965. }
  154966. /*
  154967. ** Return the text of a syntax error message on a JSON path. Space is
  154968. ** obtained from sqlite3_malloc().
  154969. */
  154970. static char *jsonPathSyntaxError(const char *zErr){
  154971. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  154972. }
  154973. /*
  154974. ** Do a node lookup using zPath. Return a pointer to the node on success.
  154975. ** Return NULL if not found or if there is an error.
  154976. **
  154977. ** On an error, write an error message into pCtx and increment the
  154978. ** pParse->nErr counter.
  154979. **
  154980. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  154981. ** nodes are appended.
  154982. */
  154983. static JsonNode *jsonLookup(
  154984. JsonParse *pParse, /* The JSON to search */
  154985. const char *zPath, /* The path to search */
  154986. int *pApnd, /* Append nodes to complete path if not NULL */
  154987. sqlite3_context *pCtx /* Report errors here, if not NULL */
  154988. ){
  154989. const char *zErr = 0;
  154990. JsonNode *pNode = 0;
  154991. char *zMsg;
  154992. if( zPath==0 ) return 0;
  154993. if( zPath[0]!='$' ){
  154994. zErr = zPath;
  154995. goto lookup_err;
  154996. }
  154997. zPath++;
  154998. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  154999. if( zErr==0 ) return pNode;
  155000. lookup_err:
  155001. pParse->nErr++;
  155002. assert( zErr!=0 && pCtx!=0 );
  155003. zMsg = jsonPathSyntaxError(zErr);
  155004. if( zMsg ){
  155005. sqlite3_result_error(pCtx, zMsg, -1);
  155006. sqlite3_free(zMsg);
  155007. }else{
  155008. sqlite3_result_error_nomem(pCtx);
  155009. }
  155010. return 0;
  155011. }
  155012. /*
  155013. ** Report the wrong number of arguments for json_insert(), json_replace()
  155014. ** or json_set().
  155015. */
  155016. static void jsonWrongNumArgs(
  155017. sqlite3_context *pCtx,
  155018. const char *zFuncName
  155019. ){
  155020. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  155021. zFuncName);
  155022. sqlite3_result_error(pCtx, zMsg, -1);
  155023. sqlite3_free(zMsg);
  155024. }
  155025. /****************************************************************************
  155026. ** SQL functions used for testing and debugging
  155027. ****************************************************************************/
  155028. #ifdef SQLITE_DEBUG
  155029. /*
  155030. ** The json_parse(JSON) function returns a string which describes
  155031. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  155032. ** well-formed.
  155033. */
  155034. static void jsonParseFunc(
  155035. sqlite3_context *ctx,
  155036. int argc,
  155037. sqlite3_value **argv
  155038. ){
  155039. JsonString s; /* Output string - not real JSON */
  155040. JsonParse x; /* The parse */
  155041. u32 i;
  155042. assert( argc==1 );
  155043. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  155044. jsonParseFindParents(&x);
  155045. jsonInit(&s, ctx);
  155046. for(i=0; i<x.nNode; i++){
  155047. const char *zType;
  155048. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  155049. assert( x.aNode[i].eType==JSON_STRING );
  155050. zType = "label";
  155051. }else{
  155052. zType = jsonType[x.aNode[i].eType];
  155053. }
  155054. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  155055. i, zType, x.aNode[i].n, x.aUp[i]);
  155056. if( x.aNode[i].u.zJContent!=0 ){
  155057. jsonAppendRaw(&s, " ", 1);
  155058. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  155059. }
  155060. jsonAppendRaw(&s, "\n", 1);
  155061. }
  155062. jsonParseReset(&x);
  155063. jsonResult(&s);
  155064. }
  155065. /*
  155066. ** The json_test1(JSON) function return true (1) if the input is JSON
  155067. ** text generated by another json function. It returns (0) if the input
  155068. ** is not known to be JSON.
  155069. */
  155070. static void jsonTest1Func(
  155071. sqlite3_context *ctx,
  155072. int argc,
  155073. sqlite3_value **argv
  155074. ){
  155075. UNUSED_PARAM(argc);
  155076. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  155077. }
  155078. #endif /* SQLITE_DEBUG */
  155079. /****************************************************************************
  155080. ** Scalar SQL function implementations
  155081. ****************************************************************************/
  155082. /*
  155083. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  155084. ** array that contains all values given in arguments. Or if any argument
  155085. ** is a BLOB, throw an error.
  155086. */
  155087. static void jsonArrayFunc(
  155088. sqlite3_context *ctx,
  155089. int argc,
  155090. sqlite3_value **argv
  155091. ){
  155092. int i;
  155093. JsonString jx;
  155094. jsonInit(&jx, ctx);
  155095. jsonAppendChar(&jx, '[');
  155096. for(i=0; i<argc; i++){
  155097. jsonAppendSeparator(&jx);
  155098. jsonAppendValue(&jx, argv[i]);
  155099. }
  155100. jsonAppendChar(&jx, ']');
  155101. jsonResult(&jx);
  155102. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  155103. }
  155104. /*
  155105. ** json_array_length(JSON)
  155106. ** json_array_length(JSON, PATH)
  155107. **
  155108. ** Return the number of elements in the top-level JSON array.
  155109. ** Return 0 if the input is not a well-formed JSON array.
  155110. */
  155111. static void jsonArrayLengthFunc(
  155112. sqlite3_context *ctx,
  155113. int argc,
  155114. sqlite3_value **argv
  155115. ){
  155116. JsonParse x; /* The parse */
  155117. sqlite3_int64 n = 0;
  155118. u32 i;
  155119. JsonNode *pNode;
  155120. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  155121. assert( x.nNode );
  155122. if( argc==2 ){
  155123. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  155124. pNode = jsonLookup(&x, zPath, 0, ctx);
  155125. }else{
  155126. pNode = x.aNode;
  155127. }
  155128. if( pNode==0 ){
  155129. x.nErr = 1;
  155130. }else if( pNode->eType==JSON_ARRAY ){
  155131. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  155132. for(i=1; i<=pNode->n; n++){
  155133. i += jsonNodeSize(&pNode[i]);
  155134. }
  155135. }
  155136. if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
  155137. jsonParseReset(&x);
  155138. }
  155139. /*
  155140. ** json_extract(JSON, PATH, ...)
  155141. **
  155142. ** Return the element described by PATH. Return NULL if there is no
  155143. ** PATH element. If there are multiple PATHs, then return a JSON array
  155144. ** with the result from each path. Throw an error if the JSON or any PATH
  155145. ** is malformed.
  155146. */
  155147. static void jsonExtractFunc(
  155148. sqlite3_context *ctx,
  155149. int argc,
  155150. sqlite3_value **argv
  155151. ){
  155152. JsonParse x; /* The parse */
  155153. JsonNode *pNode;
  155154. const char *zPath;
  155155. JsonString jx;
  155156. int i;
  155157. if( argc<2 ) return;
  155158. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  155159. jsonInit(&jx, ctx);
  155160. jsonAppendChar(&jx, '[');
  155161. for(i=1; i<argc; i++){
  155162. zPath = (const char*)sqlite3_value_text(argv[i]);
  155163. pNode = jsonLookup(&x, zPath, 0, ctx);
  155164. if( x.nErr ) break;
  155165. if( argc>2 ){
  155166. jsonAppendSeparator(&jx);
  155167. if( pNode ){
  155168. jsonRenderNode(pNode, &jx, 0);
  155169. }else{
  155170. jsonAppendRaw(&jx, "null", 4);
  155171. }
  155172. }else if( pNode ){
  155173. jsonReturn(pNode, ctx, 0);
  155174. }
  155175. }
  155176. if( argc>2 && i==argc ){
  155177. jsonAppendChar(&jx, ']');
  155178. jsonResult(&jx);
  155179. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  155180. }
  155181. jsonReset(&jx);
  155182. jsonParseReset(&x);
  155183. }
  155184. /*
  155185. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  155186. ** object that contains all name/value given in arguments. Or if any name
  155187. ** is not a string or if any value is a BLOB, throw an error.
  155188. */
  155189. static void jsonObjectFunc(
  155190. sqlite3_context *ctx,
  155191. int argc,
  155192. sqlite3_value **argv
  155193. ){
  155194. int i;
  155195. JsonString jx;
  155196. const char *z;
  155197. u32 n;
  155198. if( argc&1 ){
  155199. sqlite3_result_error(ctx, "json_object() requires an even number "
  155200. "of arguments", -1);
  155201. return;
  155202. }
  155203. jsonInit(&jx, ctx);
  155204. jsonAppendChar(&jx, '{');
  155205. for(i=0; i<argc; i+=2){
  155206. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  155207. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  155208. jsonReset(&jx);
  155209. return;
  155210. }
  155211. jsonAppendSeparator(&jx);
  155212. z = (const char*)sqlite3_value_text(argv[i]);
  155213. n = (u32)sqlite3_value_bytes(argv[i]);
  155214. jsonAppendString(&jx, z, n);
  155215. jsonAppendChar(&jx, ':');
  155216. jsonAppendValue(&jx, argv[i+1]);
  155217. }
  155218. jsonAppendChar(&jx, '}');
  155219. jsonResult(&jx);
  155220. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  155221. }
  155222. /*
  155223. ** json_remove(JSON, PATH, ...)
  155224. **
  155225. ** Remove the named elements from JSON and return the result. malformed
  155226. ** JSON or PATH arguments result in an error.
  155227. */
  155228. static void jsonRemoveFunc(
  155229. sqlite3_context *ctx,
  155230. int argc,
  155231. sqlite3_value **argv
  155232. ){
  155233. JsonParse x; /* The parse */
  155234. JsonNode *pNode;
  155235. const char *zPath;
  155236. u32 i;
  155237. if( argc<1 ) return;
  155238. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  155239. assert( x.nNode );
  155240. for(i=1; i<(u32)argc; i++){
  155241. zPath = (const char*)sqlite3_value_text(argv[i]);
  155242. if( zPath==0 ) goto remove_done;
  155243. pNode = jsonLookup(&x, zPath, 0, ctx);
  155244. if( x.nErr ) goto remove_done;
  155245. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  155246. }
  155247. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  155248. jsonReturnJson(x.aNode, ctx, 0);
  155249. }
  155250. remove_done:
  155251. jsonParseReset(&x);
  155252. }
  155253. /*
  155254. ** json_replace(JSON, PATH, VALUE, ...)
  155255. **
  155256. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  155257. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  155258. */
  155259. static void jsonReplaceFunc(
  155260. sqlite3_context *ctx,
  155261. int argc,
  155262. sqlite3_value **argv
  155263. ){
  155264. JsonParse x; /* The parse */
  155265. JsonNode *pNode;
  155266. const char *zPath;
  155267. u32 i;
  155268. if( argc<1 ) return;
  155269. if( (argc&1)==0 ) {
  155270. jsonWrongNumArgs(ctx, "replace");
  155271. return;
  155272. }
  155273. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  155274. assert( x.nNode );
  155275. for(i=1; i<(u32)argc; i+=2){
  155276. zPath = (const char*)sqlite3_value_text(argv[i]);
  155277. pNode = jsonLookup(&x, zPath, 0, ctx);
  155278. if( x.nErr ) goto replace_err;
  155279. if( pNode ){
  155280. pNode->jnFlags |= (u8)JNODE_REPLACE;
  155281. pNode->iVal = (u8)(i+1);
  155282. }
  155283. }
  155284. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  155285. sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
  155286. }else{
  155287. jsonReturnJson(x.aNode, ctx, argv);
  155288. }
  155289. replace_err:
  155290. jsonParseReset(&x);
  155291. }
  155292. /*
  155293. ** json_set(JSON, PATH, VALUE, ...)
  155294. **
  155295. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  155296. ** exist. Overwrite existing values that do exist.
  155297. ** If JSON or PATH is malformed, throw an error.
  155298. **
  155299. ** json_insert(JSON, PATH, VALUE, ...)
  155300. **
  155301. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  155302. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  155303. */
  155304. static void jsonSetFunc(
  155305. sqlite3_context *ctx,
  155306. int argc,
  155307. sqlite3_value **argv
  155308. ){
  155309. JsonParse x; /* The parse */
  155310. JsonNode *pNode;
  155311. const char *zPath;
  155312. u32 i;
  155313. int bApnd;
  155314. int bIsSet = *(int*)sqlite3_user_data(ctx);
  155315. if( argc<1 ) return;
  155316. if( (argc&1)==0 ) {
  155317. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  155318. return;
  155319. }
  155320. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  155321. assert( x.nNode );
  155322. for(i=1; i<(u32)argc; i+=2){
  155323. zPath = (const char*)sqlite3_value_text(argv[i]);
  155324. bApnd = 0;
  155325. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  155326. if( x.oom ){
  155327. sqlite3_result_error_nomem(ctx);
  155328. goto jsonSetDone;
  155329. }else if( x.nErr ){
  155330. goto jsonSetDone;
  155331. }else if( pNode && (bApnd || bIsSet) ){
  155332. pNode->jnFlags |= (u8)JNODE_REPLACE;
  155333. pNode->iVal = (u8)(i+1);
  155334. }
  155335. }
  155336. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  155337. sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
  155338. }else{
  155339. jsonReturnJson(x.aNode, ctx, argv);
  155340. }
  155341. jsonSetDone:
  155342. jsonParseReset(&x);
  155343. }
  155344. /*
  155345. ** json_type(JSON)
  155346. ** json_type(JSON, PATH)
  155347. **
  155348. ** Return the top-level "type" of a JSON string. Throw an error if
  155349. ** either the JSON or PATH inputs are not well-formed.
  155350. */
  155351. static void jsonTypeFunc(
  155352. sqlite3_context *ctx,
  155353. int argc,
  155354. sqlite3_value **argv
  155355. ){
  155356. JsonParse x; /* The parse */
  155357. const char *zPath;
  155358. JsonNode *pNode;
  155359. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  155360. assert( x.nNode );
  155361. if( argc==2 ){
  155362. zPath = (const char*)sqlite3_value_text(argv[1]);
  155363. pNode = jsonLookup(&x, zPath, 0, ctx);
  155364. }else{
  155365. pNode = x.aNode;
  155366. }
  155367. if( pNode ){
  155368. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  155369. }
  155370. jsonParseReset(&x);
  155371. }
  155372. /*
  155373. ** json_valid(JSON)
  155374. **
  155375. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  155376. ** Return 0 otherwise.
  155377. */
  155378. static void jsonValidFunc(
  155379. sqlite3_context *ctx,
  155380. int argc,
  155381. sqlite3_value **argv
  155382. ){
  155383. JsonParse x; /* The parse */
  155384. int rc = 0;
  155385. UNUSED_PARAM(argc);
  155386. if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  155387. rc = 1;
  155388. }
  155389. jsonParseReset(&x);
  155390. sqlite3_result_int(ctx, rc);
  155391. }
  155392. /****************************************************************************
  155393. ** Aggregate SQL function implementations
  155394. ****************************************************************************/
  155395. /*
  155396. ** json_group_array(VALUE)
  155397. **
  155398. ** Return a JSON array composed of all values in the aggregate.
  155399. */
  155400. static void jsonArrayStep(
  155401. sqlite3_context *ctx,
  155402. int argc,
  155403. sqlite3_value **argv
  155404. ){
  155405. JsonString *pStr;
  155406. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  155407. if( pStr ){
  155408. if( pStr->zBuf==0 ){
  155409. jsonInit(pStr, ctx);
  155410. jsonAppendChar(pStr, '[');
  155411. }else{
  155412. jsonAppendChar(pStr, ',');
  155413. pStr->pCtx = ctx;
  155414. }
  155415. jsonAppendValue(pStr, argv[0]);
  155416. }
  155417. }
  155418. static void jsonArrayFinal(sqlite3_context *ctx){
  155419. JsonString *pStr;
  155420. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  155421. if( pStr ){
  155422. pStr->pCtx = ctx;
  155423. jsonAppendChar(pStr, ']');
  155424. if( pStr->bErr ){
  155425. sqlite3_result_error_nomem(ctx);
  155426. assert( pStr->bStatic );
  155427. }else{
  155428. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  155429. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  155430. pStr->bStatic = 1;
  155431. }
  155432. }else{
  155433. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  155434. }
  155435. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  155436. }
  155437. /*
  155438. ** json_group_obj(NAME,VALUE)
  155439. **
  155440. ** Return a JSON object composed of all names and values in the aggregate.
  155441. */
  155442. static void jsonObjectStep(
  155443. sqlite3_context *ctx,
  155444. int argc,
  155445. sqlite3_value **argv
  155446. ){
  155447. JsonString *pStr;
  155448. const char *z;
  155449. u32 n;
  155450. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  155451. if( pStr ){
  155452. if( pStr->zBuf==0 ){
  155453. jsonInit(pStr, ctx);
  155454. jsonAppendChar(pStr, '{');
  155455. }else{
  155456. jsonAppendChar(pStr, ',');
  155457. pStr->pCtx = ctx;
  155458. }
  155459. z = (const char*)sqlite3_value_text(argv[0]);
  155460. n = (u32)sqlite3_value_bytes(argv[0]);
  155461. jsonAppendString(pStr, z, n);
  155462. jsonAppendChar(pStr, ':');
  155463. jsonAppendValue(pStr, argv[1]);
  155464. }
  155465. }
  155466. static void jsonObjectFinal(sqlite3_context *ctx){
  155467. JsonString *pStr;
  155468. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  155469. if( pStr ){
  155470. jsonAppendChar(pStr, '}');
  155471. if( pStr->bErr ){
  155472. sqlite3_result_error_nomem(ctx);
  155473. assert( pStr->bStatic );
  155474. }else{
  155475. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  155476. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  155477. pStr->bStatic = 1;
  155478. }
  155479. }else{
  155480. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  155481. }
  155482. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  155483. }
  155484. #ifndef SQLITE_OMIT_VIRTUALTABLE
  155485. /****************************************************************************
  155486. ** The json_each virtual table
  155487. ****************************************************************************/
  155488. typedef struct JsonEachCursor JsonEachCursor;
  155489. struct JsonEachCursor {
  155490. sqlite3_vtab_cursor base; /* Base class - must be first */
  155491. u32 iRowid; /* The rowid */
  155492. u32 iBegin; /* The first node of the scan */
  155493. u32 i; /* Index in sParse.aNode[] of current row */
  155494. u32 iEnd; /* EOF when i equals or exceeds this value */
  155495. u8 eType; /* Type of top-level element */
  155496. u8 bRecursive; /* True for json_tree(). False for json_each() */
  155497. char *zJson; /* Input JSON */
  155498. char *zRoot; /* Path by which to filter zJson */
  155499. JsonParse sParse; /* Parse of the input JSON */
  155500. };
  155501. /* Constructor for the json_each virtual table */
  155502. static int jsonEachConnect(
  155503. sqlite3 *db,
  155504. void *pAux,
  155505. int argc, const char *const*argv,
  155506. sqlite3_vtab **ppVtab,
  155507. char **pzErr
  155508. ){
  155509. sqlite3_vtab *pNew;
  155510. int rc;
  155511. /* Column numbers */
  155512. #define JEACH_KEY 0
  155513. #define JEACH_VALUE 1
  155514. #define JEACH_TYPE 2
  155515. #define JEACH_ATOM 3
  155516. #define JEACH_ID 4
  155517. #define JEACH_PARENT 5
  155518. #define JEACH_FULLKEY 6
  155519. #define JEACH_PATH 7
  155520. #define JEACH_JSON 8
  155521. #define JEACH_ROOT 9
  155522. UNUSED_PARAM(pzErr);
  155523. UNUSED_PARAM(argv);
  155524. UNUSED_PARAM(argc);
  155525. UNUSED_PARAM(pAux);
  155526. rc = sqlite3_declare_vtab(db,
  155527. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  155528. "json HIDDEN,root HIDDEN)");
  155529. if( rc==SQLITE_OK ){
  155530. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  155531. if( pNew==0 ) return SQLITE_NOMEM;
  155532. memset(pNew, 0, sizeof(*pNew));
  155533. }
  155534. return rc;
  155535. }
  155536. /* destructor for json_each virtual table */
  155537. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  155538. sqlite3_free(pVtab);
  155539. return SQLITE_OK;
  155540. }
  155541. /* constructor for a JsonEachCursor object for json_each(). */
  155542. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  155543. JsonEachCursor *pCur;
  155544. UNUSED_PARAM(p);
  155545. pCur = sqlite3_malloc( sizeof(*pCur) );
  155546. if( pCur==0 ) return SQLITE_NOMEM;
  155547. memset(pCur, 0, sizeof(*pCur));
  155548. *ppCursor = &pCur->base;
  155549. return SQLITE_OK;
  155550. }
  155551. /* constructor for a JsonEachCursor object for json_tree(). */
  155552. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  155553. int rc = jsonEachOpenEach(p, ppCursor);
  155554. if( rc==SQLITE_OK ){
  155555. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  155556. pCur->bRecursive = 1;
  155557. }
  155558. return rc;
  155559. }
  155560. /* Reset a JsonEachCursor back to its original state. Free any memory
  155561. ** held. */
  155562. static void jsonEachCursorReset(JsonEachCursor *p){
  155563. sqlite3_free(p->zJson);
  155564. sqlite3_free(p->zRoot);
  155565. jsonParseReset(&p->sParse);
  155566. p->iRowid = 0;
  155567. p->i = 0;
  155568. p->iEnd = 0;
  155569. p->eType = 0;
  155570. p->zJson = 0;
  155571. p->zRoot = 0;
  155572. }
  155573. /* Destructor for a jsonEachCursor object */
  155574. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  155575. JsonEachCursor *p = (JsonEachCursor*)cur;
  155576. jsonEachCursorReset(p);
  155577. sqlite3_free(cur);
  155578. return SQLITE_OK;
  155579. }
  155580. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  155581. ** of the JSON object */
  155582. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  155583. JsonEachCursor *p = (JsonEachCursor*)cur;
  155584. return p->i >= p->iEnd;
  155585. }
  155586. /* Advance the cursor to the next element for json_tree() */
  155587. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  155588. JsonEachCursor *p = (JsonEachCursor*)cur;
  155589. if( p->bRecursive ){
  155590. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  155591. p->i++;
  155592. p->iRowid++;
  155593. if( p->i<p->iEnd ){
  155594. u32 iUp = p->sParse.aUp[p->i];
  155595. JsonNode *pUp = &p->sParse.aNode[iUp];
  155596. p->eType = pUp->eType;
  155597. if( pUp->eType==JSON_ARRAY ){
  155598. if( iUp==p->i-1 ){
  155599. pUp->u.iKey = 0;
  155600. }else{
  155601. pUp->u.iKey++;
  155602. }
  155603. }
  155604. }
  155605. }else{
  155606. switch( p->eType ){
  155607. case JSON_ARRAY: {
  155608. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  155609. p->iRowid++;
  155610. break;
  155611. }
  155612. case JSON_OBJECT: {
  155613. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  155614. p->iRowid++;
  155615. break;
  155616. }
  155617. default: {
  155618. p->i = p->iEnd;
  155619. break;
  155620. }
  155621. }
  155622. }
  155623. return SQLITE_OK;
  155624. }
  155625. /* Append the name of the path for element i to pStr
  155626. */
  155627. static void jsonEachComputePath(
  155628. JsonEachCursor *p, /* The cursor */
  155629. JsonString *pStr, /* Write the path here */
  155630. u32 i /* Path to this element */
  155631. ){
  155632. JsonNode *pNode, *pUp;
  155633. u32 iUp;
  155634. if( i==0 ){
  155635. jsonAppendChar(pStr, '$');
  155636. return;
  155637. }
  155638. iUp = p->sParse.aUp[i];
  155639. jsonEachComputePath(p, pStr, iUp);
  155640. pNode = &p->sParse.aNode[i];
  155641. pUp = &p->sParse.aNode[iUp];
  155642. if( pUp->eType==JSON_ARRAY ){
  155643. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  155644. }else{
  155645. assert( pUp->eType==JSON_OBJECT );
  155646. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  155647. assert( pNode->eType==JSON_STRING );
  155648. assert( pNode->jnFlags & JNODE_LABEL );
  155649. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  155650. }
  155651. }
  155652. /* Return the value of a column */
  155653. static int jsonEachColumn(
  155654. sqlite3_vtab_cursor *cur, /* The cursor */
  155655. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  155656. int i /* Which column to return */
  155657. ){
  155658. JsonEachCursor *p = (JsonEachCursor*)cur;
  155659. JsonNode *pThis = &p->sParse.aNode[p->i];
  155660. switch( i ){
  155661. case JEACH_KEY: {
  155662. if( p->i==0 ) break;
  155663. if( p->eType==JSON_OBJECT ){
  155664. jsonReturn(pThis, ctx, 0);
  155665. }else if( p->eType==JSON_ARRAY ){
  155666. u32 iKey;
  155667. if( p->bRecursive ){
  155668. if( p->iRowid==0 ) break;
  155669. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  155670. }else{
  155671. iKey = p->iRowid;
  155672. }
  155673. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  155674. }
  155675. break;
  155676. }
  155677. case JEACH_VALUE: {
  155678. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  155679. jsonReturn(pThis, ctx, 0);
  155680. break;
  155681. }
  155682. case JEACH_TYPE: {
  155683. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  155684. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  155685. break;
  155686. }
  155687. case JEACH_ATOM: {
  155688. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  155689. if( pThis->eType>=JSON_ARRAY ) break;
  155690. jsonReturn(pThis, ctx, 0);
  155691. break;
  155692. }
  155693. case JEACH_ID: {
  155694. sqlite3_result_int64(ctx,
  155695. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  155696. break;
  155697. }
  155698. case JEACH_PARENT: {
  155699. if( p->i>p->iBegin && p->bRecursive ){
  155700. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  155701. }
  155702. break;
  155703. }
  155704. case JEACH_FULLKEY: {
  155705. JsonString x;
  155706. jsonInit(&x, ctx);
  155707. if( p->bRecursive ){
  155708. jsonEachComputePath(p, &x, p->i);
  155709. }else{
  155710. if( p->zRoot ){
  155711. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  155712. }else{
  155713. jsonAppendChar(&x, '$');
  155714. }
  155715. if( p->eType==JSON_ARRAY ){
  155716. jsonPrintf(30, &x, "[%d]", p->iRowid);
  155717. }else{
  155718. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  155719. }
  155720. }
  155721. jsonResult(&x);
  155722. break;
  155723. }
  155724. case JEACH_PATH: {
  155725. if( p->bRecursive ){
  155726. JsonString x;
  155727. jsonInit(&x, ctx);
  155728. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  155729. jsonResult(&x);
  155730. break;
  155731. }
  155732. /* For json_each() path and root are the same so fall through
  155733. ** into the root case */
  155734. }
  155735. case JEACH_ROOT: {
  155736. const char *zRoot = p->zRoot;
  155737. if( zRoot==0 ) zRoot = "$";
  155738. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  155739. break;
  155740. }
  155741. case JEACH_JSON: {
  155742. assert( i==JEACH_JSON );
  155743. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  155744. break;
  155745. }
  155746. }
  155747. return SQLITE_OK;
  155748. }
  155749. /* Return the current rowid value */
  155750. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  155751. JsonEachCursor *p = (JsonEachCursor*)cur;
  155752. *pRowid = p->iRowid;
  155753. return SQLITE_OK;
  155754. }
  155755. /* The query strategy is to look for an equality constraint on the json
  155756. ** column. Without such a constraint, the table cannot operate. idxNum is
  155757. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  155758. ** and 0 otherwise.
  155759. */
  155760. static int jsonEachBestIndex(
  155761. sqlite3_vtab *tab,
  155762. sqlite3_index_info *pIdxInfo
  155763. ){
  155764. int i;
  155765. int jsonIdx = -1;
  155766. int rootIdx = -1;
  155767. const struct sqlite3_index_constraint *pConstraint;
  155768. UNUSED_PARAM(tab);
  155769. pConstraint = pIdxInfo->aConstraint;
  155770. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  155771. if( pConstraint->usable==0 ) continue;
  155772. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  155773. switch( pConstraint->iColumn ){
  155774. case JEACH_JSON: jsonIdx = i; break;
  155775. case JEACH_ROOT: rootIdx = i; break;
  155776. default: /* no-op */ break;
  155777. }
  155778. }
  155779. if( jsonIdx<0 ){
  155780. pIdxInfo->idxNum = 0;
  155781. pIdxInfo->estimatedCost = 1e99;
  155782. }else{
  155783. pIdxInfo->estimatedCost = 1.0;
  155784. pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  155785. pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  155786. if( rootIdx<0 ){
  155787. pIdxInfo->idxNum = 1;
  155788. }else{
  155789. pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  155790. pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  155791. pIdxInfo->idxNum = 3;
  155792. }
  155793. }
  155794. return SQLITE_OK;
  155795. }
  155796. /* Start a search on a new JSON string */
  155797. static int jsonEachFilter(
  155798. sqlite3_vtab_cursor *cur,
  155799. int idxNum, const char *idxStr,
  155800. int argc, sqlite3_value **argv
  155801. ){
  155802. JsonEachCursor *p = (JsonEachCursor*)cur;
  155803. const char *z;
  155804. const char *zRoot = 0;
  155805. sqlite3_int64 n;
  155806. UNUSED_PARAM(idxStr);
  155807. UNUSED_PARAM(argc);
  155808. jsonEachCursorReset(p);
  155809. if( idxNum==0 ) return SQLITE_OK;
  155810. z = (const char*)sqlite3_value_text(argv[0]);
  155811. if( z==0 ) return SQLITE_OK;
  155812. n = sqlite3_value_bytes(argv[0]);
  155813. p->zJson = sqlite3_malloc64( n+1 );
  155814. if( p->zJson==0 ) return SQLITE_NOMEM;
  155815. memcpy(p->zJson, z, (size_t)n+1);
  155816. if( jsonParse(&p->sParse, 0, p->zJson) ){
  155817. int rc = SQLITE_NOMEM;
  155818. if( p->sParse.oom==0 ){
  155819. sqlite3_free(cur->pVtab->zErrMsg);
  155820. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  155821. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  155822. }
  155823. jsonEachCursorReset(p);
  155824. return rc;
  155825. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  155826. jsonEachCursorReset(p);
  155827. return SQLITE_NOMEM;
  155828. }else{
  155829. JsonNode *pNode = 0;
  155830. if( idxNum==3 ){
  155831. const char *zErr = 0;
  155832. zRoot = (const char*)sqlite3_value_text(argv[1]);
  155833. if( zRoot==0 ) return SQLITE_OK;
  155834. n = sqlite3_value_bytes(argv[1]);
  155835. p->zRoot = sqlite3_malloc64( n+1 );
  155836. if( p->zRoot==0 ) return SQLITE_NOMEM;
  155837. memcpy(p->zRoot, zRoot, (size_t)n+1);
  155838. if( zRoot[0]!='$' ){
  155839. zErr = zRoot;
  155840. }else{
  155841. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  155842. }
  155843. if( zErr ){
  155844. sqlite3_free(cur->pVtab->zErrMsg);
  155845. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  155846. jsonEachCursorReset(p);
  155847. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  155848. }else if( pNode==0 ){
  155849. return SQLITE_OK;
  155850. }
  155851. }else{
  155852. pNode = p->sParse.aNode;
  155853. }
  155854. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  155855. p->eType = pNode->eType;
  155856. if( p->eType>=JSON_ARRAY ){
  155857. pNode->u.iKey = 0;
  155858. p->iEnd = p->i + pNode->n + 1;
  155859. if( p->bRecursive ){
  155860. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  155861. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  155862. p->i--;
  155863. }
  155864. }else{
  155865. p->i++;
  155866. }
  155867. }else{
  155868. p->iEnd = p->i+1;
  155869. }
  155870. }
  155871. return SQLITE_OK;
  155872. }
  155873. /* The methods of the json_each virtual table */
  155874. static sqlite3_module jsonEachModule = {
  155875. 0, /* iVersion */
  155876. 0, /* xCreate */
  155877. jsonEachConnect, /* xConnect */
  155878. jsonEachBestIndex, /* xBestIndex */
  155879. jsonEachDisconnect, /* xDisconnect */
  155880. 0, /* xDestroy */
  155881. jsonEachOpenEach, /* xOpen - open a cursor */
  155882. jsonEachClose, /* xClose - close a cursor */
  155883. jsonEachFilter, /* xFilter - configure scan constraints */
  155884. jsonEachNext, /* xNext - advance a cursor */
  155885. jsonEachEof, /* xEof - check for end of scan */
  155886. jsonEachColumn, /* xColumn - read data */
  155887. jsonEachRowid, /* xRowid - read data */
  155888. 0, /* xUpdate */
  155889. 0, /* xBegin */
  155890. 0, /* xSync */
  155891. 0, /* xCommit */
  155892. 0, /* xRollback */
  155893. 0, /* xFindMethod */
  155894. 0, /* xRename */
  155895. 0, /* xSavepoint */
  155896. 0, /* xRelease */
  155897. 0 /* xRollbackTo */
  155898. };
  155899. /* The methods of the json_tree virtual table. */
  155900. static sqlite3_module jsonTreeModule = {
  155901. 0, /* iVersion */
  155902. 0, /* xCreate */
  155903. jsonEachConnect, /* xConnect */
  155904. jsonEachBestIndex, /* xBestIndex */
  155905. jsonEachDisconnect, /* xDisconnect */
  155906. 0, /* xDestroy */
  155907. jsonEachOpenTree, /* xOpen - open a cursor */
  155908. jsonEachClose, /* xClose - close a cursor */
  155909. jsonEachFilter, /* xFilter - configure scan constraints */
  155910. jsonEachNext, /* xNext - advance a cursor */
  155911. jsonEachEof, /* xEof - check for end of scan */
  155912. jsonEachColumn, /* xColumn - read data */
  155913. jsonEachRowid, /* xRowid - read data */
  155914. 0, /* xUpdate */
  155915. 0, /* xBegin */
  155916. 0, /* xSync */
  155917. 0, /* xCommit */
  155918. 0, /* xRollback */
  155919. 0, /* xFindMethod */
  155920. 0, /* xRename */
  155921. 0, /* xSavepoint */
  155922. 0, /* xRelease */
  155923. 0 /* xRollbackTo */
  155924. };
  155925. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  155926. /****************************************************************************
  155927. ** The following routines are the only publically visible identifiers in this
  155928. ** file. Call the following routines in order to register the various SQL
  155929. ** functions and the virtual table implemented by this file.
  155930. ****************************************************************************/
  155931. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  155932. int rc = SQLITE_OK;
  155933. unsigned int i;
  155934. static const struct {
  155935. const char *zName;
  155936. int nArg;
  155937. int flag;
  155938. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  155939. } aFunc[] = {
  155940. { "json", 1, 0, jsonRemoveFunc },
  155941. { "json_array", -1, 0, jsonArrayFunc },
  155942. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  155943. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  155944. { "json_extract", -1, 0, jsonExtractFunc },
  155945. { "json_insert", -1, 0, jsonSetFunc },
  155946. { "json_object", -1, 0, jsonObjectFunc },
  155947. { "json_remove", -1, 0, jsonRemoveFunc },
  155948. { "json_replace", -1, 0, jsonReplaceFunc },
  155949. { "json_set", -1, 1, jsonSetFunc },
  155950. { "json_type", 1, 0, jsonTypeFunc },
  155951. { "json_type", 2, 0, jsonTypeFunc },
  155952. { "json_valid", 1, 0, jsonValidFunc },
  155953. #if SQLITE_DEBUG
  155954. /* DEBUG and TESTING functions */
  155955. { "json_parse", 1, 0, jsonParseFunc },
  155956. { "json_test1", 1, 0, jsonTest1Func },
  155957. #endif
  155958. };
  155959. static const struct {
  155960. const char *zName;
  155961. int nArg;
  155962. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  155963. void (*xFinal)(sqlite3_context*);
  155964. } aAgg[] = {
  155965. { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
  155966. { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
  155967. };
  155968. #ifndef SQLITE_OMIT_VIRTUALTABLE
  155969. static const struct {
  155970. const char *zName;
  155971. sqlite3_module *pModule;
  155972. } aMod[] = {
  155973. { "json_each", &jsonEachModule },
  155974. { "json_tree", &jsonTreeModule },
  155975. };
  155976. #endif
  155977. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  155978. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  155979. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  155980. (void*)&aFunc[i].flag,
  155981. aFunc[i].xFunc, 0, 0);
  155982. }
  155983. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  155984. rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
  155985. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  155986. 0, aAgg[i].xStep, aAgg[i].xFinal);
  155987. }
  155988. #ifndef SQLITE_OMIT_VIRTUALTABLE
  155989. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  155990. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  155991. }
  155992. #endif
  155993. return rc;
  155994. }
  155995. #ifndef SQLITE_CORE
  155996. #ifdef _WIN32
  155997. __declspec(dllexport)
  155998. #endif
  155999. SQLITE_API int SQLITE_STDCALL sqlite3_json_init(
  156000. sqlite3 *db,
  156001. char **pzErrMsg,
  156002. const sqlite3_api_routines *pApi
  156003. ){
  156004. SQLITE_EXTENSION_INIT2(pApi);
  156005. (void)pzErrMsg; /* Unused parameter */
  156006. return sqlite3Json1Init(db);
  156007. }
  156008. #endif
  156009. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  156010. /************** End of json1.c ***********************************************/
  156011. /************** Begin file fts5.c ********************************************/
  156012. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  156013. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  156014. # define NDEBUG 1
  156015. #endif
  156016. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  156017. # undef NDEBUG
  156018. #endif
  156019. /*
  156020. ** 2014 May 31
  156021. **
  156022. ** The author disclaims copyright to this source code. In place of
  156023. ** a legal notice, here is a blessing:
  156024. **
  156025. ** May you do good and not evil.
  156026. ** May you find forgiveness for yourself and forgive others.
  156027. ** May you share freely, never taking more than you give.
  156028. **
  156029. ******************************************************************************
  156030. **
  156031. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  156032. ** FTS5 may be extended with:
  156033. **
  156034. ** * custom tokenizers, and
  156035. ** * custom auxiliary functions.
  156036. */
  156037. #ifndef _FTS5_H
  156038. #define _FTS5_H
  156039. /* #include "sqlite3.h" */
  156040. #if 0
  156041. extern "C" {
  156042. #endif
  156043. /*************************************************************************
  156044. ** CUSTOM AUXILIARY FUNCTIONS
  156045. **
  156046. ** Virtual table implementations may overload SQL functions by implementing
  156047. ** the sqlite3_module.xFindFunction() method.
  156048. */
  156049. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  156050. typedef struct Fts5Context Fts5Context;
  156051. typedef struct Fts5PhraseIter Fts5PhraseIter;
  156052. typedef void (*fts5_extension_function)(
  156053. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  156054. Fts5Context *pFts, /* First arg to pass to pApi functions */
  156055. sqlite3_context *pCtx, /* Context for returning result/error */
  156056. int nVal, /* Number of values in apVal[] array */
  156057. sqlite3_value **apVal /* Array of trailing arguments */
  156058. );
  156059. struct Fts5PhraseIter {
  156060. const unsigned char *a;
  156061. const unsigned char *b;
  156062. };
  156063. /*
  156064. ** EXTENSION API FUNCTIONS
  156065. **
  156066. ** xUserData(pFts):
  156067. ** Return a copy of the context pointer the extension function was
  156068. ** registered with.
  156069. **
  156070. ** xColumnTotalSize(pFts, iCol, pnToken):
  156071. ** If parameter iCol is less than zero, set output variable *pnToken
  156072. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  156073. ** non-negative but less than the number of columns in the table, return
  156074. ** the total number of tokens in column iCol, considering all rows in
  156075. ** the FTS5 table.
  156076. **
  156077. ** If parameter iCol is greater than or equal to the number of columns
  156078. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  156079. ** an OOM condition or IO error), an appropriate SQLite error code is
  156080. ** returned.
  156081. **
  156082. ** xColumnCount(pFts):
  156083. ** Return the number of columns in the table.
  156084. **
  156085. ** xColumnSize(pFts, iCol, pnToken):
  156086. ** If parameter iCol is less than zero, set output variable *pnToken
  156087. ** to the total number of tokens in the current row. Or, if iCol is
  156088. ** non-negative but less than the number of columns in the table, set
  156089. ** *pnToken to the number of tokens in column iCol of the current row.
  156090. **
  156091. ** If parameter iCol is greater than or equal to the number of columns
  156092. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  156093. ** an OOM condition or IO error), an appropriate SQLite error code is
  156094. ** returned.
  156095. **
  156096. ** xColumnText:
  156097. ** This function attempts to retrieve the text of column iCol of the
  156098. ** current document. If successful, (*pz) is set to point to a buffer
  156099. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  156100. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  156101. ** if an error occurs, an SQLite error code is returned and the final values
  156102. ** of (*pz) and (*pn) are undefined.
  156103. **
  156104. ** xPhraseCount:
  156105. ** Returns the number of phrases in the current query expression.
  156106. **
  156107. ** xPhraseSize:
  156108. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  156109. ** are numbered starting from zero.
  156110. **
  156111. ** xInstCount:
  156112. ** Set *pnInst to the total number of occurrences of all phrases within
  156113. ** the query within the current row. Return SQLITE_OK if successful, or
  156114. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  156115. **
  156116. ** xInst:
  156117. ** Query for the details of phrase match iIdx within the current row.
  156118. ** Phrase matches are numbered starting from zero, so the iIdx argument
  156119. ** should be greater than or equal to zero and smaller than the value
  156120. ** output by xInstCount().
  156121. **
  156122. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  156123. ** if an error occurs.
  156124. **
  156125. ** xRowid:
  156126. ** Returns the rowid of the current row.
  156127. **
  156128. ** xTokenize:
  156129. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  156130. **
  156131. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  156132. ** This API function is used to query the FTS table for phrase iPhrase
  156133. ** of the current query. Specifically, a query equivalent to:
  156134. **
  156135. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  156136. **
  156137. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  156138. ** current query is executed. For each row visited, the callback function
  156139. ** passed as the fourth argument is invoked. The context and API objects
  156140. ** passed to the callback function may be used to access the properties of
  156141. ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
  156142. ** passed as the third argument to pUserData.
  156143. **
  156144. ** If the callback function returns any value other than SQLITE_OK, the
  156145. ** query is abandoned and the xQueryPhrase function returns immediately.
  156146. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  156147. ** Otherwise, the error code is propagated upwards.
  156148. **
  156149. ** If the query runs to completion without incident, SQLITE_OK is returned.
  156150. ** Or, if some error occurs before the query completes or is aborted by
  156151. ** the callback, an SQLite error code is returned.
  156152. **
  156153. **
  156154. ** xSetAuxdata(pFts5, pAux, xDelete)
  156155. **
  156156. ** Save the pointer passed as the second argument as the extension functions
  156157. ** "auxiliary data". The pointer may then be retrieved by the current or any
  156158. ** future invocation of the same fts5 extension function made as part of
  156159. ** of the same MATCH query using the xGetAuxdata() API.
  156160. **
  156161. ** Each extension function is allocated a single auxiliary data slot for
  156162. ** each FTS query (MATCH expression). If the extension function is invoked
  156163. ** more than once for a single FTS query, then all invocations share a
  156164. ** single auxiliary data context.
  156165. **
  156166. ** If there is already an auxiliary data pointer when this function is
  156167. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  156168. ** was specified along with the original pointer, it is invoked at this
  156169. ** point.
  156170. **
  156171. ** The xDelete callback, if one is specified, is also invoked on the
  156172. ** auxiliary data pointer after the FTS5 query has finished.
  156173. **
  156174. ** If an error (e.g. an OOM condition) occurs within this function, an
  156175. ** the auxiliary data is set to NULL and an error code returned. If the
  156176. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  156177. ** pointer before returning.
  156178. **
  156179. **
  156180. ** xGetAuxdata(pFts5, bClear)
  156181. **
  156182. ** Returns the current auxiliary data pointer for the fts5 extension
  156183. ** function. See the xSetAuxdata() method for details.
  156184. **
  156185. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  156186. ** (set to NULL) before this function returns. In this case the xDelete,
  156187. ** if any, is not invoked.
  156188. **
  156189. **
  156190. ** xRowCount(pFts5, pnRow)
  156191. **
  156192. ** This function is used to retrieve the total number of rows in the table.
  156193. ** In other words, the same value that would be returned by:
  156194. **
  156195. ** SELECT count(*) FROM ftstable;
  156196. **
  156197. ** xPhraseFirst()
  156198. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  156199. ** method, to iterate through all instances of a single query phrase within
  156200. ** the current row. This is the same information as is accessible via the
  156201. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  156202. ** to use, this API may be faster under some circumstances. To iterate
  156203. ** through instances of phrase iPhrase, use the following code:
  156204. **
  156205. ** Fts5PhraseIter iter;
  156206. ** int iCol, iOff;
  156207. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  156208. ** iOff>=0;
  156209. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  156210. ** ){
  156211. ** // An instance of phrase iPhrase at offset iOff of column iCol
  156212. ** }
  156213. **
  156214. ** The Fts5PhraseIter structure is defined above. Applications should not
  156215. ** modify this structure directly - it should only be used as shown above
  156216. ** with the xPhraseFirst() and xPhraseNext() API methods.
  156217. **
  156218. ** xPhraseNext()
  156219. ** See xPhraseFirst above.
  156220. */
  156221. struct Fts5ExtensionApi {
  156222. int iVersion; /* Currently always set to 1 */
  156223. void *(*xUserData)(Fts5Context*);
  156224. int (*xColumnCount)(Fts5Context*);
  156225. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  156226. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  156227. int (*xTokenize)(Fts5Context*,
  156228. const char *pText, int nText, /* Text to tokenize */
  156229. void *pCtx, /* Context passed to xToken() */
  156230. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  156231. );
  156232. int (*xPhraseCount)(Fts5Context*);
  156233. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  156234. int (*xInstCount)(Fts5Context*, int *pnInst);
  156235. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  156236. sqlite3_int64 (*xRowid)(Fts5Context*);
  156237. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  156238. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  156239. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  156240. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  156241. );
  156242. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  156243. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  156244. void (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  156245. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  156246. };
  156247. /*
  156248. ** CUSTOM AUXILIARY FUNCTIONS
  156249. *************************************************************************/
  156250. /*************************************************************************
  156251. ** CUSTOM TOKENIZERS
  156252. **
  156253. ** Applications may also register custom tokenizer types. A tokenizer
  156254. ** is registered by providing fts5 with a populated instance of the
  156255. ** following structure. All structure methods must be defined, setting
  156256. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  156257. ** behaviour. The structure methods are expected to function as follows:
  156258. **
  156259. ** xCreate:
  156260. ** This function is used to allocate and inititalize a tokenizer instance.
  156261. ** A tokenizer instance is required to actually tokenize text.
  156262. **
  156263. ** The first argument passed to this function is a copy of the (void*)
  156264. ** pointer provided by the application when the fts5_tokenizer object
  156265. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  156266. ** The second and third arguments are an array of nul-terminated strings
  156267. ** containing the tokenizer arguments, if any, specified following the
  156268. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  156269. ** to create the FTS5 table.
  156270. **
  156271. ** The final argument is an output variable. If successful, (*ppOut)
  156272. ** should be set to point to the new tokenizer handle and SQLITE_OK
  156273. ** returned. If an error occurs, some value other than SQLITE_OK should
  156274. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  156275. ** is undefined.
  156276. **
  156277. ** xDelete:
  156278. ** This function is invoked to delete a tokenizer handle previously
  156279. ** allocated using xCreate(). Fts5 guarantees that this function will
  156280. ** be invoked exactly once for each successful call to xCreate().
  156281. **
  156282. ** xTokenize:
  156283. ** This function is expected to tokenize the nText byte string indicated
  156284. ** by argument pText. pText may or may not be nul-terminated. The first
  156285. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  156286. ** returned by an earlier call to xCreate().
  156287. **
  156288. ** The second argument indicates the reason that FTS5 is requesting
  156289. ** tokenization of the supplied text. This is always one of the following
  156290. ** four values:
  156291. **
  156292. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  156293. ** or removed from the FTS table. The tokenizer is being invoked to
  156294. ** determine the set of tokens to add to (or delete from) the
  156295. ** FTS index.
  156296. **
  156297. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  156298. ** against the FTS index. The tokenizer is being called to tokenize
  156299. ** a bareword or quoted string specified as part of the query.
  156300. **
  156301. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  156302. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  156303. ** followed by a "*" character, indicating that the last token
  156304. ** returned by the tokenizer will be treated as a token prefix.
  156305. **
  156306. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  156307. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  156308. ** function. Or an fts5_api.xColumnSize() request made by the same
  156309. ** on a columnsize=0 database.
  156310. ** </ul>
  156311. **
  156312. ** For each token in the input string, the supplied callback xToken() must
  156313. ** be invoked. The first argument to it should be a copy of the pointer
  156314. ** passed as the second argument to xTokenize(). The third and fourth
  156315. ** arguments are a pointer to a buffer containing the token text, and the
  156316. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  156317. ** of the first byte of and first byte immediately following the text from
  156318. ** which the token is derived within the input.
  156319. **
  156320. ** The second argument passed to the xToken() callback ("tflags") should
  156321. ** normally be set to 0. The exception is if the tokenizer supports
  156322. ** synonyms. In this case see the discussion below for details.
  156323. **
  156324. ** FTS5 assumes the xToken() callback is invoked for each token in the
  156325. ** order that they occur within the input text.
  156326. **
  156327. ** If an xToken() callback returns any value other than SQLITE_OK, then
  156328. ** the tokenization should be abandoned and the xTokenize() method should
  156329. ** immediately return a copy of the xToken() return value. Or, if the
  156330. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  156331. ** if an error occurs with the xTokenize() implementation itself, it
  156332. ** may abandon the tokenization and return any error code other than
  156333. ** SQLITE_OK or SQLITE_DONE.
  156334. **
  156335. ** SYNONYM SUPPORT
  156336. **
  156337. ** Custom tokenizers may also support synonyms. Consider a case in which a
  156338. ** user wishes to query for a phrase such as "first place". Using the
  156339. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  156340. ** of "first place" within the document set, but not alternative forms
  156341. ** such as "1st place". In some applications, it would be better to match
  156342. ** all instances of "first place" or "1st place" regardless of which form
  156343. ** the user specified in the MATCH query text.
  156344. **
  156345. ** There are several ways to approach this in FTS5:
  156346. **
  156347. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  156348. ** In the above example, this means that the tokenizer returns the
  156349. ** same token for inputs "first" and "1st". Say that token is in
  156350. ** fact "first", so that when the user inserts the document "I won
  156351. ** 1st place" entries are added to the index for tokens "i", "won",
  156352. ** "first" and "place". If the user then queries for '1st + place',
  156353. ** the tokenizer substitutes "first" for "1st" and the query works
  156354. ** as expected.
  156355. **
  156356. ** <li> By adding multiple synonyms for a single term to the FTS index.
  156357. ** In this case, when tokenizing query text, the tokenizer may
  156358. ** provide multiple synonyms for a single term within the document.
  156359. ** FTS5 then queries the index for each synonym individually. For
  156360. ** example, faced with the query:
  156361. **
  156362. ** <codeblock>
  156363. ** ... MATCH 'first place'</codeblock>
  156364. **
  156365. ** the tokenizer offers both "1st" and "first" as synonyms for the
  156366. ** first token in the MATCH query and FTS5 effectively runs a query
  156367. ** similar to:
  156368. **
  156369. ** <codeblock>
  156370. ** ... MATCH '(first OR 1st) place'</codeblock>
  156371. **
  156372. ** except that, for the purposes of auxiliary functions, the query
  156373. ** still appears to contain just two phrases - "(first OR 1st)"
  156374. ** being treated as a single phrase.
  156375. **
  156376. ** <li> By adding multiple synonyms for a single term to the FTS index.
  156377. ** Using this method, when tokenizing document text, the tokenizer
  156378. ** provides multiple synonyms for each token. So that when a
  156379. ** document such as "I won first place" is tokenized, entries are
  156380. ** added to the FTS index for "i", "won", "first", "1st" and
  156381. ** "place".
  156382. **
  156383. ** This way, even if the tokenizer does not provide synonyms
  156384. ** when tokenizing query text (it should not - to do would be
  156385. ** inefficient), it doesn't matter if the user queries for
  156386. ** 'first + place' or '1st + place', as there are entires in the
  156387. ** FTS index corresponding to both forms of the first token.
  156388. ** </ol>
  156389. **
  156390. ** Whether it is parsing document or query text, any call to xToken that
  156391. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  156392. ** is considered to supply a synonym for the previous token. For example,
  156393. ** when parsing the document "I won first place", a tokenizer that supports
  156394. ** synonyms would call xToken() 5 times, as follows:
  156395. **
  156396. ** <codeblock>
  156397. ** xToken(pCtx, 0, "i", 1, 0, 1);
  156398. ** xToken(pCtx, 0, "won", 3, 2, 5);
  156399. ** xToken(pCtx, 0, "first", 5, 6, 11);
  156400. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  156401. ** xToken(pCtx, 0, "place", 5, 12, 17);
  156402. **</codeblock>
  156403. **
  156404. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  156405. ** xToken() is called. Multiple synonyms may be specified for a single token
  156406. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  156407. ** There is no limit to the number of synonyms that may be provided for a
  156408. ** single token.
  156409. **
  156410. ** In many cases, method (1) above is the best approach. It does not add
  156411. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  156412. ** so it is efficient in terms of disk space and query speed. However, it
  156413. ** does not support prefix queries very well. If, as suggested above, the
  156414. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  156415. **
  156416. ** <codeblock>
  156417. ** ... MATCH '1s*'</codeblock>
  156418. **
  156419. ** will not match documents that contain the token "1st" (as the tokenizer
  156420. ** will probably not map "1s" to any prefix of "first").
  156421. **
  156422. ** For full prefix support, method (3) may be preferred. In this case,
  156423. ** because the index contains entries for both "first" and "1st", prefix
  156424. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  156425. ** extra entries are added to the FTS index, this method uses more space
  156426. ** within the database.
  156427. **
  156428. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  156429. ** a query such as '1s*' will match documents that contain the literal
  156430. ** token "1st", but not "first" (assuming the tokenizer is not able to
  156431. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  156432. ** will match against "1st" and "first". This method does not require
  156433. ** extra disk space, as no extra entries are added to the FTS index.
  156434. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  156435. ** as separate queries of the FTS index are required for each synonym.
  156436. **
  156437. ** When using methods (2) or (3), it is important that the tokenizer only
  156438. ** provide synonyms when tokenizing document text (method (2)) or query
  156439. ** text (method (3)), not both. Doing so will not cause any errors, but is
  156440. ** inefficient.
  156441. */
  156442. typedef struct Fts5Tokenizer Fts5Tokenizer;
  156443. typedef struct fts5_tokenizer fts5_tokenizer;
  156444. struct fts5_tokenizer {
  156445. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  156446. void (*xDelete)(Fts5Tokenizer*);
  156447. int (*xTokenize)(Fts5Tokenizer*,
  156448. void *pCtx,
  156449. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  156450. const char *pText, int nText,
  156451. int (*xToken)(
  156452. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  156453. int tflags, /* Mask of FTS5_TOKEN_* flags */
  156454. const char *pToken, /* Pointer to buffer containing token */
  156455. int nToken, /* Size of token in bytes */
  156456. int iStart, /* Byte offset of token within input text */
  156457. int iEnd /* Byte offset of end of token within input text */
  156458. )
  156459. );
  156460. };
  156461. /* Flags that may be passed as the third argument to xTokenize() */
  156462. #define FTS5_TOKENIZE_QUERY 0x0001
  156463. #define FTS5_TOKENIZE_PREFIX 0x0002
  156464. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  156465. #define FTS5_TOKENIZE_AUX 0x0008
  156466. /* Flags that may be passed by the tokenizer implementation back to FTS5
  156467. ** as the third argument to the supplied xToken callback. */
  156468. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  156469. /*
  156470. ** END OF CUSTOM TOKENIZERS
  156471. *************************************************************************/
  156472. /*************************************************************************
  156473. ** FTS5 EXTENSION REGISTRATION API
  156474. */
  156475. typedef struct fts5_api fts5_api;
  156476. struct fts5_api {
  156477. int iVersion; /* Currently always set to 2 */
  156478. /* Create a new tokenizer */
  156479. int (*xCreateTokenizer)(
  156480. fts5_api *pApi,
  156481. const char *zName,
  156482. void *pContext,
  156483. fts5_tokenizer *pTokenizer,
  156484. void (*xDestroy)(void*)
  156485. );
  156486. /* Find an existing tokenizer */
  156487. int (*xFindTokenizer)(
  156488. fts5_api *pApi,
  156489. const char *zName,
  156490. void **ppContext,
  156491. fts5_tokenizer *pTokenizer
  156492. );
  156493. /* Create a new auxiliary function */
  156494. int (*xCreateFunction)(
  156495. fts5_api *pApi,
  156496. const char *zName,
  156497. void *pContext,
  156498. fts5_extension_function xFunction,
  156499. void (*xDestroy)(void*)
  156500. );
  156501. };
  156502. /*
  156503. ** END OF REGISTRATION API
  156504. *************************************************************************/
  156505. #if 0
  156506. } /* end of the 'extern "C"' block */
  156507. #endif
  156508. #endif /* _FTS5_H */
  156509. /*
  156510. ** 2014 May 31
  156511. **
  156512. ** The author disclaims copyright to this source code. In place of
  156513. ** a legal notice, here is a blessing:
  156514. **
  156515. ** May you do good and not evil.
  156516. ** May you find forgiveness for yourself and forgive others.
  156517. ** May you share freely, never taking more than you give.
  156518. **
  156519. ******************************************************************************
  156520. **
  156521. */
  156522. #ifndef _FTS5INT_H
  156523. #define _FTS5INT_H
  156524. /* #include "fts5.h" */
  156525. /* #include "sqlite3ext.h" */
  156526. SQLITE_EXTENSION_INIT1
  156527. /* #include <string.h> */
  156528. /* #include <assert.h> */
  156529. #ifndef SQLITE_AMALGAMATION
  156530. typedef unsigned char u8;
  156531. typedef unsigned int u32;
  156532. typedef unsigned short u16;
  156533. typedef sqlite3_int64 i64;
  156534. typedef sqlite3_uint64 u64;
  156535. #define ArraySize(x) (sizeof(x) / sizeof(x[0]))
  156536. #define testcase(x)
  156537. #define ALWAYS(x) 1
  156538. #define NEVER(x) 0
  156539. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  156540. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  156541. /*
  156542. ** Constants for the largest and smallest possible 64-bit signed integers.
  156543. */
  156544. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  156545. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  156546. #endif
  156547. /*
  156548. ** Maximum number of prefix indexes on single FTS5 table. This must be
  156549. ** less than 32. If it is set to anything large than that, an #error
  156550. ** directive in fts5_index.c will cause the build to fail.
  156551. */
  156552. #define FTS5_MAX_PREFIX_INDEXES 31
  156553. #define FTS5_DEFAULT_NEARDIST 10
  156554. #define FTS5_DEFAULT_RANK "bm25"
  156555. /* Name of rank and rowid columns */
  156556. #define FTS5_RANK_NAME "rank"
  156557. #define FTS5_ROWID_NAME "rowid"
  156558. #ifdef SQLITE_DEBUG
  156559. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  156560. static int sqlite3Fts5Corrupt(void);
  156561. #else
  156562. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  156563. #endif
  156564. /*
  156565. ** The assert_nc() macro is similar to the assert() macro, except that it
  156566. ** is used for assert() conditions that are true only if it can be
  156567. ** guranteed that the database is not corrupt.
  156568. */
  156569. #ifdef SQLITE_DEBUG
  156570. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  156571. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  156572. #else
  156573. # define assert_nc(x) assert(x)
  156574. #endif
  156575. typedef struct Fts5Global Fts5Global;
  156576. typedef struct Fts5Colset Fts5Colset;
  156577. /* If a NEAR() clump or phrase may only match a specific set of columns,
  156578. ** then an object of the following type is used to record the set of columns.
  156579. ** Each entry in the aiCol[] array is a column that may be matched.
  156580. **
  156581. ** This object is used by fts5_expr.c and fts5_index.c.
  156582. */
  156583. struct Fts5Colset {
  156584. int nCol;
  156585. int aiCol[1];
  156586. };
  156587. /**************************************************************************
  156588. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  156589. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  156590. */
  156591. typedef struct Fts5Config Fts5Config;
  156592. /*
  156593. ** An instance of the following structure encodes all information that can
  156594. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  156595. **
  156596. ** And all information loaded from the %_config table.
  156597. **
  156598. ** nAutomerge:
  156599. ** The minimum number of segments that an auto-merge operation should
  156600. ** attempt to merge together. A value of 1 sets the object to use the
  156601. ** compile time default. Zero disables auto-merge altogether.
  156602. **
  156603. ** zContent:
  156604. **
  156605. ** zContentRowid:
  156606. ** The value of the content_rowid= option, if one was specified. Or
  156607. ** the string "rowid" otherwise. This text is not quoted - if it is
  156608. ** used as part of an SQL statement it needs to be quoted appropriately.
  156609. **
  156610. ** zContentExprlist:
  156611. **
  156612. ** pzErrmsg:
  156613. ** This exists in order to allow the fts5_index.c module to return a
  156614. ** decent error message if it encounters a file-format version it does
  156615. ** not understand.
  156616. **
  156617. ** bColumnsize:
  156618. ** True if the %_docsize table is created.
  156619. **
  156620. ** bPrefixIndex:
  156621. ** This is only used for debugging. If set to false, any prefix indexes
  156622. ** are ignored. This value is configured using:
  156623. **
  156624. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  156625. **
  156626. */
  156627. struct Fts5Config {
  156628. sqlite3 *db; /* Database handle */
  156629. char *zDb; /* Database holding FTS index (e.g. "main") */
  156630. char *zName; /* Name of FTS index */
  156631. int nCol; /* Number of columns */
  156632. char **azCol; /* Column names */
  156633. u8 *abUnindexed; /* True for unindexed columns */
  156634. int nPrefix; /* Number of prefix indexes */
  156635. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  156636. int eContent; /* An FTS5_CONTENT value */
  156637. char *zContent; /* content table */
  156638. char *zContentRowid; /* "content_rowid=" option value */
  156639. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  156640. char *zContentExprlist;
  156641. Fts5Tokenizer *pTok;
  156642. fts5_tokenizer *pTokApi;
  156643. /* Values loaded from the %_config table */
  156644. int iCookie; /* Incremented when %_config is modified */
  156645. int pgsz; /* Approximate page size used in %_data */
  156646. int nAutomerge; /* 'automerge' setting */
  156647. int nCrisisMerge; /* Maximum allowed segments per level */
  156648. int nHashSize; /* Bytes of memory for in-memory hash */
  156649. char *zRank; /* Name of rank function */
  156650. char *zRankArgs; /* Arguments to rank function */
  156651. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  156652. char **pzErrmsg;
  156653. #ifdef SQLITE_DEBUG
  156654. int bPrefixIndex; /* True to use prefix-indexes */
  156655. #endif
  156656. };
  156657. /* Current expected value of %_config table 'version' field */
  156658. #define FTS5_CURRENT_VERSION 4
  156659. #define FTS5_CONTENT_NORMAL 0
  156660. #define FTS5_CONTENT_NONE 1
  156661. #define FTS5_CONTENT_EXTERNAL 2
  156662. static int sqlite3Fts5ConfigParse(
  156663. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  156664. );
  156665. static void sqlite3Fts5ConfigFree(Fts5Config*);
  156666. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  156667. static int sqlite3Fts5Tokenize(
  156668. Fts5Config *pConfig, /* FTS5 Configuration object */
  156669. int flags, /* FTS5_TOKENIZE_* flags */
  156670. const char *pText, int nText, /* Text to tokenize */
  156671. void *pCtx, /* Context passed to xToken() */
  156672. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  156673. );
  156674. static void sqlite3Fts5Dequote(char *z);
  156675. /* Load the contents of the %_config table */
  156676. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  156677. /* Set the value of a single config attribute */
  156678. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  156679. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  156680. /*
  156681. ** End of interface to code in fts5_config.c.
  156682. **************************************************************************/
  156683. /**************************************************************************
  156684. ** Interface to code in fts5_buffer.c.
  156685. */
  156686. /*
  156687. ** Buffer object for the incremental building of string data.
  156688. */
  156689. typedef struct Fts5Buffer Fts5Buffer;
  156690. struct Fts5Buffer {
  156691. u8 *p;
  156692. int n;
  156693. int nSpace;
  156694. };
  156695. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, int);
  156696. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  156697. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, int, const u8*);
  156698. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  156699. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  156700. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  156701. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  156702. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  156703. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  156704. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  156705. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  156706. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  156707. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  156708. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  156709. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  156710. (pBuf)->n + (nn) <= (pBuf)->nSpace ? 0 : \
  156711. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  156712. )
  156713. /* Write and decode big-endian 32-bit integer values */
  156714. static void sqlite3Fts5Put32(u8*, int);
  156715. static int sqlite3Fts5Get32(const u8*);
  156716. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  156717. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  156718. typedef struct Fts5PoslistReader Fts5PoslistReader;
  156719. struct Fts5PoslistReader {
  156720. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  156721. const u8 *a; /* Position list to iterate through */
  156722. int n; /* Size of buffer at a[] in bytes */
  156723. int i; /* Current offset in a[] */
  156724. u8 bFlag; /* For client use (any custom purpose) */
  156725. /* Output variables */
  156726. u8 bEof; /* Set to true at EOF */
  156727. i64 iPos; /* (iCol<<32) + iPos */
  156728. };
  156729. static int sqlite3Fts5PoslistReaderInit(
  156730. const u8 *a, int n, /* Poslist buffer to iterate through */
  156731. Fts5PoslistReader *pIter /* Iterator object to initialize */
  156732. );
  156733. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  156734. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  156735. struct Fts5PoslistWriter {
  156736. i64 iPrev;
  156737. };
  156738. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  156739. static int sqlite3Fts5PoslistNext64(
  156740. const u8 *a, int n, /* Buffer containing poslist */
  156741. int *pi, /* IN/OUT: Offset within a[] */
  156742. i64 *piOff /* IN/OUT: Current offset */
  156743. );
  156744. /* Malloc utility */
  156745. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  156746. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  156747. /* Character set tests (like isspace(), isalpha() etc.) */
  156748. static int sqlite3Fts5IsBareword(char t);
  156749. /*
  156750. ** End of interface to code in fts5_buffer.c.
  156751. **************************************************************************/
  156752. /**************************************************************************
  156753. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  156754. ** to access the data stored in the %_data table.
  156755. */
  156756. typedef struct Fts5Index Fts5Index;
  156757. typedef struct Fts5IndexIter Fts5IndexIter;
  156758. /*
  156759. ** Values used as part of the flags argument passed to IndexQuery().
  156760. */
  156761. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  156762. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  156763. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  156764. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  156765. /*
  156766. ** Create/destroy an Fts5Index object.
  156767. */
  156768. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  156769. static int sqlite3Fts5IndexClose(Fts5Index *p);
  156770. /*
  156771. ** for(
  156772. ** sqlite3Fts5IndexQuery(p, "token", 5, 0, 0, &pIter);
  156773. ** 0==sqlite3Fts5IterEof(pIter);
  156774. ** sqlite3Fts5IterNext(pIter)
  156775. ** ){
  156776. ** i64 iRowid = sqlite3Fts5IterRowid(pIter);
  156777. ** }
  156778. */
  156779. /*
  156780. ** Open a new iterator to iterate though all rowids that match the
  156781. ** specified token or token prefix.
  156782. */
  156783. static int sqlite3Fts5IndexQuery(
  156784. Fts5Index *p, /* FTS index to query */
  156785. const char *pToken, int nToken, /* Token (or prefix) to query for */
  156786. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  156787. Fts5Colset *pColset, /* Match these columns only */
  156788. Fts5IndexIter **ppIter /* OUT: New iterator object */
  156789. );
  156790. /*
  156791. ** The various operations on open token or token prefix iterators opened
  156792. ** using sqlite3Fts5IndexQuery().
  156793. */
  156794. static int sqlite3Fts5IterEof(Fts5IndexIter*);
  156795. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  156796. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  156797. static i64 sqlite3Fts5IterRowid(Fts5IndexIter*);
  156798. static int sqlite3Fts5IterPoslist(Fts5IndexIter*,Fts5Colset*, const u8**, int*, i64*);
  156799. static int sqlite3Fts5IterPoslistBuffer(Fts5IndexIter *pIter, Fts5Buffer *pBuf);
  156800. /*
  156801. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  156802. */
  156803. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  156804. /*
  156805. ** This interface is used by the fts5vocab module.
  156806. */
  156807. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  156808. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  156809. /*
  156810. ** Insert or remove data to or from the index. Each time a document is
  156811. ** added to or removed from the index, this function is called one or more
  156812. ** times.
  156813. **
  156814. ** For an insert, it must be called once for each token in the new document.
  156815. ** If the operation is a delete, it must be called (at least) once for each
  156816. ** unique token in the document with an iCol value less than zero. The iPos
  156817. ** argument is ignored for a delete.
  156818. */
  156819. static int sqlite3Fts5IndexWrite(
  156820. Fts5Index *p, /* Index to write to */
  156821. int iCol, /* Column token appears in (-ve -> delete) */
  156822. int iPos, /* Position of token within column */
  156823. const char *pToken, int nToken /* Token to add or remove to or from index */
  156824. );
  156825. /*
  156826. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  156827. ** document iDocid.
  156828. */
  156829. static int sqlite3Fts5IndexBeginWrite(
  156830. Fts5Index *p, /* Index to write to */
  156831. int bDelete, /* True if current operation is a delete */
  156832. i64 iDocid /* Docid to add or remove data from */
  156833. );
  156834. /*
  156835. ** Flush any data stored in the in-memory hash tables to the database.
  156836. ** If the bCommit flag is true, also close any open blob handles.
  156837. */
  156838. static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
  156839. /*
  156840. ** Discard any data stored in the in-memory hash tables. Do not write it
  156841. ** to the database. Additionally, assume that the contents of the %_data
  156842. ** table may have changed on disk. So any in-memory caches of %_data
  156843. ** records must be invalidated.
  156844. */
  156845. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  156846. /*
  156847. ** Get or set the "averages" values.
  156848. */
  156849. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  156850. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  156851. /*
  156852. ** Functions called by the storage module as part of integrity-check.
  156853. */
  156854. static u64 sqlite3Fts5IndexCksum(Fts5Config*,i64,int,int,const char*,int);
  156855. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  156856. /*
  156857. ** Called during virtual module initialization to register UDF
  156858. ** fts5_decode() with SQLite
  156859. */
  156860. static int sqlite3Fts5IndexInit(sqlite3*);
  156861. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  156862. /*
  156863. ** Return the total number of entries read from the %_data table by
  156864. ** this connection since it was created.
  156865. */
  156866. static int sqlite3Fts5IndexReads(Fts5Index *p);
  156867. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  156868. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  156869. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  156870. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  156871. /*
  156872. ** End of interface to code in fts5_index.c.
  156873. **************************************************************************/
  156874. /**************************************************************************
  156875. ** Interface to code in fts5_varint.c.
  156876. */
  156877. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  156878. static int sqlite3Fts5GetVarintLen(u32 iVal);
  156879. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  156880. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  156881. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  156882. #define fts5GetVarint sqlite3Fts5GetVarint
  156883. #define fts5FastGetVarint32(a, iOff, nVal) { \
  156884. nVal = (a)[iOff++]; \
  156885. if( nVal & 0x80 ){ \
  156886. iOff--; \
  156887. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  156888. } \
  156889. }
  156890. /*
  156891. ** End of interface to code in fts5_varint.c.
  156892. **************************************************************************/
  156893. /**************************************************************************
  156894. ** Interface to code in fts5.c.
  156895. */
  156896. static int sqlite3Fts5GetTokenizer(
  156897. Fts5Global*,
  156898. const char **azArg,
  156899. int nArg,
  156900. Fts5Tokenizer**,
  156901. fts5_tokenizer**,
  156902. char **pzErr
  156903. );
  156904. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
  156905. /*
  156906. ** End of interface to code in fts5.c.
  156907. **************************************************************************/
  156908. /**************************************************************************
  156909. ** Interface to code in fts5_hash.c.
  156910. */
  156911. typedef struct Fts5Hash Fts5Hash;
  156912. /*
  156913. ** Create a hash table, free a hash table.
  156914. */
  156915. static int sqlite3Fts5HashNew(Fts5Hash**, int *pnSize);
  156916. static void sqlite3Fts5HashFree(Fts5Hash*);
  156917. static int sqlite3Fts5HashWrite(
  156918. Fts5Hash*,
  156919. i64 iRowid, /* Rowid for this entry */
  156920. int iCol, /* Column token appears in (-ve -> delete) */
  156921. int iPos, /* Position of token within column */
  156922. char bByte,
  156923. const char *pToken, int nToken /* Token to add or remove to or from index */
  156924. );
  156925. /*
  156926. ** Empty (but do not delete) a hash table.
  156927. */
  156928. static void sqlite3Fts5HashClear(Fts5Hash*);
  156929. static int sqlite3Fts5HashQuery(
  156930. Fts5Hash*, /* Hash table to query */
  156931. const char *pTerm, int nTerm, /* Query term */
  156932. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  156933. int *pnDoclist /* OUT: Size of doclist in bytes */
  156934. );
  156935. static int sqlite3Fts5HashScanInit(
  156936. Fts5Hash*, /* Hash table to query */
  156937. const char *pTerm, int nTerm /* Query prefix */
  156938. );
  156939. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  156940. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  156941. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  156942. const char **pzTerm, /* OUT: term (nul-terminated) */
  156943. const u8 **ppDoclist, /* OUT: pointer to doclist */
  156944. int *pnDoclist /* OUT: size of doclist in bytes */
  156945. );
  156946. /*
  156947. ** End of interface to code in fts5_hash.c.
  156948. **************************************************************************/
  156949. /**************************************************************************
  156950. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  156951. ** code to access the data stored in the %_content and %_docsize tables.
  156952. */
  156953. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  156954. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  156955. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  156956. typedef struct Fts5Storage Fts5Storage;
  156957. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  156958. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  156959. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  156960. static int sqlite3Fts5DropAll(Fts5Config*);
  156961. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  156962. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64);
  156963. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  156964. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  156965. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  156966. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  156967. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  156968. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  156969. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  156970. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  156971. static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
  156972. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  156973. static int sqlite3Fts5StorageConfigValue(
  156974. Fts5Storage *p, const char*, sqlite3_value*, int
  156975. );
  156976. static int sqlite3Fts5StorageSpecialDelete(Fts5Storage *p, i64 iDel, sqlite3_value**);
  156977. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  156978. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  156979. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  156980. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  156981. /*
  156982. ** End of interface to code in fts5_storage.c.
  156983. **************************************************************************/
  156984. /**************************************************************************
  156985. ** Interface to code in fts5_expr.c.
  156986. */
  156987. typedef struct Fts5Expr Fts5Expr;
  156988. typedef struct Fts5ExprNode Fts5ExprNode;
  156989. typedef struct Fts5Parse Fts5Parse;
  156990. typedef struct Fts5Token Fts5Token;
  156991. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  156992. typedef struct Fts5ExprNearset Fts5ExprNearset;
  156993. struct Fts5Token {
  156994. const char *p; /* Token text (not NULL terminated) */
  156995. int n; /* Size of buffer p in bytes */
  156996. };
  156997. /* Parse a MATCH expression. */
  156998. static int sqlite3Fts5ExprNew(
  156999. Fts5Config *pConfig,
  157000. const char *zExpr,
  157001. Fts5Expr **ppNew,
  157002. char **pzErr
  157003. );
  157004. /*
  157005. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  157006. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  157007. ** rc = sqlite3Fts5ExprNext(pExpr)
  157008. ** ){
  157009. ** // The document with rowid iRowid matches the expression!
  157010. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  157011. ** }
  157012. */
  157013. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  157014. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  157015. static int sqlite3Fts5ExprEof(Fts5Expr*);
  157016. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  157017. static void sqlite3Fts5ExprFree(Fts5Expr*);
  157018. /* Called during startup to register a UDF with SQLite */
  157019. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  157020. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  157021. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  157022. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  157023. static int sqlite3Fts5ExprClonePhrase(Fts5Config*, Fts5Expr*, int, Fts5Expr**);
  157024. /*******************************************
  157025. ** The fts5_expr.c API above this point is used by the other hand-written
  157026. ** C code in this module. The interfaces below this point are called by
  157027. ** the parser code in fts5parse.y. */
  157028. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  157029. static Fts5ExprNode *sqlite3Fts5ParseNode(
  157030. Fts5Parse *pParse,
  157031. int eType,
  157032. Fts5ExprNode *pLeft,
  157033. Fts5ExprNode *pRight,
  157034. Fts5ExprNearset *pNear
  157035. );
  157036. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  157037. Fts5Parse *pParse,
  157038. Fts5ExprPhrase *pPhrase,
  157039. Fts5Token *pToken,
  157040. int bPrefix
  157041. );
  157042. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  157043. Fts5Parse*,
  157044. Fts5ExprNearset*,
  157045. Fts5ExprPhrase*
  157046. );
  157047. static Fts5Colset *sqlite3Fts5ParseColset(
  157048. Fts5Parse*,
  157049. Fts5Colset*,
  157050. Fts5Token *
  157051. );
  157052. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  157053. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  157054. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  157055. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  157056. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
  157057. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  157058. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  157059. /*
  157060. ** End of interface to code in fts5_expr.c.
  157061. **************************************************************************/
  157062. /**************************************************************************
  157063. ** Interface to code in fts5_aux.c.
  157064. */
  157065. static int sqlite3Fts5AuxInit(fts5_api*);
  157066. /*
  157067. ** End of interface to code in fts5_aux.c.
  157068. **************************************************************************/
  157069. /**************************************************************************
  157070. ** Interface to code in fts5_tokenizer.c.
  157071. */
  157072. static int sqlite3Fts5TokenizerInit(fts5_api*);
  157073. /*
  157074. ** End of interface to code in fts5_tokenizer.c.
  157075. **************************************************************************/
  157076. /**************************************************************************
  157077. ** Interface to code in fts5_vocab.c.
  157078. */
  157079. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  157080. /*
  157081. ** End of interface to code in fts5_vocab.c.
  157082. **************************************************************************/
  157083. /**************************************************************************
  157084. ** Interface to automatically generated code in fts5_unicode2.c.
  157085. */
  157086. static int sqlite3Fts5UnicodeIsalnum(int c);
  157087. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  157088. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  157089. /*
  157090. ** End of interface to code in fts5_unicode2.c.
  157091. **************************************************************************/
  157092. #endif
  157093. #define FTS5_OR 1
  157094. #define FTS5_AND 2
  157095. #define FTS5_NOT 3
  157096. #define FTS5_TERM 4
  157097. #define FTS5_COLON 5
  157098. #define FTS5_LP 6
  157099. #define FTS5_RP 7
  157100. #define FTS5_LCP 8
  157101. #define FTS5_RCP 9
  157102. #define FTS5_STRING 10
  157103. #define FTS5_COMMA 11
  157104. #define FTS5_PLUS 12
  157105. #define FTS5_STAR 13
  157106. /*
  157107. ** 2000-05-29
  157108. **
  157109. ** The author disclaims copyright to this source code. In place of
  157110. ** a legal notice, here is a blessing:
  157111. **
  157112. ** May you do good and not evil.
  157113. ** May you find forgiveness for yourself and forgive others.
  157114. ** May you share freely, never taking more than you give.
  157115. **
  157116. *************************************************************************
  157117. ** Driver template for the LEMON parser generator.
  157118. **
  157119. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  157120. ** this template to construct a parser. The "lemon" program inserts text
  157121. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  157122. ** interstitial "-" characters) contained in this template is changed into
  157123. ** the value of the %name directive from the grammar. Otherwise, the content
  157124. ** of this template is copied straight through into the generate parser
  157125. ** source file.
  157126. **
  157127. ** The following is the concatenation of all %include directives from the
  157128. ** input grammar file:
  157129. */
  157130. /* #include <stdio.h> */
  157131. /************ Begin %include sections from the grammar ************************/
  157132. /* #include "fts5Int.h" */
  157133. /* #include "fts5parse.h" */
  157134. /*
  157135. ** Disable all error recovery processing in the parser push-down
  157136. ** automaton.
  157137. */
  157138. #define fts5YYNOERRORRECOVERY 1
  157139. /*
  157140. ** Make fts5yytestcase() the same as testcase()
  157141. */
  157142. #define fts5yytestcase(X) testcase(X)
  157143. /*
  157144. ** Indicate that sqlite3ParserFree() will never be called with a null
  157145. ** pointer.
  157146. */
  157147. #define fts5YYPARSEFREENOTNULL 1
  157148. /*
  157149. ** Alternative datatype for the argument to the malloc() routine passed
  157150. ** into sqlite3ParserAlloc(). The default is size_t.
  157151. */
  157152. #define fts5YYMALLOCARGTYPE u64
  157153. /**************** End of %include directives **********************************/
  157154. /* These constants specify the various numeric values for terminal symbols
  157155. ** in a format understandable to "makeheaders". This section is blank unless
  157156. ** "lemon" is run with the "-m" command-line option.
  157157. ***************** Begin makeheaders token definitions *************************/
  157158. /**************** End makeheaders token definitions ***************************/
  157159. /* The next sections is a series of control #defines.
  157160. ** various aspects of the generated parser.
  157161. ** fts5YYCODETYPE is the data type used to store the integer codes
  157162. ** that represent terminal and non-terminal symbols.
  157163. ** "unsigned char" is used if there are fewer than
  157164. ** 256 symbols. Larger types otherwise.
  157165. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  157166. ** any terminal or nonterminal symbol.
  157167. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  157168. ** (also known as: "terminal symbols") have fall-back
  157169. ** values which should be used if the original symbol
  157170. ** would not parse. This permits keywords to sometimes
  157171. ** be used as identifiers, for example.
  157172. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  157173. ** that indicate what to do in response to the next
  157174. ** token.
  157175. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  157176. ** symbols. Background: A "minor type" is a semantic
  157177. ** value associated with a terminal or non-terminal
  157178. ** symbols. For example, for an "ID" terminal symbol,
  157179. ** the minor type might be the name of the identifier.
  157180. ** Each non-terminal can have a different minor type.
  157181. ** Terminal symbols all have the same minor type, though.
  157182. ** This macros defines the minor type for terminal
  157183. ** symbols.
  157184. ** fts5YYMINORTYPE is the data type used for all minor types.
  157185. ** This is typically a union of many types, one of
  157186. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  157187. ** for terminal symbols is called "fts5yy0".
  157188. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  157189. ** zero the stack is dynamically sized using realloc()
  157190. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  157191. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  157192. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  157193. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  157194. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  157195. ** defined, then do no error processing.
  157196. ** fts5YYNSTATE the combined number of states.
  157197. ** fts5YYNRULE the number of rules in the grammar
  157198. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  157199. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  157200. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  157201. ** fts5YY_MIN_REDUCE Maximum value for reduce actions
  157202. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  157203. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  157204. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  157205. */
  157206. #ifndef INTERFACE
  157207. # define INTERFACE 1
  157208. #endif
  157209. /************* Begin control #defines *****************************************/
  157210. #define fts5YYCODETYPE unsigned char
  157211. #define fts5YYNOCODE 27
  157212. #define fts5YYACTIONTYPE unsigned char
  157213. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  157214. typedef union {
  157215. int fts5yyinit;
  157216. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  157217. Fts5Colset* fts5yy3;
  157218. Fts5ExprPhrase* fts5yy11;
  157219. Fts5ExprNode* fts5yy18;
  157220. int fts5yy20;
  157221. Fts5ExprNearset* fts5yy26;
  157222. } fts5YYMINORTYPE;
  157223. #ifndef fts5YYSTACKDEPTH
  157224. #define fts5YYSTACKDEPTH 100
  157225. #endif
  157226. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  157227. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  157228. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
  157229. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
  157230. #define fts5YYNSTATE 26
  157231. #define fts5YYNRULE 24
  157232. #define fts5YY_MAX_SHIFT 25
  157233. #define fts5YY_MIN_SHIFTREDUCE 40
  157234. #define fts5YY_MAX_SHIFTREDUCE 63
  157235. #define fts5YY_MIN_REDUCE 64
  157236. #define fts5YY_MAX_REDUCE 87
  157237. #define fts5YY_ERROR_ACTION 88
  157238. #define fts5YY_ACCEPT_ACTION 89
  157239. #define fts5YY_NO_ACTION 90
  157240. /************* End control #defines *******************************************/
  157241. /* The fts5yyzerominor constant is used to initialize instances of
  157242. ** fts5YYMINORTYPE objects to zero. */
  157243. static const fts5YYMINORTYPE fts5yyzerominor = { 0 };
  157244. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  157245. ** otherwise.
  157246. **
  157247. ** Applications can choose to define fts5yytestcase() in the %include section
  157248. ** to a macro that can assist in verifying code coverage. For production
  157249. ** code the fts5yytestcase() macro should be turned off. But it is useful
  157250. ** for testing.
  157251. */
  157252. #ifndef fts5yytestcase
  157253. # define fts5yytestcase(X)
  157254. #endif
  157255. /* Next are the tables used to determine what action to take based on the
  157256. ** current state and lookahead token. These tables are used to implement
  157257. ** functions that take a state number and lookahead value and return an
  157258. ** action integer.
  157259. **
  157260. ** Suppose the action integer is N. Then the action is determined as
  157261. ** follows
  157262. **
  157263. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  157264. ** token onto the stack and goto state N.
  157265. **
  157266. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  157267. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  157268. **
  157269. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  157270. ** and fts5YY_MAX_REDUCE
  157271. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  157272. **
  157273. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  157274. **
  157275. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  157276. ** slots in the fts5yy_action[] table.
  157277. **
  157278. ** The action table is constructed as a single large table named fts5yy_action[].
  157279. ** Given state S and lookahead X, the action is computed as
  157280. **
  157281. ** fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  157282. **
  157283. ** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
  157284. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
  157285. ** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
  157286. ** and that fts5yy_default[S] should be used instead.
  157287. **
  157288. ** The formula above is for computing the action when the lookahead is
  157289. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  157290. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  157291. ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
  157292. ** fts5YY_SHIFT_USE_DFLT.
  157293. **
  157294. ** The following are the tables generated in this section:
  157295. **
  157296. ** fts5yy_action[] A single table containing all actions.
  157297. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  157298. ** fts5yy_action. Used to detect hash collisions.
  157299. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  157300. ** shifting terminals.
  157301. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  157302. ** shifting non-terminals after a reduce.
  157303. ** fts5yy_default[] Default action for each state.
  157304. **
  157305. *********** Begin parsing tables **********************************************/
  157306. #define fts5YY_ACTTAB_COUNT (78)
  157307. static const fts5YYACTIONTYPE fts5yy_action[] = {
  157308. /* 0 */ 89, 15, 46, 5, 48, 24, 12, 19, 23, 14,
  157309. /* 10 */ 46, 5, 48, 24, 20, 21, 23, 43, 46, 5,
  157310. /* 20 */ 48, 24, 6, 18, 23, 17, 46, 5, 48, 24,
  157311. /* 30 */ 75, 7, 23, 25, 46, 5, 48, 24, 62, 47,
  157312. /* 40 */ 23, 48, 24, 7, 11, 23, 9, 3, 4, 2,
  157313. /* 50 */ 62, 50, 52, 44, 64, 3, 4, 2, 49, 4,
  157314. /* 60 */ 2, 1, 23, 11, 16, 9, 12, 2, 10, 61,
  157315. /* 70 */ 53, 59, 62, 60, 22, 13, 55, 8,
  157316. };
  157317. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  157318. /* 0 */ 15, 16, 17, 18, 19, 20, 10, 11, 23, 16,
  157319. /* 10 */ 17, 18, 19, 20, 23, 24, 23, 16, 17, 18,
  157320. /* 20 */ 19, 20, 22, 23, 23, 16, 17, 18, 19, 20,
  157321. /* 30 */ 5, 6, 23, 16, 17, 18, 19, 20, 13, 17,
  157322. /* 40 */ 23, 19, 20, 6, 8, 23, 10, 1, 2, 3,
  157323. /* 50 */ 13, 9, 10, 7, 0, 1, 2, 3, 19, 2,
  157324. /* 60 */ 3, 6, 23, 8, 21, 10, 10, 3, 10, 25,
  157325. /* 70 */ 10, 10, 13, 25, 12, 10, 7, 5,
  157326. };
  157327. #define fts5YY_SHIFT_USE_DFLT (-5)
  157328. #define fts5YY_SHIFT_COUNT (25)
  157329. #define fts5YY_SHIFT_MIN (-4)
  157330. #define fts5YY_SHIFT_MAX (72)
  157331. static const signed char fts5yy_shift_ofst[] = {
  157332. /* 0 */ 55, 55, 55, 55, 55, 36, -4, 56, 58, 25,
  157333. /* 10 */ 37, 60, 59, 59, 46, 54, 42, 57, 62, 61,
  157334. /* 20 */ 62, 69, 65, 62, 72, 64,
  157335. };
  157336. #define fts5YY_REDUCE_USE_DFLT (-16)
  157337. #define fts5YY_REDUCE_COUNT (13)
  157338. #define fts5YY_REDUCE_MIN (-15)
  157339. #define fts5YY_REDUCE_MAX (48)
  157340. static const signed char fts5yy_reduce_ofst[] = {
  157341. /* 0 */ -15, -7, 1, 9, 17, 22, -9, 0, 39, 44,
  157342. /* 10 */ 44, 43, 44, 48,
  157343. };
  157344. static const fts5YYACTIONTYPE fts5yy_default[] = {
  157345. /* 0 */ 88, 88, 88, 88, 88, 69, 82, 88, 88, 87,
  157346. /* 10 */ 87, 88, 87, 87, 88, 88, 88, 66, 80, 88,
  157347. /* 20 */ 81, 88, 88, 78, 88, 65,
  157348. };
  157349. /********** End of lemon-generated parsing tables *****************************/
  157350. /* The next table maps tokens (terminal symbols) into fallback tokens.
  157351. ** If a construct like the following:
  157352. **
  157353. ** %fallback ID X Y Z.
  157354. **
  157355. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  157356. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  157357. ** but it does not parse, the type of the token is changed to ID and
  157358. ** the parse is retried before an error is thrown.
  157359. **
  157360. ** This feature can be used, for example, to cause some keywords in a language
  157361. ** to revert to identifiers if they keyword does not apply in the context where
  157362. ** it appears.
  157363. */
  157364. #ifdef fts5YYFALLBACK
  157365. static const fts5YYCODETYPE fts5yyFallback[] = {
  157366. };
  157367. #endif /* fts5YYFALLBACK */
  157368. /* The following structure represents a single element of the
  157369. ** parser's stack. Information stored includes:
  157370. **
  157371. ** + The state number for the parser at this level of the stack.
  157372. **
  157373. ** + The value of the token stored at this level of the stack.
  157374. ** (In other words, the "major" token.)
  157375. **
  157376. ** + The semantic value stored at this level of the stack. This is
  157377. ** the information used by the action routines in the grammar.
  157378. ** It is sometimes called the "minor" token.
  157379. **
  157380. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  157381. ** actually contains the reduce action for the second half of the
  157382. ** SHIFTREDUCE.
  157383. */
  157384. struct fts5yyStackEntry {
  157385. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  157386. fts5YYCODETYPE major; /* The major token value. This is the code
  157387. ** number for the token at this stack level */
  157388. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  157389. ** is the value of the token */
  157390. };
  157391. typedef struct fts5yyStackEntry fts5yyStackEntry;
  157392. /* The state of the parser is completely contained in an instance of
  157393. ** the following structure */
  157394. struct fts5yyParser {
  157395. int fts5yyidx; /* Index of top element in stack */
  157396. #ifdef fts5YYTRACKMAXSTACKDEPTH
  157397. int fts5yyidxMax; /* Maximum value of fts5yyidx */
  157398. #endif
  157399. int fts5yyerrcnt; /* Shifts left before out of the error */
  157400. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  157401. #if fts5YYSTACKDEPTH<=0
  157402. int fts5yystksz; /* Current side of the stack */
  157403. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  157404. #else
  157405. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  157406. #endif
  157407. };
  157408. typedef struct fts5yyParser fts5yyParser;
  157409. #ifndef NDEBUG
  157410. /* #include <stdio.h> */
  157411. static FILE *fts5yyTraceFILE = 0;
  157412. static char *fts5yyTracePrompt = 0;
  157413. #endif /* NDEBUG */
  157414. #ifndef NDEBUG
  157415. /*
  157416. ** Turn parser tracing on by giving a stream to which to write the trace
  157417. ** and a prompt to preface each trace message. Tracing is turned off
  157418. ** by making either argument NULL
  157419. **
  157420. ** Inputs:
  157421. ** <ul>
  157422. ** <li> A FILE* to which trace output should be written.
  157423. ** If NULL, then tracing is turned off.
  157424. ** <li> A prefix string written at the beginning of every
  157425. ** line of trace output. If NULL, then tracing is
  157426. ** turned off.
  157427. ** </ul>
  157428. **
  157429. ** Outputs:
  157430. ** None.
  157431. */
  157432. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  157433. fts5yyTraceFILE = TraceFILE;
  157434. fts5yyTracePrompt = zTracePrompt;
  157435. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  157436. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  157437. }
  157438. #endif /* NDEBUG */
  157439. #ifndef NDEBUG
  157440. /* For tracing shifts, the names of all terminals and nonterminals
  157441. ** are required. The following table supplies these names */
  157442. static const char *const fts5yyTokenName[] = {
  157443. "$", "OR", "AND", "NOT",
  157444. "TERM", "COLON", "LP", "RP",
  157445. "LCP", "RCP", "STRING", "COMMA",
  157446. "PLUS", "STAR", "error", "input",
  157447. "expr", "cnearset", "exprlist", "nearset",
  157448. "colset", "colsetlist", "nearphrases", "phrase",
  157449. "neardist_opt", "star_opt",
  157450. };
  157451. #endif /* NDEBUG */
  157452. #ifndef NDEBUG
  157453. /* For tracing reduce actions, the names of all rules are required.
  157454. */
  157455. static const char *const fts5yyRuleName[] = {
  157456. /* 0 */ "input ::= expr",
  157457. /* 1 */ "expr ::= expr AND expr",
  157458. /* 2 */ "expr ::= expr OR expr",
  157459. /* 3 */ "expr ::= expr NOT expr",
  157460. /* 4 */ "expr ::= LP expr RP",
  157461. /* 5 */ "expr ::= exprlist",
  157462. /* 6 */ "exprlist ::= cnearset",
  157463. /* 7 */ "exprlist ::= exprlist cnearset",
  157464. /* 8 */ "cnearset ::= nearset",
  157465. /* 9 */ "cnearset ::= colset COLON nearset",
  157466. /* 10 */ "colset ::= LCP colsetlist RCP",
  157467. /* 11 */ "colset ::= STRING",
  157468. /* 12 */ "colsetlist ::= colsetlist STRING",
  157469. /* 13 */ "colsetlist ::= STRING",
  157470. /* 14 */ "nearset ::= phrase",
  157471. /* 15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  157472. /* 16 */ "nearphrases ::= phrase",
  157473. /* 17 */ "nearphrases ::= nearphrases phrase",
  157474. /* 18 */ "neardist_opt ::=",
  157475. /* 19 */ "neardist_opt ::= COMMA STRING",
  157476. /* 20 */ "phrase ::= phrase PLUS STRING star_opt",
  157477. /* 21 */ "phrase ::= STRING star_opt",
  157478. /* 22 */ "star_opt ::= STAR",
  157479. /* 23 */ "star_opt ::=",
  157480. };
  157481. #endif /* NDEBUG */
  157482. #if fts5YYSTACKDEPTH<=0
  157483. /*
  157484. ** Try to increase the size of the parser stack.
  157485. */
  157486. static void fts5yyGrowStack(fts5yyParser *p){
  157487. int newSize;
  157488. fts5yyStackEntry *pNew;
  157489. newSize = p->fts5yystksz*2 + 100;
  157490. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  157491. if( pNew ){
  157492. p->fts5yystack = pNew;
  157493. p->fts5yystksz = newSize;
  157494. #ifndef NDEBUG
  157495. if( fts5yyTraceFILE ){
  157496. fprintf(fts5yyTraceFILE,"%sStack grows to %d entries!\n",
  157497. fts5yyTracePrompt, p->fts5yystksz);
  157498. }
  157499. #endif
  157500. }
  157501. }
  157502. #endif
  157503. /* Datatype of the argument to the memory allocated passed as the
  157504. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  157505. ** putting an appropriate #define in the %include section of the input
  157506. ** grammar.
  157507. */
  157508. #ifndef fts5YYMALLOCARGTYPE
  157509. # define fts5YYMALLOCARGTYPE size_t
  157510. #endif
  157511. /*
  157512. ** This function allocates a new parser.
  157513. ** The only argument is a pointer to a function which works like
  157514. ** malloc.
  157515. **
  157516. ** Inputs:
  157517. ** A pointer to the function used to allocate memory.
  157518. **
  157519. ** Outputs:
  157520. ** A pointer to a parser. This pointer is used in subsequent calls
  157521. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  157522. */
  157523. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
  157524. fts5yyParser *pParser;
  157525. pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  157526. if( pParser ){
  157527. pParser->fts5yyidx = -1;
  157528. #ifdef fts5YYTRACKMAXSTACKDEPTH
  157529. pParser->fts5yyidxMax = 0;
  157530. #endif
  157531. #if fts5YYSTACKDEPTH<=0
  157532. pParser->fts5yystack = NULL;
  157533. pParser->fts5yystksz = 0;
  157534. fts5yyGrowStack(pParser);
  157535. #endif
  157536. }
  157537. return pParser;
  157538. }
  157539. /* The following function deletes the "minor type" or semantic value
  157540. ** associated with a symbol. The symbol can be either a terminal
  157541. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  157542. ** a pointer to the value to be deleted. The code used to do the
  157543. ** deletions is derived from the %destructor and/or %token_destructor
  157544. ** directives of the input grammar.
  157545. */
  157546. static void fts5yy_destructor(
  157547. fts5yyParser *fts5yypParser, /* The parser */
  157548. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  157549. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  157550. ){
  157551. sqlite3Fts5ParserARG_FETCH;
  157552. switch( fts5yymajor ){
  157553. /* Here is inserted the actions which take place when a
  157554. ** terminal or non-terminal is destroyed. This can happen
  157555. ** when the symbol is popped from the stack during a
  157556. ** reduce or during error processing or when a parser is
  157557. ** being destroyed before it is finished parsing.
  157558. **
  157559. ** Note: during a reduce, the only symbols destroyed are those
  157560. ** which appear on the RHS of the rule, but which are *not* used
  157561. ** inside the C code.
  157562. */
  157563. /********* Begin destructor definitions ***************************************/
  157564. case 15: /* input */
  157565. {
  157566. (void)pParse;
  157567. }
  157568. break;
  157569. case 16: /* expr */
  157570. case 17: /* cnearset */
  157571. case 18: /* exprlist */
  157572. {
  157573. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18));
  157574. }
  157575. break;
  157576. case 19: /* nearset */
  157577. case 22: /* nearphrases */
  157578. {
  157579. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26));
  157580. }
  157581. break;
  157582. case 20: /* colset */
  157583. case 21: /* colsetlist */
  157584. {
  157585. sqlite3_free((fts5yypminor->fts5yy3));
  157586. }
  157587. break;
  157588. case 23: /* phrase */
  157589. {
  157590. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
  157591. }
  157592. break;
  157593. /********* End destructor definitions *****************************************/
  157594. default: break; /* If no destructor action specified: do nothing */
  157595. }
  157596. }
  157597. /*
  157598. ** Pop the parser's stack once.
  157599. **
  157600. ** If there is a destructor routine associated with the token which
  157601. ** is popped from the stack, then call it.
  157602. */
  157603. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  157604. fts5yyStackEntry *fts5yytos;
  157605. assert( pParser->fts5yyidx>=0 );
  157606. fts5yytos = &pParser->fts5yystack[pParser->fts5yyidx--];
  157607. #ifndef NDEBUG
  157608. if( fts5yyTraceFILE ){
  157609. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  157610. fts5yyTracePrompt,
  157611. fts5yyTokenName[fts5yytos->major]);
  157612. }
  157613. #endif
  157614. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  157615. }
  157616. /*
  157617. ** Deallocate and destroy a parser. Destructors are called for
  157618. ** all stack elements before shutting the parser down.
  157619. **
  157620. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  157621. ** is defined in a %include section of the input grammar) then it is
  157622. ** assumed that the input pointer is never NULL.
  157623. */
  157624. static void sqlite3Fts5ParserFree(
  157625. void *p, /* The parser to be deleted */
  157626. void (*freeProc)(void*) /* Function used to reclaim memory */
  157627. ){
  157628. fts5yyParser *pParser = (fts5yyParser*)p;
  157629. #ifndef fts5YYPARSEFREENEVERNULL
  157630. if( pParser==0 ) return;
  157631. #endif
  157632. while( pParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(pParser);
  157633. #if fts5YYSTACKDEPTH<=0
  157634. free(pParser->fts5yystack);
  157635. #endif
  157636. (*freeProc)((void*)pParser);
  157637. }
  157638. /*
  157639. ** Return the peak depth of the stack for a parser.
  157640. */
  157641. #ifdef fts5YYTRACKMAXSTACKDEPTH
  157642. static int sqlite3Fts5ParserStackPeak(void *p){
  157643. fts5yyParser *pParser = (fts5yyParser*)p;
  157644. return pParser->fts5yyidxMax;
  157645. }
  157646. #endif
  157647. /*
  157648. ** Find the appropriate action for a parser given the terminal
  157649. ** look-ahead token iLookAhead.
  157650. */
  157651. static int fts5yy_find_shift_action(
  157652. fts5yyParser *pParser, /* The parser */
  157653. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  157654. ){
  157655. int i;
  157656. int stateno = pParser->fts5yystack[pParser->fts5yyidx].stateno;
  157657. if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
  157658. assert( stateno <= fts5YY_SHIFT_COUNT );
  157659. do{
  157660. i = fts5yy_shift_ofst[stateno];
  157661. if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
  157662. assert( iLookAhead!=fts5YYNOCODE );
  157663. i += iLookAhead;
  157664. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  157665. if( iLookAhead>0 ){
  157666. #ifdef fts5YYFALLBACK
  157667. fts5YYCODETYPE iFallback; /* Fallback token */
  157668. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  157669. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  157670. #ifndef NDEBUG
  157671. if( fts5yyTraceFILE ){
  157672. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  157673. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  157674. }
  157675. #endif
  157676. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  157677. iLookAhead = iFallback;
  157678. continue;
  157679. }
  157680. #endif
  157681. #ifdef fts5YYWILDCARD
  157682. {
  157683. int j = i - iLookAhead + fts5YYWILDCARD;
  157684. if(
  157685. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  157686. j>=0 &&
  157687. #endif
  157688. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  157689. j<fts5YY_ACTTAB_COUNT &&
  157690. #endif
  157691. fts5yy_lookahead[j]==fts5YYWILDCARD
  157692. ){
  157693. #ifndef NDEBUG
  157694. if( fts5yyTraceFILE ){
  157695. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  157696. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  157697. fts5yyTokenName[fts5YYWILDCARD]);
  157698. }
  157699. #endif /* NDEBUG */
  157700. return fts5yy_action[j];
  157701. }
  157702. }
  157703. #endif /* fts5YYWILDCARD */
  157704. }
  157705. return fts5yy_default[stateno];
  157706. }else{
  157707. return fts5yy_action[i];
  157708. }
  157709. }while(1);
  157710. }
  157711. /*
  157712. ** Find the appropriate action for a parser given the non-terminal
  157713. ** look-ahead token iLookAhead.
  157714. */
  157715. static int fts5yy_find_reduce_action(
  157716. int stateno, /* Current state number */
  157717. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  157718. ){
  157719. int i;
  157720. #ifdef fts5YYERRORSYMBOL
  157721. if( stateno>fts5YY_REDUCE_COUNT ){
  157722. return fts5yy_default[stateno];
  157723. }
  157724. #else
  157725. assert( stateno<=fts5YY_REDUCE_COUNT );
  157726. #endif
  157727. i = fts5yy_reduce_ofst[stateno];
  157728. assert( i!=fts5YY_REDUCE_USE_DFLT );
  157729. assert( iLookAhead!=fts5YYNOCODE );
  157730. i += iLookAhead;
  157731. #ifdef fts5YYERRORSYMBOL
  157732. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  157733. return fts5yy_default[stateno];
  157734. }
  157735. #else
  157736. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  157737. assert( fts5yy_lookahead[i]==iLookAhead );
  157738. #endif
  157739. return fts5yy_action[i];
  157740. }
  157741. /*
  157742. ** The following routine is called if the stack overflows.
  157743. */
  157744. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser, fts5YYMINORTYPE *fts5yypMinor){
  157745. sqlite3Fts5ParserARG_FETCH;
  157746. fts5yypParser->fts5yyidx--;
  157747. #ifndef NDEBUG
  157748. if( fts5yyTraceFILE ){
  157749. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  157750. }
  157751. #endif
  157752. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  157753. /* Here code is inserted which will execute if the parser
  157754. ** stack every overflows */
  157755. /******** Begin %stack_overflow code ******************************************/
  157756. assert( 0 );
  157757. /******** End %stack_overflow code ********************************************/
  157758. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  157759. }
  157760. /*
  157761. ** Print tracing information for a SHIFT action
  157762. */
  157763. #ifndef NDEBUG
  157764. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
  157765. if( fts5yyTraceFILE ){
  157766. if( fts5yyNewState<fts5YYNSTATE ){
  157767. fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
  157768. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major],
  157769. fts5yyNewState);
  157770. }else{
  157771. fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
  157772. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major]);
  157773. }
  157774. }
  157775. }
  157776. #else
  157777. # define fts5yyTraceShift(X,Y)
  157778. #endif
  157779. /*
  157780. ** Perform a shift action.
  157781. */
  157782. static void fts5yy_shift(
  157783. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  157784. int fts5yyNewState, /* The new state to shift in */
  157785. int fts5yyMajor, /* The major token to shift in */
  157786. fts5YYMINORTYPE *fts5yypMinor /* Pointer to the minor token to shift in */
  157787. ){
  157788. fts5yyStackEntry *fts5yytos;
  157789. fts5yypParser->fts5yyidx++;
  157790. #ifdef fts5YYTRACKMAXSTACKDEPTH
  157791. if( fts5yypParser->fts5yyidx>fts5yypParser->fts5yyidxMax ){
  157792. fts5yypParser->fts5yyidxMax = fts5yypParser->fts5yyidx;
  157793. }
  157794. #endif
  157795. #if fts5YYSTACKDEPTH>0
  157796. if( fts5yypParser->fts5yyidx>=fts5YYSTACKDEPTH ){
  157797. fts5yyStackOverflow(fts5yypParser, fts5yypMinor);
  157798. return;
  157799. }
  157800. #else
  157801. if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
  157802. fts5yyGrowStack(fts5yypParser);
  157803. if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
  157804. fts5yyStackOverflow(fts5yypParser, fts5yypMinor);
  157805. return;
  157806. }
  157807. }
  157808. #endif
  157809. fts5yytos = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
  157810. fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
  157811. fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
  157812. fts5yytos->minor = *fts5yypMinor;
  157813. fts5yyTraceShift(fts5yypParser, fts5yyNewState);
  157814. }
  157815. /* The following table contains information about every rule that
  157816. ** is used during the reduce.
  157817. */
  157818. static const struct {
  157819. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  157820. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  157821. } fts5yyRuleInfo[] = {
  157822. { 15, 1 },
  157823. { 16, 3 },
  157824. { 16, 3 },
  157825. { 16, 3 },
  157826. { 16, 3 },
  157827. { 16, 1 },
  157828. { 18, 1 },
  157829. { 18, 2 },
  157830. { 17, 1 },
  157831. { 17, 3 },
  157832. { 20, 3 },
  157833. { 20, 1 },
  157834. { 21, 2 },
  157835. { 21, 1 },
  157836. { 19, 1 },
  157837. { 19, 5 },
  157838. { 22, 1 },
  157839. { 22, 2 },
  157840. { 24, 0 },
  157841. { 24, 2 },
  157842. { 23, 4 },
  157843. { 23, 2 },
  157844. { 25, 1 },
  157845. { 25, 0 },
  157846. };
  157847. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  157848. /*
  157849. ** Perform a reduce action and the shift that must immediately
  157850. ** follow the reduce.
  157851. */
  157852. static void fts5yy_reduce(
  157853. fts5yyParser *fts5yypParser, /* The parser */
  157854. int fts5yyruleno /* Number of the rule by which to reduce */
  157855. ){
  157856. int fts5yygoto; /* The next state */
  157857. int fts5yyact; /* The next action */
  157858. fts5YYMINORTYPE fts5yygotominor; /* The LHS of the rule reduced */
  157859. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  157860. int fts5yysize; /* Amount to pop the stack */
  157861. sqlite3Fts5ParserARG_FETCH;
  157862. fts5yymsp = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
  157863. #ifndef NDEBUG
  157864. if( fts5yyTraceFILE && fts5yyruleno>=0
  157865. && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  157866. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  157867. fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
  157868. fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
  157869. }
  157870. #endif /* NDEBUG */
  157871. fts5yygotominor = fts5yyzerominor;
  157872. switch( fts5yyruleno ){
  157873. /* Beginning here are the reduction cases. A typical example
  157874. ** follows:
  157875. ** case 0:
  157876. ** #line <lineno> <grammarfile>
  157877. ** { ... } // User supplied code
  157878. ** #line <lineno> <thisfile>
  157879. ** break;
  157880. */
  157881. /********** Begin reduce actions **********************************************/
  157882. case 0: /* input ::= expr */
  157883. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
  157884. break;
  157885. case 1: /* expr ::= expr AND expr */
  157886. {
  157887. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  157888. }
  157889. break;
  157890. case 2: /* expr ::= expr OR expr */
  157891. {
  157892. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  157893. }
  157894. break;
  157895. case 3: /* expr ::= expr NOT expr */
  157896. {
  157897. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  157898. }
  157899. break;
  157900. case 4: /* expr ::= LP expr RP */
  157901. {fts5yygotominor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
  157902. break;
  157903. case 5: /* expr ::= exprlist */
  157904. case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
  157905. {fts5yygotominor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
  157906. break;
  157907. case 7: /* exprlist ::= exprlist cnearset */
  157908. {
  157909. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
  157910. }
  157911. break;
  157912. case 8: /* cnearset ::= nearset */
  157913. {
  157914. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
  157915. }
  157916. break;
  157917. case 9: /* cnearset ::= colset COLON nearset */
  157918. {
  157919. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
  157920. fts5yygotominor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
  157921. }
  157922. break;
  157923. case 10: /* colset ::= LCP colsetlist RCP */
  157924. { fts5yygotominor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
  157925. break;
  157926. case 11: /* colset ::= STRING */
  157927. {
  157928. fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  157929. }
  157930. break;
  157931. case 12: /* colsetlist ::= colsetlist STRING */
  157932. {
  157933. fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
  157934. break;
  157935. case 13: /* colsetlist ::= STRING */
  157936. {
  157937. fts5yygotominor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  157938. }
  157939. break;
  157940. case 14: /* nearset ::= phrase */
  157941. { fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
  157942. break;
  157943. case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  157944. {
  157945. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  157946. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
  157947. fts5yygotominor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
  157948. }
  157949. break;
  157950. case 16: /* nearphrases ::= phrase */
  157951. {
  157952. fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
  157953. }
  157954. break;
  157955. case 17: /* nearphrases ::= nearphrases phrase */
  157956. {
  157957. fts5yygotominor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
  157958. }
  157959. break;
  157960. case 18: /* neardist_opt ::= */
  157961. { fts5yygotominor.fts5yy0.p = 0; fts5yygotominor.fts5yy0.n = 0; }
  157962. break;
  157963. case 19: /* neardist_opt ::= COMMA STRING */
  157964. { fts5yygotominor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  157965. break;
  157966. case 20: /* phrase ::= phrase PLUS STRING star_opt */
  157967. {
  157968. fts5yygotominor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
  157969. }
  157970. break;
  157971. case 21: /* phrase ::= STRING star_opt */
  157972. {
  157973. fts5yygotominor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
  157974. }
  157975. break;
  157976. case 22: /* star_opt ::= STAR */
  157977. { fts5yygotominor.fts5yy20 = 1; }
  157978. break;
  157979. case 23: /* star_opt ::= */
  157980. { fts5yygotominor.fts5yy20 = 0; }
  157981. break;
  157982. default:
  157983. break;
  157984. /********** End reduce actions ************************************************/
  157985. };
  157986. assert( fts5yyruleno>=0 && fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  157987. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  157988. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  157989. fts5yypParser->fts5yyidx -= fts5yysize;
  157990. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  157991. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  157992. if( fts5yyact>fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  157993. /* If the reduce action popped at least
  157994. ** one element off the stack, then we can push the new element back
  157995. ** onto the stack here, and skip the stack overflow test in fts5yy_shift().
  157996. ** That gives a significant speed improvement. */
  157997. if( fts5yysize ){
  157998. fts5yypParser->fts5yyidx++;
  157999. fts5yymsp -= fts5yysize-1;
  158000. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  158001. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  158002. fts5yymsp->minor = fts5yygotominor;
  158003. fts5yyTraceShift(fts5yypParser, fts5yyact);
  158004. }else{
  158005. fts5yy_shift(fts5yypParser,fts5yyact,fts5yygoto,&fts5yygotominor);
  158006. }
  158007. }else{
  158008. assert( fts5yyact == fts5YY_ACCEPT_ACTION );
  158009. fts5yy_accept(fts5yypParser);
  158010. }
  158011. }
  158012. /*
  158013. ** The following code executes when the parse fails
  158014. */
  158015. #ifndef fts5YYNOERRORRECOVERY
  158016. static void fts5yy_parse_failed(
  158017. fts5yyParser *fts5yypParser /* The parser */
  158018. ){
  158019. sqlite3Fts5ParserARG_FETCH;
  158020. #ifndef NDEBUG
  158021. if( fts5yyTraceFILE ){
  158022. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  158023. }
  158024. #endif
  158025. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  158026. /* Here code is inserted which will be executed whenever the
  158027. ** parser fails */
  158028. /************ Begin %parse_failure code ***************************************/
  158029. /************ End %parse_failure code *****************************************/
  158030. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  158031. }
  158032. #endif /* fts5YYNOERRORRECOVERY */
  158033. /*
  158034. ** The following code executes when a syntax error first occurs.
  158035. */
  158036. static void fts5yy_syntax_error(
  158037. fts5yyParser *fts5yypParser, /* The parser */
  158038. int fts5yymajor, /* The major type of the error token */
  158039. fts5YYMINORTYPE fts5yyminor /* The minor type of the error token */
  158040. ){
  158041. sqlite3Fts5ParserARG_FETCH;
  158042. #define FTS5TOKEN (fts5yyminor.fts5yy0)
  158043. /************ Begin %syntax_error code ****************************************/
  158044. sqlite3Fts5ParseError(
  158045. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  158046. );
  158047. /************ End %syntax_error code ******************************************/
  158048. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  158049. }
  158050. /*
  158051. ** The following is executed when the parser accepts
  158052. */
  158053. static void fts5yy_accept(
  158054. fts5yyParser *fts5yypParser /* The parser */
  158055. ){
  158056. sqlite3Fts5ParserARG_FETCH;
  158057. #ifndef NDEBUG
  158058. if( fts5yyTraceFILE ){
  158059. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  158060. }
  158061. #endif
  158062. while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
  158063. /* Here code is inserted which will be executed whenever the
  158064. ** parser accepts */
  158065. /*********** Begin %parse_accept code *****************************************/
  158066. /*********** End %parse_accept code *******************************************/
  158067. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  158068. }
  158069. /* The main parser program.
  158070. ** The first argument is a pointer to a structure obtained from
  158071. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  158072. ** The second argument is the major token number. The third is
  158073. ** the minor token. The fourth optional argument is whatever the
  158074. ** user wants (and specified in the grammar) and is available for
  158075. ** use by the action routines.
  158076. **
  158077. ** Inputs:
  158078. ** <ul>
  158079. ** <li> A pointer to the parser (an opaque structure.)
  158080. ** <li> The major token number.
  158081. ** <li> The minor token number.
  158082. ** <li> An option argument of a grammar-specified type.
  158083. ** </ul>
  158084. **
  158085. ** Outputs:
  158086. ** None.
  158087. */
  158088. static void sqlite3Fts5Parser(
  158089. void *fts5yyp, /* The parser */
  158090. int fts5yymajor, /* The major token code number */
  158091. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  158092. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  158093. ){
  158094. fts5YYMINORTYPE fts5yyminorunion;
  158095. int fts5yyact; /* The parser action. */
  158096. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  158097. int fts5yyendofinput; /* True if we are at the end of input */
  158098. #endif
  158099. #ifdef fts5YYERRORSYMBOL
  158100. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  158101. #endif
  158102. fts5yyParser *fts5yypParser; /* The parser */
  158103. /* (re)initialize the parser, if necessary */
  158104. fts5yypParser = (fts5yyParser*)fts5yyp;
  158105. if( fts5yypParser->fts5yyidx<0 ){
  158106. #if fts5YYSTACKDEPTH<=0
  158107. if( fts5yypParser->fts5yystksz <=0 ){
  158108. /*memset(&fts5yyminorunion, 0, sizeof(fts5yyminorunion));*/
  158109. fts5yyminorunion = fts5yyzerominor;
  158110. fts5yyStackOverflow(fts5yypParser, &fts5yyminorunion);
  158111. return;
  158112. }
  158113. #endif
  158114. fts5yypParser->fts5yyidx = 0;
  158115. fts5yypParser->fts5yyerrcnt = -1;
  158116. fts5yypParser->fts5yystack[0].stateno = 0;
  158117. fts5yypParser->fts5yystack[0].major = 0;
  158118. #ifndef NDEBUG
  158119. if( fts5yyTraceFILE ){
  158120. fprintf(fts5yyTraceFILE,"%sInitialize. Empty stack. State 0\n",
  158121. fts5yyTracePrompt);
  158122. }
  158123. #endif
  158124. }
  158125. fts5yyminorunion.fts5yy0 = fts5yyminor;
  158126. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  158127. fts5yyendofinput = (fts5yymajor==0);
  158128. #endif
  158129. sqlite3Fts5ParserARG_STORE;
  158130. #ifndef NDEBUG
  158131. if( fts5yyTraceFILE ){
  158132. fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  158133. }
  158134. #endif
  158135. do{
  158136. fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
  158137. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  158138. if( fts5yyact > fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  158139. fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,&fts5yyminorunion);
  158140. fts5yypParser->fts5yyerrcnt--;
  158141. fts5yymajor = fts5YYNOCODE;
  158142. }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
  158143. fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
  158144. }else{
  158145. assert( fts5yyact == fts5YY_ERROR_ACTION );
  158146. #ifdef fts5YYERRORSYMBOL
  158147. int fts5yymx;
  158148. #endif
  158149. #ifndef NDEBUG
  158150. if( fts5yyTraceFILE ){
  158151. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  158152. }
  158153. #endif
  158154. #ifdef fts5YYERRORSYMBOL
  158155. /* A syntax error has occurred.
  158156. ** The response to an error depends upon whether or not the
  158157. ** grammar defines an error token "ERROR".
  158158. **
  158159. ** This is what we do if the grammar does define ERROR:
  158160. **
  158161. ** * Call the %syntax_error function.
  158162. **
  158163. ** * Begin popping the stack until we enter a state where
  158164. ** it is legal to shift the error symbol, then shift
  158165. ** the error symbol.
  158166. **
  158167. ** * Set the error count to three.
  158168. **
  158169. ** * Begin accepting and shifting new tokens. No new error
  158170. ** processing will occur until three tokens have been
  158171. ** shifted successfully.
  158172. **
  158173. */
  158174. if( fts5yypParser->fts5yyerrcnt<0 ){
  158175. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
  158176. }
  158177. fts5yymx = fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major;
  158178. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  158179. #ifndef NDEBUG
  158180. if( fts5yyTraceFILE ){
  158181. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  158182. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  158183. }
  158184. #endif
  158185. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  158186. fts5yymajor = fts5YYNOCODE;
  158187. }else{
  158188. while(
  158189. fts5yypParser->fts5yyidx >= 0 &&
  158190. fts5yymx != fts5YYERRORSYMBOL &&
  158191. (fts5yyact = fts5yy_find_reduce_action(
  158192. fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].stateno,
  158193. fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
  158194. ){
  158195. fts5yy_pop_parser_stack(fts5yypParser);
  158196. }
  158197. if( fts5yypParser->fts5yyidx < 0 || fts5yymajor==0 ){
  158198. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  158199. fts5yy_parse_failed(fts5yypParser);
  158200. fts5yymajor = fts5YYNOCODE;
  158201. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  158202. fts5YYMINORTYPE u2;
  158203. u2.fts5YYERRSYMDT = 0;
  158204. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,&u2);
  158205. }
  158206. }
  158207. fts5yypParser->fts5yyerrcnt = 3;
  158208. fts5yyerrorhit = 1;
  158209. #elif defined(fts5YYNOERRORRECOVERY)
  158210. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  158211. ** do any kind of error recovery. Instead, simply invoke the syntax
  158212. ** error routine and continue going as if nothing had happened.
  158213. **
  158214. ** Applications can set this macro (for example inside %include) if
  158215. ** they intend to abandon the parse upon the first syntax error seen.
  158216. */
  158217. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
  158218. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  158219. fts5yymajor = fts5YYNOCODE;
  158220. #else /* fts5YYERRORSYMBOL is not defined */
  158221. /* This is what we do if the grammar does not define ERROR:
  158222. **
  158223. ** * Report an error message, and throw away the input token.
  158224. **
  158225. ** * If the input token is $, then fail the parse.
  158226. **
  158227. ** As before, subsequent error messages are suppressed until
  158228. ** three input tokens have been successfully shifted.
  158229. */
  158230. if( fts5yypParser->fts5yyerrcnt<=0 ){
  158231. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminorunion);
  158232. }
  158233. fts5yypParser->fts5yyerrcnt = 3;
  158234. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  158235. if( fts5yyendofinput ){
  158236. fts5yy_parse_failed(fts5yypParser);
  158237. }
  158238. fts5yymajor = fts5YYNOCODE;
  158239. #endif
  158240. }
  158241. }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yyidx>=0 );
  158242. #ifndef NDEBUG
  158243. if( fts5yyTraceFILE ){
  158244. int i;
  158245. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  158246. for(i=1; i<=fts5yypParser->fts5yyidx; i++)
  158247. fprintf(fts5yyTraceFILE,"%c%s", i==1 ? '[' : ' ',
  158248. fts5yyTokenName[fts5yypParser->fts5yystack[i].major]);
  158249. fprintf(fts5yyTraceFILE,"]\n");
  158250. }
  158251. #endif
  158252. return;
  158253. }
  158254. /*
  158255. ** 2014 May 31
  158256. **
  158257. ** The author disclaims copyright to this source code. In place of
  158258. ** a legal notice, here is a blessing:
  158259. **
  158260. ** May you do good and not evil.
  158261. ** May you find forgiveness for yourself and forgive others.
  158262. ** May you share freely, never taking more than you give.
  158263. **
  158264. ******************************************************************************
  158265. */
  158266. /* #include "fts5Int.h" */
  158267. #include <math.h> /* amalgamator: keep */
  158268. /*
  158269. ** Object used to iterate through all "coalesced phrase instances" in
  158270. ** a single column of the current row. If the phrase instances in the
  158271. ** column being considered do not overlap, this object simply iterates
  158272. ** through them. Or, if they do overlap (share one or more tokens in
  158273. ** common), each set of overlapping instances is treated as a single
  158274. ** match. See documentation for the highlight() auxiliary function for
  158275. ** details.
  158276. **
  158277. ** Usage is:
  158278. **
  158279. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  158280. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  158281. ** rc = fts5CInstIterNext(&iter)
  158282. ** ){
  158283. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  158284. ** }
  158285. **
  158286. */
  158287. typedef struct CInstIter CInstIter;
  158288. struct CInstIter {
  158289. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  158290. Fts5Context *pFts; /* First arg to pass to pApi functions */
  158291. int iCol; /* Column to search */
  158292. int iInst; /* Next phrase instance index */
  158293. int nInst; /* Total number of phrase instances */
  158294. /* Output variables */
  158295. int iStart; /* First token in coalesced phrase instance */
  158296. int iEnd; /* Last token in coalesced phrase instance */
  158297. };
  158298. /*
  158299. ** Advance the iterator to the next coalesced phrase instance. Return
  158300. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  158301. */
  158302. static int fts5CInstIterNext(CInstIter *pIter){
  158303. int rc = SQLITE_OK;
  158304. pIter->iStart = -1;
  158305. pIter->iEnd = -1;
  158306. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  158307. int ip; int ic; int io;
  158308. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  158309. if( rc==SQLITE_OK ){
  158310. if( ic==pIter->iCol ){
  158311. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  158312. if( pIter->iStart<0 ){
  158313. pIter->iStart = io;
  158314. pIter->iEnd = iEnd;
  158315. }else if( io<=pIter->iEnd ){
  158316. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  158317. }else{
  158318. break;
  158319. }
  158320. }
  158321. pIter->iInst++;
  158322. }
  158323. }
  158324. return rc;
  158325. }
  158326. /*
  158327. ** Initialize the iterator object indicated by the final parameter to
  158328. ** iterate through coalesced phrase instances in column iCol.
  158329. */
  158330. static int fts5CInstIterInit(
  158331. const Fts5ExtensionApi *pApi,
  158332. Fts5Context *pFts,
  158333. int iCol,
  158334. CInstIter *pIter
  158335. ){
  158336. int rc;
  158337. memset(pIter, 0, sizeof(CInstIter));
  158338. pIter->pApi = pApi;
  158339. pIter->pFts = pFts;
  158340. pIter->iCol = iCol;
  158341. rc = pApi->xInstCount(pFts, &pIter->nInst);
  158342. if( rc==SQLITE_OK ){
  158343. rc = fts5CInstIterNext(pIter);
  158344. }
  158345. return rc;
  158346. }
  158347. /*************************************************************************
  158348. ** Start of highlight() implementation.
  158349. */
  158350. typedef struct HighlightContext HighlightContext;
  158351. struct HighlightContext {
  158352. CInstIter iter; /* Coalesced Instance Iterator */
  158353. int iPos; /* Current token offset in zIn[] */
  158354. int iRangeStart; /* First token to include */
  158355. int iRangeEnd; /* If non-zero, last token to include */
  158356. const char *zOpen; /* Opening highlight */
  158357. const char *zClose; /* Closing highlight */
  158358. const char *zIn; /* Input text */
  158359. int nIn; /* Size of input text in bytes */
  158360. int iOff; /* Current offset within zIn[] */
  158361. char *zOut; /* Output value */
  158362. };
  158363. /*
  158364. ** Append text to the HighlightContext output string - p->zOut. Argument
  158365. ** z points to a buffer containing n bytes of text to append. If n is
  158366. ** negative, everything up until the first '\0' is appended to the output.
  158367. **
  158368. ** If *pRc is set to any value other than SQLITE_OK when this function is
  158369. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  158370. ** *pRc is set to an error code before returning.
  158371. */
  158372. static void fts5HighlightAppend(
  158373. int *pRc,
  158374. HighlightContext *p,
  158375. const char *z, int n
  158376. ){
  158377. if( *pRc==SQLITE_OK ){
  158378. if( n<0 ) n = (int)strlen(z);
  158379. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  158380. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  158381. }
  158382. }
  158383. /*
  158384. ** Tokenizer callback used by implementation of highlight() function.
  158385. */
  158386. static int fts5HighlightCb(
  158387. void *pContext, /* Pointer to HighlightContext object */
  158388. int tflags, /* Mask of FTS5_TOKEN_* flags */
  158389. const char *pToken, /* Buffer containing token */
  158390. int nToken, /* Size of token in bytes */
  158391. int iStartOff, /* Start offset of token */
  158392. int iEndOff /* End offset of token */
  158393. ){
  158394. HighlightContext *p = (HighlightContext*)pContext;
  158395. int rc = SQLITE_OK;
  158396. int iPos;
  158397. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  158398. iPos = p->iPos++;
  158399. if( p->iRangeEnd>0 ){
  158400. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  158401. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  158402. }
  158403. if( iPos==p->iter.iStart ){
  158404. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  158405. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  158406. p->iOff = iStartOff;
  158407. }
  158408. if( iPos==p->iter.iEnd ){
  158409. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  158410. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  158411. }
  158412. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  158413. fts5HighlightAppend(&rc, p, p->zClose, -1);
  158414. p->iOff = iEndOff;
  158415. if( rc==SQLITE_OK ){
  158416. rc = fts5CInstIterNext(&p->iter);
  158417. }
  158418. }
  158419. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  158420. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  158421. p->iOff = iEndOff;
  158422. if( iPos<p->iter.iEnd ){
  158423. fts5HighlightAppend(&rc, p, p->zClose, -1);
  158424. }
  158425. }
  158426. return rc;
  158427. }
  158428. /*
  158429. ** Implementation of highlight() function.
  158430. */
  158431. static void fts5HighlightFunction(
  158432. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  158433. Fts5Context *pFts, /* First arg to pass to pApi functions */
  158434. sqlite3_context *pCtx, /* Context for returning result/error */
  158435. int nVal, /* Number of values in apVal[] array */
  158436. sqlite3_value **apVal /* Array of trailing arguments */
  158437. ){
  158438. HighlightContext ctx;
  158439. int rc;
  158440. int iCol;
  158441. if( nVal!=3 ){
  158442. const char *zErr = "wrong number of arguments to function highlight()";
  158443. sqlite3_result_error(pCtx, zErr, -1);
  158444. return;
  158445. }
  158446. iCol = sqlite3_value_int(apVal[0]);
  158447. memset(&ctx, 0, sizeof(HighlightContext));
  158448. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  158449. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  158450. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  158451. if( ctx.zIn ){
  158452. if( rc==SQLITE_OK ){
  158453. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  158454. }
  158455. if( rc==SQLITE_OK ){
  158456. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  158457. }
  158458. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  158459. if( rc==SQLITE_OK ){
  158460. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  158461. }
  158462. sqlite3_free(ctx.zOut);
  158463. }
  158464. if( rc!=SQLITE_OK ){
  158465. sqlite3_result_error_code(pCtx, rc);
  158466. }
  158467. }
  158468. /*
  158469. ** End of highlight() implementation.
  158470. **************************************************************************/
  158471. /*
  158472. ** Implementation of snippet() function.
  158473. */
  158474. static void fts5SnippetFunction(
  158475. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  158476. Fts5Context *pFts, /* First arg to pass to pApi functions */
  158477. sqlite3_context *pCtx, /* Context for returning result/error */
  158478. int nVal, /* Number of values in apVal[] array */
  158479. sqlite3_value **apVal /* Array of trailing arguments */
  158480. ){
  158481. HighlightContext ctx;
  158482. int rc = SQLITE_OK; /* Return code */
  158483. int iCol; /* 1st argument to snippet() */
  158484. const char *zEllips; /* 4th argument to snippet() */
  158485. int nToken; /* 5th argument to snippet() */
  158486. int nInst = 0; /* Number of instance matches this row */
  158487. int i; /* Used to iterate through instances */
  158488. int nPhrase; /* Number of phrases in query */
  158489. unsigned char *aSeen; /* Array of "seen instance" flags */
  158490. int iBestCol; /* Column containing best snippet */
  158491. int iBestStart = 0; /* First token of best snippet */
  158492. int iBestLast; /* Last token of best snippet */
  158493. int nBestScore = 0; /* Score of best snippet */
  158494. int nColSize = 0; /* Total size of iBestCol in tokens */
  158495. if( nVal!=5 ){
  158496. const char *zErr = "wrong number of arguments to function snippet()";
  158497. sqlite3_result_error(pCtx, zErr, -1);
  158498. return;
  158499. }
  158500. memset(&ctx, 0, sizeof(HighlightContext));
  158501. iCol = sqlite3_value_int(apVal[0]);
  158502. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  158503. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  158504. zEllips = (const char*)sqlite3_value_text(apVal[3]);
  158505. nToken = sqlite3_value_int(apVal[4]);
  158506. iBestLast = nToken-1;
  158507. iBestCol = (iCol>=0 ? iCol : 0);
  158508. nPhrase = pApi->xPhraseCount(pFts);
  158509. aSeen = sqlite3_malloc(nPhrase);
  158510. if( aSeen==0 ){
  158511. rc = SQLITE_NOMEM;
  158512. }
  158513. if( rc==SQLITE_OK ){
  158514. rc = pApi->xInstCount(pFts, &nInst);
  158515. }
  158516. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  158517. int ip, iSnippetCol, iStart;
  158518. memset(aSeen, 0, nPhrase);
  158519. rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
  158520. if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
  158521. int nScore = 1000;
  158522. int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
  158523. int j;
  158524. aSeen[ip] = 1;
  158525. for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
  158526. int ic; int io; int iFinal;
  158527. rc = pApi->xInst(pFts, j, &ip, &ic, &io);
  158528. iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
  158529. if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
  158530. nScore += aSeen[ip] ? 1000 : 1;
  158531. aSeen[ip] = 1;
  158532. if( iFinal>iLast ) iLast = iFinal;
  158533. }
  158534. }
  158535. if( rc==SQLITE_OK && nScore>nBestScore ){
  158536. iBestCol = iSnippetCol;
  158537. iBestStart = iStart;
  158538. iBestLast = iLast;
  158539. nBestScore = nScore;
  158540. }
  158541. }
  158542. }
  158543. if( rc==SQLITE_OK ){
  158544. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  158545. }
  158546. if( rc==SQLITE_OK ){
  158547. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  158548. }
  158549. if( ctx.zIn ){
  158550. if( rc==SQLITE_OK ){
  158551. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  158552. }
  158553. if( (iBestStart+nToken-1)>iBestLast ){
  158554. iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
  158555. }
  158556. if( iBestStart+nToken>nColSize ){
  158557. iBestStart = nColSize - nToken;
  158558. }
  158559. if( iBestStart<0 ) iBestStart = 0;
  158560. ctx.iRangeStart = iBestStart;
  158561. ctx.iRangeEnd = iBestStart + nToken - 1;
  158562. if( iBestStart>0 ){
  158563. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  158564. }
  158565. if( rc==SQLITE_OK ){
  158566. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  158567. }
  158568. if( ctx.iRangeEnd>=(nColSize-1) ){
  158569. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  158570. }else{
  158571. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  158572. }
  158573. if( rc==SQLITE_OK ){
  158574. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  158575. }else{
  158576. sqlite3_result_error_code(pCtx, rc);
  158577. }
  158578. sqlite3_free(ctx.zOut);
  158579. }
  158580. sqlite3_free(aSeen);
  158581. }
  158582. /************************************************************************/
  158583. /*
  158584. ** The first time the bm25() function is called for a query, an instance
  158585. ** of the following structure is allocated and populated.
  158586. */
  158587. typedef struct Fts5Bm25Data Fts5Bm25Data;
  158588. struct Fts5Bm25Data {
  158589. int nPhrase; /* Number of phrases in query */
  158590. double avgdl; /* Average number of tokens in each row */
  158591. double *aIDF; /* IDF for each phrase */
  158592. double *aFreq; /* Array used to calculate phrase freq. */
  158593. };
  158594. /*
  158595. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  158596. ** table matched by each individual phrase within the query.
  158597. */
  158598. static int fts5CountCb(
  158599. const Fts5ExtensionApi *pApi,
  158600. Fts5Context *pFts,
  158601. void *pUserData /* Pointer to sqlite3_int64 variable */
  158602. ){
  158603. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  158604. (*pn)++;
  158605. return SQLITE_OK;
  158606. }
  158607. /*
  158608. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  158609. ** If the object has not already been allocated, allocate and populate it
  158610. ** now.
  158611. */
  158612. static int fts5Bm25GetData(
  158613. const Fts5ExtensionApi *pApi,
  158614. Fts5Context *pFts,
  158615. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  158616. ){
  158617. int rc = SQLITE_OK; /* Return code */
  158618. Fts5Bm25Data *p; /* Object to return */
  158619. p = pApi->xGetAuxdata(pFts, 0);
  158620. if( p==0 ){
  158621. int nPhrase; /* Number of phrases in query */
  158622. sqlite3_int64 nRow = 0; /* Number of rows in table */
  158623. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  158624. int nByte; /* Bytes of space to allocate */
  158625. int i;
  158626. /* Allocate the Fts5Bm25Data object */
  158627. nPhrase = pApi->xPhraseCount(pFts);
  158628. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  158629. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  158630. if( p==0 ){
  158631. rc = SQLITE_NOMEM;
  158632. }else{
  158633. memset(p, 0, nByte);
  158634. p->nPhrase = nPhrase;
  158635. p->aIDF = (double*)&p[1];
  158636. p->aFreq = &p->aIDF[nPhrase];
  158637. }
  158638. /* Calculate the average document length for this FTS5 table */
  158639. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  158640. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  158641. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  158642. /* Calculate an IDF for each phrase in the query */
  158643. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  158644. sqlite3_int64 nHit = 0;
  158645. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  158646. if( rc==SQLITE_OK ){
  158647. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  158648. ** This is done using the standard BM25 formula as found on wikipedia:
  158649. **
  158650. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  158651. **
  158652. ** where "N" is the total number of documents in the set and nHit
  158653. ** is the number that contain at least one instance of the phrase
  158654. ** under consideration.
  158655. **
  158656. ** The problem with this is that if (N < 2*nHit), the IDF is
  158657. ** negative. Which is undesirable. So the mimimum allowable IDF is
  158658. ** (1e-6) - roughly the same as a term that appears in just over
  158659. ** half of set of 5,000,000 documents. */
  158660. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  158661. if( idf<=0.0 ) idf = 1e-6;
  158662. p->aIDF[i] = idf;
  158663. }
  158664. }
  158665. if( rc!=SQLITE_OK ){
  158666. sqlite3_free(p);
  158667. }else{
  158668. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  158669. }
  158670. if( rc!=SQLITE_OK ) p = 0;
  158671. }
  158672. *ppData = p;
  158673. return rc;
  158674. }
  158675. /*
  158676. ** Implementation of bm25() function.
  158677. */
  158678. static void fts5Bm25Function(
  158679. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  158680. Fts5Context *pFts, /* First arg to pass to pApi functions */
  158681. sqlite3_context *pCtx, /* Context for returning result/error */
  158682. int nVal, /* Number of values in apVal[] array */
  158683. sqlite3_value **apVal /* Array of trailing arguments */
  158684. ){
  158685. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  158686. const double b = 0.75; /* Constant "b" from BM25 formula */
  158687. int rc = SQLITE_OK; /* Error code */
  158688. double score = 0.0; /* SQL function return value */
  158689. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  158690. int i; /* Iterator variable */
  158691. int nInst = 0; /* Value returned by xInstCount() */
  158692. double D = 0.0; /* Total number of tokens in row */
  158693. double *aFreq = 0; /* Array of phrase freq. for current row */
  158694. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  158695. ** for each phrase in the query for the current row. */
  158696. rc = fts5Bm25GetData(pApi, pFts, &pData);
  158697. if( rc==SQLITE_OK ){
  158698. aFreq = pData->aFreq;
  158699. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  158700. rc = pApi->xInstCount(pFts, &nInst);
  158701. }
  158702. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  158703. int ip; int ic; int io;
  158704. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  158705. if( rc==SQLITE_OK ){
  158706. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  158707. aFreq[ip] += w;
  158708. }
  158709. }
  158710. /* Figure out the total size of the current row in tokens. */
  158711. if( rc==SQLITE_OK ){
  158712. int nTok;
  158713. rc = pApi->xColumnSize(pFts, -1, &nTok);
  158714. D = (double)nTok;
  158715. }
  158716. /* Determine the BM25 score for the current row. */
  158717. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  158718. score += pData->aIDF[i] * (
  158719. ( aFreq[i] * (k1 + 1.0) ) /
  158720. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  158721. );
  158722. }
  158723. /* If no error has occurred, return the calculated score. Otherwise,
  158724. ** throw an SQL exception. */
  158725. if( rc==SQLITE_OK ){
  158726. sqlite3_result_double(pCtx, -1.0 * score);
  158727. }else{
  158728. sqlite3_result_error_code(pCtx, rc);
  158729. }
  158730. }
  158731. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  158732. struct Builtin {
  158733. const char *zFunc; /* Function name (nul-terminated) */
  158734. void *pUserData; /* User-data pointer */
  158735. fts5_extension_function xFunc;/* Callback function */
  158736. void (*xDestroy)(void*); /* Destructor function */
  158737. } aBuiltin [] = {
  158738. { "snippet", 0, fts5SnippetFunction, 0 },
  158739. { "highlight", 0, fts5HighlightFunction, 0 },
  158740. { "bm25", 0, fts5Bm25Function, 0 },
  158741. };
  158742. int rc = SQLITE_OK; /* Return code */
  158743. int i; /* To iterate through builtin functions */
  158744. for(i=0; rc==SQLITE_OK && i<(int)ArraySize(aBuiltin); i++){
  158745. rc = pApi->xCreateFunction(pApi,
  158746. aBuiltin[i].zFunc,
  158747. aBuiltin[i].pUserData,
  158748. aBuiltin[i].xFunc,
  158749. aBuiltin[i].xDestroy
  158750. );
  158751. }
  158752. return rc;
  158753. }
  158754. /*
  158755. ** 2014 May 31
  158756. **
  158757. ** The author disclaims copyright to this source code. In place of
  158758. ** a legal notice, here is a blessing:
  158759. **
  158760. ** May you do good and not evil.
  158761. ** May you find forgiveness for yourself and forgive others.
  158762. ** May you share freely, never taking more than you give.
  158763. **
  158764. ******************************************************************************
  158765. */
  158766. /* #include "fts5Int.h" */
  158767. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, int nByte){
  158768. int nNew = pBuf->nSpace ? pBuf->nSpace*2 : 64;
  158769. u8 *pNew;
  158770. while( nNew<nByte ){
  158771. nNew = nNew * 2;
  158772. }
  158773. pNew = sqlite3_realloc(pBuf->p, nNew);
  158774. if( pNew==0 ){
  158775. *pRc = SQLITE_NOMEM;
  158776. return 1;
  158777. }else{
  158778. pBuf->nSpace = nNew;
  158779. pBuf->p = pNew;
  158780. }
  158781. return 0;
  158782. }
  158783. /*
  158784. ** Encode value iVal as an SQLite varint and append it to the buffer object
  158785. ** pBuf. If an OOM error occurs, set the error code in p.
  158786. */
  158787. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  158788. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  158789. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  158790. }
  158791. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  158792. aBuf[0] = (iVal>>24) & 0x00FF;
  158793. aBuf[1] = (iVal>>16) & 0x00FF;
  158794. aBuf[2] = (iVal>> 8) & 0x00FF;
  158795. aBuf[3] = (iVal>> 0) & 0x00FF;
  158796. }
  158797. static int sqlite3Fts5Get32(const u8 *aBuf){
  158798. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  158799. }
  158800. /*
  158801. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  158802. ** the error code in p. If an error has already occurred when this function
  158803. ** is called, it is a no-op.
  158804. */
  158805. static void sqlite3Fts5BufferAppendBlob(
  158806. int *pRc,
  158807. Fts5Buffer *pBuf,
  158808. int nData,
  158809. const u8 *pData
  158810. ){
  158811. assert( *pRc || nData>=0 );
  158812. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  158813. memcpy(&pBuf->p[pBuf->n], pData, nData);
  158814. pBuf->n += nData;
  158815. }
  158816. /*
  158817. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  158818. ** ensures that the byte following the buffer data is set to 0x00, even
  158819. ** though this byte is not included in the pBuf->n count.
  158820. */
  158821. static void sqlite3Fts5BufferAppendString(
  158822. int *pRc,
  158823. Fts5Buffer *pBuf,
  158824. const char *zStr
  158825. ){
  158826. int nStr = (int)strlen(zStr);
  158827. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  158828. pBuf->n--;
  158829. }
  158830. /*
  158831. ** Argument zFmt is a printf() style format string. This function performs
  158832. ** the printf() style processing, then appends the results to buffer pBuf.
  158833. **
  158834. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  158835. ** following the buffer data is set to 0x00, even though this byte is not
  158836. ** included in the pBuf->n count.
  158837. */
  158838. static void sqlite3Fts5BufferAppendPrintf(
  158839. int *pRc,
  158840. Fts5Buffer *pBuf,
  158841. char *zFmt, ...
  158842. ){
  158843. if( *pRc==SQLITE_OK ){
  158844. char *zTmp;
  158845. va_list ap;
  158846. va_start(ap, zFmt);
  158847. zTmp = sqlite3_vmprintf(zFmt, ap);
  158848. va_end(ap);
  158849. if( zTmp==0 ){
  158850. *pRc = SQLITE_NOMEM;
  158851. }else{
  158852. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  158853. sqlite3_free(zTmp);
  158854. }
  158855. }
  158856. }
  158857. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  158858. char *zRet = 0;
  158859. if( *pRc==SQLITE_OK ){
  158860. va_list ap;
  158861. va_start(ap, zFmt);
  158862. zRet = sqlite3_vmprintf(zFmt, ap);
  158863. va_end(ap);
  158864. if( zRet==0 ){
  158865. *pRc = SQLITE_NOMEM;
  158866. }
  158867. }
  158868. return zRet;
  158869. }
  158870. /*
  158871. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  158872. */
  158873. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  158874. sqlite3_free(pBuf->p);
  158875. memset(pBuf, 0, sizeof(Fts5Buffer));
  158876. }
  158877. /*
  158878. ** Zero the contents of the buffer object. But do not free the associated
  158879. ** memory allocation.
  158880. */
  158881. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  158882. pBuf->n = 0;
  158883. }
  158884. /*
  158885. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  158886. ** the error code in p. If an error has already occurred when this function
  158887. ** is called, it is a no-op.
  158888. */
  158889. static void sqlite3Fts5BufferSet(
  158890. int *pRc,
  158891. Fts5Buffer *pBuf,
  158892. int nData,
  158893. const u8 *pData
  158894. ){
  158895. pBuf->n = 0;
  158896. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  158897. }
  158898. static int sqlite3Fts5PoslistNext64(
  158899. const u8 *a, int n, /* Buffer containing poslist */
  158900. int *pi, /* IN/OUT: Offset within a[] */
  158901. i64 *piOff /* IN/OUT: Current offset */
  158902. ){
  158903. int i = *pi;
  158904. if( i>=n ){
  158905. /* EOF */
  158906. *piOff = -1;
  158907. return 1;
  158908. }else{
  158909. i64 iOff = *piOff;
  158910. int iVal;
  158911. fts5FastGetVarint32(a, i, iVal);
  158912. if( iVal==1 ){
  158913. fts5FastGetVarint32(a, i, iVal);
  158914. iOff = ((i64)iVal) << 32;
  158915. fts5FastGetVarint32(a, i, iVal);
  158916. }
  158917. *piOff = iOff + (iVal-2);
  158918. *pi = i;
  158919. return 0;
  158920. }
  158921. }
  158922. /*
  158923. ** Advance the iterator object passed as the only argument. Return true
  158924. ** if the iterator reaches EOF, or false otherwise.
  158925. */
  158926. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  158927. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  158928. pIter->bEof = 1;
  158929. }
  158930. return pIter->bEof;
  158931. }
  158932. static int sqlite3Fts5PoslistReaderInit(
  158933. const u8 *a, int n, /* Poslist buffer to iterate through */
  158934. Fts5PoslistReader *pIter /* Iterator object to initialize */
  158935. ){
  158936. memset(pIter, 0, sizeof(*pIter));
  158937. pIter->a = a;
  158938. pIter->n = n;
  158939. sqlite3Fts5PoslistReaderNext(pIter);
  158940. return pIter->bEof;
  158941. }
  158942. static int sqlite3Fts5PoslistWriterAppend(
  158943. Fts5Buffer *pBuf,
  158944. Fts5PoslistWriter *pWriter,
  158945. i64 iPos
  158946. ){
  158947. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  158948. int rc = SQLITE_OK;
  158949. if( 0==fts5BufferGrow(&rc, pBuf, 5+5+5) ){
  158950. if( (iPos & colmask) != (pWriter->iPrev & colmask) ){
  158951. pBuf->p[pBuf->n++] = 1;
  158952. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  158953. pWriter->iPrev = (iPos & colmask);
  158954. }
  158955. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-pWriter->iPrev)+2);
  158956. pWriter->iPrev = iPos;
  158957. }
  158958. return rc;
  158959. }
  158960. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  158961. void *pRet = 0;
  158962. if( *pRc==SQLITE_OK ){
  158963. pRet = sqlite3_malloc(nByte);
  158964. if( pRet==0 && nByte>0 ){
  158965. *pRc = SQLITE_NOMEM;
  158966. }else{
  158967. memset(pRet, 0, nByte);
  158968. }
  158969. }
  158970. return pRet;
  158971. }
  158972. /*
  158973. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  158974. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  158975. ** the length of the string is determined using strlen().
  158976. **
  158977. ** It is the responsibility of the caller to eventually free the returned
  158978. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  158979. */
  158980. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  158981. char *zRet = 0;
  158982. if( *pRc==SQLITE_OK ){
  158983. if( nIn<0 ){
  158984. nIn = (int)strlen(pIn);
  158985. }
  158986. zRet = (char*)sqlite3_malloc(nIn+1);
  158987. if( zRet ){
  158988. memcpy(zRet, pIn, nIn);
  158989. zRet[nIn] = '\0';
  158990. }else{
  158991. *pRc = SQLITE_NOMEM;
  158992. }
  158993. }
  158994. return zRet;
  158995. }
  158996. /*
  158997. ** Return true if character 't' may be part of an FTS5 bareword, or false
  158998. ** otherwise. Characters that may be part of barewords:
  158999. **
  159000. ** * All non-ASCII characters,
  159001. ** * The 52 upper and lower case ASCII characters, and
  159002. ** * The 10 integer ASCII characters.
  159003. ** * The underscore character "_" (0x5F).
  159004. ** * The unicode "subsitute" character (0x1A).
  159005. */
  159006. static int sqlite3Fts5IsBareword(char t){
  159007. u8 aBareword[128] = {
  159008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  159009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  159010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  159011. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  159012. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  159013. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  159014. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  159015. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  159016. };
  159017. return (t & 0x80) || aBareword[(int)t];
  159018. }
  159019. /*
  159020. ** 2014 Jun 09
  159021. **
  159022. ** The author disclaims copyright to this source code. In place of
  159023. ** a legal notice, here is a blessing:
  159024. **
  159025. ** May you do good and not evil.
  159026. ** May you find forgiveness for yourself and forgive others.
  159027. ** May you share freely, never taking more than you give.
  159028. **
  159029. ******************************************************************************
  159030. **
  159031. ** This is an SQLite module implementing full-text search.
  159032. */
  159033. /* #include "fts5Int.h" */
  159034. #define FTS5_DEFAULT_PAGE_SIZE 4050
  159035. #define FTS5_DEFAULT_AUTOMERGE 4
  159036. #define FTS5_DEFAULT_CRISISMERGE 16
  159037. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  159038. /* Maximum allowed page size */
  159039. #define FTS5_MAX_PAGE_SIZE (128*1024)
  159040. static int fts5_iswhitespace(char x){
  159041. return (x==' ');
  159042. }
  159043. static int fts5_isopenquote(char x){
  159044. return (x=='"' || x=='\'' || x=='[' || x=='`');
  159045. }
  159046. /*
  159047. ** Argument pIn points to a character that is part of a nul-terminated
  159048. ** string. Return a pointer to the first character following *pIn in
  159049. ** the string that is not a white-space character.
  159050. */
  159051. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  159052. const char *p = pIn;
  159053. if( p ){
  159054. while( fts5_iswhitespace(*p) ){ p++; }
  159055. }
  159056. return p;
  159057. }
  159058. /*
  159059. ** Argument pIn points to a character that is part of a nul-terminated
  159060. ** string. Return a pointer to the first character following *pIn in
  159061. ** the string that is not a "bareword" character.
  159062. */
  159063. static const char *fts5ConfigSkipBareword(const char *pIn){
  159064. const char *p = pIn;
  159065. while ( sqlite3Fts5IsBareword(*p) ) p++;
  159066. if( p==pIn ) p = 0;
  159067. return p;
  159068. }
  159069. static int fts5_isdigit(char a){
  159070. return (a>='0' && a<='9');
  159071. }
  159072. static const char *fts5ConfigSkipLiteral(const char *pIn){
  159073. const char *p = pIn;
  159074. switch( *p ){
  159075. case 'n': case 'N':
  159076. if( sqlite3_strnicmp("null", p, 4)==0 ){
  159077. p = &p[4];
  159078. }else{
  159079. p = 0;
  159080. }
  159081. break;
  159082. case 'x': case 'X':
  159083. p++;
  159084. if( *p=='\'' ){
  159085. p++;
  159086. while( (*p>='a' && *p<='f')
  159087. || (*p>='A' && *p<='F')
  159088. || (*p>='0' && *p<='9')
  159089. ){
  159090. p++;
  159091. }
  159092. if( *p=='\'' && 0==((p-pIn)%2) ){
  159093. p++;
  159094. }else{
  159095. p = 0;
  159096. }
  159097. }else{
  159098. p = 0;
  159099. }
  159100. break;
  159101. case '\'':
  159102. p++;
  159103. while( p ){
  159104. if( *p=='\'' ){
  159105. p++;
  159106. if( *p!='\'' ) break;
  159107. }
  159108. p++;
  159109. if( *p==0 ) p = 0;
  159110. }
  159111. break;
  159112. default:
  159113. /* maybe a number */
  159114. if( *p=='+' || *p=='-' ) p++;
  159115. while( fts5_isdigit(*p) ) p++;
  159116. /* At this point, if the literal was an integer, the parse is
  159117. ** finished. Or, if it is a floating point value, it may continue
  159118. ** with either a decimal point or an 'E' character. */
  159119. if( *p=='.' && fts5_isdigit(p[1]) ){
  159120. p += 2;
  159121. while( fts5_isdigit(*p) ) p++;
  159122. }
  159123. if( p==pIn ) p = 0;
  159124. break;
  159125. }
  159126. return p;
  159127. }
  159128. /*
  159129. ** The first character of the string pointed to by argument z is guaranteed
  159130. ** to be an open-quote character (see function fts5_isopenquote()).
  159131. **
  159132. ** This function searches for the corresponding close-quote character within
  159133. ** the string and, if found, dequotes the string in place and adds a new
  159134. ** nul-terminator byte.
  159135. **
  159136. ** If the close-quote is found, the value returned is the byte offset of
  159137. ** the character immediately following it. Or, if the close-quote is not
  159138. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  159139. ** undefined state.
  159140. */
  159141. static int fts5Dequote(char *z){
  159142. char q;
  159143. int iIn = 1;
  159144. int iOut = 0;
  159145. q = z[0];
  159146. /* Set stack variable q to the close-quote character */
  159147. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  159148. if( q=='[' ) q = ']';
  159149. while( ALWAYS(z[iIn]) ){
  159150. if( z[iIn]==q ){
  159151. if( z[iIn+1]!=q ){
  159152. /* Character iIn was the close quote. */
  159153. iIn++;
  159154. break;
  159155. }else{
  159156. /* Character iIn and iIn+1 form an escaped quote character. Skip
  159157. ** the input cursor past both and copy a single quote character
  159158. ** to the output buffer. */
  159159. iIn += 2;
  159160. z[iOut++] = q;
  159161. }
  159162. }else{
  159163. z[iOut++] = z[iIn++];
  159164. }
  159165. }
  159166. z[iOut] = '\0';
  159167. return iIn;
  159168. }
  159169. /*
  159170. ** Convert an SQL-style quoted string into a normal string by removing
  159171. ** the quote characters. The conversion is done in-place. If the
  159172. ** input does not begin with a quote character, then this routine
  159173. ** is a no-op.
  159174. **
  159175. ** Examples:
  159176. **
  159177. ** "abc" becomes abc
  159178. ** 'xyz' becomes xyz
  159179. ** [pqr] becomes pqr
  159180. ** `mno` becomes mno
  159181. */
  159182. static void sqlite3Fts5Dequote(char *z){
  159183. char quote; /* Quote character (if any ) */
  159184. assert( 0==fts5_iswhitespace(z[0]) );
  159185. quote = z[0];
  159186. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  159187. fts5Dequote(z);
  159188. }
  159189. }
  159190. /*
  159191. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  159192. ** configuration object pConfig as appropriate.
  159193. **
  159194. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  159195. ** an error occurs, an SQLite error code is returned and an error message
  159196. ** may be left in *pzErr. It is the responsibility of the caller to
  159197. ** eventually free any such error message using sqlite3_free().
  159198. */
  159199. static int fts5ConfigParseSpecial(
  159200. Fts5Global *pGlobal,
  159201. Fts5Config *pConfig, /* Configuration object to update */
  159202. const char *zCmd, /* Special command to parse */
  159203. const char *zArg, /* Argument to parse */
  159204. char **pzErr /* OUT: Error message */
  159205. ){
  159206. int rc = SQLITE_OK;
  159207. int nCmd = (int)strlen(zCmd);
  159208. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  159209. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  159210. const char *p;
  159211. int bFirst = 1;
  159212. if( pConfig->aPrefix==0 ){
  159213. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  159214. if( rc ) return rc;
  159215. }
  159216. p = zArg;
  159217. while( 1 ){
  159218. int nPre = 0;
  159219. while( p[0]==' ' ) p++;
  159220. if( bFirst==0 && p[0]==',' ){
  159221. p++;
  159222. while( p[0]==' ' ) p++;
  159223. }else if( p[0]=='\0' ){
  159224. break;
  159225. }
  159226. if( p[0]<'0' || p[0]>'9' ){
  159227. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  159228. rc = SQLITE_ERROR;
  159229. break;
  159230. }
  159231. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  159232. *pzErr = sqlite3_mprintf(
  159233. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  159234. );
  159235. rc = SQLITE_ERROR;
  159236. break;
  159237. }
  159238. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  159239. nPre = nPre*10 + (p[0] - '0');
  159240. p++;
  159241. }
  159242. if( rc==SQLITE_OK && (nPre<=0 || nPre>=1000) ){
  159243. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  159244. rc = SQLITE_ERROR;
  159245. break;
  159246. }
  159247. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  159248. pConfig->nPrefix++;
  159249. bFirst = 0;
  159250. }
  159251. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  159252. return rc;
  159253. }
  159254. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  159255. const char *p = (const char*)zArg;
  159256. int nArg = (int)strlen(zArg) + 1;
  159257. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  159258. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  159259. char *pSpace = pDel;
  159260. if( azArg && pSpace ){
  159261. if( pConfig->pTok ){
  159262. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  159263. rc = SQLITE_ERROR;
  159264. }else{
  159265. for(nArg=0; p && *p; nArg++){
  159266. const char *p2 = fts5ConfigSkipWhitespace(p);
  159267. if( *p2=='\'' ){
  159268. p = fts5ConfigSkipLiteral(p2);
  159269. }else{
  159270. p = fts5ConfigSkipBareword(p2);
  159271. }
  159272. if( p ){
  159273. memcpy(pSpace, p2, p-p2);
  159274. azArg[nArg] = pSpace;
  159275. sqlite3Fts5Dequote(pSpace);
  159276. pSpace += (p - p2) + 1;
  159277. p = fts5ConfigSkipWhitespace(p);
  159278. }
  159279. }
  159280. if( p==0 ){
  159281. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  159282. rc = SQLITE_ERROR;
  159283. }else{
  159284. rc = sqlite3Fts5GetTokenizer(pGlobal,
  159285. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  159286. pzErr
  159287. );
  159288. }
  159289. }
  159290. }
  159291. sqlite3_free(azArg);
  159292. sqlite3_free(pDel);
  159293. return rc;
  159294. }
  159295. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  159296. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  159297. *pzErr = sqlite3_mprintf("multiple content=... directives");
  159298. rc = SQLITE_ERROR;
  159299. }else{
  159300. if( zArg[0] ){
  159301. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  159302. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  159303. }else{
  159304. pConfig->eContent = FTS5_CONTENT_NONE;
  159305. }
  159306. }
  159307. return rc;
  159308. }
  159309. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  159310. if( pConfig->zContentRowid ){
  159311. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  159312. rc = SQLITE_ERROR;
  159313. }else{
  159314. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  159315. }
  159316. return rc;
  159317. }
  159318. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  159319. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  159320. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  159321. rc = SQLITE_ERROR;
  159322. }else{
  159323. pConfig->bColumnsize = (zArg[0]=='1');
  159324. }
  159325. return rc;
  159326. }
  159327. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  159328. return SQLITE_ERROR;
  159329. }
  159330. /*
  159331. ** Allocate an instance of the default tokenizer ("simple") at
  159332. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  159333. ** code if an error occurs.
  159334. */
  159335. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  159336. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  159337. return sqlite3Fts5GetTokenizer(
  159338. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  159339. );
  159340. }
  159341. /*
  159342. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  159343. ** Return a pointer to the character immediately following the last in
  159344. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  159345. ** to find close-quote character).
  159346. **
  159347. ** Before returning, set pzOut to point to a new buffer containing a
  159348. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  159349. ** quoted, *pbQuoted is also set to 1 before returning.
  159350. **
  159351. ** If *pRc is other than SQLITE_OK when this function is called, it is
  159352. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  159353. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  159354. ** set if a parse error (failed to find close quote) occurs.
  159355. */
  159356. static const char *fts5ConfigGobbleWord(
  159357. int *pRc, /* IN/OUT: Error code */
  159358. const char *zIn, /* Buffer to gobble string/bareword from */
  159359. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  159360. int *pbQuoted /* OUT: Set to true if dequoting required */
  159361. ){
  159362. const char *zRet = 0;
  159363. int nIn = (int)strlen(zIn);
  159364. char *zOut = sqlite3_malloc(nIn+1);
  159365. assert( *pRc==SQLITE_OK );
  159366. *pbQuoted = 0;
  159367. *pzOut = 0;
  159368. if( zOut==0 ){
  159369. *pRc = SQLITE_NOMEM;
  159370. }else{
  159371. memcpy(zOut, zIn, nIn+1);
  159372. if( fts5_isopenquote(zOut[0]) ){
  159373. int ii = fts5Dequote(zOut);
  159374. zRet = &zIn[ii];
  159375. *pbQuoted = 1;
  159376. }else{
  159377. zRet = fts5ConfigSkipBareword(zIn);
  159378. zOut[zRet-zIn] = '\0';
  159379. }
  159380. }
  159381. if( zRet==0 ){
  159382. sqlite3_free(zOut);
  159383. }else{
  159384. *pzOut = zOut;
  159385. }
  159386. return zRet;
  159387. }
  159388. static int fts5ConfigParseColumn(
  159389. Fts5Config *p,
  159390. char *zCol,
  159391. char *zArg,
  159392. char **pzErr
  159393. ){
  159394. int rc = SQLITE_OK;
  159395. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  159396. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  159397. ){
  159398. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  159399. rc = SQLITE_ERROR;
  159400. }else if( zArg ){
  159401. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  159402. p->abUnindexed[p->nCol] = 1;
  159403. }else{
  159404. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  159405. rc = SQLITE_ERROR;
  159406. }
  159407. }
  159408. p->azCol[p->nCol++] = zCol;
  159409. return rc;
  159410. }
  159411. /*
  159412. ** Populate the Fts5Config.zContentExprlist string.
  159413. */
  159414. static int fts5ConfigMakeExprlist(Fts5Config *p){
  159415. int i;
  159416. int rc = SQLITE_OK;
  159417. Fts5Buffer buf = {0, 0, 0};
  159418. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  159419. if( p->eContent!=FTS5_CONTENT_NONE ){
  159420. for(i=0; i<p->nCol; i++){
  159421. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  159422. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  159423. }else{
  159424. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  159425. }
  159426. }
  159427. }
  159428. assert( p->zContentExprlist==0 );
  159429. p->zContentExprlist = (char*)buf.p;
  159430. return rc;
  159431. }
  159432. /*
  159433. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  159434. ** or xConnect method of the virtual table. This function attempts to
  159435. ** allocate an instance of Fts5Config containing the results of parsing
  159436. ** those arguments.
  159437. **
  159438. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  159439. ** new Fts5Config object. If an error occurs, an SQLite error code is
  159440. ** returned, *ppOut is set to NULL and an error message may be left in
  159441. ** *pzErr. It is the responsibility of the caller to eventually free any
  159442. ** such error message using sqlite3_free().
  159443. */
  159444. static int sqlite3Fts5ConfigParse(
  159445. Fts5Global *pGlobal,
  159446. sqlite3 *db,
  159447. int nArg, /* Number of arguments */
  159448. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  159449. Fts5Config **ppOut, /* OUT: Results of parse */
  159450. char **pzErr /* OUT: Error message */
  159451. ){
  159452. int rc = SQLITE_OK; /* Return code */
  159453. Fts5Config *pRet; /* New object to return */
  159454. int i;
  159455. int nByte;
  159456. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  159457. if( pRet==0 ) return SQLITE_NOMEM;
  159458. memset(pRet, 0, sizeof(Fts5Config));
  159459. pRet->db = db;
  159460. pRet->iCookie = -1;
  159461. nByte = nArg * (sizeof(char*) + sizeof(u8));
  159462. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  159463. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  159464. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  159465. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  159466. pRet->bColumnsize = 1;
  159467. #ifdef SQLITE_DEBUG
  159468. pRet->bPrefixIndex = 1;
  159469. #endif
  159470. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  159471. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  159472. rc = SQLITE_ERROR;
  159473. }
  159474. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  159475. const char *zOrig = azArg[i];
  159476. const char *z;
  159477. char *zOne = 0;
  159478. char *zTwo = 0;
  159479. int bOption = 0;
  159480. int bMustBeCol = 0;
  159481. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  159482. z = fts5ConfigSkipWhitespace(z);
  159483. if( z && *z=='=' ){
  159484. bOption = 1;
  159485. z++;
  159486. if( bMustBeCol ) z = 0;
  159487. }
  159488. z = fts5ConfigSkipWhitespace(z);
  159489. if( z && z[0] ){
  159490. int bDummy;
  159491. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  159492. if( z && z[0] ) z = 0;
  159493. }
  159494. if( rc==SQLITE_OK ){
  159495. if( z==0 ){
  159496. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  159497. rc = SQLITE_ERROR;
  159498. }else{
  159499. if( bOption ){
  159500. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  159501. }else{
  159502. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  159503. zOne = 0;
  159504. }
  159505. }
  159506. }
  159507. sqlite3_free(zOne);
  159508. sqlite3_free(zTwo);
  159509. }
  159510. /* If a tokenizer= option was successfully parsed, the tokenizer has
  159511. ** already been allocated. Otherwise, allocate an instance of the default
  159512. ** tokenizer (unicode61) now. */
  159513. if( rc==SQLITE_OK && pRet->pTok==0 ){
  159514. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  159515. }
  159516. /* If no zContent option was specified, fill in the default values. */
  159517. if( rc==SQLITE_OK && pRet->zContent==0 ){
  159518. const char *zTail = 0;
  159519. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  159520. || pRet->eContent==FTS5_CONTENT_NONE
  159521. );
  159522. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  159523. zTail = "content";
  159524. }else if( pRet->bColumnsize ){
  159525. zTail = "docsize";
  159526. }
  159527. if( zTail ){
  159528. pRet->zContent = sqlite3Fts5Mprintf(
  159529. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  159530. );
  159531. }
  159532. }
  159533. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  159534. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  159535. }
  159536. /* Formulate the zContentExprlist text */
  159537. if( rc==SQLITE_OK ){
  159538. rc = fts5ConfigMakeExprlist(pRet);
  159539. }
  159540. if( rc!=SQLITE_OK ){
  159541. sqlite3Fts5ConfigFree(pRet);
  159542. *ppOut = 0;
  159543. }
  159544. return rc;
  159545. }
  159546. /*
  159547. ** Free the configuration object passed as the only argument.
  159548. */
  159549. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  159550. if( pConfig ){
  159551. int i;
  159552. if( pConfig->pTok ){
  159553. pConfig->pTokApi->xDelete(pConfig->pTok);
  159554. }
  159555. sqlite3_free(pConfig->zDb);
  159556. sqlite3_free(pConfig->zName);
  159557. for(i=0; i<pConfig->nCol; i++){
  159558. sqlite3_free(pConfig->azCol[i]);
  159559. }
  159560. sqlite3_free(pConfig->azCol);
  159561. sqlite3_free(pConfig->aPrefix);
  159562. sqlite3_free(pConfig->zRank);
  159563. sqlite3_free(pConfig->zRankArgs);
  159564. sqlite3_free(pConfig->zContent);
  159565. sqlite3_free(pConfig->zContentRowid);
  159566. sqlite3_free(pConfig->zContentExprlist);
  159567. sqlite3_free(pConfig);
  159568. }
  159569. }
  159570. /*
  159571. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  159572. ** object passed as the only argument. Return SQLITE_OK if successful, or
  159573. ** an SQLite error code if an error occurs.
  159574. */
  159575. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  159576. int i;
  159577. int rc = SQLITE_OK;
  159578. char *zSql;
  159579. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  159580. for(i=0; zSql && i<pConfig->nCol; i++){
  159581. const char *zSep = (i==0?"":", ");
  159582. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  159583. }
  159584. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  159585. zSql, pConfig->zName, FTS5_RANK_NAME
  159586. );
  159587. assert( zSql || rc==SQLITE_NOMEM );
  159588. if( zSql ){
  159589. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  159590. sqlite3_free(zSql);
  159591. }
  159592. return rc;
  159593. }
  159594. /*
  159595. ** Tokenize the text passed via the second and third arguments.
  159596. **
  159597. ** The callback is invoked once for each token in the input text. The
  159598. ** arguments passed to it are, in order:
  159599. **
  159600. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  159601. ** const char *pToken // Pointer to buffer containing token
  159602. ** int nToken // Size of token in bytes
  159603. ** int iStart // Byte offset of start of token within input text
  159604. ** int iEnd // Byte offset of end of token within input text
  159605. ** int iPos // Position of token in input (first token is 0)
  159606. **
  159607. ** If the callback returns a non-zero value the tokenization is abandoned
  159608. ** and no further callbacks are issued.
  159609. **
  159610. ** This function returns SQLITE_OK if successful or an SQLite error code
  159611. ** if an error occurs. If the tokenization was abandoned early because
  159612. ** the callback returned SQLITE_DONE, this is not an error and this function
  159613. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  159614. ** because the callback returned another non-zero value, it is assumed
  159615. ** to be an SQLite error code and returned to the caller.
  159616. */
  159617. static int sqlite3Fts5Tokenize(
  159618. Fts5Config *pConfig, /* FTS5 Configuration object */
  159619. int flags, /* FTS5_TOKENIZE_* flags */
  159620. const char *pText, int nText, /* Text to tokenize */
  159621. void *pCtx, /* Context passed to xToken() */
  159622. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  159623. ){
  159624. if( pText==0 ) return SQLITE_OK;
  159625. return pConfig->pTokApi->xTokenize(
  159626. pConfig->pTok, pCtx, flags, pText, nText, xToken
  159627. );
  159628. }
  159629. /*
  159630. ** Argument pIn points to the first character in what is expected to be
  159631. ** a comma-separated list of SQL literals followed by a ')' character.
  159632. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  159633. ** NULL to indicate a parse error.
  159634. */
  159635. static const char *fts5ConfigSkipArgs(const char *pIn){
  159636. const char *p = pIn;
  159637. while( 1 ){
  159638. p = fts5ConfigSkipWhitespace(p);
  159639. p = fts5ConfigSkipLiteral(p);
  159640. p = fts5ConfigSkipWhitespace(p);
  159641. if( p==0 || *p==')' ) break;
  159642. if( *p!=',' ){
  159643. p = 0;
  159644. break;
  159645. }
  159646. p++;
  159647. }
  159648. return p;
  159649. }
  159650. /*
  159651. ** Parameter zIn contains a rank() function specification. The format of
  159652. ** this is:
  159653. **
  159654. ** + Bareword (function name)
  159655. ** + Open parenthesis - "("
  159656. ** + Zero or more SQL literals in a comma separated list
  159657. ** + Close parenthesis - ")"
  159658. */
  159659. static int sqlite3Fts5ConfigParseRank(
  159660. const char *zIn, /* Input string */
  159661. char **pzRank, /* OUT: Rank function name */
  159662. char **pzRankArgs /* OUT: Rank function arguments */
  159663. ){
  159664. const char *p = zIn;
  159665. const char *pRank;
  159666. char *zRank = 0;
  159667. char *zRankArgs = 0;
  159668. int rc = SQLITE_OK;
  159669. *pzRank = 0;
  159670. *pzRankArgs = 0;
  159671. if( p==0 ){
  159672. rc = SQLITE_ERROR;
  159673. }else{
  159674. p = fts5ConfigSkipWhitespace(p);
  159675. pRank = p;
  159676. p = fts5ConfigSkipBareword(p);
  159677. if( p ){
  159678. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  159679. if( zRank ) memcpy(zRank, pRank, p-pRank);
  159680. }else{
  159681. rc = SQLITE_ERROR;
  159682. }
  159683. if( rc==SQLITE_OK ){
  159684. p = fts5ConfigSkipWhitespace(p);
  159685. if( *p!='(' ) rc = SQLITE_ERROR;
  159686. p++;
  159687. }
  159688. if( rc==SQLITE_OK ){
  159689. const char *pArgs;
  159690. p = fts5ConfigSkipWhitespace(p);
  159691. pArgs = p;
  159692. if( *p!=')' ){
  159693. p = fts5ConfigSkipArgs(p);
  159694. if( p==0 ){
  159695. rc = SQLITE_ERROR;
  159696. }else{
  159697. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  159698. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  159699. }
  159700. }
  159701. }
  159702. }
  159703. if( rc!=SQLITE_OK ){
  159704. sqlite3_free(zRank);
  159705. assert( zRankArgs==0 );
  159706. }else{
  159707. *pzRank = zRank;
  159708. *pzRankArgs = zRankArgs;
  159709. }
  159710. return rc;
  159711. }
  159712. static int sqlite3Fts5ConfigSetValue(
  159713. Fts5Config *pConfig,
  159714. const char *zKey,
  159715. sqlite3_value *pVal,
  159716. int *pbBadkey
  159717. ){
  159718. int rc = SQLITE_OK;
  159719. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  159720. int pgsz = 0;
  159721. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  159722. pgsz = sqlite3_value_int(pVal);
  159723. }
  159724. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  159725. *pbBadkey = 1;
  159726. }else{
  159727. pConfig->pgsz = pgsz;
  159728. }
  159729. }
  159730. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  159731. int nHashSize = -1;
  159732. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  159733. nHashSize = sqlite3_value_int(pVal);
  159734. }
  159735. if( nHashSize<=0 ){
  159736. *pbBadkey = 1;
  159737. }else{
  159738. pConfig->nHashSize = nHashSize;
  159739. }
  159740. }
  159741. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  159742. int nAutomerge = -1;
  159743. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  159744. nAutomerge = sqlite3_value_int(pVal);
  159745. }
  159746. if( nAutomerge<0 || nAutomerge>64 ){
  159747. *pbBadkey = 1;
  159748. }else{
  159749. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  159750. pConfig->nAutomerge = nAutomerge;
  159751. }
  159752. }
  159753. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  159754. int nCrisisMerge = -1;
  159755. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  159756. nCrisisMerge = sqlite3_value_int(pVal);
  159757. }
  159758. if( nCrisisMerge<0 ){
  159759. *pbBadkey = 1;
  159760. }else{
  159761. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  159762. pConfig->nCrisisMerge = nCrisisMerge;
  159763. }
  159764. }
  159765. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  159766. const char *zIn = (const char*)sqlite3_value_text(pVal);
  159767. char *zRank;
  159768. char *zRankArgs;
  159769. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  159770. if( rc==SQLITE_OK ){
  159771. sqlite3_free(pConfig->zRank);
  159772. sqlite3_free(pConfig->zRankArgs);
  159773. pConfig->zRank = zRank;
  159774. pConfig->zRankArgs = zRankArgs;
  159775. }else if( rc==SQLITE_ERROR ){
  159776. rc = SQLITE_OK;
  159777. *pbBadkey = 1;
  159778. }
  159779. }else{
  159780. *pbBadkey = 1;
  159781. }
  159782. return rc;
  159783. }
  159784. /*
  159785. ** Load the contents of the %_config table into memory.
  159786. */
  159787. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  159788. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  159789. char *zSql;
  159790. sqlite3_stmt *p = 0;
  159791. int rc = SQLITE_OK;
  159792. int iVersion = 0;
  159793. /* Set default values */
  159794. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  159795. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  159796. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  159797. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  159798. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  159799. if( zSql ){
  159800. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  159801. sqlite3_free(zSql);
  159802. }
  159803. assert( rc==SQLITE_OK || p==0 );
  159804. if( rc==SQLITE_OK ){
  159805. while( SQLITE_ROW==sqlite3_step(p) ){
  159806. const char *zK = (const char*)sqlite3_column_text(p, 0);
  159807. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  159808. if( 0==sqlite3_stricmp(zK, "version") ){
  159809. iVersion = sqlite3_value_int(pVal);
  159810. }else{
  159811. int bDummy = 0;
  159812. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  159813. }
  159814. }
  159815. rc = sqlite3_finalize(p);
  159816. }
  159817. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  159818. rc = SQLITE_ERROR;
  159819. if( pConfig->pzErrmsg ){
  159820. assert( 0==*pConfig->pzErrmsg );
  159821. *pConfig->pzErrmsg = sqlite3_mprintf(
  159822. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  159823. iVersion, FTS5_CURRENT_VERSION
  159824. );
  159825. }
  159826. }
  159827. if( rc==SQLITE_OK ){
  159828. pConfig->iCookie = iCookie;
  159829. }
  159830. return rc;
  159831. }
  159832. /*
  159833. ** 2014 May 31
  159834. **
  159835. ** The author disclaims copyright to this source code. In place of
  159836. ** a legal notice, here is a blessing:
  159837. **
  159838. ** May you do good and not evil.
  159839. ** May you find forgiveness for yourself and forgive others.
  159840. ** May you share freely, never taking more than you give.
  159841. **
  159842. ******************************************************************************
  159843. **
  159844. */
  159845. /* #include "fts5Int.h" */
  159846. /* #include "fts5parse.h" */
  159847. /*
  159848. ** All token types in the generated fts5parse.h file are greater than 0.
  159849. */
  159850. #define FTS5_EOF 0
  159851. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  159852. typedef struct Fts5ExprTerm Fts5ExprTerm;
  159853. /*
  159854. ** Functions generated by lemon from fts5parse.y.
  159855. */
  159856. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  159857. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  159858. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  159859. #ifndef NDEBUG
  159860. /* #include <stdio.h> */
  159861. static void sqlite3Fts5ParserTrace(FILE*, char*);
  159862. #endif
  159863. struct Fts5Expr {
  159864. Fts5Index *pIndex;
  159865. Fts5ExprNode *pRoot;
  159866. int bDesc; /* Iterate in descending rowid order */
  159867. int nPhrase; /* Number of phrases in expression */
  159868. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  159869. };
  159870. /*
  159871. ** eType:
  159872. ** Expression node type. Always one of:
  159873. **
  159874. ** FTS5_AND (nChild, apChild valid)
  159875. ** FTS5_OR (nChild, apChild valid)
  159876. ** FTS5_NOT (nChild, apChild valid)
  159877. ** FTS5_STRING (pNear valid)
  159878. ** FTS5_TERM (pNear valid)
  159879. */
  159880. struct Fts5ExprNode {
  159881. int eType; /* Node type */
  159882. int bEof; /* True at EOF */
  159883. int bNomatch; /* True if entry is not a match */
  159884. i64 iRowid; /* Current rowid */
  159885. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  159886. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  159887. ** AND or OR nodes, it contains 2 or more entries. */
  159888. int nChild; /* Number of child nodes */
  159889. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  159890. };
  159891. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  159892. /*
  159893. ** An instance of the following structure represents a single search term
  159894. ** or term prefix.
  159895. */
  159896. struct Fts5ExprTerm {
  159897. int bPrefix; /* True for a prefix term */
  159898. char *zTerm; /* nul-terminated term */
  159899. Fts5IndexIter *pIter; /* Iterator for this term */
  159900. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  159901. };
  159902. /*
  159903. ** A phrase. One or more terms that must appear in a contiguous sequence
  159904. ** within a document for it to match.
  159905. */
  159906. struct Fts5ExprPhrase {
  159907. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  159908. Fts5Buffer poslist; /* Current position list */
  159909. int nTerm; /* Number of entries in aTerm[] */
  159910. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  159911. };
  159912. /*
  159913. ** One or more phrases that must appear within a certain token distance of
  159914. ** each other within each matching document.
  159915. */
  159916. struct Fts5ExprNearset {
  159917. int nNear; /* NEAR parameter */
  159918. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  159919. int nPhrase; /* Number of entries in aPhrase[] array */
  159920. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  159921. };
  159922. /*
  159923. ** Parse context.
  159924. */
  159925. struct Fts5Parse {
  159926. Fts5Config *pConfig;
  159927. char *zErr;
  159928. int rc;
  159929. int nPhrase; /* Size of apPhrase array */
  159930. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  159931. Fts5ExprNode *pExpr; /* Result of a successful parse */
  159932. };
  159933. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  159934. va_list ap;
  159935. va_start(ap, zFmt);
  159936. if( pParse->rc==SQLITE_OK ){
  159937. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  159938. pParse->rc = SQLITE_ERROR;
  159939. }
  159940. va_end(ap);
  159941. }
  159942. static int fts5ExprIsspace(char t){
  159943. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  159944. }
  159945. /*
  159946. ** Read the first token from the nul-terminated string at *pz.
  159947. */
  159948. static int fts5ExprGetToken(
  159949. Fts5Parse *pParse,
  159950. const char **pz, /* IN/OUT: Pointer into buffer */
  159951. Fts5Token *pToken
  159952. ){
  159953. const char *z = *pz;
  159954. int tok;
  159955. /* Skip past any whitespace */
  159956. while( fts5ExprIsspace(*z) ) z++;
  159957. pToken->p = z;
  159958. pToken->n = 1;
  159959. switch( *z ){
  159960. case '(': tok = FTS5_LP; break;
  159961. case ')': tok = FTS5_RP; break;
  159962. case '{': tok = FTS5_LCP; break;
  159963. case '}': tok = FTS5_RCP; break;
  159964. case ':': tok = FTS5_COLON; break;
  159965. case ',': tok = FTS5_COMMA; break;
  159966. case '+': tok = FTS5_PLUS; break;
  159967. case '*': tok = FTS5_STAR; break;
  159968. case '\0': tok = FTS5_EOF; break;
  159969. case '"': {
  159970. const char *z2;
  159971. tok = FTS5_STRING;
  159972. for(z2=&z[1]; 1; z2++){
  159973. if( z2[0]=='"' ){
  159974. z2++;
  159975. if( z2[0]!='"' ) break;
  159976. }
  159977. if( z2[0]=='\0' ){
  159978. sqlite3Fts5ParseError(pParse, "unterminated string");
  159979. return FTS5_EOF;
  159980. }
  159981. }
  159982. pToken->n = (z2 - z);
  159983. break;
  159984. }
  159985. default: {
  159986. const char *z2;
  159987. if( sqlite3Fts5IsBareword(z[0])==0 ){
  159988. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  159989. return FTS5_EOF;
  159990. }
  159991. tok = FTS5_STRING;
  159992. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  159993. pToken->n = (z2 - z);
  159994. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  159995. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  159996. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  159997. break;
  159998. }
  159999. }
  160000. *pz = &pToken->p[pToken->n];
  160001. return tok;
  160002. }
  160003. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  160004. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  160005. static int sqlite3Fts5ExprNew(
  160006. Fts5Config *pConfig, /* FTS5 Configuration */
  160007. const char *zExpr, /* Expression text */
  160008. Fts5Expr **ppNew,
  160009. char **pzErr
  160010. ){
  160011. Fts5Parse sParse;
  160012. Fts5Token token;
  160013. const char *z = zExpr;
  160014. int t; /* Next token type */
  160015. void *pEngine;
  160016. Fts5Expr *pNew;
  160017. *ppNew = 0;
  160018. *pzErr = 0;
  160019. memset(&sParse, 0, sizeof(sParse));
  160020. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  160021. if( pEngine==0 ){ return SQLITE_NOMEM; }
  160022. sParse.pConfig = pConfig;
  160023. do {
  160024. t = fts5ExprGetToken(&sParse, &z, &token);
  160025. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  160026. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  160027. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  160028. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  160029. if( sParse.rc==SQLITE_OK ){
  160030. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  160031. if( pNew==0 ){
  160032. sParse.rc = SQLITE_NOMEM;
  160033. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  160034. }else{
  160035. pNew->pRoot = sParse.pExpr;
  160036. pNew->pIndex = 0;
  160037. pNew->apExprPhrase = sParse.apPhrase;
  160038. pNew->nPhrase = sParse.nPhrase;
  160039. sParse.apPhrase = 0;
  160040. }
  160041. }
  160042. sqlite3_free(sParse.apPhrase);
  160043. *pzErr = sParse.zErr;
  160044. return sParse.rc;
  160045. }
  160046. /*
  160047. ** Free the expression node object passed as the only argument.
  160048. */
  160049. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  160050. if( p ){
  160051. int i;
  160052. for(i=0; i<p->nChild; i++){
  160053. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  160054. }
  160055. sqlite3Fts5ParseNearsetFree(p->pNear);
  160056. sqlite3_free(p);
  160057. }
  160058. }
  160059. /*
  160060. ** Free the expression object passed as the only argument.
  160061. */
  160062. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  160063. if( p ){
  160064. sqlite3Fts5ParseNodeFree(p->pRoot);
  160065. sqlite3_free(p->apExprPhrase);
  160066. sqlite3_free(p);
  160067. }
  160068. }
  160069. /*
  160070. ** Argument pTerm must be a synonym iterator. Return the current rowid
  160071. ** that it points to.
  160072. */
  160073. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  160074. i64 iRet = 0;
  160075. int bRetValid = 0;
  160076. Fts5ExprTerm *p;
  160077. assert( pTerm->pSynonym );
  160078. assert( bDesc==0 || bDesc==1 );
  160079. for(p=pTerm; p; p=p->pSynonym){
  160080. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  160081. i64 iRowid = sqlite3Fts5IterRowid(p->pIter);
  160082. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  160083. iRet = iRowid;
  160084. bRetValid = 1;
  160085. }
  160086. }
  160087. }
  160088. if( pbEof && bRetValid==0 ) *pbEof = 1;
  160089. return iRet;
  160090. }
  160091. /*
  160092. ** Argument pTerm must be a synonym iterator.
  160093. */
  160094. static int fts5ExprSynonymPoslist(
  160095. Fts5ExprTerm *pTerm,
  160096. Fts5Colset *pColset,
  160097. i64 iRowid,
  160098. int *pbDel, /* OUT: Caller should sqlite3_free(*pa) */
  160099. u8 **pa, int *pn
  160100. ){
  160101. Fts5PoslistReader aStatic[4];
  160102. Fts5PoslistReader *aIter = aStatic;
  160103. int nIter = 0;
  160104. int nAlloc = 4;
  160105. int rc = SQLITE_OK;
  160106. Fts5ExprTerm *p;
  160107. assert( pTerm->pSynonym );
  160108. for(p=pTerm; p; p=p->pSynonym){
  160109. Fts5IndexIter *pIter = p->pIter;
  160110. if( sqlite3Fts5IterEof(pIter)==0 && sqlite3Fts5IterRowid(pIter)==iRowid ){
  160111. const u8 *a;
  160112. int n;
  160113. i64 dummy;
  160114. rc = sqlite3Fts5IterPoslist(pIter, pColset, &a, &n, &dummy);
  160115. if( rc!=SQLITE_OK ) goto synonym_poslist_out;
  160116. if( nIter==nAlloc ){
  160117. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  160118. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  160119. if( aNew==0 ){
  160120. rc = SQLITE_NOMEM;
  160121. goto synonym_poslist_out;
  160122. }
  160123. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  160124. nAlloc = nAlloc*2;
  160125. if( aIter!=aStatic ) sqlite3_free(aIter);
  160126. aIter = aNew;
  160127. }
  160128. sqlite3Fts5PoslistReaderInit(a, n, &aIter[nIter]);
  160129. assert( aIter[nIter].bEof==0 );
  160130. nIter++;
  160131. }
  160132. }
  160133. assert( *pbDel==0 );
  160134. if( nIter==1 ){
  160135. *pa = (u8*)aIter[0].a;
  160136. *pn = aIter[0].n;
  160137. }else{
  160138. Fts5PoslistWriter writer = {0};
  160139. Fts5Buffer buf = {0,0,0};
  160140. i64 iPrev = -1;
  160141. while( 1 ){
  160142. int i;
  160143. i64 iMin = FTS5_LARGEST_INT64;
  160144. for(i=0; i<nIter; i++){
  160145. if( aIter[i].bEof==0 ){
  160146. if( aIter[i].iPos==iPrev ){
  160147. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  160148. }
  160149. if( aIter[i].iPos<iMin ){
  160150. iMin = aIter[i].iPos;
  160151. }
  160152. }
  160153. }
  160154. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  160155. rc = sqlite3Fts5PoslistWriterAppend(&buf, &writer, iMin);
  160156. iPrev = iMin;
  160157. }
  160158. if( rc ){
  160159. sqlite3_free(buf.p);
  160160. }else{
  160161. *pa = buf.p;
  160162. *pn = buf.n;
  160163. *pbDel = 1;
  160164. }
  160165. }
  160166. synonym_poslist_out:
  160167. if( aIter!=aStatic ) sqlite3_free(aIter);
  160168. return rc;
  160169. }
  160170. /*
  160171. ** All individual term iterators in pPhrase are guaranteed to be valid and
  160172. ** pointing to the same rowid when this function is called. This function
  160173. ** checks if the current rowid really is a match, and if so populates
  160174. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  160175. ** is set to true if this is really a match, or false otherwise.
  160176. **
  160177. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  160178. ** otherwise. It is not considered an error code if the current rowid is
  160179. ** not a match.
  160180. */
  160181. static int fts5ExprPhraseIsMatch(
  160182. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  160183. Fts5Colset *pColset, /* Restrict matches to these columns */
  160184. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  160185. int *pbMatch /* OUT: Set to true if really a match */
  160186. ){
  160187. Fts5PoslistWriter writer = {0};
  160188. Fts5PoslistReader aStatic[4];
  160189. Fts5PoslistReader *aIter = aStatic;
  160190. int i;
  160191. int rc = SQLITE_OK;
  160192. fts5BufferZero(&pPhrase->poslist);
  160193. /* If the aStatic[] array is not large enough, allocate a large array
  160194. ** using sqlite3_malloc(). This approach could be improved upon. */
  160195. if( pPhrase->nTerm>(int)ArraySize(aStatic) ){
  160196. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  160197. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  160198. if( !aIter ) return SQLITE_NOMEM;
  160199. }
  160200. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  160201. /* Initialize a term iterator for each term in the phrase */
  160202. for(i=0; i<pPhrase->nTerm; i++){
  160203. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  160204. i64 dummy;
  160205. int n = 0;
  160206. int bFlag = 0;
  160207. const u8 *a = 0;
  160208. if( pTerm->pSynonym ){
  160209. rc = fts5ExprSynonymPoslist(
  160210. pTerm, pColset, pNode->iRowid, &bFlag, (u8**)&a, &n
  160211. );
  160212. }else{
  160213. rc = sqlite3Fts5IterPoslist(pTerm->pIter, pColset, &a, &n, &dummy);
  160214. }
  160215. if( rc!=SQLITE_OK ) goto ismatch_out;
  160216. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  160217. aIter[i].bFlag = (u8)bFlag;
  160218. if( aIter[i].bEof ) goto ismatch_out;
  160219. }
  160220. while( 1 ){
  160221. int bMatch;
  160222. i64 iPos = aIter[0].iPos;
  160223. do {
  160224. bMatch = 1;
  160225. for(i=0; i<pPhrase->nTerm; i++){
  160226. Fts5PoslistReader *pPos = &aIter[i];
  160227. i64 iAdj = iPos + i;
  160228. if( pPos->iPos!=iAdj ){
  160229. bMatch = 0;
  160230. while( pPos->iPos<iAdj ){
  160231. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  160232. }
  160233. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  160234. }
  160235. }
  160236. }while( bMatch==0 );
  160237. /* Append position iPos to the output */
  160238. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  160239. if( rc!=SQLITE_OK ) goto ismatch_out;
  160240. for(i=0; i<pPhrase->nTerm; i++){
  160241. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  160242. }
  160243. }
  160244. ismatch_out:
  160245. *pbMatch = (pPhrase->poslist.n>0);
  160246. for(i=0; i<pPhrase->nTerm; i++){
  160247. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  160248. }
  160249. if( aIter!=aStatic ) sqlite3_free(aIter);
  160250. return rc;
  160251. }
  160252. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  160253. struct Fts5LookaheadReader {
  160254. const u8 *a; /* Buffer containing position list */
  160255. int n; /* Size of buffer a[] in bytes */
  160256. int i; /* Current offset in position list */
  160257. i64 iPos; /* Current position */
  160258. i64 iLookahead; /* Next position */
  160259. };
  160260. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  160261. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  160262. p->iPos = p->iLookahead;
  160263. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  160264. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  160265. }
  160266. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  160267. }
  160268. static int fts5LookaheadReaderInit(
  160269. const u8 *a, int n, /* Buffer to read position list from */
  160270. Fts5LookaheadReader *p /* Iterator object to initialize */
  160271. ){
  160272. memset(p, 0, sizeof(Fts5LookaheadReader));
  160273. p->a = a;
  160274. p->n = n;
  160275. fts5LookaheadReaderNext(p);
  160276. return fts5LookaheadReaderNext(p);
  160277. }
  160278. #if 0
  160279. static int fts5LookaheadReaderEof(Fts5LookaheadReader *p){
  160280. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  160281. }
  160282. #endif
  160283. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  160284. struct Fts5NearTrimmer {
  160285. Fts5LookaheadReader reader; /* Input iterator */
  160286. Fts5PoslistWriter writer; /* Writer context */
  160287. Fts5Buffer *pOut; /* Output poslist */
  160288. };
  160289. /*
  160290. ** The near-set object passed as the first argument contains more than
  160291. ** one phrase. All phrases currently point to the same row. The
  160292. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  160293. ** tests if the current row contains instances of each phrase sufficiently
  160294. ** close together to meet the NEAR constraint. Non-zero is returned if it
  160295. ** does, or zero otherwise.
  160296. **
  160297. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  160298. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  160299. ** occurs within this function (*pRc) is set accordingly before returning.
  160300. ** The return value is undefined in both these cases.
  160301. **
  160302. ** If no error occurs and non-zero (a match) is returned, the position-list
  160303. ** of each phrase object is edited to contain only those entries that
  160304. ** meet the constraint before returning.
  160305. */
  160306. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  160307. Fts5NearTrimmer aStatic[4];
  160308. Fts5NearTrimmer *a = aStatic;
  160309. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  160310. int i;
  160311. int rc = *pRc;
  160312. int bMatch;
  160313. assert( pNear->nPhrase>1 );
  160314. /* If the aStatic[] array is not large enough, allocate a large array
  160315. ** using sqlite3_malloc(). This approach could be improved upon. */
  160316. if( pNear->nPhrase>(int)ArraySize(aStatic) ){
  160317. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  160318. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  160319. }else{
  160320. memset(aStatic, 0, sizeof(aStatic));
  160321. }
  160322. if( rc!=SQLITE_OK ){
  160323. *pRc = rc;
  160324. return 0;
  160325. }
  160326. /* Initialize a lookahead iterator for each phrase. After passing the
  160327. ** buffer and buffer size to the lookaside-reader init function, zero
  160328. ** the phrase poslist buffer. The new poslist for the phrase (containing
  160329. ** the same entries as the original with some entries removed on account
  160330. ** of the NEAR constraint) is written over the original even as it is
  160331. ** being read. This is safe as the entries for the new poslist are a
  160332. ** subset of the old, so it is not possible for data yet to be read to
  160333. ** be overwritten. */
  160334. for(i=0; i<pNear->nPhrase; i++){
  160335. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  160336. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  160337. pPoslist->n = 0;
  160338. a[i].pOut = pPoslist;
  160339. }
  160340. while( 1 ){
  160341. int iAdv;
  160342. i64 iMin;
  160343. i64 iMax;
  160344. /* This block advances the phrase iterators until they point to a set of
  160345. ** entries that together comprise a match. */
  160346. iMax = a[0].reader.iPos;
  160347. do {
  160348. bMatch = 1;
  160349. for(i=0; i<pNear->nPhrase; i++){
  160350. Fts5LookaheadReader *pPos = &a[i].reader;
  160351. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  160352. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  160353. bMatch = 0;
  160354. while( pPos->iPos<iMin ){
  160355. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  160356. }
  160357. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  160358. }
  160359. }
  160360. }while( bMatch==0 );
  160361. /* Add an entry to each output position list */
  160362. for(i=0; i<pNear->nPhrase; i++){
  160363. i64 iPos = a[i].reader.iPos;
  160364. Fts5PoslistWriter *pWriter = &a[i].writer;
  160365. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  160366. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  160367. }
  160368. }
  160369. iAdv = 0;
  160370. iMin = a[0].reader.iLookahead;
  160371. for(i=0; i<pNear->nPhrase; i++){
  160372. if( a[i].reader.iLookahead < iMin ){
  160373. iMin = a[i].reader.iLookahead;
  160374. iAdv = i;
  160375. }
  160376. }
  160377. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  160378. }
  160379. ismatch_out: {
  160380. int bRet = a[0].pOut->n>0;
  160381. *pRc = rc;
  160382. if( a!=aStatic ) sqlite3_free(a);
  160383. return bRet;
  160384. }
  160385. }
  160386. /*
  160387. ** Advance the first term iterator in the first phrase of pNear. Set output
  160388. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  160389. **
  160390. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  160391. ** occurs.
  160392. */
  160393. static int fts5ExprNearAdvanceFirst(
  160394. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  160395. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  160396. int bFromValid,
  160397. i64 iFrom
  160398. ){
  160399. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  160400. int rc = SQLITE_OK;
  160401. if( pTerm->pSynonym ){
  160402. int bEof = 1;
  160403. Fts5ExprTerm *p;
  160404. /* Find the firstest rowid any synonym points to. */
  160405. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  160406. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  160407. ** is valid - each iterator that points to a rowid before iFrom. */
  160408. for(p=pTerm; p; p=p->pSynonym){
  160409. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  160410. i64 ii = sqlite3Fts5IterRowid(p->pIter);
  160411. if( ii==iRowid
  160412. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  160413. ){
  160414. if( bFromValid ){
  160415. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  160416. }else{
  160417. rc = sqlite3Fts5IterNext(p->pIter);
  160418. }
  160419. if( rc!=SQLITE_OK ) break;
  160420. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  160421. bEof = 0;
  160422. }
  160423. }else{
  160424. bEof = 0;
  160425. }
  160426. }
  160427. }
  160428. /* Set the EOF flag if either all synonym iterators are at EOF or an
  160429. ** error has occurred. */
  160430. pNode->bEof = (rc || bEof);
  160431. }else{
  160432. Fts5IndexIter *pIter = pTerm->pIter;
  160433. assert( Fts5NodeIsString(pNode) );
  160434. if( bFromValid ){
  160435. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  160436. }else{
  160437. rc = sqlite3Fts5IterNext(pIter);
  160438. }
  160439. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  160440. }
  160441. return rc;
  160442. }
  160443. /*
  160444. ** Advance iterator pIter until it points to a value equal to or laster
  160445. ** than the initial value of *piLast. If this means the iterator points
  160446. ** to a value laster than *piLast, update *piLast to the new lastest value.
  160447. **
  160448. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  160449. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  160450. ** are set, return a non-zero value. Otherwise, return zero.
  160451. */
  160452. static int fts5ExprAdvanceto(
  160453. Fts5IndexIter *pIter, /* Iterator to advance */
  160454. int bDesc, /* True if iterator is "rowid DESC" */
  160455. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  160456. int *pRc, /* OUT: Error code */
  160457. int *pbEof /* OUT: Set to true if EOF */
  160458. ){
  160459. i64 iLast = *piLast;
  160460. i64 iRowid;
  160461. iRowid = sqlite3Fts5IterRowid(pIter);
  160462. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  160463. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  160464. if( rc || sqlite3Fts5IterEof(pIter) ){
  160465. *pRc = rc;
  160466. *pbEof = 1;
  160467. return 1;
  160468. }
  160469. iRowid = sqlite3Fts5IterRowid(pIter);
  160470. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  160471. }
  160472. *piLast = iRowid;
  160473. return 0;
  160474. }
  160475. static int fts5ExprSynonymAdvanceto(
  160476. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  160477. int bDesc, /* True if iterator is "rowid DESC" */
  160478. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  160479. int *pRc /* OUT: Error code */
  160480. ){
  160481. int rc = SQLITE_OK;
  160482. i64 iLast = *piLast;
  160483. Fts5ExprTerm *p;
  160484. int bEof = 0;
  160485. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  160486. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  160487. i64 iRowid = sqlite3Fts5IterRowid(p->pIter);
  160488. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  160489. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  160490. }
  160491. }
  160492. }
  160493. if( rc!=SQLITE_OK ){
  160494. *pRc = rc;
  160495. bEof = 1;
  160496. }else{
  160497. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  160498. }
  160499. return bEof;
  160500. }
  160501. static int fts5ExprNearTest(
  160502. int *pRc,
  160503. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  160504. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  160505. ){
  160506. Fts5ExprNearset *pNear = pNode->pNear;
  160507. int rc = *pRc;
  160508. int i;
  160509. /* Check that each phrase in the nearset matches the current row.
  160510. ** Populate the pPhrase->poslist buffers at the same time. If any
  160511. ** phrase is not a match, break out of the loop early. */
  160512. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  160513. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  160514. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
  160515. int bMatch = 0;
  160516. rc = fts5ExprPhraseIsMatch(pNode, pNear->pColset, pPhrase, &bMatch);
  160517. if( bMatch==0 ) break;
  160518. }else{
  160519. rc = sqlite3Fts5IterPoslistBuffer(
  160520. pPhrase->aTerm[0].pIter, &pPhrase->poslist
  160521. );
  160522. }
  160523. }
  160524. *pRc = rc;
  160525. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  160526. return 1;
  160527. }
  160528. return 0;
  160529. }
  160530. static int fts5ExprTokenTest(
  160531. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  160532. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  160533. ){
  160534. /* As this "NEAR" object is actually a single phrase that consists
  160535. ** of a single term only, grab pointers into the poslist managed by the
  160536. ** fts5_index.c iterator object. This is much faster than synthesizing
  160537. ** a new poslist the way we have to for more complicated phrase or NEAR
  160538. ** expressions. */
  160539. Fts5ExprNearset *pNear = pNode->pNear;
  160540. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  160541. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  160542. Fts5Colset *pColset = pNear->pColset;
  160543. int rc;
  160544. assert( pNode->eType==FTS5_TERM );
  160545. assert( pNear->nPhrase==1 && pPhrase->nTerm==1 );
  160546. assert( pPhrase->aTerm[0].pSynonym==0 );
  160547. rc = sqlite3Fts5IterPoslist(pIter, pColset,
  160548. (const u8**)&pPhrase->poslist.p, &pPhrase->poslist.n, &pNode->iRowid
  160549. );
  160550. pNode->bNomatch = (pPhrase->poslist.n==0);
  160551. return rc;
  160552. }
  160553. /*
  160554. ** All individual term iterators in pNear are guaranteed to be valid when
  160555. ** this function is called. This function checks if all term iterators
  160556. ** point to the same rowid, and if not, advances them until they do.
  160557. ** If an EOF is reached before this happens, *pbEof is set to true before
  160558. ** returning.
  160559. **
  160560. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  160561. ** otherwise. It is not considered an error code if an iterator reaches
  160562. ** EOF.
  160563. */
  160564. static int fts5ExprNearNextMatch(
  160565. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  160566. Fts5ExprNode *pNode
  160567. ){
  160568. Fts5ExprNearset *pNear = pNode->pNear;
  160569. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  160570. int rc = SQLITE_OK;
  160571. i64 iLast; /* Lastest rowid any iterator points to */
  160572. int i, j; /* Phrase and token index, respectively */
  160573. int bMatch; /* True if all terms are at the same rowid */
  160574. const int bDesc = pExpr->bDesc;
  160575. /* Check that this node should not be FTS5_TERM */
  160576. assert( pNear->nPhrase>1
  160577. || pNear->apPhrase[0]->nTerm>1
  160578. || pNear->apPhrase[0]->aTerm[0].pSynonym
  160579. );
  160580. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  160581. ** iterator skips through rowids in the default ascending order, this means
  160582. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  160583. ** means the minimum rowid. */
  160584. if( pLeft->aTerm[0].pSynonym ){
  160585. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  160586. }else{
  160587. iLast = sqlite3Fts5IterRowid(pLeft->aTerm[0].pIter);
  160588. }
  160589. do {
  160590. bMatch = 1;
  160591. for(i=0; i<pNear->nPhrase; i++){
  160592. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  160593. for(j=0; j<pPhrase->nTerm; j++){
  160594. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  160595. if( pTerm->pSynonym ){
  160596. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  160597. if( iRowid==iLast ) continue;
  160598. bMatch = 0;
  160599. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  160600. pNode->bEof = 1;
  160601. return rc;
  160602. }
  160603. }else{
  160604. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  160605. i64 iRowid = sqlite3Fts5IterRowid(pIter);
  160606. if( iRowid==iLast ) continue;
  160607. bMatch = 0;
  160608. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  160609. return rc;
  160610. }
  160611. }
  160612. }
  160613. }
  160614. }while( bMatch==0 );
  160615. pNode->iRowid = iLast;
  160616. pNode->bNomatch = (0==fts5ExprNearTest(&rc, pExpr, pNode));
  160617. return rc;
  160618. }
  160619. /*
  160620. ** Initialize all term iterators in the pNear object. If any term is found
  160621. ** to match no documents at all, return immediately without initializing any
  160622. ** further iterators.
  160623. */
  160624. static int fts5ExprNearInitAll(
  160625. Fts5Expr *pExpr,
  160626. Fts5ExprNode *pNode
  160627. ){
  160628. Fts5ExprNearset *pNear = pNode->pNear;
  160629. int i, j;
  160630. int rc = SQLITE_OK;
  160631. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  160632. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  160633. for(j=0; j<pPhrase->nTerm; j++){
  160634. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  160635. Fts5ExprTerm *p;
  160636. int bEof = 1;
  160637. for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
  160638. if( p->pIter ){
  160639. sqlite3Fts5IterClose(p->pIter);
  160640. p->pIter = 0;
  160641. }
  160642. rc = sqlite3Fts5IndexQuery(
  160643. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  160644. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  160645. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  160646. pNear->pColset,
  160647. &p->pIter
  160648. );
  160649. assert( rc==SQLITE_OK || p->pIter==0 );
  160650. if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
  160651. bEof = 0;
  160652. }
  160653. }
  160654. if( bEof ){
  160655. pNode->bEof = 1;
  160656. return rc;
  160657. }
  160658. }
  160659. }
  160660. return rc;
  160661. }
  160662. /* fts5ExprNodeNext() calls fts5ExprNodeNextMatch(). And vice-versa. */
  160663. static int fts5ExprNodeNextMatch(Fts5Expr*, Fts5ExprNode*);
  160664. /*
  160665. ** If pExpr is an ASC iterator, this function returns a value with the
  160666. ** same sign as:
  160667. **
  160668. ** (iLhs - iRhs)
  160669. **
  160670. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  160671. **
  160672. ** (iRhs - iLhs)
  160673. */
  160674. static int fts5RowidCmp(
  160675. Fts5Expr *pExpr,
  160676. i64 iLhs,
  160677. i64 iRhs
  160678. ){
  160679. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  160680. if( pExpr->bDesc==0 ){
  160681. if( iLhs<iRhs ) return -1;
  160682. return (iLhs > iRhs);
  160683. }else{
  160684. if( iLhs>iRhs ) return -1;
  160685. return (iLhs < iRhs);
  160686. }
  160687. }
  160688. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  160689. int i;
  160690. pNode->bEof = 1;
  160691. for(i=0; i<pNode->nChild; i++){
  160692. fts5ExprSetEof(pNode->apChild[i]);
  160693. }
  160694. }
  160695. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  160696. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  160697. Fts5ExprNearset *pNear = pNode->pNear;
  160698. int i;
  160699. for(i=0; i<pNear->nPhrase; i++){
  160700. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  160701. pPhrase->poslist.n = 0;
  160702. }
  160703. }else{
  160704. int i;
  160705. for(i=0; i<pNode->nChild; i++){
  160706. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  160707. }
  160708. }
  160709. }
  160710. static int fts5ExprNodeNext(Fts5Expr*, Fts5ExprNode*, int, i64);
  160711. /*
  160712. ** Argument pNode is an FTS5_AND node.
  160713. */
  160714. static int fts5ExprAndNextRowid(
  160715. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  160716. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  160717. ){
  160718. int iChild;
  160719. i64 iLast = pAnd->iRowid;
  160720. int rc = SQLITE_OK;
  160721. int bMatch;
  160722. assert( pAnd->bEof==0 );
  160723. do {
  160724. pAnd->bNomatch = 0;
  160725. bMatch = 1;
  160726. for(iChild=0; iChild<pAnd->nChild; iChild++){
  160727. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  160728. if( 0 && pChild->eType==FTS5_STRING ){
  160729. /* TODO */
  160730. }else{
  160731. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  160732. if( cmp>0 ){
  160733. /* Advance pChild until it points to iLast or laster */
  160734. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  160735. if( rc!=SQLITE_OK ) return rc;
  160736. }
  160737. }
  160738. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  160739. ** the child node is guaranteed to have advanced at least as far as
  160740. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  160741. ** new lastest rowid seen so far. */
  160742. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  160743. if( pChild->bEof ){
  160744. fts5ExprSetEof(pAnd);
  160745. bMatch = 1;
  160746. break;
  160747. }else if( iLast!=pChild->iRowid ){
  160748. bMatch = 0;
  160749. iLast = pChild->iRowid;
  160750. }
  160751. if( pChild->bNomatch ){
  160752. pAnd->bNomatch = 1;
  160753. }
  160754. }
  160755. }while( bMatch==0 );
  160756. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  160757. fts5ExprNodeZeroPoslist(pAnd);
  160758. }
  160759. pAnd->iRowid = iLast;
  160760. return SQLITE_OK;
  160761. }
  160762. /*
  160763. ** Compare the values currently indicated by the two nodes as follows:
  160764. **
  160765. ** res = (*p1) - (*p2)
  160766. **
  160767. ** Nodes that point to values that come later in the iteration order are
  160768. ** considered to be larger. Nodes at EOF are the largest of all.
  160769. **
  160770. ** This means that if the iteration order is ASC, then numerically larger
  160771. ** rowids are considered larger. Or if it is the default DESC, numerically
  160772. ** smaller rowids are larger.
  160773. */
  160774. static int fts5NodeCompare(
  160775. Fts5Expr *pExpr,
  160776. Fts5ExprNode *p1,
  160777. Fts5ExprNode *p2
  160778. ){
  160779. if( p2->bEof ) return -1;
  160780. if( p1->bEof ) return +1;
  160781. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  160782. }
  160783. /*
  160784. ** Advance node iterator pNode, part of expression pExpr. If argument
  160785. ** bFromValid is zero, then pNode is advanced exactly once. Or, if argument
  160786. ** bFromValid is non-zero, then pNode is advanced until it is at or past
  160787. ** rowid value iFrom. Whether "past" means "less than" or "greater than"
  160788. ** depends on whether this is an ASC or DESC iterator.
  160789. */
  160790. static int fts5ExprNodeNext(
  160791. Fts5Expr *pExpr,
  160792. Fts5ExprNode *pNode,
  160793. int bFromValid,
  160794. i64 iFrom
  160795. ){
  160796. int rc = SQLITE_OK;
  160797. if( pNode->bEof==0 ){
  160798. switch( pNode->eType ){
  160799. case FTS5_STRING: {
  160800. rc = fts5ExprNearAdvanceFirst(pExpr, pNode, bFromValid, iFrom);
  160801. break;
  160802. };
  160803. case FTS5_TERM: {
  160804. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  160805. if( bFromValid ){
  160806. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  160807. }else{
  160808. rc = sqlite3Fts5IterNext(pIter);
  160809. }
  160810. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  160811. assert( rc==SQLITE_OK );
  160812. rc = fts5ExprTokenTest(pExpr, pNode);
  160813. }else{
  160814. pNode->bEof = 1;
  160815. }
  160816. return rc;
  160817. };
  160818. case FTS5_AND: {
  160819. Fts5ExprNode *pLeft = pNode->apChild[0];
  160820. rc = fts5ExprNodeNext(pExpr, pLeft, bFromValid, iFrom);
  160821. break;
  160822. }
  160823. case FTS5_OR: {
  160824. int i;
  160825. i64 iLast = pNode->iRowid;
  160826. for(i=0; rc==SQLITE_OK && i<pNode->nChild; i++){
  160827. Fts5ExprNode *p1 = pNode->apChild[i];
  160828. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  160829. if( p1->bEof==0 ){
  160830. if( (p1->iRowid==iLast)
  160831. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  160832. ){
  160833. rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  160834. }
  160835. }
  160836. }
  160837. break;
  160838. }
  160839. default: assert( pNode->eType==FTS5_NOT ); {
  160840. assert( pNode->nChild==2 );
  160841. rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  160842. break;
  160843. }
  160844. }
  160845. if( rc==SQLITE_OK ){
  160846. rc = fts5ExprNodeNextMatch(pExpr, pNode);
  160847. }
  160848. }
  160849. /* Assert that if bFromValid was true, either:
  160850. **
  160851. ** a) an error occurred, or
  160852. ** b) the node is now at EOF, or
  160853. ** c) the node is now at or past rowid iFrom.
  160854. */
  160855. assert( bFromValid==0
  160856. || rc!=SQLITE_OK /* a */
  160857. || pNode->bEof /* b */
  160858. || pNode->iRowid==iFrom || pExpr->bDesc==(pNode->iRowid<iFrom) /* c */
  160859. );
  160860. return rc;
  160861. }
  160862. /*
  160863. ** If pNode currently points to a match, this function returns SQLITE_OK
  160864. ** without modifying it. Otherwise, pNode is advanced until it does point
  160865. ** to a match or EOF is reached.
  160866. */
  160867. static int fts5ExprNodeNextMatch(
  160868. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  160869. Fts5ExprNode *pNode /* Expression node to test */
  160870. ){
  160871. int rc = SQLITE_OK;
  160872. if( pNode->bEof==0 ){
  160873. switch( pNode->eType ){
  160874. case FTS5_STRING: {
  160875. /* Advance the iterators until they all point to the same rowid */
  160876. rc = fts5ExprNearNextMatch(pExpr, pNode);
  160877. break;
  160878. }
  160879. case FTS5_TERM: {
  160880. rc = fts5ExprTokenTest(pExpr, pNode);
  160881. break;
  160882. }
  160883. case FTS5_AND: {
  160884. rc = fts5ExprAndNextRowid(pExpr, pNode);
  160885. break;
  160886. }
  160887. case FTS5_OR: {
  160888. Fts5ExprNode *pNext = pNode->apChild[0];
  160889. int i;
  160890. for(i=1; i<pNode->nChild; i++){
  160891. Fts5ExprNode *pChild = pNode->apChild[i];
  160892. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  160893. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  160894. pNext = pChild;
  160895. }
  160896. }
  160897. pNode->iRowid = pNext->iRowid;
  160898. pNode->bEof = pNext->bEof;
  160899. pNode->bNomatch = pNext->bNomatch;
  160900. break;
  160901. }
  160902. default: assert( pNode->eType==FTS5_NOT ); {
  160903. Fts5ExprNode *p1 = pNode->apChild[0];
  160904. Fts5ExprNode *p2 = pNode->apChild[1];
  160905. assert( pNode->nChild==2 );
  160906. while( rc==SQLITE_OK && p1->bEof==0 ){
  160907. int cmp = fts5NodeCompare(pExpr, p1, p2);
  160908. if( cmp>0 ){
  160909. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  160910. cmp = fts5NodeCompare(pExpr, p1, p2);
  160911. }
  160912. assert( rc!=SQLITE_OK || cmp<=0 );
  160913. if( cmp || p2->bNomatch ) break;
  160914. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  160915. }
  160916. pNode->bEof = p1->bEof;
  160917. pNode->iRowid = p1->iRowid;
  160918. break;
  160919. }
  160920. }
  160921. }
  160922. return rc;
  160923. }
  160924. /*
  160925. ** Set node pNode, which is part of expression pExpr, to point to the first
  160926. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  160927. **
  160928. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  160929. ** It is not an error if there are no matches.
  160930. */
  160931. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  160932. int rc = SQLITE_OK;
  160933. pNode->bEof = 0;
  160934. if( Fts5NodeIsString(pNode) ){
  160935. /* Initialize all term iterators in the NEAR object. */
  160936. rc = fts5ExprNearInitAll(pExpr, pNode);
  160937. }else{
  160938. int i;
  160939. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  160940. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  160941. }
  160942. pNode->iRowid = pNode->apChild[0]->iRowid;
  160943. }
  160944. if( rc==SQLITE_OK ){
  160945. rc = fts5ExprNodeNextMatch(pExpr, pNode);
  160946. }
  160947. return rc;
  160948. }
  160949. /*
  160950. ** Begin iterating through the set of documents in index pIdx matched by
  160951. ** the MATCH expression passed as the first argument. If the "bDesc"
  160952. ** parameter is passed a non-zero value, iteration is in descending rowid
  160953. ** order. Or, if it is zero, in ascending order.
  160954. **
  160955. ** If iterating in ascending rowid order (bDesc==0), the first document
  160956. ** visited is that with the smallest rowid that is larger than or equal
  160957. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  160958. ** then the first document visited must have a rowid smaller than or
  160959. ** equal to iFirst.
  160960. **
  160961. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  160962. ** is not considered an error if the query does not match any documents.
  160963. */
  160964. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  160965. Fts5ExprNode *pRoot = p->pRoot;
  160966. int rc = SQLITE_OK;
  160967. if( pRoot ){
  160968. p->pIndex = pIdx;
  160969. p->bDesc = bDesc;
  160970. rc = fts5ExprNodeFirst(p, pRoot);
  160971. /* If not at EOF but the current rowid occurs earlier than iFirst in
  160972. ** the iteration order, move to document iFirst or later. */
  160973. if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
  160974. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  160975. }
  160976. /* If the iterator is not at a real match, skip forward until it is. */
  160977. while( pRoot->bNomatch && rc==SQLITE_OK && pRoot->bEof==0 ){
  160978. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  160979. }
  160980. }
  160981. return rc;
  160982. }
  160983. /*
  160984. ** Move to the next document
  160985. **
  160986. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  160987. ** is not considered an error if the query does not match any documents.
  160988. */
  160989. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  160990. int rc;
  160991. Fts5ExprNode *pRoot = p->pRoot;
  160992. do {
  160993. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  160994. }while( pRoot->bNomatch && pRoot->bEof==0 && rc==SQLITE_OK );
  160995. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  160996. pRoot->bEof = 1;
  160997. }
  160998. return rc;
  160999. }
  161000. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  161001. return (p->pRoot==0 || p->pRoot->bEof);
  161002. }
  161003. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  161004. return p->pRoot->iRowid;
  161005. }
  161006. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  161007. int rc = SQLITE_OK;
  161008. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  161009. return rc;
  161010. }
  161011. /*
  161012. ** Free the phrase object passed as the only argument.
  161013. */
  161014. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  161015. if( pPhrase ){
  161016. int i;
  161017. for(i=0; i<pPhrase->nTerm; i++){
  161018. Fts5ExprTerm *pSyn;
  161019. Fts5ExprTerm *pNext;
  161020. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  161021. sqlite3_free(pTerm->zTerm);
  161022. sqlite3Fts5IterClose(pTerm->pIter);
  161023. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  161024. pNext = pSyn->pSynonym;
  161025. sqlite3Fts5IterClose(pSyn->pIter);
  161026. sqlite3_free(pSyn);
  161027. }
  161028. }
  161029. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  161030. sqlite3_free(pPhrase);
  161031. }
  161032. }
  161033. /*
  161034. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  161035. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  161036. ** appended to it and the results returned.
  161037. **
  161038. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  161039. ** NULL returned.
  161040. */
  161041. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  161042. Fts5Parse *pParse, /* Parse context */
  161043. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  161044. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  161045. ){
  161046. const int SZALLOC = 8;
  161047. Fts5ExprNearset *pRet = 0;
  161048. if( pParse->rc==SQLITE_OK ){
  161049. if( pPhrase==0 ){
  161050. return pNear;
  161051. }
  161052. if( pNear==0 ){
  161053. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  161054. pRet = sqlite3_malloc(nByte);
  161055. if( pRet==0 ){
  161056. pParse->rc = SQLITE_NOMEM;
  161057. }else{
  161058. memset(pRet, 0, nByte);
  161059. }
  161060. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  161061. int nNew = pNear->nPhrase + SZALLOC;
  161062. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  161063. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  161064. if( pRet==0 ){
  161065. pParse->rc = SQLITE_NOMEM;
  161066. }
  161067. }else{
  161068. pRet = pNear;
  161069. }
  161070. }
  161071. if( pRet==0 ){
  161072. assert( pParse->rc!=SQLITE_OK );
  161073. sqlite3Fts5ParseNearsetFree(pNear);
  161074. sqlite3Fts5ParsePhraseFree(pPhrase);
  161075. }else{
  161076. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  161077. }
  161078. return pRet;
  161079. }
  161080. typedef struct TokenCtx TokenCtx;
  161081. struct TokenCtx {
  161082. Fts5ExprPhrase *pPhrase;
  161083. int rc;
  161084. };
  161085. /*
  161086. ** Callback for tokenizing terms used by ParseTerm().
  161087. */
  161088. static int fts5ParseTokenize(
  161089. void *pContext, /* Pointer to Fts5InsertCtx object */
  161090. int tflags, /* Mask of FTS5_TOKEN_* flags */
  161091. const char *pToken, /* Buffer containing token */
  161092. int nToken, /* Size of token in bytes */
  161093. int iUnused1, /* Start offset of token */
  161094. int iUnused2 /* End offset of token */
  161095. ){
  161096. int rc = SQLITE_OK;
  161097. const int SZALLOC = 8;
  161098. TokenCtx *pCtx = (TokenCtx*)pContext;
  161099. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  161100. /* If an error has already occurred, this is a no-op */
  161101. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  161102. assert( pPhrase==0 || pPhrase->nTerm>0 );
  161103. if( pPhrase && (tflags & FTS5_TOKEN_COLOCATED) ){
  161104. Fts5ExprTerm *pSyn;
  161105. int nByte = sizeof(Fts5ExprTerm) + nToken+1;
  161106. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  161107. if( pSyn==0 ){
  161108. rc = SQLITE_NOMEM;
  161109. }else{
  161110. memset(pSyn, 0, nByte);
  161111. pSyn->zTerm = (char*)&pSyn[1];
  161112. memcpy(pSyn->zTerm, pToken, nToken);
  161113. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  161114. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  161115. }
  161116. }else{
  161117. Fts5ExprTerm *pTerm;
  161118. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  161119. Fts5ExprPhrase *pNew;
  161120. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  161121. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  161122. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  161123. );
  161124. if( pNew==0 ){
  161125. rc = SQLITE_NOMEM;
  161126. }else{
  161127. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  161128. pCtx->pPhrase = pPhrase = pNew;
  161129. pNew->nTerm = nNew - SZALLOC;
  161130. }
  161131. }
  161132. if( rc==SQLITE_OK ){
  161133. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  161134. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  161135. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  161136. }
  161137. }
  161138. pCtx->rc = rc;
  161139. return rc;
  161140. }
  161141. /*
  161142. ** Free the phrase object passed as the only argument.
  161143. */
  161144. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  161145. fts5ExprPhraseFree(pPhrase);
  161146. }
  161147. /*
  161148. ** Free the phrase object passed as the second argument.
  161149. */
  161150. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  161151. if( pNear ){
  161152. int i;
  161153. for(i=0; i<pNear->nPhrase; i++){
  161154. fts5ExprPhraseFree(pNear->apPhrase[i]);
  161155. }
  161156. sqlite3_free(pNear->pColset);
  161157. sqlite3_free(pNear);
  161158. }
  161159. }
  161160. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  161161. assert( pParse->pExpr==0 );
  161162. pParse->pExpr = p;
  161163. }
  161164. /*
  161165. ** This function is called by the parser to process a string token. The
  161166. ** string may or may not be quoted. In any case it is tokenized and a
  161167. ** phrase object consisting of all tokens returned.
  161168. */
  161169. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  161170. Fts5Parse *pParse, /* Parse context */
  161171. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  161172. Fts5Token *pToken, /* String to tokenize */
  161173. int bPrefix /* True if there is a trailing "*" */
  161174. ){
  161175. Fts5Config *pConfig = pParse->pConfig;
  161176. TokenCtx sCtx; /* Context object passed to callback */
  161177. int rc; /* Tokenize return code */
  161178. char *z = 0;
  161179. memset(&sCtx, 0, sizeof(TokenCtx));
  161180. sCtx.pPhrase = pAppend;
  161181. rc = fts5ParseStringFromToken(pToken, &z);
  161182. if( rc==SQLITE_OK ){
  161183. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
  161184. int n;
  161185. sqlite3Fts5Dequote(z);
  161186. n = (int)strlen(z);
  161187. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  161188. }
  161189. sqlite3_free(z);
  161190. if( rc || (rc = sCtx.rc) ){
  161191. pParse->rc = rc;
  161192. fts5ExprPhraseFree(sCtx.pPhrase);
  161193. sCtx.pPhrase = 0;
  161194. }else if( sCtx.pPhrase ){
  161195. if( pAppend==0 ){
  161196. if( (pParse->nPhrase % 8)==0 ){
  161197. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  161198. Fts5ExprPhrase **apNew;
  161199. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  161200. if( apNew==0 ){
  161201. pParse->rc = SQLITE_NOMEM;
  161202. fts5ExprPhraseFree(sCtx.pPhrase);
  161203. return 0;
  161204. }
  161205. pParse->apPhrase = apNew;
  161206. }
  161207. pParse->nPhrase++;
  161208. }
  161209. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  161210. assert( sCtx.pPhrase->nTerm>0 );
  161211. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
  161212. }
  161213. return sCtx.pPhrase;
  161214. }
  161215. /*
  161216. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  161217. ** expression passed as the second argument.
  161218. */
  161219. static int sqlite3Fts5ExprClonePhrase(
  161220. Fts5Config *pConfig,
  161221. Fts5Expr *pExpr,
  161222. int iPhrase,
  161223. Fts5Expr **ppNew
  161224. ){
  161225. int rc = SQLITE_OK; /* Return code */
  161226. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  161227. int i; /* Used to iterate through phrase terms */
  161228. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  161229. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  161230. pOrig = pExpr->apExprPhrase[iPhrase];
  161231. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  161232. if( rc==SQLITE_OK ){
  161233. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  161234. sizeof(Fts5ExprPhrase*));
  161235. }
  161236. if( rc==SQLITE_OK ){
  161237. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  161238. sizeof(Fts5ExprNode));
  161239. }
  161240. if( rc==SQLITE_OK ){
  161241. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  161242. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  161243. }
  161244. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  161245. int tflags = 0;
  161246. Fts5ExprTerm *p;
  161247. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  161248. const char *zTerm = p->zTerm;
  161249. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  161250. 0, 0);
  161251. tflags = FTS5_TOKEN_COLOCATED;
  161252. }
  161253. if( rc==SQLITE_OK ){
  161254. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  161255. }
  161256. }
  161257. if( rc==SQLITE_OK ){
  161258. /* All the allocations succeeded. Put the expression object together. */
  161259. pNew->pIndex = pExpr->pIndex;
  161260. pNew->nPhrase = 1;
  161261. pNew->apExprPhrase[0] = sCtx.pPhrase;
  161262. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  161263. pNew->pRoot->pNear->nPhrase = 1;
  161264. sCtx.pPhrase->pNode = pNew->pRoot;
  161265. if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
  161266. pNew->pRoot->eType = FTS5_TERM;
  161267. }else{
  161268. pNew->pRoot->eType = FTS5_STRING;
  161269. }
  161270. }else{
  161271. sqlite3Fts5ExprFree(pNew);
  161272. fts5ExprPhraseFree(sCtx.pPhrase);
  161273. pNew = 0;
  161274. }
  161275. *ppNew = pNew;
  161276. return rc;
  161277. }
  161278. /*
  161279. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  161280. ** is expected. If token pTok does not contain "NEAR", store an error
  161281. ** in the pParse object.
  161282. */
  161283. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  161284. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  161285. sqlite3Fts5ParseError(
  161286. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  161287. );
  161288. }
  161289. }
  161290. static void sqlite3Fts5ParseSetDistance(
  161291. Fts5Parse *pParse,
  161292. Fts5ExprNearset *pNear,
  161293. Fts5Token *p
  161294. ){
  161295. int nNear = 0;
  161296. int i;
  161297. if( p->n ){
  161298. for(i=0; i<p->n; i++){
  161299. char c = (char)p->p[i];
  161300. if( c<'0' || c>'9' ){
  161301. sqlite3Fts5ParseError(
  161302. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  161303. );
  161304. return;
  161305. }
  161306. nNear = nNear * 10 + (p->p[i] - '0');
  161307. }
  161308. }else{
  161309. nNear = FTS5_DEFAULT_NEARDIST;
  161310. }
  161311. pNear->nNear = nNear;
  161312. }
  161313. /*
  161314. ** The second argument passed to this function may be NULL, or it may be
  161315. ** an existing Fts5Colset object. This function returns a pointer to
  161316. ** a new colset object containing the contents of (p) with new value column
  161317. ** number iCol appended.
  161318. **
  161319. ** If an OOM error occurs, store an error code in pParse and return NULL.
  161320. ** The old colset object (if any) is not freed in this case.
  161321. */
  161322. static Fts5Colset *fts5ParseColset(
  161323. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  161324. Fts5Colset *p, /* Existing colset object */
  161325. int iCol /* New column to add to colset object */
  161326. ){
  161327. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  161328. Fts5Colset *pNew; /* New colset object to return */
  161329. assert( pParse->rc==SQLITE_OK );
  161330. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  161331. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  161332. if( pNew==0 ){
  161333. pParse->rc = SQLITE_NOMEM;
  161334. }else{
  161335. int *aiCol = pNew->aiCol;
  161336. int i, j;
  161337. for(i=0; i<nCol; i++){
  161338. if( aiCol[i]==iCol ) return pNew;
  161339. if( aiCol[i]>iCol ) break;
  161340. }
  161341. for(j=nCol; j>i; j--){
  161342. aiCol[j] = aiCol[j-1];
  161343. }
  161344. aiCol[i] = iCol;
  161345. pNew->nCol = nCol+1;
  161346. #ifndef NDEBUG
  161347. /* Check that the array is in order and contains no duplicate entries. */
  161348. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  161349. #endif
  161350. }
  161351. return pNew;
  161352. }
  161353. static Fts5Colset *sqlite3Fts5ParseColset(
  161354. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  161355. Fts5Colset *pColset, /* Existing colset object */
  161356. Fts5Token *p
  161357. ){
  161358. Fts5Colset *pRet = 0;
  161359. int iCol;
  161360. char *z; /* Dequoted copy of token p */
  161361. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  161362. if( pParse->rc==SQLITE_OK ){
  161363. Fts5Config *pConfig = pParse->pConfig;
  161364. sqlite3Fts5Dequote(z);
  161365. for(iCol=0; iCol<pConfig->nCol; iCol++){
  161366. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  161367. }
  161368. if( iCol==pConfig->nCol ){
  161369. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  161370. }else{
  161371. pRet = fts5ParseColset(pParse, pColset, iCol);
  161372. }
  161373. sqlite3_free(z);
  161374. }
  161375. if( pRet==0 ){
  161376. assert( pParse->rc!=SQLITE_OK );
  161377. sqlite3_free(pColset);
  161378. }
  161379. return pRet;
  161380. }
  161381. static void sqlite3Fts5ParseSetColset(
  161382. Fts5Parse *pParse,
  161383. Fts5ExprNearset *pNear,
  161384. Fts5Colset *pColset
  161385. ){
  161386. if( pNear ){
  161387. pNear->pColset = pColset;
  161388. }else{
  161389. sqlite3_free(pColset);
  161390. }
  161391. }
  161392. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  161393. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  161394. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  161395. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  161396. p->nChild += pSub->nChild;
  161397. sqlite3_free(pSub);
  161398. }else{
  161399. p->apChild[p->nChild++] = pSub;
  161400. }
  161401. }
  161402. /*
  161403. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  161404. ** OOM error), leave an error code in pParse and return NULL.
  161405. */
  161406. static Fts5ExprNode *sqlite3Fts5ParseNode(
  161407. Fts5Parse *pParse, /* Parse context */
  161408. int eType, /* FTS5_STRING, AND, OR or NOT */
  161409. Fts5ExprNode *pLeft, /* Left hand child expression */
  161410. Fts5ExprNode *pRight, /* Right hand child expression */
  161411. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  161412. ){
  161413. Fts5ExprNode *pRet = 0;
  161414. if( pParse->rc==SQLITE_OK ){
  161415. int nChild = 0; /* Number of children of returned node */
  161416. int nByte; /* Bytes of space to allocate for this node */
  161417. assert( (eType!=FTS5_STRING && !pNear)
  161418. || (eType==FTS5_STRING && !pLeft && !pRight)
  161419. );
  161420. if( eType==FTS5_STRING && pNear==0 ) return 0;
  161421. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  161422. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  161423. if( eType==FTS5_NOT ){
  161424. nChild = 2;
  161425. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  161426. nChild = 2;
  161427. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  161428. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  161429. }
  161430. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  161431. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  161432. if( pRet ){
  161433. pRet->eType = eType;
  161434. pRet->pNear = pNear;
  161435. if( eType==FTS5_STRING ){
  161436. int iPhrase;
  161437. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  161438. pNear->apPhrase[iPhrase]->pNode = pRet;
  161439. }
  161440. if( pNear->nPhrase==1
  161441. && pNear->apPhrase[0]->nTerm==1
  161442. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  161443. ){
  161444. pRet->eType = FTS5_TERM;
  161445. }
  161446. }else{
  161447. fts5ExprAddChildren(pRet, pLeft);
  161448. fts5ExprAddChildren(pRet, pRight);
  161449. }
  161450. }
  161451. }
  161452. if( pRet==0 ){
  161453. assert( pParse->rc!=SQLITE_OK );
  161454. sqlite3Fts5ParseNodeFree(pLeft);
  161455. sqlite3Fts5ParseNodeFree(pRight);
  161456. sqlite3Fts5ParseNearsetFree(pNear);
  161457. }
  161458. return pRet;
  161459. }
  161460. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  161461. int nByte = 0;
  161462. Fts5ExprTerm *p;
  161463. char *zQuoted;
  161464. /* Determine the maximum amount of space required. */
  161465. for(p=pTerm; p; p=p->pSynonym){
  161466. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  161467. }
  161468. zQuoted = sqlite3_malloc(nByte);
  161469. if( zQuoted ){
  161470. int i = 0;
  161471. for(p=pTerm; p; p=p->pSynonym){
  161472. char *zIn = p->zTerm;
  161473. zQuoted[i++] = '"';
  161474. while( *zIn ){
  161475. if( *zIn=='"' ) zQuoted[i++] = '"';
  161476. zQuoted[i++] = *zIn++;
  161477. }
  161478. zQuoted[i++] = '"';
  161479. if( p->pSynonym ) zQuoted[i++] = '|';
  161480. }
  161481. if( pTerm->bPrefix ){
  161482. zQuoted[i++] = ' ';
  161483. zQuoted[i++] = '*';
  161484. }
  161485. zQuoted[i++] = '\0';
  161486. }
  161487. return zQuoted;
  161488. }
  161489. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  161490. char *zNew;
  161491. va_list ap;
  161492. va_start(ap, zFmt);
  161493. zNew = sqlite3_vmprintf(zFmt, ap);
  161494. va_end(ap);
  161495. if( zApp && zNew ){
  161496. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  161497. sqlite3_free(zNew);
  161498. zNew = zNew2;
  161499. }
  161500. sqlite3_free(zApp);
  161501. return zNew;
  161502. }
  161503. /*
  161504. ** Compose a tcl-readable representation of expression pExpr. Return a
  161505. ** pointer to a buffer containing that representation. It is the
  161506. ** responsibility of the caller to at some point free the buffer using
  161507. ** sqlite3_free().
  161508. */
  161509. static char *fts5ExprPrintTcl(
  161510. Fts5Config *pConfig,
  161511. const char *zNearsetCmd,
  161512. Fts5ExprNode *pExpr
  161513. ){
  161514. char *zRet = 0;
  161515. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  161516. Fts5ExprNearset *pNear = pExpr->pNear;
  161517. int i;
  161518. int iTerm;
  161519. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  161520. if( zRet==0 ) return 0;
  161521. if( pNear->pColset ){
  161522. int *aiCol = pNear->pColset->aiCol;
  161523. int nCol = pNear->pColset->nCol;
  161524. if( nCol==1 ){
  161525. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  161526. }else{
  161527. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  161528. for(i=1; i<pNear->pColset->nCol; i++){
  161529. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  161530. }
  161531. zRet = fts5PrintfAppend(zRet, "} ");
  161532. }
  161533. if( zRet==0 ) return 0;
  161534. }
  161535. if( pNear->nPhrase>1 ){
  161536. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  161537. if( zRet==0 ) return 0;
  161538. }
  161539. zRet = fts5PrintfAppend(zRet, "--");
  161540. if( zRet==0 ) return 0;
  161541. for(i=0; i<pNear->nPhrase; i++){
  161542. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  161543. zRet = fts5PrintfAppend(zRet, " {");
  161544. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  161545. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  161546. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  161547. }
  161548. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  161549. if( zRet==0 ) return 0;
  161550. }
  161551. }else{
  161552. char const *zOp = 0;
  161553. int i;
  161554. switch( pExpr->eType ){
  161555. case FTS5_AND: zOp = "AND"; break;
  161556. case FTS5_NOT: zOp = "NOT"; break;
  161557. default:
  161558. assert( pExpr->eType==FTS5_OR );
  161559. zOp = "OR";
  161560. break;
  161561. }
  161562. zRet = sqlite3_mprintf("%s", zOp);
  161563. for(i=0; zRet && i<pExpr->nChild; i++){
  161564. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  161565. if( !z ){
  161566. sqlite3_free(zRet);
  161567. zRet = 0;
  161568. }else{
  161569. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  161570. }
  161571. }
  161572. }
  161573. return zRet;
  161574. }
  161575. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  161576. char *zRet = 0;
  161577. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  161578. Fts5ExprNearset *pNear = pExpr->pNear;
  161579. int i;
  161580. int iTerm;
  161581. if( pNear->pColset ){
  161582. int iCol = pNear->pColset->aiCol[0];
  161583. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  161584. if( zRet==0 ) return 0;
  161585. }
  161586. if( pNear->nPhrase>1 ){
  161587. zRet = fts5PrintfAppend(zRet, "NEAR(");
  161588. if( zRet==0 ) return 0;
  161589. }
  161590. for(i=0; i<pNear->nPhrase; i++){
  161591. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  161592. if( i!=0 ){
  161593. zRet = fts5PrintfAppend(zRet, " ");
  161594. if( zRet==0 ) return 0;
  161595. }
  161596. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  161597. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  161598. if( zTerm ){
  161599. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  161600. sqlite3_free(zTerm);
  161601. }
  161602. if( zTerm==0 || zRet==0 ){
  161603. sqlite3_free(zRet);
  161604. return 0;
  161605. }
  161606. }
  161607. }
  161608. if( pNear->nPhrase>1 ){
  161609. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  161610. if( zRet==0 ) return 0;
  161611. }
  161612. }else{
  161613. char const *zOp = 0;
  161614. int i;
  161615. switch( pExpr->eType ){
  161616. case FTS5_AND: zOp = " AND "; break;
  161617. case FTS5_NOT: zOp = " NOT "; break;
  161618. default:
  161619. assert( pExpr->eType==FTS5_OR );
  161620. zOp = " OR ";
  161621. break;
  161622. }
  161623. for(i=0; i<pExpr->nChild; i++){
  161624. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  161625. if( z==0 ){
  161626. sqlite3_free(zRet);
  161627. zRet = 0;
  161628. }else{
  161629. int e = pExpr->apChild[i]->eType;
  161630. int b = (e!=FTS5_STRING && e!=FTS5_TERM);
  161631. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  161632. (i==0 ? "" : zOp),
  161633. (b?"(":""), z, (b?")":"")
  161634. );
  161635. }
  161636. if( zRet==0 ) break;
  161637. }
  161638. }
  161639. return zRet;
  161640. }
  161641. /*
  161642. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  161643. ** and fts5_expr_tcl() (bTcl!=0).
  161644. */
  161645. static void fts5ExprFunction(
  161646. sqlite3_context *pCtx, /* Function call context */
  161647. int nArg, /* Number of args */
  161648. sqlite3_value **apVal, /* Function arguments */
  161649. int bTcl
  161650. ){
  161651. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  161652. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  161653. const char *zExpr = 0;
  161654. char *zErr = 0;
  161655. Fts5Expr *pExpr = 0;
  161656. int rc;
  161657. int i;
  161658. const char **azConfig; /* Array of arguments for Fts5Config */
  161659. const char *zNearsetCmd = "nearset";
  161660. int nConfig; /* Size of azConfig[] */
  161661. Fts5Config *pConfig = 0;
  161662. int iArg = 1;
  161663. if( nArg<1 ){
  161664. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  161665. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  161666. );
  161667. sqlite3_result_error(pCtx, zErr, -1);
  161668. sqlite3_free(zErr);
  161669. return;
  161670. }
  161671. if( bTcl && nArg>1 ){
  161672. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  161673. iArg = 2;
  161674. }
  161675. nConfig = 3 + (nArg-iArg);
  161676. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  161677. if( azConfig==0 ){
  161678. sqlite3_result_error_nomem(pCtx);
  161679. return;
  161680. }
  161681. azConfig[0] = 0;
  161682. azConfig[1] = "main";
  161683. azConfig[2] = "tbl";
  161684. for(i=3; iArg<nArg; iArg++){
  161685. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  161686. }
  161687. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  161688. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  161689. if( rc==SQLITE_OK ){
  161690. rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
  161691. }
  161692. if( rc==SQLITE_OK ){
  161693. char *zText;
  161694. if( pExpr->pRoot==0 ){
  161695. zText = sqlite3_mprintf("");
  161696. }else if( bTcl ){
  161697. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  161698. }else{
  161699. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  161700. }
  161701. if( zText==0 ){
  161702. rc = SQLITE_NOMEM;
  161703. }else{
  161704. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  161705. sqlite3_free(zText);
  161706. }
  161707. }
  161708. if( rc!=SQLITE_OK ){
  161709. if( zErr ){
  161710. sqlite3_result_error(pCtx, zErr, -1);
  161711. sqlite3_free(zErr);
  161712. }else{
  161713. sqlite3_result_error_code(pCtx, rc);
  161714. }
  161715. }
  161716. sqlite3_free((void *)azConfig);
  161717. sqlite3Fts5ConfigFree(pConfig);
  161718. sqlite3Fts5ExprFree(pExpr);
  161719. }
  161720. static void fts5ExprFunctionHr(
  161721. sqlite3_context *pCtx, /* Function call context */
  161722. int nArg, /* Number of args */
  161723. sqlite3_value **apVal /* Function arguments */
  161724. ){
  161725. fts5ExprFunction(pCtx, nArg, apVal, 0);
  161726. }
  161727. static void fts5ExprFunctionTcl(
  161728. sqlite3_context *pCtx, /* Function call context */
  161729. int nArg, /* Number of args */
  161730. sqlite3_value **apVal /* Function arguments */
  161731. ){
  161732. fts5ExprFunction(pCtx, nArg, apVal, 1);
  161733. }
  161734. /*
  161735. ** The implementation of an SQLite user-defined-function that accepts a
  161736. ** single integer as an argument. If the integer is an alpha-numeric
  161737. ** unicode code point, 1 is returned. Otherwise 0.
  161738. */
  161739. static void fts5ExprIsAlnum(
  161740. sqlite3_context *pCtx, /* Function call context */
  161741. int nArg, /* Number of args */
  161742. sqlite3_value **apVal /* Function arguments */
  161743. ){
  161744. int iCode;
  161745. if( nArg!=1 ){
  161746. sqlite3_result_error(pCtx,
  161747. "wrong number of arguments to function fts5_isalnum", -1
  161748. );
  161749. return;
  161750. }
  161751. iCode = sqlite3_value_int(apVal[0]);
  161752. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
  161753. }
  161754. static void fts5ExprFold(
  161755. sqlite3_context *pCtx, /* Function call context */
  161756. int nArg, /* Number of args */
  161757. sqlite3_value **apVal /* Function arguments */
  161758. ){
  161759. if( nArg!=1 && nArg!=2 ){
  161760. sqlite3_result_error(pCtx,
  161761. "wrong number of arguments to function fts5_fold", -1
  161762. );
  161763. }else{
  161764. int iCode;
  161765. int bRemoveDiacritics = 0;
  161766. iCode = sqlite3_value_int(apVal[0]);
  161767. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  161768. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  161769. }
  161770. }
  161771. /*
  161772. ** This is called during initialization to register the fts5_expr() scalar
  161773. ** UDF with the SQLite handle passed as the only argument.
  161774. */
  161775. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  161776. struct Fts5ExprFunc {
  161777. const char *z;
  161778. void (*x)(sqlite3_context*,int,sqlite3_value**);
  161779. } aFunc[] = {
  161780. { "fts5_expr", fts5ExprFunctionHr },
  161781. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  161782. { "fts5_isalnum", fts5ExprIsAlnum },
  161783. { "fts5_fold", fts5ExprFold },
  161784. };
  161785. int i;
  161786. int rc = SQLITE_OK;
  161787. void *pCtx = (void*)pGlobal;
  161788. for(i=0; rc==SQLITE_OK && i<(int)ArraySize(aFunc); i++){
  161789. struct Fts5ExprFunc *p = &aFunc[i];
  161790. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  161791. }
  161792. /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
  161793. #ifndef NDEBUG
  161794. (void)sqlite3Fts5ParserTrace;
  161795. #endif
  161796. return rc;
  161797. }
  161798. /*
  161799. ** Return the number of phrases in expression pExpr.
  161800. */
  161801. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  161802. return (pExpr ? pExpr->nPhrase : 0);
  161803. }
  161804. /*
  161805. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  161806. */
  161807. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  161808. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  161809. return pExpr->apExprPhrase[iPhrase]->nTerm;
  161810. }
  161811. /*
  161812. ** This function is used to access the current position list for phrase
  161813. ** iPhrase.
  161814. */
  161815. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  161816. int nRet;
  161817. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  161818. Fts5ExprNode *pNode = pPhrase->pNode;
  161819. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  161820. *pa = pPhrase->poslist.p;
  161821. nRet = pPhrase->poslist.n;
  161822. }else{
  161823. *pa = 0;
  161824. nRet = 0;
  161825. }
  161826. return nRet;
  161827. }
  161828. /*
  161829. ** 2014 August 11
  161830. **
  161831. ** The author disclaims copyright to this source code. In place of
  161832. ** a legal notice, here is a blessing:
  161833. **
  161834. ** May you do good and not evil.
  161835. ** May you find forgiveness for yourself and forgive others.
  161836. ** May you share freely, never taking more than you give.
  161837. **
  161838. ******************************************************************************
  161839. **
  161840. */
  161841. /* #include "fts5Int.h" */
  161842. typedef struct Fts5HashEntry Fts5HashEntry;
  161843. /*
  161844. ** This file contains the implementation of an in-memory hash table used
  161845. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  161846. ** segment.
  161847. */
  161848. struct Fts5Hash {
  161849. int *pnByte; /* Pointer to bytes counter */
  161850. int nEntry; /* Number of entries currently in hash */
  161851. int nSlot; /* Size of aSlot[] array */
  161852. Fts5HashEntry *pScan; /* Current ordered scan item */
  161853. Fts5HashEntry **aSlot; /* Array of hash slots */
  161854. };
  161855. /*
  161856. ** Each entry in the hash table is represented by an object of the
  161857. ** following type. Each object, its key (zKey[]) and its current data
  161858. ** are stored in a single memory allocation. The position list data
  161859. ** immediately follows the key data in memory.
  161860. **
  161861. ** The data that follows the key is in a similar, but not identical format
  161862. ** to the doclist data stored in the database. It is:
  161863. **
  161864. ** * Rowid, as a varint
  161865. ** * Position list, without 0x00 terminator.
  161866. ** * Size of previous position list and rowid, as a 4 byte
  161867. ** big-endian integer.
  161868. **
  161869. ** iRowidOff:
  161870. ** Offset of last rowid written to data area. Relative to first byte of
  161871. ** structure.
  161872. **
  161873. ** nData:
  161874. ** Bytes of data written since iRowidOff.
  161875. */
  161876. struct Fts5HashEntry {
  161877. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  161878. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  161879. int nAlloc; /* Total size of allocation */
  161880. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  161881. int nData; /* Total bytes of data (incl. structure) */
  161882. u8 bDel; /* Set delete-flag @ iSzPoslist */
  161883. int iCol; /* Column of last value written */
  161884. int iPos; /* Position of last value written */
  161885. i64 iRowid; /* Rowid of last value written */
  161886. char zKey[8]; /* Nul-terminated entry key */
  161887. };
  161888. /*
  161889. ** Size of Fts5HashEntry without the zKey[] array.
  161890. */
  161891. #define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
  161892. /*
  161893. ** Allocate a new hash table.
  161894. */
  161895. static int sqlite3Fts5HashNew(Fts5Hash **ppNew, int *pnByte){
  161896. int rc = SQLITE_OK;
  161897. Fts5Hash *pNew;
  161898. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  161899. if( pNew==0 ){
  161900. rc = SQLITE_NOMEM;
  161901. }else{
  161902. int nByte;
  161903. memset(pNew, 0, sizeof(Fts5Hash));
  161904. pNew->pnByte = pnByte;
  161905. pNew->nSlot = 1024;
  161906. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  161907. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  161908. if( pNew->aSlot==0 ){
  161909. sqlite3_free(pNew);
  161910. *ppNew = 0;
  161911. rc = SQLITE_NOMEM;
  161912. }else{
  161913. memset(pNew->aSlot, 0, nByte);
  161914. }
  161915. }
  161916. return rc;
  161917. }
  161918. /*
  161919. ** Free a hash table object.
  161920. */
  161921. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  161922. if( pHash ){
  161923. sqlite3Fts5HashClear(pHash);
  161924. sqlite3_free(pHash->aSlot);
  161925. sqlite3_free(pHash);
  161926. }
  161927. }
  161928. /*
  161929. ** Empty (but do not delete) a hash table.
  161930. */
  161931. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  161932. int i;
  161933. for(i=0; i<pHash->nSlot; i++){
  161934. Fts5HashEntry *pNext;
  161935. Fts5HashEntry *pSlot;
  161936. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  161937. pNext = pSlot->pHashNext;
  161938. sqlite3_free(pSlot);
  161939. }
  161940. }
  161941. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  161942. pHash->nEntry = 0;
  161943. }
  161944. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  161945. int i;
  161946. unsigned int h = 13;
  161947. for(i=n-1; i>=0; i--){
  161948. h = (h << 3) ^ h ^ p[i];
  161949. }
  161950. return (h % nSlot);
  161951. }
  161952. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  161953. int i;
  161954. unsigned int h = 13;
  161955. for(i=n-1; i>=0; i--){
  161956. h = (h << 3) ^ h ^ p[i];
  161957. }
  161958. h = (h << 3) ^ h ^ b;
  161959. return (h % nSlot);
  161960. }
  161961. /*
  161962. ** Resize the hash table by doubling the number of slots.
  161963. */
  161964. static int fts5HashResize(Fts5Hash *pHash){
  161965. int nNew = pHash->nSlot*2;
  161966. int i;
  161967. Fts5HashEntry **apNew;
  161968. Fts5HashEntry **apOld = pHash->aSlot;
  161969. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  161970. if( !apNew ) return SQLITE_NOMEM;
  161971. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  161972. for(i=0; i<pHash->nSlot; i++){
  161973. while( apOld[i] ){
  161974. int iHash;
  161975. Fts5HashEntry *p = apOld[i];
  161976. apOld[i] = p->pHashNext;
  161977. iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
  161978. p->pHashNext = apNew[iHash];
  161979. apNew[iHash] = p;
  161980. }
  161981. }
  161982. sqlite3_free(apOld);
  161983. pHash->nSlot = nNew;
  161984. pHash->aSlot = apNew;
  161985. return SQLITE_OK;
  161986. }
  161987. static void fts5HashAddPoslistSize(Fts5HashEntry *p){
  161988. if( p->iSzPoslist ){
  161989. u8 *pPtr = (u8*)p;
  161990. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  161991. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  161992. assert( p->bDel==0 || p->bDel==1 );
  161993. if( nPos<=127 ){
  161994. pPtr[p->iSzPoslist] = (u8)nPos;
  161995. }else{
  161996. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  161997. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  161998. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  161999. p->nData += (nByte-1);
  162000. }
  162001. p->bDel = 0;
  162002. p->iSzPoslist = 0;
  162003. }
  162004. }
  162005. static int sqlite3Fts5HashWrite(
  162006. Fts5Hash *pHash,
  162007. i64 iRowid, /* Rowid for this entry */
  162008. int iCol, /* Column token appears in (-ve -> delete) */
  162009. int iPos, /* Position of token within column */
  162010. char bByte, /* First byte of token */
  162011. const char *pToken, int nToken /* Token to add or remove to or from index */
  162012. ){
  162013. unsigned int iHash;
  162014. Fts5HashEntry *p;
  162015. u8 *pPtr;
  162016. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  162017. /* Attempt to locate an existing hash entry */
  162018. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  162019. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  162020. if( p->zKey[0]==bByte
  162021. && memcmp(&p->zKey[1], pToken, nToken)==0
  162022. && p->zKey[nToken+1]==0
  162023. ){
  162024. break;
  162025. }
  162026. }
  162027. /* If an existing hash entry cannot be found, create a new one. */
  162028. if( p==0 ){
  162029. int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
  162030. if( nByte<128 ) nByte = 128;
  162031. if( (pHash->nEntry*2)>=pHash->nSlot ){
  162032. int rc = fts5HashResize(pHash);
  162033. if( rc!=SQLITE_OK ) return rc;
  162034. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  162035. }
  162036. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  162037. if( !p ) return SQLITE_NOMEM;
  162038. memset(p, 0, FTS5_HASHENTRYSIZE);
  162039. p->nAlloc = nByte;
  162040. p->zKey[0] = bByte;
  162041. memcpy(&p->zKey[1], pToken, nToken);
  162042. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
  162043. p->zKey[nToken+1] = '\0';
  162044. p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
  162045. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  162046. p->iSzPoslist = p->nData;
  162047. p->nData += 1;
  162048. p->iRowid = iRowid;
  162049. p->pHashNext = pHash->aSlot[iHash];
  162050. pHash->aSlot[iHash] = p;
  162051. pHash->nEntry++;
  162052. nIncr += p->nData;
  162053. }
  162054. /* Check there is enough space to append a new entry. Worst case scenario
  162055. ** is:
  162056. **
  162057. ** + 9 bytes for a new rowid,
  162058. ** + 4 byte reserved for the "poslist size" varint.
  162059. ** + 1 byte for a "new column" byte,
  162060. ** + 3 bytes for a new column number (16-bit max) as a varint,
  162061. ** + 5 bytes for the new position offset (32-bit max).
  162062. */
  162063. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  162064. int nNew = p->nAlloc * 2;
  162065. Fts5HashEntry *pNew;
  162066. Fts5HashEntry **pp;
  162067. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  162068. if( pNew==0 ) return SQLITE_NOMEM;
  162069. pNew->nAlloc = nNew;
  162070. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  162071. *pp = pNew;
  162072. p = pNew;
  162073. }
  162074. pPtr = (u8*)p;
  162075. nIncr -= p->nData;
  162076. /* If this is a new rowid, append the 4-byte size field for the previous
  162077. ** entry, and the new rowid for this entry. */
  162078. if( iRowid!=p->iRowid ){
  162079. fts5HashAddPoslistSize(p);
  162080. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  162081. p->iSzPoslist = p->nData;
  162082. p->nData += 1;
  162083. p->iCol = 0;
  162084. p->iPos = 0;
  162085. p->iRowid = iRowid;
  162086. }
  162087. if( iCol>=0 ){
  162088. /* Append a new column value, if necessary */
  162089. assert( iCol>=p->iCol );
  162090. if( iCol!=p->iCol ){
  162091. pPtr[p->nData++] = 0x01;
  162092. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  162093. p->iCol = iCol;
  162094. p->iPos = 0;
  162095. }
  162096. /* Append the new position offset */
  162097. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  162098. p->iPos = iPos;
  162099. }else{
  162100. /* This is a delete. Set the delete flag. */
  162101. p->bDel = 1;
  162102. }
  162103. nIncr += p->nData;
  162104. *pHash->pnByte += nIncr;
  162105. return SQLITE_OK;
  162106. }
  162107. /*
  162108. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  162109. ** each sorted in key order. This function merges the two lists into a
  162110. ** single list and returns a pointer to its first element.
  162111. */
  162112. static Fts5HashEntry *fts5HashEntryMerge(
  162113. Fts5HashEntry *pLeft,
  162114. Fts5HashEntry *pRight
  162115. ){
  162116. Fts5HashEntry *p1 = pLeft;
  162117. Fts5HashEntry *p2 = pRight;
  162118. Fts5HashEntry *pRet = 0;
  162119. Fts5HashEntry **ppOut = &pRet;
  162120. while( p1 || p2 ){
  162121. if( p1==0 ){
  162122. *ppOut = p2;
  162123. p2 = 0;
  162124. }else if( p2==0 ){
  162125. *ppOut = p1;
  162126. p1 = 0;
  162127. }else{
  162128. int i = 0;
  162129. while( p1->zKey[i]==p2->zKey[i] ) i++;
  162130. if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
  162131. /* p2 is smaller */
  162132. *ppOut = p2;
  162133. ppOut = &p2->pScanNext;
  162134. p2 = p2->pScanNext;
  162135. }else{
  162136. /* p1 is smaller */
  162137. *ppOut = p1;
  162138. ppOut = &p1->pScanNext;
  162139. p1 = p1->pScanNext;
  162140. }
  162141. *ppOut = 0;
  162142. }
  162143. }
  162144. return pRet;
  162145. }
  162146. /*
  162147. ** Extract all tokens from hash table iHash and link them into a list
  162148. ** in sorted order. The hash table is cleared before returning. It is
  162149. ** the responsibility of the caller to free the elements of the returned
  162150. ** list.
  162151. */
  162152. static int fts5HashEntrySort(
  162153. Fts5Hash *pHash,
  162154. const char *pTerm, int nTerm, /* Query prefix, if any */
  162155. Fts5HashEntry **ppSorted
  162156. ){
  162157. const int nMergeSlot = 32;
  162158. Fts5HashEntry **ap;
  162159. Fts5HashEntry *pList;
  162160. int iSlot;
  162161. int i;
  162162. *ppSorted = 0;
  162163. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  162164. if( !ap ) return SQLITE_NOMEM;
  162165. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  162166. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  162167. Fts5HashEntry *pIter;
  162168. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  162169. if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
  162170. Fts5HashEntry *pEntry = pIter;
  162171. pEntry->pScanNext = 0;
  162172. for(i=0; ap[i]; i++){
  162173. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  162174. ap[i] = 0;
  162175. }
  162176. ap[i] = pEntry;
  162177. }
  162178. }
  162179. }
  162180. pList = 0;
  162181. for(i=0; i<nMergeSlot; i++){
  162182. pList = fts5HashEntryMerge(pList, ap[i]);
  162183. }
  162184. pHash->nEntry = 0;
  162185. sqlite3_free(ap);
  162186. *ppSorted = pList;
  162187. return SQLITE_OK;
  162188. }
  162189. /*
  162190. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  162191. */
  162192. static int sqlite3Fts5HashQuery(
  162193. Fts5Hash *pHash, /* Hash table to query */
  162194. const char *pTerm, int nTerm, /* Query term */
  162195. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  162196. int *pnDoclist /* OUT: Size of doclist in bytes */
  162197. ){
  162198. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  162199. Fts5HashEntry *p;
  162200. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  162201. if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
  162202. }
  162203. if( p ){
  162204. fts5HashAddPoslistSize(p);
  162205. *ppDoclist = (const u8*)&p->zKey[nTerm+1];
  162206. *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
  162207. }else{
  162208. *ppDoclist = 0;
  162209. *pnDoclist = 0;
  162210. }
  162211. return SQLITE_OK;
  162212. }
  162213. static int sqlite3Fts5HashScanInit(
  162214. Fts5Hash *p, /* Hash table to query */
  162215. const char *pTerm, int nTerm /* Query prefix */
  162216. ){
  162217. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  162218. }
  162219. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  162220. assert( !sqlite3Fts5HashScanEof(p) );
  162221. p->pScan = p->pScan->pScanNext;
  162222. }
  162223. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  162224. return (p->pScan==0);
  162225. }
  162226. static void sqlite3Fts5HashScanEntry(
  162227. Fts5Hash *pHash,
  162228. const char **pzTerm, /* OUT: term (nul-terminated) */
  162229. const u8 **ppDoclist, /* OUT: pointer to doclist */
  162230. int *pnDoclist /* OUT: size of doclist in bytes */
  162231. ){
  162232. Fts5HashEntry *p;
  162233. if( (p = pHash->pScan) ){
  162234. int nTerm = (int)strlen(p->zKey);
  162235. fts5HashAddPoslistSize(p);
  162236. *pzTerm = p->zKey;
  162237. *ppDoclist = (const u8*)&p->zKey[nTerm+1];
  162238. *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
  162239. }else{
  162240. *pzTerm = 0;
  162241. *ppDoclist = 0;
  162242. *pnDoclist = 0;
  162243. }
  162244. }
  162245. /*
  162246. ** 2014 May 31
  162247. **
  162248. ** The author disclaims copyright to this source code. In place of
  162249. ** a legal notice, here is a blessing:
  162250. **
  162251. ** May you do good and not evil.
  162252. ** May you find forgiveness for yourself and forgive others.
  162253. ** May you share freely, never taking more than you give.
  162254. **
  162255. ******************************************************************************
  162256. **
  162257. ** Low level access to the FTS index stored in the database file. The
  162258. ** routines in this file file implement all read and write access to the
  162259. ** %_data table. Other parts of the system access this functionality via
  162260. ** the interface defined in fts5Int.h.
  162261. */
  162262. /* #include "fts5Int.h" */
  162263. /*
  162264. ** Overview:
  162265. **
  162266. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  162267. ** As well as the main term index, there may be up to 31 prefix indexes.
  162268. ** The format is similar to FTS3/4, except that:
  162269. **
  162270. ** * all segment b-tree leaf data is stored in fixed size page records
  162271. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  162272. ** taken to ensure it is possible to iterate in either direction through
  162273. ** the entries in a doclist, or to seek to a specific entry within a
  162274. ** doclist, without loading it into memory.
  162275. **
  162276. ** * large doclists that span many pages have associated "doclist index"
  162277. ** records that contain a copy of the first rowid on each page spanned by
  162278. ** the doclist. This is used to speed up seek operations, and merges of
  162279. ** large doclists with very small doclists.
  162280. **
  162281. ** * extra fields in the "structure record" record the state of ongoing
  162282. ** incremental merge operations.
  162283. **
  162284. */
  162285. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  162286. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  162287. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  162288. #define FTS5_MAIN_PREFIX '0'
  162289. #if FTS5_MAX_PREFIX_INDEXES > 31
  162290. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  162291. #endif
  162292. /*
  162293. ** Details:
  162294. **
  162295. ** The %_data table managed by this module,
  162296. **
  162297. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  162298. **
  162299. ** , contains the following 5 types of records. See the comments surrounding
  162300. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  162301. ** assigned to each fo them.
  162302. **
  162303. ** 1. Structure Records:
  162304. **
  162305. ** The set of segments that make up an index - the index structure - are
  162306. ** recorded in a single record within the %_data table. The record consists
  162307. ** of a single 32-bit configuration cookie value followed by a list of
  162308. ** SQLite varints. If the FTS table features more than one index (because
  162309. ** there are one or more prefix indexes), it is guaranteed that all share
  162310. ** the same cookie value.
  162311. **
  162312. ** Immediately following the configuration cookie, the record begins with
  162313. ** three varints:
  162314. **
  162315. ** + number of levels,
  162316. ** + total number of segments on all levels,
  162317. ** + value of write counter.
  162318. **
  162319. ** Then, for each level from 0 to nMax:
  162320. **
  162321. ** + number of input segments in ongoing merge.
  162322. ** + total number of segments in level.
  162323. ** + for each segment from oldest to newest:
  162324. ** + segment id (always > 0)
  162325. ** + first leaf page number (often 1, always greater than 0)
  162326. ** + final leaf page number
  162327. **
  162328. ** 2. The Averages Record:
  162329. **
  162330. ** A single record within the %_data table. The data is a list of varints.
  162331. ** The first value is the number of rows in the index. Then, for each column
  162332. ** from left to right, the total number of tokens in the column for all
  162333. ** rows of the table.
  162334. **
  162335. ** 3. Segment leaves:
  162336. **
  162337. ** TERM/DOCLIST FORMAT:
  162338. **
  162339. ** Most of each segment leaf is taken up by term/doclist data. The
  162340. ** general format of term/doclist, starting with the first term
  162341. ** on the leaf page, is:
  162342. **
  162343. ** varint : size of first term
  162344. ** blob: first term data
  162345. ** doclist: first doclist
  162346. ** zero-or-more {
  162347. ** varint: number of bytes in common with previous term
  162348. ** varint: number of bytes of new term data (nNew)
  162349. ** blob: nNew bytes of new term data
  162350. ** doclist: next doclist
  162351. ** }
  162352. **
  162353. ** doclist format:
  162354. **
  162355. ** varint: first rowid
  162356. ** poslist: first poslist
  162357. ** zero-or-more {
  162358. ** varint: rowid delta (always > 0)
  162359. ** poslist: next poslist
  162360. ** }
  162361. **
  162362. ** poslist format:
  162363. **
  162364. ** varint: size of poslist in bytes multiplied by 2, not including
  162365. ** this field. Plus 1 if this entry carries the "delete" flag.
  162366. ** collist: collist for column 0
  162367. ** zero-or-more {
  162368. ** 0x01 byte
  162369. ** varint: column number (I)
  162370. ** collist: collist for column I
  162371. ** }
  162372. **
  162373. ** collist format:
  162374. **
  162375. ** varint: first offset + 2
  162376. ** zero-or-more {
  162377. ** varint: offset delta + 2
  162378. ** }
  162379. **
  162380. ** PAGE FORMAT
  162381. **
  162382. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  162383. ** unsigned integer fields in big-endian format. They are:
  162384. **
  162385. ** * The byte offset of the first rowid on the page, if it exists
  162386. ** and occurs before the first term (otherwise 0).
  162387. **
  162388. ** * The byte offset of the start of the page footer. If the page
  162389. ** footer is 0 bytes in size, then this field is the same as the
  162390. ** size of the leaf page in bytes.
  162391. **
  162392. ** The page footer consists of a single varint for each term located
  162393. ** on the page. Each varint is the byte offset of the current term
  162394. ** within the page, delta-compressed against the previous value. In
  162395. ** other words, the first varint in the footer is the byte offset of
  162396. ** the first term, the second is the byte offset of the second less that
  162397. ** of the first, and so on.
  162398. **
  162399. ** The term/doclist format described above is accurate if the entire
  162400. ** term/doclist data fits on a single leaf page. If this is not the case,
  162401. ** the format is changed in two ways:
  162402. **
  162403. ** + if the first rowid on a page occurs before the first term, it
  162404. ** is stored as a literal value:
  162405. **
  162406. ** varint: first rowid
  162407. **
  162408. ** + the first term on each page is stored in the same way as the
  162409. ** very first term of the segment:
  162410. **
  162411. ** varint : size of first term
  162412. ** blob: first term data
  162413. **
  162414. ** 5. Segment doclist indexes:
  162415. **
  162416. ** Doclist indexes are themselves b-trees, however they usually consist of
  162417. ** a single leaf record only. The format of each doclist index leaf page
  162418. ** is:
  162419. **
  162420. ** * Flags byte. Bits are:
  162421. ** 0x01: Clear if leaf is also the root page, otherwise set.
  162422. **
  162423. ** * Page number of fts index leaf page. As a varint.
  162424. **
  162425. ** * First rowid on page indicated by previous field. As a varint.
  162426. **
  162427. ** * A list of varints, one for each subsequent termless page. A
  162428. ** positive delta if the termless page contains at least one rowid,
  162429. ** or an 0x00 byte otherwise.
  162430. **
  162431. ** Internal doclist index nodes are:
  162432. **
  162433. ** * Flags byte. Bits are:
  162434. ** 0x01: Clear for root page, otherwise set.
  162435. **
  162436. ** * Page number of first child page. As a varint.
  162437. **
  162438. ** * Copy of first rowid on page indicated by previous field. As a varint.
  162439. **
  162440. ** * A list of delta-encoded varints - the first rowid on each subsequent
  162441. ** child page.
  162442. **
  162443. */
  162444. /*
  162445. ** Rowids for the averages and structure records in the %_data table.
  162446. */
  162447. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  162448. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  162449. /*
  162450. ** Macros determining the rowids used by segment leaves and dlidx leaves
  162451. ** and nodes. All nodes and leaves are stored in the %_data table with large
  162452. ** positive rowids.
  162453. **
  162454. ** Each segment has a unique non-zero 16-bit id.
  162455. **
  162456. ** The rowid for each segment leaf is found by passing the segment id and
  162457. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  162458. ** sequentially starting from 1.
  162459. */
  162460. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  162461. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  162462. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  162463. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  162464. #define fts5_dri(segid, dlidx, height, pgno) ( \
  162465. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  162466. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  162467. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  162468. ((i64)(pgno)) \
  162469. )
  162470. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  162471. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  162472. /*
  162473. ** Maximum segments permitted in a single index
  162474. */
  162475. #define FTS5_MAX_SEGMENT 2000
  162476. #ifdef SQLITE_DEBUG
  162477. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  162478. #endif
  162479. /*
  162480. ** Each time a blob is read from the %_data table, it is padded with this
  162481. ** many zero bytes. This makes it easier to decode the various record formats
  162482. ** without overreading if the records are corrupt.
  162483. */
  162484. #define FTS5_DATA_ZERO_PADDING 8
  162485. #define FTS5_DATA_PADDING 20
  162486. typedef struct Fts5Data Fts5Data;
  162487. typedef struct Fts5DlidxIter Fts5DlidxIter;
  162488. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  162489. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  162490. typedef struct Fts5PageWriter Fts5PageWriter;
  162491. typedef struct Fts5SegIter Fts5SegIter;
  162492. typedef struct Fts5DoclistIter Fts5DoclistIter;
  162493. typedef struct Fts5SegWriter Fts5SegWriter;
  162494. typedef struct Fts5Structure Fts5Structure;
  162495. typedef struct Fts5StructureLevel Fts5StructureLevel;
  162496. typedef struct Fts5StructureSegment Fts5StructureSegment;
  162497. struct Fts5Data {
  162498. u8 *p; /* Pointer to buffer containing record */
  162499. int nn; /* Size of record in bytes */
  162500. int szLeaf; /* Size of leaf without page-index */
  162501. };
  162502. /*
  162503. ** One object per %_data table.
  162504. */
  162505. struct Fts5Index {
  162506. Fts5Config *pConfig; /* Virtual table configuration */
  162507. char *zDataTbl; /* Name of %_data table */
  162508. int nWorkUnit; /* Leaf pages in a "unit" of work */
  162509. /*
  162510. ** Variables related to the accumulation of tokens and doclists within the
  162511. ** in-memory hash tables before they are flushed to disk.
  162512. */
  162513. Fts5Hash *pHash; /* Hash table for in-memory data */
  162514. int nPendingData; /* Current bytes of pending data */
  162515. i64 iWriteRowid; /* Rowid for current doc being written */
  162516. int bDelete; /* Current write is a delete */
  162517. /* Error state. */
  162518. int rc; /* Current error code */
  162519. /* State used by the fts5DataXXX() functions. */
  162520. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  162521. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  162522. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  162523. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  162524. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  162525. sqlite3_stmt *pIdxSelect;
  162526. int nRead; /* Total number of blocks read */
  162527. };
  162528. struct Fts5DoclistIter {
  162529. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  162530. /* Output variables. aPoslist==0 at EOF */
  162531. i64 iRowid;
  162532. u8 *aPoslist;
  162533. int nPoslist;
  162534. int nSize;
  162535. };
  162536. /*
  162537. ** The contents of the "structure" record for each index are represented
  162538. ** using an Fts5Structure record in memory. Which uses instances of the
  162539. ** other Fts5StructureXXX types as components.
  162540. */
  162541. struct Fts5StructureSegment {
  162542. int iSegid; /* Segment id */
  162543. int pgnoFirst; /* First leaf page number in segment */
  162544. int pgnoLast; /* Last leaf page number in segment */
  162545. };
  162546. struct Fts5StructureLevel {
  162547. int nMerge; /* Number of segments in incr-merge */
  162548. int nSeg; /* Total number of segments on level */
  162549. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  162550. };
  162551. struct Fts5Structure {
  162552. int nRef; /* Object reference count */
  162553. u64 nWriteCounter; /* Total leaves written to level 0 */
  162554. int nSegment; /* Total segments in this structure */
  162555. int nLevel; /* Number of levels in this index */
  162556. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  162557. };
  162558. /*
  162559. ** An object of type Fts5SegWriter is used to write to segments.
  162560. */
  162561. struct Fts5PageWriter {
  162562. int pgno; /* Page number for this page */
  162563. int iPrevPgidx; /* Previous value written into pgidx */
  162564. Fts5Buffer buf; /* Buffer containing leaf data */
  162565. Fts5Buffer pgidx; /* Buffer containing page-index */
  162566. Fts5Buffer term; /* Buffer containing previous term on page */
  162567. };
  162568. struct Fts5DlidxWriter {
  162569. int pgno; /* Page number for this page */
  162570. int bPrevValid; /* True if iPrev is valid */
  162571. i64 iPrev; /* Previous rowid value written to page */
  162572. Fts5Buffer buf; /* Buffer containing page data */
  162573. };
  162574. struct Fts5SegWriter {
  162575. int iSegid; /* Segid to write to */
  162576. Fts5PageWriter writer; /* PageWriter object */
  162577. i64 iPrevRowid; /* Previous rowid written to current leaf */
  162578. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  162579. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  162580. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  162581. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  162582. int nLeafWritten; /* Number of leaf pages written */
  162583. int nEmpty; /* Number of contiguous term-less nodes */
  162584. int nDlidx; /* Allocated size of aDlidx[] array */
  162585. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  162586. /* Values to insert into the %_idx table */
  162587. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  162588. int iBtPage; /* Page number corresponding to btterm */
  162589. };
  162590. typedef struct Fts5CResult Fts5CResult;
  162591. struct Fts5CResult {
  162592. u16 iFirst; /* aSeg[] index of firstest iterator */
  162593. u8 bTermEq; /* True if the terms are equal */
  162594. };
  162595. /*
  162596. ** Object for iterating through a single segment, visiting each term/rowid
  162597. ** pair in the segment.
  162598. **
  162599. ** pSeg:
  162600. ** The segment to iterate through.
  162601. **
  162602. ** iLeafPgno:
  162603. ** Current leaf page number within segment.
  162604. **
  162605. ** iLeafOffset:
  162606. ** Byte offset within the current leaf that is the first byte of the
  162607. ** position list data (one byte passed the position-list size field).
  162608. ** rowid field of the current entry. Usually this is the size field of the
  162609. ** position list data. The exception is if the rowid for the current entry
  162610. ** is the last thing on the leaf page.
  162611. **
  162612. ** pLeaf:
  162613. ** Buffer containing current leaf page data. Set to NULL at EOF.
  162614. **
  162615. ** iTermLeafPgno, iTermLeafOffset:
  162616. ** Leaf page number containing the last term read from the segment. And
  162617. ** the offset immediately following the term data.
  162618. **
  162619. ** flags:
  162620. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  162621. **
  162622. ** FTS5_SEGITER_ONETERM:
  162623. ** If set, set the iterator to point to EOF after the current doclist
  162624. ** has been exhausted. Do not proceed to the next term in the segment.
  162625. **
  162626. ** FTS5_SEGITER_REVERSE:
  162627. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  162628. ** it is set, iterate through rowid in descending order instead of the
  162629. ** default ascending order.
  162630. **
  162631. ** iRowidOffset/nRowidOffset/aRowidOffset:
  162632. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  162633. **
  162634. ** For each rowid on the page corresponding to the current term, the
  162635. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  162636. ** start of the "position-list-size" field within the page.
  162637. **
  162638. ** iTermIdx:
  162639. ** Index of current term on iTermLeafPgno.
  162640. */
  162641. struct Fts5SegIter {
  162642. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  162643. int flags; /* Mask of configuration flags */
  162644. int iLeafPgno; /* Current leaf page number */
  162645. Fts5Data *pLeaf; /* Current leaf data */
  162646. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  162647. int iLeafOffset; /* Byte offset within current leaf */
  162648. /* The page and offset from which the current term was read. The offset
  162649. ** is the offset of the first rowid in the current doclist. */
  162650. int iTermLeafPgno;
  162651. int iTermLeafOffset;
  162652. int iPgidxOff; /* Next offset in pgidx */
  162653. int iEndofDoclist;
  162654. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  162655. int iRowidOffset; /* Current entry in aRowidOffset[] */
  162656. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  162657. int *aRowidOffset; /* Array of offset to rowid fields */
  162658. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  162659. /* Variables populated based on current entry. */
  162660. Fts5Buffer term; /* Current term */
  162661. i64 iRowid; /* Current rowid */
  162662. int nPos; /* Number of bytes in current position list */
  162663. int bDel; /* True if the delete flag is set */
  162664. };
  162665. /*
  162666. ** Argument is a pointer to an Fts5Data structure that contains a
  162667. ** leaf page.
  162668. */
  162669. #define ASSERT_SZLEAF_OK(x) assert( \
  162670. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  162671. )
  162672. #define FTS5_SEGITER_ONETERM 0x01
  162673. #define FTS5_SEGITER_REVERSE 0x02
  162674. /*
  162675. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  162676. ** page. This macro evaluates to true if the leaf contains no terms, or
  162677. ** false if it contains at least one term.
  162678. */
  162679. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  162680. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  162681. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  162682. /*
  162683. ** Object for iterating through the merged results of one or more segments,
  162684. ** visiting each term/rowid pair in the merged data.
  162685. **
  162686. ** nSeg is always a power of two greater than or equal to the number of
  162687. ** segments that this object is merging data from. Both the aSeg[] and
  162688. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  162689. ** with zeroed objects - these are handled as if they were iterators opened
  162690. ** on empty segments.
  162691. **
  162692. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  162693. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  162694. ** comparison in this context is the index of the iterator that currently
  162695. ** points to the smaller term/rowid combination. Iterators at EOF are
  162696. ** considered to be greater than all other iterators.
  162697. **
  162698. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  162699. ** the smallest key overall. aFirst[0] is unused.
  162700. **
  162701. ** poslist:
  162702. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  162703. ** There is no way to tell if this is populated or not.
  162704. */
  162705. struct Fts5IndexIter {
  162706. Fts5Index *pIndex; /* Index that owns this iterator */
  162707. Fts5Structure *pStruct; /* Database structure for this iterator */
  162708. Fts5Buffer poslist; /* Buffer containing current poslist */
  162709. int nSeg; /* Size of aSeg[] array */
  162710. int bRev; /* True to iterate in reverse order */
  162711. u8 bSkipEmpty; /* True to skip deleted entries */
  162712. u8 bEof; /* True at EOF */
  162713. u8 bFiltered; /* True if column-filter already applied */
  162714. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  162715. Fts5CResult *aFirst; /* Current merge state (see above) */
  162716. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  162717. };
  162718. /*
  162719. ** An instance of the following type is used to iterate through the contents
  162720. ** of a doclist-index record.
  162721. **
  162722. ** pData:
  162723. ** Record containing the doclist-index data.
  162724. **
  162725. ** bEof:
  162726. ** Set to true once iterator has reached EOF.
  162727. **
  162728. ** iOff:
  162729. ** Set to the current offset within record pData.
  162730. */
  162731. struct Fts5DlidxLvl {
  162732. Fts5Data *pData; /* Data for current page of this level */
  162733. int iOff; /* Current offset into pData */
  162734. int bEof; /* At EOF already */
  162735. int iFirstOff; /* Used by reverse iterators */
  162736. /* Output variables */
  162737. int iLeafPgno; /* Page number of current leaf page */
  162738. i64 iRowid; /* First rowid on leaf iLeafPgno */
  162739. };
  162740. struct Fts5DlidxIter {
  162741. int nLvl;
  162742. int iSegid;
  162743. Fts5DlidxLvl aLvl[1];
  162744. };
  162745. static void fts5PutU16(u8 *aOut, u16 iVal){
  162746. aOut[0] = (iVal>>8);
  162747. aOut[1] = (iVal&0xFF);
  162748. }
  162749. static u16 fts5GetU16(const u8 *aIn){
  162750. return ((u16)aIn[0] << 8) + aIn[1];
  162751. }
  162752. /*
  162753. ** Allocate and return a buffer at least nByte bytes in size.
  162754. **
  162755. ** If an OOM error is encountered, return NULL and set the error code in
  162756. ** the Fts5Index handle passed as the first argument.
  162757. */
  162758. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  162759. return sqlite3Fts5MallocZero(&p->rc, nByte);
  162760. }
  162761. /*
  162762. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  162763. **
  162764. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  162765. ** +ve if pRight is smaller than pLeft. In other words:
  162766. **
  162767. ** res = *pLeft - *pRight
  162768. */
  162769. #ifdef SQLITE_DEBUG
  162770. static int fts5BufferCompareBlob(
  162771. Fts5Buffer *pLeft, /* Left hand side of comparison */
  162772. const u8 *pRight, int nRight /* Right hand side of comparison */
  162773. ){
  162774. int nCmp = MIN(pLeft->n, nRight);
  162775. int res = memcmp(pLeft->p, pRight, nCmp);
  162776. return (res==0 ? (pLeft->n - nRight) : res);
  162777. }
  162778. #endif
  162779. /*
  162780. ** Compare the contents of the two buffers using memcmp(). If one buffer
  162781. ** is a prefix of the other, it is considered the lesser.
  162782. **
  162783. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  162784. ** +ve if pRight is smaller than pLeft. In other words:
  162785. **
  162786. ** res = *pLeft - *pRight
  162787. */
  162788. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  162789. int nCmp = MIN(pLeft->n, pRight->n);
  162790. int res = memcmp(pLeft->p, pRight->p, nCmp);
  162791. return (res==0 ? (pLeft->n - pRight->n) : res);
  162792. }
  162793. #ifdef SQLITE_DEBUG
  162794. static int fts5BlobCompare(
  162795. const u8 *pLeft, int nLeft,
  162796. const u8 *pRight, int nRight
  162797. ){
  162798. int nCmp = MIN(nLeft, nRight);
  162799. int res = memcmp(pLeft, pRight, nCmp);
  162800. return (res==0 ? (nLeft - nRight) : res);
  162801. }
  162802. #endif
  162803. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  162804. int ret;
  162805. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  162806. return ret;
  162807. }
  162808. /*
  162809. ** Close the read-only blob handle, if it is open.
  162810. */
  162811. static void fts5CloseReader(Fts5Index *p){
  162812. if( p->pReader ){
  162813. sqlite3_blob *pReader = p->pReader;
  162814. p->pReader = 0;
  162815. sqlite3_blob_close(pReader);
  162816. }
  162817. }
  162818. /*
  162819. ** Retrieve a record from the %_data table.
  162820. **
  162821. ** If an error occurs, NULL is returned and an error left in the
  162822. ** Fts5Index object.
  162823. */
  162824. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  162825. Fts5Data *pRet = 0;
  162826. if( p->rc==SQLITE_OK ){
  162827. int rc = SQLITE_OK;
  162828. if( p->pReader ){
  162829. /* This call may return SQLITE_ABORT if there has been a savepoint
  162830. ** rollback since it was last used. In this case a new blob handle
  162831. ** is required. */
  162832. sqlite3_blob *pBlob = p->pReader;
  162833. p->pReader = 0;
  162834. rc = sqlite3_blob_reopen(pBlob, iRowid);
  162835. assert( p->pReader==0 );
  162836. p->pReader = pBlob;
  162837. if( rc!=SQLITE_OK ){
  162838. fts5CloseReader(p);
  162839. }
  162840. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  162841. }
  162842. /* If the blob handle is not open at this point, open it and seek
  162843. ** to the requested entry. */
  162844. if( p->pReader==0 && rc==SQLITE_OK ){
  162845. Fts5Config *pConfig = p->pConfig;
  162846. rc = sqlite3_blob_open(pConfig->db,
  162847. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  162848. );
  162849. }
  162850. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  162851. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  162852. ** All the reasons those functions might return SQLITE_ERROR - missing
  162853. ** table, missing row, non-blob/text in block column - indicate
  162854. ** backing store corruption. */
  162855. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  162856. if( rc==SQLITE_OK ){
  162857. u8 *aOut = 0; /* Read blob data into this buffer */
  162858. int nByte = sqlite3_blob_bytes(p->pReader);
  162859. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  162860. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  162861. if( pRet ){
  162862. pRet->nn = nByte;
  162863. aOut = pRet->p = (u8*)&pRet[1];
  162864. }else{
  162865. rc = SQLITE_NOMEM;
  162866. }
  162867. if( rc==SQLITE_OK ){
  162868. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  162869. }
  162870. if( rc!=SQLITE_OK ){
  162871. sqlite3_free(pRet);
  162872. pRet = 0;
  162873. }else{
  162874. /* TODO1: Fix this */
  162875. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  162876. }
  162877. }
  162878. p->rc = rc;
  162879. p->nRead++;
  162880. }
  162881. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  162882. return pRet;
  162883. }
  162884. /*
  162885. ** Release a reference to data record returned by an earlier call to
  162886. ** fts5DataRead().
  162887. */
  162888. static void fts5DataRelease(Fts5Data *pData){
  162889. sqlite3_free(pData);
  162890. }
  162891. static int fts5IndexPrepareStmt(
  162892. Fts5Index *p,
  162893. sqlite3_stmt **ppStmt,
  162894. char *zSql
  162895. ){
  162896. if( p->rc==SQLITE_OK ){
  162897. if( zSql ){
  162898. p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
  162899. }else{
  162900. p->rc = SQLITE_NOMEM;
  162901. }
  162902. }
  162903. sqlite3_free(zSql);
  162904. return p->rc;
  162905. }
  162906. /*
  162907. ** INSERT OR REPLACE a record into the %_data table.
  162908. */
  162909. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  162910. if( p->rc!=SQLITE_OK ) return;
  162911. if( p->pWriter==0 ){
  162912. Fts5Config *pConfig = p->pConfig;
  162913. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  162914. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  162915. pConfig->zDb, pConfig->zName
  162916. ));
  162917. if( p->rc ) return;
  162918. }
  162919. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  162920. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  162921. sqlite3_step(p->pWriter);
  162922. p->rc = sqlite3_reset(p->pWriter);
  162923. }
  162924. /*
  162925. ** Execute the following SQL:
  162926. **
  162927. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  162928. */
  162929. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  162930. if( p->rc!=SQLITE_OK ) return;
  162931. if( p->pDeleter==0 ){
  162932. int rc;
  162933. Fts5Config *pConfig = p->pConfig;
  162934. char *zSql = sqlite3_mprintf(
  162935. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  162936. pConfig->zDb, pConfig->zName
  162937. );
  162938. if( zSql==0 ){
  162939. rc = SQLITE_NOMEM;
  162940. }else{
  162941. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
  162942. sqlite3_free(zSql);
  162943. }
  162944. if( rc!=SQLITE_OK ){
  162945. p->rc = rc;
  162946. return;
  162947. }
  162948. }
  162949. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  162950. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  162951. sqlite3_step(p->pDeleter);
  162952. p->rc = sqlite3_reset(p->pDeleter);
  162953. }
  162954. /*
  162955. ** Remove all records associated with segment iSegid.
  162956. */
  162957. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  162958. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  162959. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  162960. fts5DataDelete(p, iFirst, iLast);
  162961. if( p->pIdxDeleter==0 ){
  162962. Fts5Config *pConfig = p->pConfig;
  162963. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  162964. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  162965. pConfig->zDb, pConfig->zName
  162966. ));
  162967. }
  162968. if( p->rc==SQLITE_OK ){
  162969. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  162970. sqlite3_step(p->pIdxDeleter);
  162971. p->rc = sqlite3_reset(p->pIdxDeleter);
  162972. }
  162973. }
  162974. /*
  162975. ** Release a reference to an Fts5Structure object returned by an earlier
  162976. ** call to fts5StructureRead() or fts5StructureDecode().
  162977. */
  162978. static void fts5StructureRelease(Fts5Structure *pStruct){
  162979. if( pStruct && 0>=(--pStruct->nRef) ){
  162980. int i;
  162981. assert( pStruct->nRef==0 );
  162982. for(i=0; i<pStruct->nLevel; i++){
  162983. sqlite3_free(pStruct->aLevel[i].aSeg);
  162984. }
  162985. sqlite3_free(pStruct);
  162986. }
  162987. }
  162988. static void fts5StructureRef(Fts5Structure *pStruct){
  162989. pStruct->nRef++;
  162990. }
  162991. /*
  162992. ** Deserialize and return the structure record currently stored in serialized
  162993. ** form within buffer pData/nData.
  162994. **
  162995. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  162996. ** are over-allocated by one slot. This allows the structure contents
  162997. ** to be more easily edited.
  162998. **
  162999. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  163000. ** returned. Otherwise, *ppOut is set to point to the new object and
  163001. ** SQLITE_OK returned.
  163002. */
  163003. static int fts5StructureDecode(
  163004. const u8 *pData, /* Buffer containing serialized structure */
  163005. int nData, /* Size of buffer pData in bytes */
  163006. int *piCookie, /* Configuration cookie value */
  163007. Fts5Structure **ppOut /* OUT: Deserialized object */
  163008. ){
  163009. int rc = SQLITE_OK;
  163010. int i = 0;
  163011. int iLvl;
  163012. int nLevel = 0;
  163013. int nSegment = 0;
  163014. int nByte; /* Bytes of space to allocate at pRet */
  163015. Fts5Structure *pRet = 0; /* Structure object to return */
  163016. /* Grab the cookie value */
  163017. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  163018. i = 4;
  163019. /* Read the total number of levels and segments from the start of the
  163020. ** structure record. */
  163021. i += fts5GetVarint32(&pData[i], nLevel);
  163022. i += fts5GetVarint32(&pData[i], nSegment);
  163023. nByte = (
  163024. sizeof(Fts5Structure) + /* Main structure */
  163025. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  163026. );
  163027. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  163028. if( pRet ){
  163029. pRet->nRef = 1;
  163030. pRet->nLevel = nLevel;
  163031. pRet->nSegment = nSegment;
  163032. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  163033. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  163034. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  163035. int nTotal;
  163036. int iSeg;
  163037. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  163038. i += fts5GetVarint32(&pData[i], nTotal);
  163039. assert( nTotal>=pLvl->nMerge );
  163040. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  163041. nTotal * sizeof(Fts5StructureSegment)
  163042. );
  163043. if( rc==SQLITE_OK ){
  163044. pLvl->nSeg = nTotal;
  163045. for(iSeg=0; iSeg<nTotal; iSeg++){
  163046. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  163047. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  163048. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  163049. }
  163050. }else{
  163051. fts5StructureRelease(pRet);
  163052. pRet = 0;
  163053. }
  163054. }
  163055. }
  163056. *ppOut = pRet;
  163057. return rc;
  163058. }
  163059. /*
  163060. **
  163061. */
  163062. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  163063. if( *pRc==SQLITE_OK ){
  163064. Fts5Structure *pStruct = *ppStruct;
  163065. int nLevel = pStruct->nLevel;
  163066. int nByte = (
  163067. sizeof(Fts5Structure) + /* Main structure */
  163068. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  163069. );
  163070. pStruct = sqlite3_realloc(pStruct, nByte);
  163071. if( pStruct ){
  163072. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  163073. pStruct->nLevel++;
  163074. *ppStruct = pStruct;
  163075. }else{
  163076. *pRc = SQLITE_NOMEM;
  163077. }
  163078. }
  163079. }
  163080. /*
  163081. ** Extend level iLvl so that there is room for at least nExtra more
  163082. ** segments.
  163083. */
  163084. static void fts5StructureExtendLevel(
  163085. int *pRc,
  163086. Fts5Structure *pStruct,
  163087. int iLvl,
  163088. int nExtra,
  163089. int bInsert
  163090. ){
  163091. if( *pRc==SQLITE_OK ){
  163092. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  163093. Fts5StructureSegment *aNew;
  163094. int nByte;
  163095. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  163096. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  163097. if( aNew ){
  163098. if( bInsert==0 ){
  163099. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  163100. }else{
  163101. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  163102. memmove(&aNew[nExtra], aNew, nMove);
  163103. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  163104. }
  163105. pLvl->aSeg = aNew;
  163106. }else{
  163107. *pRc = SQLITE_NOMEM;
  163108. }
  163109. }
  163110. }
  163111. /*
  163112. ** Read, deserialize and return the structure record.
  163113. **
  163114. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  163115. ** are over-allocated as described for function fts5StructureDecode()
  163116. ** above.
  163117. **
  163118. ** If an error occurs, NULL is returned and an error code left in the
  163119. ** Fts5Index handle. If an error has already occurred when this function
  163120. ** is called, it is a no-op.
  163121. */
  163122. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  163123. Fts5Config *pConfig = p->pConfig;
  163124. Fts5Structure *pRet = 0; /* Object to return */
  163125. int iCookie; /* Configuration cookie */
  163126. Fts5Data *pData;
  163127. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  163128. if( p->rc ) return 0;
  163129. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  163130. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  163131. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  163132. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  163133. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  163134. }
  163135. fts5DataRelease(pData);
  163136. if( p->rc!=SQLITE_OK ){
  163137. fts5StructureRelease(pRet);
  163138. pRet = 0;
  163139. }
  163140. return pRet;
  163141. }
  163142. /*
  163143. ** Return the total number of segments in index structure pStruct. This
  163144. ** function is only ever used as part of assert() conditions.
  163145. */
  163146. #ifdef SQLITE_DEBUG
  163147. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  163148. int nSegment = 0; /* Total number of segments */
  163149. if( pStruct ){
  163150. int iLvl; /* Used to iterate through levels */
  163151. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  163152. nSegment += pStruct->aLevel[iLvl].nSeg;
  163153. }
  163154. }
  163155. return nSegment;
  163156. }
  163157. #endif
  163158. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  163159. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  163160. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  163161. (pBuf)->n += nBlob; \
  163162. }
  163163. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  163164. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  163165. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  163166. }
  163167. /*
  163168. ** Serialize and store the "structure" record.
  163169. **
  163170. ** If an error occurs, leave an error code in the Fts5Index object. If an
  163171. ** error has already occurred, this function is a no-op.
  163172. */
  163173. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  163174. if( p->rc==SQLITE_OK ){
  163175. Fts5Buffer buf; /* Buffer to serialize record into */
  163176. int iLvl; /* Used to iterate through levels */
  163177. int iCookie; /* Cookie value to store */
  163178. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  163179. memset(&buf, 0, sizeof(Fts5Buffer));
  163180. /* Append the current configuration cookie */
  163181. iCookie = p->pConfig->iCookie;
  163182. if( iCookie<0 ) iCookie = 0;
  163183. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  163184. sqlite3Fts5Put32(buf.p, iCookie);
  163185. buf.n = 4;
  163186. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  163187. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  163188. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  163189. }
  163190. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  163191. int iSeg; /* Used to iterate through segments */
  163192. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  163193. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  163194. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  163195. assert( pLvl->nMerge<=pLvl->nSeg );
  163196. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  163197. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  163198. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  163199. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  163200. }
  163201. }
  163202. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  163203. fts5BufferFree(&buf);
  163204. }
  163205. }
  163206. #if 0
  163207. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  163208. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  163209. int rc = SQLITE_OK;
  163210. Fts5Buffer buf;
  163211. memset(&buf, 0, sizeof(buf));
  163212. fts5DebugStructure(&rc, &buf, pStruct);
  163213. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  163214. fflush(stdout);
  163215. fts5BufferFree(&buf);
  163216. }
  163217. #else
  163218. # define fts5PrintStructure(x,y)
  163219. #endif
  163220. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  163221. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  163222. }
  163223. /*
  163224. ** Return a copy of index structure pStruct. Except, promote as many
  163225. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  163226. ** returned.
  163227. */
  163228. static void fts5StructurePromoteTo(
  163229. Fts5Index *p,
  163230. int iPromote,
  163231. int szPromote,
  163232. Fts5Structure *pStruct
  163233. ){
  163234. int il, is;
  163235. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  163236. if( pOut->nMerge==0 ){
  163237. for(il=iPromote+1; il<pStruct->nLevel; il++){
  163238. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  163239. if( pLvl->nMerge ) return;
  163240. for(is=pLvl->nSeg-1; is>=0; is--){
  163241. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  163242. if( sz>szPromote ) return;
  163243. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  163244. if( p->rc ) return;
  163245. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  163246. pOut->nSeg++;
  163247. pLvl->nSeg--;
  163248. }
  163249. }
  163250. }
  163251. }
  163252. /*
  163253. ** A new segment has just been written to level iLvl of index structure
  163254. ** pStruct. This function determines if any segments should be promoted
  163255. ** as a result. Segments are promoted in two scenarios:
  163256. **
  163257. ** a) If the segment just written is smaller than one or more segments
  163258. ** within the previous populated level, it is promoted to the previous
  163259. ** populated level.
  163260. **
  163261. ** b) If the segment just written is larger than the newest segment on
  163262. ** the next populated level, then that segment, and any other adjacent
  163263. ** segments that are also smaller than the one just written, are
  163264. ** promoted.
  163265. **
  163266. ** If one or more segments are promoted, the structure object is updated
  163267. ** to reflect this.
  163268. */
  163269. static void fts5StructurePromote(
  163270. Fts5Index *p, /* FTS5 backend object */
  163271. int iLvl, /* Index level just updated */
  163272. Fts5Structure *pStruct /* Index structure */
  163273. ){
  163274. if( p->rc==SQLITE_OK ){
  163275. int iTst;
  163276. int iPromote = -1;
  163277. int szPromote = 0; /* Promote anything this size or smaller */
  163278. Fts5StructureSegment *pSeg; /* Segment just written */
  163279. int szSeg; /* Size of segment just written */
  163280. int nSeg = pStruct->aLevel[iLvl].nSeg;
  163281. if( nSeg==0 ) return;
  163282. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  163283. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  163284. /* Check for condition (a) */
  163285. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  163286. if( iTst>=0 ){
  163287. int i;
  163288. int szMax = 0;
  163289. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  163290. assert( pTst->nMerge==0 );
  163291. for(i=0; i<pTst->nSeg; i++){
  163292. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  163293. if( sz>szMax ) szMax = sz;
  163294. }
  163295. if( szMax>=szSeg ){
  163296. /* Condition (a) is true. Promote the newest segment on level
  163297. ** iLvl to level iTst. */
  163298. iPromote = iTst;
  163299. szPromote = szMax;
  163300. }
  163301. }
  163302. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  163303. ** is a no-op if it is not. */
  163304. if( iPromote<0 ){
  163305. iPromote = iLvl;
  163306. szPromote = szSeg;
  163307. }
  163308. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  163309. }
  163310. }
  163311. /*
  163312. ** Advance the iterator passed as the only argument. If the end of the
  163313. ** doclist-index page is reached, return non-zero.
  163314. */
  163315. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  163316. Fts5Data *pData = pLvl->pData;
  163317. if( pLvl->iOff==0 ){
  163318. assert( pLvl->bEof==0 );
  163319. pLvl->iOff = 1;
  163320. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  163321. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  163322. pLvl->iFirstOff = pLvl->iOff;
  163323. }else{
  163324. int iOff;
  163325. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  163326. if( pData->p[iOff] ) break;
  163327. }
  163328. if( iOff<pData->nn ){
  163329. i64 iVal;
  163330. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  163331. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  163332. pLvl->iRowid += iVal;
  163333. pLvl->iOff = iOff;
  163334. }else{
  163335. pLvl->bEof = 1;
  163336. }
  163337. }
  163338. return pLvl->bEof;
  163339. }
  163340. /*
  163341. ** Advance the iterator passed as the only argument.
  163342. */
  163343. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  163344. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  163345. assert( iLvl<pIter->nLvl );
  163346. if( fts5DlidxLvlNext(pLvl) ){
  163347. if( (iLvl+1) < pIter->nLvl ){
  163348. fts5DlidxIterNextR(p, pIter, iLvl+1);
  163349. if( pLvl[1].bEof==0 ){
  163350. fts5DataRelease(pLvl->pData);
  163351. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  163352. pLvl->pData = fts5DataRead(p,
  163353. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  163354. );
  163355. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  163356. }
  163357. }
  163358. }
  163359. return pIter->aLvl[0].bEof;
  163360. }
  163361. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  163362. return fts5DlidxIterNextR(p, pIter, 0);
  163363. }
  163364. /*
  163365. ** The iterator passed as the first argument has the following fields set
  163366. ** as follows. This function sets up the rest of the iterator so that it
  163367. ** points to the first rowid in the doclist-index.
  163368. **
  163369. ** pData:
  163370. ** pointer to doclist-index record,
  163371. **
  163372. ** When this function is called pIter->iLeafPgno is the page number the
  163373. ** doclist is associated with (the one featuring the term).
  163374. */
  163375. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  163376. int i;
  163377. for(i=0; i<pIter->nLvl; i++){
  163378. fts5DlidxLvlNext(&pIter->aLvl[i]);
  163379. }
  163380. return pIter->aLvl[0].bEof;
  163381. }
  163382. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  163383. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  163384. }
  163385. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  163386. int i;
  163387. /* Advance each level to the last entry on the last page */
  163388. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  163389. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  163390. while( fts5DlidxLvlNext(pLvl)==0 );
  163391. pLvl->bEof = 0;
  163392. if( i>0 ){
  163393. Fts5DlidxLvl *pChild = &pLvl[-1];
  163394. fts5DataRelease(pChild->pData);
  163395. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  163396. pChild->pData = fts5DataRead(p,
  163397. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  163398. );
  163399. }
  163400. }
  163401. }
  163402. /*
  163403. ** Move the iterator passed as the only argument to the previous entry.
  163404. */
  163405. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  163406. int iOff = pLvl->iOff;
  163407. assert( pLvl->bEof==0 );
  163408. if( iOff<=pLvl->iFirstOff ){
  163409. pLvl->bEof = 1;
  163410. }else{
  163411. u8 *a = pLvl->pData->p;
  163412. i64 iVal;
  163413. int iLimit;
  163414. int ii;
  163415. int nZero = 0;
  163416. /* Currently iOff points to the first byte of a varint. This block
  163417. ** decrements iOff until it points to the first byte of the previous
  163418. ** varint. Taking care not to read any memory locations that occur
  163419. ** before the buffer in memory. */
  163420. iLimit = (iOff>9 ? iOff-9 : 0);
  163421. for(iOff--; iOff>iLimit; iOff--){
  163422. if( (a[iOff-1] & 0x80)==0 ) break;
  163423. }
  163424. fts5GetVarint(&a[iOff], (u64*)&iVal);
  163425. pLvl->iRowid -= iVal;
  163426. pLvl->iLeafPgno--;
  163427. /* Skip backwards past any 0x00 varints. */
  163428. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  163429. nZero++;
  163430. }
  163431. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  163432. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  163433. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  163434. ** bytes before a[ii]. */
  163435. int bZero = 0; /* True if last 0x00 counts */
  163436. if( (ii-8)>=pLvl->iFirstOff ){
  163437. int j;
  163438. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  163439. bZero = (j>8);
  163440. }
  163441. if( bZero==0 ) nZero--;
  163442. }
  163443. pLvl->iLeafPgno -= nZero;
  163444. pLvl->iOff = iOff - nZero;
  163445. }
  163446. return pLvl->bEof;
  163447. }
  163448. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  163449. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  163450. assert( iLvl<pIter->nLvl );
  163451. if( fts5DlidxLvlPrev(pLvl) ){
  163452. if( (iLvl+1) < pIter->nLvl ){
  163453. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  163454. if( pLvl[1].bEof==0 ){
  163455. fts5DataRelease(pLvl->pData);
  163456. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  163457. pLvl->pData = fts5DataRead(p,
  163458. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  163459. );
  163460. if( pLvl->pData ){
  163461. while( fts5DlidxLvlNext(pLvl)==0 );
  163462. pLvl->bEof = 0;
  163463. }
  163464. }
  163465. }
  163466. }
  163467. return pIter->aLvl[0].bEof;
  163468. }
  163469. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  163470. return fts5DlidxIterPrevR(p, pIter, 0);
  163471. }
  163472. /*
  163473. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  163474. */
  163475. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  163476. if( pIter ){
  163477. int i;
  163478. for(i=0; i<pIter->nLvl; i++){
  163479. fts5DataRelease(pIter->aLvl[i].pData);
  163480. }
  163481. sqlite3_free(pIter);
  163482. }
  163483. }
  163484. static Fts5DlidxIter *fts5DlidxIterInit(
  163485. Fts5Index *p, /* Fts5 Backend to iterate within */
  163486. int bRev, /* True for ORDER BY ASC */
  163487. int iSegid, /* Segment id */
  163488. int iLeafPg /* Leaf page number to load dlidx for */
  163489. ){
  163490. Fts5DlidxIter *pIter = 0;
  163491. int i;
  163492. int bDone = 0;
  163493. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  163494. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  163495. Fts5DlidxIter *pNew;
  163496. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  163497. if( pNew==0 ){
  163498. p->rc = SQLITE_NOMEM;
  163499. }else{
  163500. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  163501. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  163502. pIter = pNew;
  163503. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  163504. pLvl->pData = fts5DataRead(p, iRowid);
  163505. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  163506. bDone = 1;
  163507. }
  163508. pIter->nLvl = i+1;
  163509. }
  163510. }
  163511. if( p->rc==SQLITE_OK ){
  163512. pIter->iSegid = iSegid;
  163513. if( bRev==0 ){
  163514. fts5DlidxIterFirst(pIter);
  163515. }else{
  163516. fts5DlidxIterLast(p, pIter);
  163517. }
  163518. }
  163519. if( p->rc!=SQLITE_OK ){
  163520. fts5DlidxIterFree(pIter);
  163521. pIter = 0;
  163522. }
  163523. return pIter;
  163524. }
  163525. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  163526. return pIter->aLvl[0].iRowid;
  163527. }
  163528. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  163529. return pIter->aLvl[0].iLeafPgno;
  163530. }
  163531. /*
  163532. ** Load the next leaf page into the segment iterator.
  163533. */
  163534. static void fts5SegIterNextPage(
  163535. Fts5Index *p, /* FTS5 backend object */
  163536. Fts5SegIter *pIter /* Iterator to advance to next page */
  163537. ){
  163538. Fts5Data *pLeaf;
  163539. Fts5StructureSegment *pSeg = pIter->pSeg;
  163540. fts5DataRelease(pIter->pLeaf);
  163541. pIter->iLeafPgno++;
  163542. if( pIter->pNextLeaf ){
  163543. pIter->pLeaf = pIter->pNextLeaf;
  163544. pIter->pNextLeaf = 0;
  163545. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  163546. pIter->pLeaf = fts5DataRead(p,
  163547. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  163548. );
  163549. }else{
  163550. pIter->pLeaf = 0;
  163551. }
  163552. pLeaf = pIter->pLeaf;
  163553. if( pLeaf ){
  163554. pIter->iPgidxOff = pLeaf->szLeaf;
  163555. if( fts5LeafIsTermless(pLeaf) ){
  163556. pIter->iEndofDoclist = pLeaf->nn+1;
  163557. }else{
  163558. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  163559. pIter->iEndofDoclist
  163560. );
  163561. }
  163562. }
  163563. }
  163564. /*
  163565. ** Argument p points to a buffer containing a varint to be interpreted as a
  163566. ** position list size field. Read the varint and return the number of bytes
  163567. ** read. Before returning, set *pnSz to the number of bytes in the position
  163568. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  163569. */
  163570. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  163571. int nSz;
  163572. int n = 0;
  163573. fts5FastGetVarint32(p, n, nSz);
  163574. assert_nc( nSz>=0 );
  163575. *pnSz = nSz/2;
  163576. *pbDel = nSz & 0x0001;
  163577. return n;
  163578. }
  163579. /*
  163580. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  163581. ** position-list size field. Read the value of the field and store it
  163582. ** in the following variables:
  163583. **
  163584. ** Fts5SegIter.nPos
  163585. ** Fts5SegIter.bDel
  163586. **
  163587. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  163588. ** position list content (if any).
  163589. */
  163590. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  163591. if( p->rc==SQLITE_OK ){
  163592. int iOff = pIter->iLeafOffset; /* Offset to read at */
  163593. int nSz;
  163594. ASSERT_SZLEAF_OK(pIter->pLeaf);
  163595. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  163596. pIter->bDel = (nSz & 0x0001);
  163597. pIter->nPos = nSz>>1;
  163598. pIter->iLeafOffset = iOff;
  163599. assert_nc( pIter->nPos>=0 );
  163600. }
  163601. }
  163602. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  163603. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  163604. int iOff = pIter->iLeafOffset;
  163605. ASSERT_SZLEAF_OK(pIter->pLeaf);
  163606. if( iOff>=pIter->pLeaf->szLeaf ){
  163607. fts5SegIterNextPage(p, pIter);
  163608. if( pIter->pLeaf==0 ){
  163609. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  163610. return;
  163611. }
  163612. iOff = 4;
  163613. a = pIter->pLeaf->p;
  163614. }
  163615. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  163616. pIter->iLeafOffset = iOff;
  163617. }
  163618. /*
  163619. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  163620. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  163621. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  163622. ** the first term in the segment).
  163623. **
  163624. ** This function populates:
  163625. **
  163626. ** Fts5SegIter.term
  163627. ** Fts5SegIter.rowid
  163628. **
  163629. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  163630. ** the first position list. The position list belonging to document
  163631. ** (Fts5SegIter.iRowid).
  163632. */
  163633. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  163634. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  163635. int iOff = pIter->iLeafOffset; /* Offset to read at */
  163636. int nNew; /* Bytes of new data */
  163637. iOff += fts5GetVarint32(&a[iOff], nNew);
  163638. pIter->term.n = nKeep;
  163639. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  163640. iOff += nNew;
  163641. pIter->iTermLeafOffset = iOff;
  163642. pIter->iTermLeafPgno = pIter->iLeafPgno;
  163643. pIter->iLeafOffset = iOff;
  163644. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  163645. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  163646. }else{
  163647. int nExtra;
  163648. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  163649. pIter->iEndofDoclist += nExtra;
  163650. }
  163651. fts5SegIterLoadRowid(p, pIter);
  163652. }
  163653. /*
  163654. ** Initialize the iterator object pIter to iterate through the entries in
  163655. ** segment pSeg. The iterator is left pointing to the first entry when
  163656. ** this function returns.
  163657. **
  163658. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  163659. ** an error has already occurred when this function is called, it is a no-op.
  163660. */
  163661. static void fts5SegIterInit(
  163662. Fts5Index *p, /* FTS index object */
  163663. Fts5StructureSegment *pSeg, /* Description of segment */
  163664. Fts5SegIter *pIter /* Object to populate */
  163665. ){
  163666. if( pSeg->pgnoFirst==0 ){
  163667. /* This happens if the segment is being used as an input to an incremental
  163668. ** merge and all data has already been "trimmed". See function
  163669. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  163670. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  163671. ** at EOF already. */
  163672. assert( pIter->pLeaf==0 );
  163673. return;
  163674. }
  163675. if( p->rc==SQLITE_OK ){
  163676. memset(pIter, 0, sizeof(*pIter));
  163677. pIter->pSeg = pSeg;
  163678. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  163679. fts5SegIterNextPage(p, pIter);
  163680. }
  163681. if( p->rc==SQLITE_OK ){
  163682. pIter->iLeafOffset = 4;
  163683. assert_nc( pIter->pLeaf->nn>4 );
  163684. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  163685. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  163686. fts5SegIterLoadTerm(p, pIter, 0);
  163687. fts5SegIterLoadNPos(p, pIter);
  163688. }
  163689. }
  163690. /*
  163691. ** This function is only ever called on iterators created by calls to
  163692. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  163693. **
  163694. ** The iterator is in an unusual state when this function is called: the
  163695. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  163696. ** the position-list size field for the first relevant rowid on the page.
  163697. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  163698. **
  163699. ** This function advances the iterator so that it points to the last
  163700. ** relevant rowid on the page and, if necessary, initializes the
  163701. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  163702. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  163703. ** byte of the position list content associated with said rowid.
  163704. */
  163705. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  163706. int n = pIter->pLeaf->szLeaf;
  163707. int i = pIter->iLeafOffset;
  163708. u8 *a = pIter->pLeaf->p;
  163709. int iRowidOffset = 0;
  163710. if( n>pIter->iEndofDoclist ){
  163711. n = pIter->iEndofDoclist;
  163712. }
  163713. ASSERT_SZLEAF_OK(pIter->pLeaf);
  163714. while( 1 ){
  163715. i64 iDelta = 0;
  163716. int nPos;
  163717. int bDummy;
  163718. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  163719. i += nPos;
  163720. if( i>=n ) break;
  163721. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  163722. pIter->iRowid += iDelta;
  163723. if( iRowidOffset>=pIter->nRowidOffset ){
  163724. int nNew = pIter->nRowidOffset + 8;
  163725. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  163726. if( aNew==0 ){
  163727. p->rc = SQLITE_NOMEM;
  163728. break;
  163729. }
  163730. pIter->aRowidOffset = aNew;
  163731. pIter->nRowidOffset = nNew;
  163732. }
  163733. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  163734. pIter->iLeafOffset = i;
  163735. }
  163736. pIter->iRowidOffset = iRowidOffset;
  163737. fts5SegIterLoadNPos(p, pIter);
  163738. }
  163739. /*
  163740. **
  163741. */
  163742. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  163743. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  163744. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  163745. fts5DataRelease(pIter->pLeaf);
  163746. pIter->pLeaf = 0;
  163747. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  163748. Fts5Data *pNew;
  163749. pIter->iLeafPgno--;
  163750. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  163751. pIter->pSeg->iSegid, pIter->iLeafPgno
  163752. ));
  163753. if( pNew ){
  163754. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  163755. ** thing on the page - i.e. the first rowid is on the following page.
  163756. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  163757. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  163758. assert( pIter->pLeaf==0 );
  163759. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  163760. pIter->pLeaf = pNew;
  163761. pIter->iLeafOffset = pIter->iTermLeafOffset;
  163762. }
  163763. }else{
  163764. int iRowidOff;
  163765. iRowidOff = fts5LeafFirstRowidOff(pNew);
  163766. if( iRowidOff ){
  163767. pIter->pLeaf = pNew;
  163768. pIter->iLeafOffset = iRowidOff;
  163769. }
  163770. }
  163771. if( pIter->pLeaf ){
  163772. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  163773. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  163774. break;
  163775. }else{
  163776. fts5DataRelease(pNew);
  163777. }
  163778. }
  163779. }
  163780. if( pIter->pLeaf ){
  163781. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  163782. fts5SegIterReverseInitPage(p, pIter);
  163783. }
  163784. }
  163785. /*
  163786. ** Return true if the iterator passed as the second argument currently
  163787. ** points to a delete marker. A delete marker is an entry with a 0 byte
  163788. ** position-list.
  163789. */
  163790. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5IndexIter *pIter){
  163791. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  163792. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  163793. }
  163794. /*
  163795. ** Advance iterator pIter to the next entry.
  163796. **
  163797. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  163798. ** is not considered an error if the iterator reaches EOF. If an error has
  163799. ** already occurred when this function is called, it is a no-op.
  163800. */
  163801. static void fts5SegIterNext(
  163802. Fts5Index *p, /* FTS5 backend object */
  163803. Fts5SegIter *pIter, /* Iterator to advance */
  163804. int *pbNewTerm /* OUT: Set for new term */
  163805. ){
  163806. assert( pbNewTerm==0 || *pbNewTerm==0 );
  163807. if( p->rc==SQLITE_OK ){
  163808. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  163809. assert( pIter->pNextLeaf==0 );
  163810. if( pIter->iRowidOffset>0 ){
  163811. u8 *a = pIter->pLeaf->p;
  163812. int iOff;
  163813. int nPos;
  163814. int bDummy;
  163815. i64 iDelta;
  163816. pIter->iRowidOffset--;
  163817. pIter->iLeafOffset = iOff = pIter->aRowidOffset[pIter->iRowidOffset];
  163818. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDummy);
  163819. iOff += nPos;
  163820. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  163821. pIter->iRowid -= iDelta;
  163822. fts5SegIterLoadNPos(p, pIter);
  163823. }else{
  163824. fts5SegIterReverseNewPage(p, pIter);
  163825. }
  163826. }else{
  163827. Fts5Data *pLeaf = pIter->pLeaf;
  163828. int iOff;
  163829. int bNewTerm = 0;
  163830. int nKeep = 0;
  163831. /* Search for the end of the position list within the current page. */
  163832. u8 *a = pLeaf->p;
  163833. int n = pLeaf->szLeaf;
  163834. ASSERT_SZLEAF_OK(pLeaf);
  163835. iOff = pIter->iLeafOffset + pIter->nPos;
  163836. if( iOff<n ){
  163837. /* The next entry is on the current page. */
  163838. assert_nc( iOff<=pIter->iEndofDoclist );
  163839. if( iOff>=pIter->iEndofDoclist ){
  163840. bNewTerm = 1;
  163841. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  163842. iOff += fts5GetVarint32(&a[iOff], nKeep);
  163843. }
  163844. }else{
  163845. u64 iDelta;
  163846. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  163847. pIter->iRowid += iDelta;
  163848. assert_nc( iDelta>0 );
  163849. }
  163850. pIter->iLeafOffset = iOff;
  163851. }else if( pIter->pSeg==0 ){
  163852. const u8 *pList = 0;
  163853. const char *zTerm = 0;
  163854. int nList = 0;
  163855. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  163856. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  163857. sqlite3Fts5HashScanNext(p->pHash);
  163858. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  163859. }
  163860. if( pList==0 ){
  163861. fts5DataRelease(pIter->pLeaf);
  163862. pIter->pLeaf = 0;
  163863. }else{
  163864. pIter->pLeaf->p = (u8*)pList;
  163865. pIter->pLeaf->nn = nList;
  163866. pIter->pLeaf->szLeaf = nList;
  163867. pIter->iEndofDoclist = nList+1;
  163868. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  163869. (u8*)zTerm);
  163870. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  163871. *pbNewTerm = 1;
  163872. }
  163873. }else{
  163874. iOff = 0;
  163875. /* Next entry is not on the current page */
  163876. while( iOff==0 ){
  163877. fts5SegIterNextPage(p, pIter);
  163878. pLeaf = pIter->pLeaf;
  163879. if( pLeaf==0 ) break;
  163880. ASSERT_SZLEAF_OK(pLeaf);
  163881. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  163882. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  163883. pIter->iLeafOffset = iOff;
  163884. if( pLeaf->nn>pLeaf->szLeaf ){
  163885. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  163886. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  163887. );
  163888. }
  163889. }
  163890. else if( pLeaf->nn>pLeaf->szLeaf ){
  163891. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  163892. &pLeaf->p[pLeaf->szLeaf], iOff
  163893. );
  163894. pIter->iLeafOffset = iOff;
  163895. pIter->iEndofDoclist = iOff;
  163896. bNewTerm = 1;
  163897. }
  163898. if( iOff>=pLeaf->szLeaf ){
  163899. p->rc = FTS5_CORRUPT;
  163900. return;
  163901. }
  163902. }
  163903. }
  163904. /* Check if the iterator is now at EOF. If so, return early. */
  163905. if( pIter->pLeaf ){
  163906. if( bNewTerm ){
  163907. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  163908. fts5DataRelease(pIter->pLeaf);
  163909. pIter->pLeaf = 0;
  163910. }else{
  163911. fts5SegIterLoadTerm(p, pIter, nKeep);
  163912. fts5SegIterLoadNPos(p, pIter);
  163913. if( pbNewTerm ) *pbNewTerm = 1;
  163914. }
  163915. }else{
  163916. /* The following could be done by calling fts5SegIterLoadNPos(). But
  163917. ** this block is particularly performance critical, so equivalent
  163918. ** code is inlined. */
  163919. int nSz;
  163920. assert( p->rc==SQLITE_OK );
  163921. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  163922. pIter->bDel = (nSz & 0x0001);
  163923. pIter->nPos = nSz>>1;
  163924. assert_nc( pIter->nPos>=0 );
  163925. }
  163926. }
  163927. }
  163928. }
  163929. }
  163930. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  163931. /*
  163932. ** Iterator pIter currently points to the first rowid in a doclist. This
  163933. ** function sets the iterator up so that iterates in reverse order through
  163934. ** the doclist.
  163935. */
  163936. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  163937. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  163938. Fts5Data *pLast = 0;
  163939. int pgnoLast = 0;
  163940. if( pDlidx ){
  163941. int iSegid = pIter->pSeg->iSegid;
  163942. pgnoLast = fts5DlidxIterPgno(pDlidx);
  163943. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  163944. }else{
  163945. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  163946. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  163947. ** position-list content for the current rowid. Back it up so that it
  163948. ** points to the start of the position-list size field. */
  163949. pIter->iLeafOffset -= sqlite3Fts5GetVarintLen(pIter->nPos*2+pIter->bDel);
  163950. /* If this condition is true then the largest rowid for the current
  163951. ** term may not be stored on the current page. So search forward to
  163952. ** see where said rowid really is. */
  163953. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  163954. int pgno;
  163955. Fts5StructureSegment *pSeg = pIter->pSeg;
  163956. /* The last rowid in the doclist may not be on the current page. Search
  163957. ** forward to find the page containing the last rowid. */
  163958. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  163959. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  163960. Fts5Data *pNew = fts5DataRead(p, iAbs);
  163961. if( pNew ){
  163962. int iRowid, bTermless;
  163963. iRowid = fts5LeafFirstRowidOff(pNew);
  163964. bTermless = fts5LeafIsTermless(pNew);
  163965. if( iRowid ){
  163966. SWAPVAL(Fts5Data*, pNew, pLast);
  163967. pgnoLast = pgno;
  163968. }
  163969. fts5DataRelease(pNew);
  163970. if( bTermless==0 ) break;
  163971. }
  163972. }
  163973. }
  163974. }
  163975. /* If pLast is NULL at this point, then the last rowid for this doclist
  163976. ** lies on the page currently indicated by the iterator. In this case
  163977. ** pIter->iLeafOffset is already set to point to the position-list size
  163978. ** field associated with the first relevant rowid on the page.
  163979. **
  163980. ** Or, if pLast is non-NULL, then it is the page that contains the last
  163981. ** rowid. In this case configure the iterator so that it points to the
  163982. ** first rowid on this page.
  163983. */
  163984. if( pLast ){
  163985. int iOff;
  163986. fts5DataRelease(pIter->pLeaf);
  163987. pIter->pLeaf = pLast;
  163988. pIter->iLeafPgno = pgnoLast;
  163989. iOff = fts5LeafFirstRowidOff(pLast);
  163990. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  163991. pIter->iLeafOffset = iOff;
  163992. if( fts5LeafIsTermless(pLast) ){
  163993. pIter->iEndofDoclist = pLast->nn+1;
  163994. }else{
  163995. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  163996. }
  163997. }
  163998. fts5SegIterReverseInitPage(p, pIter);
  163999. }
  164000. /*
  164001. ** Iterator pIter currently points to the first rowid of a doclist.
  164002. ** There is a doclist-index associated with the final term on the current
  164003. ** page. If the current term is the last term on the page, load the
  164004. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  164005. */
  164006. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  164007. int iSeg = pIter->pSeg->iSegid;
  164008. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  164009. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  164010. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  164011. assert( pIter->pDlidx==0 );
  164012. /* Check if the current doclist ends on this page. If it does, return
  164013. ** early without loading the doclist-index (as it belongs to a different
  164014. ** term. */
  164015. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  164016. && pIter->iEndofDoclist<pLeaf->szLeaf
  164017. ){
  164018. return;
  164019. }
  164020. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  164021. }
  164022. #define fts5IndexSkipVarint(a, iOff) { \
  164023. int iEnd = iOff+9; \
  164024. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  164025. }
  164026. /*
  164027. ** The iterator object passed as the second argument currently contains
  164028. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  164029. ** function searches the leaf page for a term matching (pTerm/nTerm).
  164030. **
  164031. ** If the specified term is found on the page, then the iterator is left
  164032. ** pointing to it. If argument bGe is zero and the term is not found,
  164033. ** the iterator is left pointing at EOF.
  164034. **
  164035. ** If bGe is non-zero and the specified term is not found, then the
  164036. ** iterator is left pointing to the smallest term in the segment that
  164037. ** is larger than the specified term, even if this term is not on the
  164038. ** current page.
  164039. */
  164040. static void fts5LeafSeek(
  164041. Fts5Index *p, /* Leave any error code here */
  164042. int bGe, /* True for a >= search */
  164043. Fts5SegIter *pIter, /* Iterator to seek */
  164044. const u8 *pTerm, int nTerm /* Term to search for */
  164045. ){
  164046. int iOff;
  164047. const u8 *a = pIter->pLeaf->p;
  164048. int szLeaf = pIter->pLeaf->szLeaf;
  164049. int n = pIter->pLeaf->nn;
  164050. int nMatch = 0;
  164051. int nKeep = 0;
  164052. int nNew = 0;
  164053. int iTermOff;
  164054. int iPgidx; /* Current offset in pgidx */
  164055. int bEndOfPage = 0;
  164056. assert( p->rc==SQLITE_OK );
  164057. iPgidx = szLeaf;
  164058. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  164059. iOff = iTermOff;
  164060. while( 1 ){
  164061. /* Figure out how many new bytes are in this term */
  164062. fts5FastGetVarint32(a, iOff, nNew);
  164063. if( nKeep<nMatch ){
  164064. goto search_failed;
  164065. }
  164066. assert( nKeep>=nMatch );
  164067. if( nKeep==nMatch ){
  164068. int nCmp;
  164069. int i;
  164070. nCmp = MIN(nNew, nTerm-nMatch);
  164071. for(i=0; i<nCmp; i++){
  164072. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  164073. }
  164074. nMatch += i;
  164075. if( nTerm==nMatch ){
  164076. if( i==nNew ){
  164077. goto search_success;
  164078. }else{
  164079. goto search_failed;
  164080. }
  164081. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  164082. goto search_failed;
  164083. }
  164084. }
  164085. if( iPgidx>=n ){
  164086. bEndOfPage = 1;
  164087. break;
  164088. }
  164089. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  164090. iTermOff += nKeep;
  164091. iOff = iTermOff;
  164092. /* Read the nKeep field of the next term. */
  164093. fts5FastGetVarint32(a, iOff, nKeep);
  164094. }
  164095. search_failed:
  164096. if( bGe==0 ){
  164097. fts5DataRelease(pIter->pLeaf);
  164098. pIter->pLeaf = 0;
  164099. return;
  164100. }else if( bEndOfPage ){
  164101. do {
  164102. fts5SegIterNextPage(p, pIter);
  164103. if( pIter->pLeaf==0 ) return;
  164104. a = pIter->pLeaf->p;
  164105. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  164106. iPgidx = pIter->pLeaf->szLeaf;
  164107. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  164108. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  164109. p->rc = FTS5_CORRUPT;
  164110. }else{
  164111. nKeep = 0;
  164112. iTermOff = iOff;
  164113. n = pIter->pLeaf->nn;
  164114. iOff += fts5GetVarint32(&a[iOff], nNew);
  164115. break;
  164116. }
  164117. }
  164118. }while( 1 );
  164119. }
  164120. search_success:
  164121. pIter->iLeafOffset = iOff + nNew;
  164122. pIter->iTermLeafOffset = pIter->iLeafOffset;
  164123. pIter->iTermLeafPgno = pIter->iLeafPgno;
  164124. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  164125. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  164126. if( iPgidx>=n ){
  164127. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  164128. }else{
  164129. int nExtra;
  164130. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  164131. pIter->iEndofDoclist = iTermOff + nExtra;
  164132. }
  164133. pIter->iPgidxOff = iPgidx;
  164134. fts5SegIterLoadRowid(p, pIter);
  164135. fts5SegIterLoadNPos(p, pIter);
  164136. }
  164137. /*
  164138. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  164139. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  164140. **
  164141. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  164142. ** an error has already occurred when this function is called, it is a no-op.
  164143. */
  164144. static void fts5SegIterSeekInit(
  164145. Fts5Index *p, /* FTS5 backend */
  164146. Fts5Buffer *pBuf, /* Buffer to use for loading pages */
  164147. const u8 *pTerm, int nTerm, /* Term to seek to */
  164148. int flags, /* Mask of FTS5INDEX_XXX flags */
  164149. Fts5StructureSegment *pSeg, /* Description of segment */
  164150. Fts5SegIter *pIter /* Object to populate */
  164151. ){
  164152. int iPg = 1;
  164153. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  164154. int bDlidx = 0; /* True if there is a doclist-index */
  164155. static int nCall = 0;
  164156. nCall++;
  164157. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  164158. assert( pTerm && nTerm );
  164159. memset(pIter, 0, sizeof(*pIter));
  164160. pIter->pSeg = pSeg;
  164161. /* This block sets stack variable iPg to the leaf page number that may
  164162. ** contain term (pTerm/nTerm), if it is present in the segment. */
  164163. if( p->pIdxSelect==0 ){
  164164. Fts5Config *pConfig = p->pConfig;
  164165. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  164166. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  164167. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  164168. pConfig->zDb, pConfig->zName
  164169. ));
  164170. }
  164171. if( p->rc ) return;
  164172. sqlite3_bind_int(p->pIdxSelect, 1, pSeg->iSegid);
  164173. sqlite3_bind_blob(p->pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  164174. if( SQLITE_ROW==sqlite3_step(p->pIdxSelect) ){
  164175. i64 val = sqlite3_column_int(p->pIdxSelect, 0);
  164176. iPg = (int)(val>>1);
  164177. bDlidx = (val & 0x0001);
  164178. }
  164179. p->rc = sqlite3_reset(p->pIdxSelect);
  164180. if( iPg<pSeg->pgnoFirst ){
  164181. iPg = pSeg->pgnoFirst;
  164182. bDlidx = 0;
  164183. }
  164184. pIter->iLeafPgno = iPg - 1;
  164185. fts5SegIterNextPage(p, pIter);
  164186. if( pIter->pLeaf ){
  164187. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  164188. }
  164189. if( p->rc==SQLITE_OK && bGe==0 ){
  164190. pIter->flags |= FTS5_SEGITER_ONETERM;
  164191. if( pIter->pLeaf ){
  164192. if( flags & FTS5INDEX_QUERY_DESC ){
  164193. pIter->flags |= FTS5_SEGITER_REVERSE;
  164194. }
  164195. if( bDlidx ){
  164196. fts5SegIterLoadDlidx(p, pIter);
  164197. }
  164198. if( flags & FTS5INDEX_QUERY_DESC ){
  164199. fts5SegIterReverse(p, pIter);
  164200. }
  164201. }
  164202. }
  164203. /* Either:
  164204. **
  164205. ** 1) an error has occurred, or
  164206. ** 2) the iterator points to EOF, or
  164207. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  164208. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  164209. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  164210. */
  164211. assert( p->rc!=SQLITE_OK /* 1 */
  164212. || pIter->pLeaf==0 /* 2 */
  164213. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  164214. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  164215. );
  164216. }
  164217. /*
  164218. ** Initialize the object pIter to point to term pTerm/nTerm within the
  164219. ** in-memory hash table. If there is no such term in the hash-table, the
  164220. ** iterator is set to EOF.
  164221. **
  164222. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  164223. ** an error has already occurred when this function is called, it is a no-op.
  164224. */
  164225. static void fts5SegIterHashInit(
  164226. Fts5Index *p, /* FTS5 backend */
  164227. const u8 *pTerm, int nTerm, /* Term to seek to */
  164228. int flags, /* Mask of FTS5INDEX_XXX flags */
  164229. Fts5SegIter *pIter /* Object to populate */
  164230. ){
  164231. const u8 *pList = 0;
  164232. int nList = 0;
  164233. const u8 *z = 0;
  164234. int n = 0;
  164235. assert( p->pHash );
  164236. assert( p->rc==SQLITE_OK );
  164237. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  164238. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  164239. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  164240. n = (z ? (int)strlen((const char*)z) : 0);
  164241. }else{
  164242. pIter->flags |= FTS5_SEGITER_ONETERM;
  164243. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  164244. z = pTerm;
  164245. n = nTerm;
  164246. }
  164247. if( pList ){
  164248. Fts5Data *pLeaf;
  164249. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  164250. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  164251. if( pLeaf==0 ) return;
  164252. pLeaf->p = (u8*)pList;
  164253. pLeaf->nn = pLeaf->szLeaf = nList;
  164254. pIter->pLeaf = pLeaf;
  164255. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  164256. pIter->iEndofDoclist = pLeaf->nn+1;
  164257. if( flags & FTS5INDEX_QUERY_DESC ){
  164258. pIter->flags |= FTS5_SEGITER_REVERSE;
  164259. fts5SegIterReverseInitPage(p, pIter);
  164260. }else{
  164261. fts5SegIterLoadNPos(p, pIter);
  164262. }
  164263. }
  164264. }
  164265. /*
  164266. ** Zero the iterator passed as the only argument.
  164267. */
  164268. static void fts5SegIterClear(Fts5SegIter *pIter){
  164269. fts5BufferFree(&pIter->term);
  164270. fts5DataRelease(pIter->pLeaf);
  164271. fts5DataRelease(pIter->pNextLeaf);
  164272. fts5DlidxIterFree(pIter->pDlidx);
  164273. sqlite3_free(pIter->aRowidOffset);
  164274. memset(pIter, 0, sizeof(Fts5SegIter));
  164275. }
  164276. #ifdef SQLITE_DEBUG
  164277. /*
  164278. ** This function is used as part of the big assert() procedure implemented by
  164279. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  164280. ** in *pRes is the correct result of comparing the current positions of the
  164281. ** two iterators.
  164282. */
  164283. static void fts5AssertComparisonResult(
  164284. Fts5IndexIter *pIter,
  164285. Fts5SegIter *p1,
  164286. Fts5SegIter *p2,
  164287. Fts5CResult *pRes
  164288. ){
  164289. int i1 = p1 - pIter->aSeg;
  164290. int i2 = p2 - pIter->aSeg;
  164291. if( p1->pLeaf || p2->pLeaf ){
  164292. if( p1->pLeaf==0 ){
  164293. assert( pRes->iFirst==i2 );
  164294. }else if( p2->pLeaf==0 ){
  164295. assert( pRes->iFirst==i1 );
  164296. }else{
  164297. int nMin = MIN(p1->term.n, p2->term.n);
  164298. int res = memcmp(p1->term.p, p2->term.p, nMin);
  164299. if( res==0 ) res = p1->term.n - p2->term.n;
  164300. if( res==0 ){
  164301. assert( pRes->bTermEq==1 );
  164302. assert( p1->iRowid!=p2->iRowid );
  164303. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  164304. }else{
  164305. assert( pRes->bTermEq==0 );
  164306. }
  164307. if( res<0 ){
  164308. assert( pRes->iFirst==i1 );
  164309. }else{
  164310. assert( pRes->iFirst==i2 );
  164311. }
  164312. }
  164313. }
  164314. }
  164315. /*
  164316. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  164317. ** is compiled. In that case, this function is essentially an assert()
  164318. ** statement used to verify that the contents of the pIter->aFirst[] array
  164319. ** are correct.
  164320. */
  164321. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5IndexIter *pIter){
  164322. if( p->rc==SQLITE_OK ){
  164323. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  164324. int i;
  164325. assert( (pFirst->pLeaf==0)==pIter->bEof );
  164326. /* Check that pIter->iSwitchRowid is set correctly. */
  164327. for(i=0; i<pIter->nSeg; i++){
  164328. Fts5SegIter *p1 = &pIter->aSeg[i];
  164329. assert( p1==pFirst
  164330. || p1->pLeaf==0
  164331. || fts5BufferCompare(&pFirst->term, &p1->term)
  164332. || p1->iRowid==pIter->iSwitchRowid
  164333. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  164334. );
  164335. }
  164336. for(i=0; i<pIter->nSeg; i+=2){
  164337. Fts5SegIter *p1 = &pIter->aSeg[i];
  164338. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  164339. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  164340. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  164341. }
  164342. for(i=1; i<(pIter->nSeg / 2); i+=2){
  164343. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  164344. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  164345. Fts5CResult *pRes = &pIter->aFirst[i];
  164346. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  164347. }
  164348. }
  164349. }
  164350. #else
  164351. # define fts5AssertMultiIterSetup(x,y)
  164352. #endif
  164353. /*
  164354. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  164355. **
  164356. ** If the returned value is non-zero, then it is the index of an entry
  164357. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  164358. ** to a key that is a duplicate of another, higher priority,
  164359. ** segment-iterator in the pSeg->aSeg[] array.
  164360. */
  164361. static int fts5MultiIterDoCompare(Fts5IndexIter *pIter, int iOut){
  164362. int i1; /* Index of left-hand Fts5SegIter */
  164363. int i2; /* Index of right-hand Fts5SegIter */
  164364. int iRes;
  164365. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  164366. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  164367. Fts5CResult *pRes = &pIter->aFirst[iOut];
  164368. assert( iOut<pIter->nSeg && iOut>0 );
  164369. assert( pIter->bRev==0 || pIter->bRev==1 );
  164370. if( iOut>=(pIter->nSeg/2) ){
  164371. i1 = (iOut - pIter->nSeg/2) * 2;
  164372. i2 = i1 + 1;
  164373. }else{
  164374. i1 = pIter->aFirst[iOut*2].iFirst;
  164375. i2 = pIter->aFirst[iOut*2+1].iFirst;
  164376. }
  164377. p1 = &pIter->aSeg[i1];
  164378. p2 = &pIter->aSeg[i2];
  164379. pRes->bTermEq = 0;
  164380. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  164381. iRes = i2;
  164382. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  164383. iRes = i1;
  164384. }else{
  164385. int res = fts5BufferCompare(&p1->term, &p2->term);
  164386. if( res==0 ){
  164387. assert( i2>i1 );
  164388. assert( i2!=0 );
  164389. pRes->bTermEq = 1;
  164390. if( p1->iRowid==p2->iRowid ){
  164391. p1->bDel = p2->bDel;
  164392. return i2;
  164393. }
  164394. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  164395. }
  164396. assert( res!=0 );
  164397. if( res<0 ){
  164398. iRes = i1;
  164399. }else{
  164400. iRes = i2;
  164401. }
  164402. }
  164403. pRes->iFirst = (u16)iRes;
  164404. return 0;
  164405. }
  164406. /*
  164407. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  164408. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  164409. */
  164410. static void fts5SegIterGotoPage(
  164411. Fts5Index *p, /* FTS5 backend object */
  164412. Fts5SegIter *pIter, /* Iterator to advance */
  164413. int iLeafPgno
  164414. ){
  164415. assert( iLeafPgno>pIter->iLeafPgno );
  164416. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  164417. p->rc = FTS5_CORRUPT;
  164418. }else{
  164419. fts5DataRelease(pIter->pNextLeaf);
  164420. pIter->pNextLeaf = 0;
  164421. pIter->iLeafPgno = iLeafPgno-1;
  164422. fts5SegIterNextPage(p, pIter);
  164423. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  164424. if( p->rc==SQLITE_OK ){
  164425. int iOff;
  164426. u8 *a = pIter->pLeaf->p;
  164427. int n = pIter->pLeaf->szLeaf;
  164428. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  164429. if( iOff<4 || iOff>=n ){
  164430. p->rc = FTS5_CORRUPT;
  164431. }else{
  164432. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  164433. pIter->iLeafOffset = iOff;
  164434. fts5SegIterLoadNPos(p, pIter);
  164435. }
  164436. }
  164437. }
  164438. }
  164439. /*
  164440. ** Advance the iterator passed as the second argument until it is at or
  164441. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  164442. ** always advanced at least once.
  164443. */
  164444. static void fts5SegIterNextFrom(
  164445. Fts5Index *p, /* FTS5 backend object */
  164446. Fts5SegIter *pIter, /* Iterator to advance */
  164447. i64 iMatch /* Advance iterator at least this far */
  164448. ){
  164449. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  164450. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  164451. int iLeafPgno = pIter->iLeafPgno;
  164452. int bMove = 1;
  164453. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  164454. assert( pIter->pDlidx );
  164455. assert( pIter->pLeaf );
  164456. if( bRev==0 ){
  164457. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  164458. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  164459. fts5DlidxIterNext(p, pDlidx);
  164460. }
  164461. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  164462. if( iLeafPgno>pIter->iLeafPgno ){
  164463. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  164464. bMove = 0;
  164465. }
  164466. }else{
  164467. assert( pIter->pNextLeaf==0 );
  164468. assert( iMatch<pIter->iRowid );
  164469. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  164470. fts5DlidxIterPrev(p, pDlidx);
  164471. }
  164472. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  164473. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  164474. if( iLeafPgno<pIter->iLeafPgno ){
  164475. pIter->iLeafPgno = iLeafPgno+1;
  164476. fts5SegIterReverseNewPage(p, pIter);
  164477. bMove = 0;
  164478. }
  164479. }
  164480. do{
  164481. if( bMove ) fts5SegIterNext(p, pIter, 0);
  164482. if( pIter->pLeaf==0 ) break;
  164483. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  164484. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  164485. bMove = 1;
  164486. }while( p->rc==SQLITE_OK );
  164487. }
  164488. /*
  164489. ** Free the iterator object passed as the second argument.
  164490. */
  164491. static void fts5MultiIterFree(Fts5Index *p, Fts5IndexIter *pIter){
  164492. if( pIter ){
  164493. int i;
  164494. for(i=0; i<pIter->nSeg; i++){
  164495. fts5SegIterClear(&pIter->aSeg[i]);
  164496. }
  164497. fts5StructureRelease(pIter->pStruct);
  164498. fts5BufferFree(&pIter->poslist);
  164499. sqlite3_free(pIter);
  164500. }
  164501. }
  164502. static void fts5MultiIterAdvanced(
  164503. Fts5Index *p, /* FTS5 backend to iterate within */
  164504. Fts5IndexIter *pIter, /* Iterator to update aFirst[] array for */
  164505. int iChanged, /* Index of sub-iterator just advanced */
  164506. int iMinset /* Minimum entry in aFirst[] to set */
  164507. ){
  164508. int i;
  164509. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  164510. int iEq;
  164511. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  164512. fts5SegIterNext(p, &pIter->aSeg[iEq], 0);
  164513. i = pIter->nSeg + iEq;
  164514. }
  164515. }
  164516. }
  164517. /*
  164518. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  164519. ** points to the same term though - just a different rowid. This function
  164520. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  164521. ** If it does so successfully, 0 is returned. Otherwise 1.
  164522. **
  164523. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  164524. ** on the iterator instead. That function does the same as this one, except
  164525. ** that it deals with more complicated cases as well.
  164526. */
  164527. static int fts5MultiIterAdvanceRowid(
  164528. Fts5Index *p, /* FTS5 backend to iterate within */
  164529. Fts5IndexIter *pIter, /* Iterator to update aFirst[] array for */
  164530. int iChanged /* Index of sub-iterator just advanced */
  164531. ){
  164532. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  164533. if( pNew->iRowid==pIter->iSwitchRowid
  164534. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  164535. ){
  164536. int i;
  164537. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  164538. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  164539. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  164540. Fts5CResult *pRes = &pIter->aFirst[i];
  164541. assert( pNew->pLeaf );
  164542. assert( pRes->bTermEq==0 || pOther->pLeaf );
  164543. if( pRes->bTermEq ){
  164544. if( pNew->iRowid==pOther->iRowid ){
  164545. return 1;
  164546. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  164547. pIter->iSwitchRowid = pOther->iRowid;
  164548. pNew = pOther;
  164549. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  164550. pIter->iSwitchRowid = pOther->iRowid;
  164551. }
  164552. }
  164553. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  164554. if( i==1 ) break;
  164555. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  164556. }
  164557. }
  164558. return 0;
  164559. }
  164560. /*
  164561. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  164562. */
  164563. static void fts5MultiIterSetEof(Fts5IndexIter *pIter){
  164564. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  164565. pIter->bEof = pSeg->pLeaf==0;
  164566. pIter->iSwitchRowid = pSeg->iRowid;
  164567. }
  164568. /*
  164569. ** Move the iterator to the next entry.
  164570. **
  164571. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  164572. ** considered an error if the iterator reaches EOF, or if it is already at
  164573. ** EOF when this function is called.
  164574. */
  164575. static void fts5MultiIterNext(
  164576. Fts5Index *p,
  164577. Fts5IndexIter *pIter,
  164578. int bFrom, /* True if argument iFrom is valid */
  164579. i64 iFrom /* Advance at least as far as this */
  164580. ){
  164581. if( p->rc==SQLITE_OK ){
  164582. int bUseFrom = bFrom;
  164583. do {
  164584. int iFirst = pIter->aFirst[1].iFirst;
  164585. int bNewTerm = 0;
  164586. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  164587. assert( p->rc==SQLITE_OK );
  164588. if( bUseFrom && pSeg->pDlidx ){
  164589. fts5SegIterNextFrom(p, pSeg, iFrom);
  164590. }else{
  164591. fts5SegIterNext(p, pSeg, &bNewTerm);
  164592. }
  164593. if( pSeg->pLeaf==0 || bNewTerm
  164594. || fts5MultiIterAdvanceRowid(p, pIter, iFirst)
  164595. ){
  164596. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  164597. fts5MultiIterSetEof(pIter);
  164598. }
  164599. fts5AssertMultiIterSetup(p, pIter);
  164600. bUseFrom = 0;
  164601. }while( pIter->bSkipEmpty && fts5MultiIterIsEmpty(p, pIter) );
  164602. }
  164603. }
  164604. static void fts5MultiIterNext2(
  164605. Fts5Index *p,
  164606. Fts5IndexIter *pIter,
  164607. int *pbNewTerm /* OUT: True if *might* be new term */
  164608. ){
  164609. assert( pIter->bSkipEmpty );
  164610. if( p->rc==SQLITE_OK ){
  164611. do {
  164612. int iFirst = pIter->aFirst[1].iFirst;
  164613. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  164614. int bNewTerm = 0;
  164615. fts5SegIterNext(p, pSeg, &bNewTerm);
  164616. if( pSeg->pLeaf==0 || bNewTerm
  164617. || fts5MultiIterAdvanceRowid(p, pIter, iFirst)
  164618. ){
  164619. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  164620. fts5MultiIterSetEof(pIter);
  164621. *pbNewTerm = 1;
  164622. }else{
  164623. *pbNewTerm = 0;
  164624. }
  164625. fts5AssertMultiIterSetup(p, pIter);
  164626. }while( fts5MultiIterIsEmpty(p, pIter) );
  164627. }
  164628. }
  164629. static Fts5IndexIter *fts5MultiIterAlloc(
  164630. Fts5Index *p, /* FTS5 backend to iterate within */
  164631. int nSeg
  164632. ){
  164633. Fts5IndexIter *pNew;
  164634. int nSlot; /* Power of two >= nSeg */
  164635. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  164636. pNew = fts5IdxMalloc(p,
  164637. sizeof(Fts5IndexIter) + /* pNew */
  164638. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  164639. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  164640. );
  164641. if( pNew ){
  164642. pNew->nSeg = nSlot;
  164643. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  164644. pNew->pIndex = p;
  164645. }
  164646. return pNew;
  164647. }
  164648. /*
  164649. ** Allocate a new Fts5IndexIter object.
  164650. **
  164651. ** The new object will be used to iterate through data in structure pStruct.
  164652. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  164653. ** is zero or greater, data from the first nSegment segments on level iLevel
  164654. ** is merged.
  164655. **
  164656. ** The iterator initially points to the first term/rowid entry in the
  164657. ** iterated data.
  164658. */
  164659. static void fts5MultiIterNew(
  164660. Fts5Index *p, /* FTS5 backend to iterate within */
  164661. Fts5Structure *pStruct, /* Structure of specific index */
  164662. int bSkipEmpty, /* True to ignore delete-keys */
  164663. int flags, /* FTS5INDEX_QUERY_XXX flags */
  164664. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  164665. int iLevel, /* Level to iterate (-1 for all) */
  164666. int nSegment, /* Number of segments to merge (iLevel>=0) */
  164667. Fts5IndexIter **ppOut /* New object */
  164668. ){
  164669. int nSeg = 0; /* Number of segment-iters in use */
  164670. int iIter = 0; /* */
  164671. int iSeg; /* Used to iterate through segments */
  164672. Fts5Buffer buf = {0,0,0}; /* Buffer used by fts5SegIterSeekInit() */
  164673. Fts5StructureLevel *pLvl;
  164674. Fts5IndexIter *pNew;
  164675. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  164676. /* Allocate space for the new multi-seg-iterator. */
  164677. if( p->rc==SQLITE_OK ){
  164678. if( iLevel<0 ){
  164679. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  164680. nSeg = pStruct->nSegment;
  164681. nSeg += (p->pHash ? 1 : 0);
  164682. }else{
  164683. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  164684. }
  164685. }
  164686. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  164687. if( pNew==0 ) return;
  164688. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  164689. pNew->bSkipEmpty = (u8)bSkipEmpty;
  164690. pNew->pStruct = pStruct;
  164691. fts5StructureRef(pStruct);
  164692. /* Initialize each of the component segment iterators. */
  164693. if( iLevel<0 ){
  164694. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  164695. if( p->pHash ){
  164696. /* Add a segment iterator for the current contents of the hash table. */
  164697. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  164698. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  164699. }
  164700. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  164701. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  164702. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  164703. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  164704. if( pTerm==0 ){
  164705. fts5SegIterInit(p, pSeg, pIter);
  164706. }else{
  164707. fts5SegIterSeekInit(p, &buf, pTerm, nTerm, flags, pSeg, pIter);
  164708. }
  164709. }
  164710. }
  164711. }else{
  164712. pLvl = &pStruct->aLevel[iLevel];
  164713. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  164714. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  164715. }
  164716. }
  164717. assert( iIter==nSeg );
  164718. /* If the above was successful, each component iterators now points
  164719. ** to the first entry in its segment. In this case initialize the
  164720. ** aFirst[] array. Or, if an error has occurred, free the iterator
  164721. ** object and set the output variable to NULL. */
  164722. if( p->rc==SQLITE_OK ){
  164723. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  164724. int iEq;
  164725. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  164726. fts5SegIterNext(p, &pNew->aSeg[iEq], 0);
  164727. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  164728. }
  164729. }
  164730. fts5MultiIterSetEof(pNew);
  164731. fts5AssertMultiIterSetup(p, pNew);
  164732. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  164733. fts5MultiIterNext(p, pNew, 0, 0);
  164734. }
  164735. }else{
  164736. fts5MultiIterFree(p, pNew);
  164737. *ppOut = 0;
  164738. }
  164739. fts5BufferFree(&buf);
  164740. }
  164741. /*
  164742. ** Create an Fts5IndexIter that iterates through the doclist provided
  164743. ** as the second argument.
  164744. */
  164745. static void fts5MultiIterNew2(
  164746. Fts5Index *p, /* FTS5 backend to iterate within */
  164747. Fts5Data *pData, /* Doclist to iterate through */
  164748. int bDesc, /* True for descending rowid order */
  164749. Fts5IndexIter **ppOut /* New object */
  164750. ){
  164751. Fts5IndexIter *pNew;
  164752. pNew = fts5MultiIterAlloc(p, 2);
  164753. if( pNew ){
  164754. Fts5SegIter *pIter = &pNew->aSeg[1];
  164755. pNew->bFiltered = 1;
  164756. pIter->flags = FTS5_SEGITER_ONETERM;
  164757. if( pData->szLeaf>0 ){
  164758. pIter->pLeaf = pData;
  164759. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  164760. pIter->iEndofDoclist = pData->nn;
  164761. pNew->aFirst[1].iFirst = 1;
  164762. if( bDesc ){
  164763. pNew->bRev = 1;
  164764. pIter->flags |= FTS5_SEGITER_REVERSE;
  164765. fts5SegIterReverseInitPage(p, pIter);
  164766. }else{
  164767. fts5SegIterLoadNPos(p, pIter);
  164768. }
  164769. pData = 0;
  164770. }else{
  164771. pNew->bEof = 1;
  164772. }
  164773. *ppOut = pNew;
  164774. }
  164775. fts5DataRelease(pData);
  164776. }
  164777. /*
  164778. ** Return true if the iterator is at EOF or if an error has occurred.
  164779. ** False otherwise.
  164780. */
  164781. static int fts5MultiIterEof(Fts5Index *p, Fts5IndexIter *pIter){
  164782. assert( p->rc
  164783. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->bEof
  164784. );
  164785. return (p->rc || pIter->bEof);
  164786. }
  164787. /*
  164788. ** Return the rowid of the entry that the iterator currently points
  164789. ** to. If the iterator points to EOF when this function is called the
  164790. ** results are undefined.
  164791. */
  164792. static i64 fts5MultiIterRowid(Fts5IndexIter *pIter){
  164793. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  164794. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  164795. }
  164796. /*
  164797. ** Move the iterator to the next entry at or following iMatch.
  164798. */
  164799. static void fts5MultiIterNextFrom(
  164800. Fts5Index *p,
  164801. Fts5IndexIter *pIter,
  164802. i64 iMatch
  164803. ){
  164804. while( 1 ){
  164805. i64 iRowid;
  164806. fts5MultiIterNext(p, pIter, 1, iMatch);
  164807. if( fts5MultiIterEof(p, pIter) ) break;
  164808. iRowid = fts5MultiIterRowid(pIter);
  164809. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  164810. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  164811. }
  164812. }
  164813. /*
  164814. ** Return a pointer to a buffer containing the term associated with the
  164815. ** entry that the iterator currently points to.
  164816. */
  164817. static const u8 *fts5MultiIterTerm(Fts5IndexIter *pIter, int *pn){
  164818. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  164819. *pn = p->term.n;
  164820. return p->term.p;
  164821. }
  164822. static void fts5ChunkIterate(
  164823. Fts5Index *p, /* Index object */
  164824. Fts5SegIter *pSeg, /* Poslist of this iterator */
  164825. void *pCtx, /* Context pointer for xChunk callback */
  164826. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  164827. ){
  164828. int nRem = pSeg->nPos; /* Number of bytes still to come */
  164829. Fts5Data *pData = 0;
  164830. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  164831. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  164832. int pgno = pSeg->iLeafPgno;
  164833. int pgnoSave = 0;
  164834. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  164835. pgnoSave = pgno+1;
  164836. }
  164837. while( 1 ){
  164838. xChunk(p, pCtx, pChunk, nChunk);
  164839. nRem -= nChunk;
  164840. fts5DataRelease(pData);
  164841. if( nRem<=0 ){
  164842. break;
  164843. }else{
  164844. pgno++;
  164845. pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  164846. if( pData==0 ) break;
  164847. pChunk = &pData->p[4];
  164848. nChunk = MIN(nRem, pData->szLeaf - 4);
  164849. if( pgno==pgnoSave ){
  164850. assert( pSeg->pNextLeaf==0 );
  164851. pSeg->pNextLeaf = pData;
  164852. pData = 0;
  164853. }
  164854. }
  164855. }
  164856. }
  164857. /*
  164858. ** Allocate a new segment-id for the structure pStruct. The new segment
  164859. ** id must be between 1 and 65335 inclusive, and must not be used by
  164860. ** any currently existing segment. If a free segment id cannot be found,
  164861. ** SQLITE_FULL is returned.
  164862. **
  164863. ** If an error has already occurred, this function is a no-op. 0 is
  164864. ** returned in this case.
  164865. */
  164866. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  164867. int iSegid = 0;
  164868. if( p->rc==SQLITE_OK ){
  164869. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  164870. p->rc = SQLITE_FULL;
  164871. }else{
  164872. while( iSegid==0 ){
  164873. int iLvl, iSeg;
  164874. sqlite3_randomness(sizeof(u32), (void*)&iSegid);
  164875. iSegid = iSegid & ((1 << FTS5_DATA_ID_B)-1);
  164876. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  164877. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  164878. if( iSegid==pStruct->aLevel[iLvl].aSeg[iSeg].iSegid ){
  164879. iSegid = 0;
  164880. }
  164881. }
  164882. }
  164883. }
  164884. }
  164885. }
  164886. return iSegid;
  164887. }
  164888. /*
  164889. ** Discard all data currently cached in the hash-tables.
  164890. */
  164891. static void fts5IndexDiscardData(Fts5Index *p){
  164892. assert( p->pHash || p->nPendingData==0 );
  164893. if( p->pHash ){
  164894. sqlite3Fts5HashClear(p->pHash);
  164895. p->nPendingData = 0;
  164896. }
  164897. }
  164898. /*
  164899. ** Return the size of the prefix, in bytes, that buffer (nNew/pNew) shares
  164900. ** with buffer (nOld/pOld).
  164901. */
  164902. static int fts5PrefixCompress(
  164903. int nOld, const u8 *pOld,
  164904. int nNew, const u8 *pNew
  164905. ){
  164906. int i;
  164907. assert( fts5BlobCompare(pOld, nOld, pNew, nNew)<0 );
  164908. for(i=0; i<nOld; i++){
  164909. if( pOld[i]!=pNew[i] ) break;
  164910. }
  164911. return i;
  164912. }
  164913. static void fts5WriteDlidxClear(
  164914. Fts5Index *p,
  164915. Fts5SegWriter *pWriter,
  164916. int bFlush /* If true, write dlidx to disk */
  164917. ){
  164918. int i;
  164919. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  164920. for(i=0; i<pWriter->nDlidx; i++){
  164921. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  164922. if( pDlidx->buf.n==0 ) break;
  164923. if( bFlush ){
  164924. assert( pDlidx->pgno!=0 );
  164925. fts5DataWrite(p,
  164926. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  164927. pDlidx->buf.p, pDlidx->buf.n
  164928. );
  164929. }
  164930. sqlite3Fts5BufferZero(&pDlidx->buf);
  164931. pDlidx->bPrevValid = 0;
  164932. }
  164933. }
  164934. /*
  164935. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  164936. ** Any new array elements are zeroed before returning.
  164937. */
  164938. static int fts5WriteDlidxGrow(
  164939. Fts5Index *p,
  164940. Fts5SegWriter *pWriter,
  164941. int nLvl
  164942. ){
  164943. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  164944. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  164945. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  164946. );
  164947. if( aDlidx==0 ){
  164948. p->rc = SQLITE_NOMEM;
  164949. }else{
  164950. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  164951. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  164952. pWriter->aDlidx = aDlidx;
  164953. pWriter->nDlidx = nLvl;
  164954. }
  164955. }
  164956. return p->rc;
  164957. }
  164958. /*
  164959. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  164960. ** enough, flush it to disk and return 1. Otherwise discard it and return
  164961. ** zero.
  164962. */
  164963. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  164964. int bFlag = 0;
  164965. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  164966. ** to the database, also write the doclist-index to disk. */
  164967. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  164968. bFlag = 1;
  164969. }
  164970. fts5WriteDlidxClear(p, pWriter, bFlag);
  164971. pWriter->nEmpty = 0;
  164972. return bFlag;
  164973. }
  164974. /*
  164975. ** This function is called whenever processing of the doclist for the
  164976. ** last term on leaf page (pWriter->iBtPage) is completed.
  164977. **
  164978. ** The doclist-index for that term is currently stored in-memory within the
  164979. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  164980. ** writes it out to disk. Or, if it is too small to bother with, discards
  164981. ** it.
  164982. **
  164983. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  164984. */
  164985. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  164986. int bFlag;
  164987. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  164988. if( pWriter->iBtPage==0 ) return;
  164989. bFlag = fts5WriteFlushDlidx(p, pWriter);
  164990. if( p->rc==SQLITE_OK ){
  164991. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  164992. /* The following was already done in fts5WriteInit(): */
  164993. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  164994. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  164995. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  164996. sqlite3_step(p->pIdxWriter);
  164997. p->rc = sqlite3_reset(p->pIdxWriter);
  164998. }
  164999. pWriter->iBtPage = 0;
  165000. }
  165001. /*
  165002. ** This is called once for each leaf page except the first that contains
  165003. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  165004. ** is larger than all terms written to earlier leaves, and equal to or
  165005. ** smaller than the first term on the new leaf.
  165006. **
  165007. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  165008. ** has already occurred when this function is called, it is a no-op.
  165009. */
  165010. static void fts5WriteBtreeTerm(
  165011. Fts5Index *p, /* FTS5 backend object */
  165012. Fts5SegWriter *pWriter, /* Writer object */
  165013. int nTerm, const u8 *pTerm /* First term on new page */
  165014. ){
  165015. fts5WriteFlushBtree(p, pWriter);
  165016. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  165017. pWriter->iBtPage = pWriter->writer.pgno;
  165018. }
  165019. /*
  165020. ** This function is called when flushing a leaf page that contains no
  165021. ** terms at all to disk.
  165022. */
  165023. static void fts5WriteBtreeNoTerm(
  165024. Fts5Index *p, /* FTS5 backend object */
  165025. Fts5SegWriter *pWriter /* Writer object */
  165026. ){
  165027. /* If there were no rowids on the leaf page either and the doclist-index
  165028. ** has already been started, append an 0x00 byte to it. */
  165029. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  165030. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  165031. assert( pDlidx->bPrevValid );
  165032. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  165033. }
  165034. /* Increment the "number of sequential leaves without a term" counter. */
  165035. pWriter->nEmpty++;
  165036. }
  165037. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  165038. i64 iRowid;
  165039. int iOff;
  165040. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  165041. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  165042. return iRowid;
  165043. }
  165044. /*
  165045. ** Rowid iRowid has just been appended to the current leaf page. It is the
  165046. ** first on the page. This function appends an appropriate entry to the current
  165047. ** doclist-index.
  165048. */
  165049. static void fts5WriteDlidxAppend(
  165050. Fts5Index *p,
  165051. Fts5SegWriter *pWriter,
  165052. i64 iRowid
  165053. ){
  165054. int i;
  165055. int bDone = 0;
  165056. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  165057. i64 iVal;
  165058. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  165059. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  165060. /* The current doclist-index page is full. Write it to disk and push
  165061. ** a copy of iRowid (which will become the first rowid on the next
  165062. ** doclist-index leaf page) up into the next level of the b-tree
  165063. ** hierarchy. If the node being flushed is currently the root node,
  165064. ** also push its first rowid upwards. */
  165065. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  165066. fts5DataWrite(p,
  165067. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  165068. pDlidx->buf.p, pDlidx->buf.n
  165069. );
  165070. fts5WriteDlidxGrow(p, pWriter, i+2);
  165071. pDlidx = &pWriter->aDlidx[i];
  165072. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  165073. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  165074. /* This was the root node. Push its first rowid up to the new root. */
  165075. pDlidx[1].pgno = pDlidx->pgno;
  165076. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  165077. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  165078. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  165079. pDlidx[1].bPrevValid = 1;
  165080. pDlidx[1].iPrev = iFirst;
  165081. }
  165082. sqlite3Fts5BufferZero(&pDlidx->buf);
  165083. pDlidx->bPrevValid = 0;
  165084. pDlidx->pgno++;
  165085. }else{
  165086. bDone = 1;
  165087. }
  165088. if( pDlidx->bPrevValid ){
  165089. iVal = iRowid - pDlidx->iPrev;
  165090. }else{
  165091. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  165092. assert( pDlidx->buf.n==0 );
  165093. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  165094. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  165095. iVal = iRowid;
  165096. }
  165097. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  165098. pDlidx->bPrevValid = 1;
  165099. pDlidx->iPrev = iRowid;
  165100. }
  165101. }
  165102. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  165103. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  165104. Fts5PageWriter *pPage = &pWriter->writer;
  165105. i64 iRowid;
  165106. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  165107. /* Set the szLeaf header field. */
  165108. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  165109. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  165110. if( pWriter->bFirstTermInPage ){
  165111. /* No term was written to this page. */
  165112. assert( pPage->pgidx.n==0 );
  165113. fts5WriteBtreeNoTerm(p, pWriter);
  165114. }else{
  165115. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  165116. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  165117. }
  165118. /* Write the page out to disk */
  165119. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  165120. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  165121. /* Initialize the next page. */
  165122. fts5BufferZero(&pPage->buf);
  165123. fts5BufferZero(&pPage->pgidx);
  165124. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  165125. pPage->iPrevPgidx = 0;
  165126. pPage->pgno++;
  165127. /* Increase the leaves written counter */
  165128. pWriter->nLeafWritten++;
  165129. /* The new leaf holds no terms or rowids */
  165130. pWriter->bFirstTermInPage = 1;
  165131. pWriter->bFirstRowidInPage = 1;
  165132. }
  165133. /*
  165134. ** Append term pTerm/nTerm to the segment being written by the writer passed
  165135. ** as the second argument.
  165136. **
  165137. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  165138. ** already occurred, this function is a no-op.
  165139. */
  165140. static void fts5WriteAppendTerm(
  165141. Fts5Index *p,
  165142. Fts5SegWriter *pWriter,
  165143. int nTerm, const u8 *pTerm
  165144. ){
  165145. int nPrefix; /* Bytes of prefix compression for term */
  165146. Fts5PageWriter *pPage = &pWriter->writer;
  165147. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  165148. assert( p->rc==SQLITE_OK );
  165149. assert( pPage->buf.n>=4 );
  165150. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  165151. /* If the current leaf page is full, flush it to disk. */
  165152. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  165153. if( pPage->buf.n>4 ){
  165154. fts5WriteFlushLeaf(p, pWriter);
  165155. }
  165156. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  165157. }
  165158. /* TODO1: Updating pgidx here. */
  165159. pPgidx->n += sqlite3Fts5PutVarint(
  165160. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  165161. );
  165162. pPage->iPrevPgidx = pPage->buf.n;
  165163. #if 0
  165164. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  165165. pPgidx->n += 2;
  165166. #endif
  165167. if( pWriter->bFirstTermInPage ){
  165168. nPrefix = 0;
  165169. if( pPage->pgno!=1 ){
  165170. /* This is the first term on a leaf that is not the leftmost leaf in
  165171. ** the segment b-tree. In this case it is necessary to add a term to
  165172. ** the b-tree hierarchy that is (a) larger than the largest term
  165173. ** already written to the segment and (b) smaller than or equal to
  165174. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  165175. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  165176. ** previous term.
  165177. **
  165178. ** Usually, the previous term is available in pPage->term. The exception
  165179. ** is if this is the first term written in an incremental-merge step.
  165180. ** In this case the previous term is not available, so just write a
  165181. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  165182. ** inefficient, but still correct. */
  165183. int n = nTerm;
  165184. if( pPage->term.n ){
  165185. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, nTerm, pTerm);
  165186. }
  165187. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  165188. pPage = &pWriter->writer;
  165189. }
  165190. }else{
  165191. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, nTerm, pTerm);
  165192. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  165193. }
  165194. /* Append the number of bytes of new data, then the term data itself
  165195. ** to the page. */
  165196. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  165197. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  165198. /* Update the Fts5PageWriter.term field. */
  165199. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  165200. pWriter->bFirstTermInPage = 0;
  165201. pWriter->bFirstRowidInPage = 0;
  165202. pWriter->bFirstRowidInDoclist = 1;
  165203. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  165204. pWriter->aDlidx[0].pgno = pPage->pgno;
  165205. }
  165206. /*
  165207. ** Append a rowid and position-list size field to the writers output.
  165208. */
  165209. static void fts5WriteAppendRowid(
  165210. Fts5Index *p,
  165211. Fts5SegWriter *pWriter,
  165212. i64 iRowid,
  165213. int nPos
  165214. ){
  165215. if( p->rc==SQLITE_OK ){
  165216. Fts5PageWriter *pPage = &pWriter->writer;
  165217. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  165218. fts5WriteFlushLeaf(p, pWriter);
  165219. }
  165220. /* If this is to be the first rowid written to the page, set the
  165221. ** rowid-pointer in the page-header. Also append a value to the dlidx
  165222. ** buffer, in case a doclist-index is required. */
  165223. if( pWriter->bFirstRowidInPage ){
  165224. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  165225. fts5WriteDlidxAppend(p, pWriter, iRowid);
  165226. }
  165227. /* Write the rowid. */
  165228. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  165229. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  165230. }else{
  165231. assert( p->rc || iRowid>pWriter->iPrevRowid );
  165232. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  165233. }
  165234. pWriter->iPrevRowid = iRowid;
  165235. pWriter->bFirstRowidInDoclist = 0;
  165236. pWriter->bFirstRowidInPage = 0;
  165237. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPos);
  165238. }
  165239. }
  165240. static void fts5WriteAppendPoslistData(
  165241. Fts5Index *p,
  165242. Fts5SegWriter *pWriter,
  165243. const u8 *aData,
  165244. int nData
  165245. ){
  165246. Fts5PageWriter *pPage = &pWriter->writer;
  165247. const u8 *a = aData;
  165248. int n = nData;
  165249. assert( p->pConfig->pgsz>0 );
  165250. while( p->rc==SQLITE_OK
  165251. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  165252. ){
  165253. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  165254. int nCopy = 0;
  165255. while( nCopy<nReq ){
  165256. i64 dummy;
  165257. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  165258. }
  165259. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  165260. a += nCopy;
  165261. n -= nCopy;
  165262. fts5WriteFlushLeaf(p, pWriter);
  165263. }
  165264. if( n>0 ){
  165265. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  165266. }
  165267. }
  165268. /*
  165269. ** Flush any data cached by the writer object to the database. Free any
  165270. ** allocations associated with the writer.
  165271. */
  165272. static void fts5WriteFinish(
  165273. Fts5Index *p,
  165274. Fts5SegWriter *pWriter, /* Writer object */
  165275. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  165276. ){
  165277. int i;
  165278. Fts5PageWriter *pLeaf = &pWriter->writer;
  165279. if( p->rc==SQLITE_OK ){
  165280. assert( pLeaf->pgno>=1 );
  165281. if( pLeaf->buf.n>4 ){
  165282. fts5WriteFlushLeaf(p, pWriter);
  165283. }
  165284. *pnLeaf = pLeaf->pgno-1;
  165285. fts5WriteFlushBtree(p, pWriter);
  165286. }
  165287. fts5BufferFree(&pLeaf->term);
  165288. fts5BufferFree(&pLeaf->buf);
  165289. fts5BufferFree(&pLeaf->pgidx);
  165290. fts5BufferFree(&pWriter->btterm);
  165291. for(i=0; i<pWriter->nDlidx; i++){
  165292. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  165293. }
  165294. sqlite3_free(pWriter->aDlidx);
  165295. }
  165296. static void fts5WriteInit(
  165297. Fts5Index *p,
  165298. Fts5SegWriter *pWriter,
  165299. int iSegid
  165300. ){
  165301. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  165302. memset(pWriter, 0, sizeof(Fts5SegWriter));
  165303. pWriter->iSegid = iSegid;
  165304. fts5WriteDlidxGrow(p, pWriter, 1);
  165305. pWriter->writer.pgno = 1;
  165306. pWriter->bFirstTermInPage = 1;
  165307. pWriter->iBtPage = 1;
  165308. assert( pWriter->writer.buf.n==0 );
  165309. assert( pWriter->writer.pgidx.n==0 );
  165310. /* Grow the two buffers to pgsz + padding bytes in size. */
  165311. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  165312. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  165313. if( p->pIdxWriter==0 ){
  165314. Fts5Config *pConfig = p->pConfig;
  165315. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  165316. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  165317. pConfig->zDb, pConfig->zName
  165318. ));
  165319. }
  165320. if( p->rc==SQLITE_OK ){
  165321. /* Initialize the 4-byte leaf-page header to 0x00. */
  165322. memset(pWriter->writer.buf.p, 0, 4);
  165323. pWriter->writer.buf.n = 4;
  165324. /* Bind the current output segment id to the index-writer. This is an
  165325. ** optimization over binding the same value over and over as rows are
  165326. ** inserted into %_idx by the current writer. */
  165327. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  165328. }
  165329. }
  165330. /*
  165331. ** Iterator pIter was used to iterate through the input segments of on an
  165332. ** incremental merge operation. This function is called if the incremental
  165333. ** merge step has finished but the input has not been completely exhausted.
  165334. */
  165335. static void fts5TrimSegments(Fts5Index *p, Fts5IndexIter *pIter){
  165336. int i;
  165337. Fts5Buffer buf;
  165338. memset(&buf, 0, sizeof(Fts5Buffer));
  165339. for(i=0; i<pIter->nSeg; i++){
  165340. Fts5SegIter *pSeg = &pIter->aSeg[i];
  165341. if( pSeg->pSeg==0 ){
  165342. /* no-op */
  165343. }else if( pSeg->pLeaf==0 ){
  165344. /* All keys from this input segment have been transfered to the output.
  165345. ** Set both the first and last page-numbers to 0 to indicate that the
  165346. ** segment is now empty. */
  165347. pSeg->pSeg->pgnoLast = 0;
  165348. pSeg->pSeg->pgnoFirst = 0;
  165349. }else{
  165350. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  165351. i64 iLeafRowid;
  165352. Fts5Data *pData;
  165353. int iId = pSeg->pSeg->iSegid;
  165354. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  165355. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  165356. pData = fts5DataRead(p, iLeafRowid);
  165357. if( pData ){
  165358. fts5BufferZero(&buf);
  165359. fts5BufferGrow(&p->rc, &buf, pData->nn);
  165360. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  165361. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  165362. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  165363. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  165364. if( p->rc==SQLITE_OK ){
  165365. /* Set the szLeaf field */
  165366. fts5PutU16(&buf.p[2], (u16)buf.n);
  165367. }
  165368. /* Set up the new page-index array */
  165369. fts5BufferAppendVarint(&p->rc, &buf, 4);
  165370. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  165371. && pSeg->iEndofDoclist<pData->szLeaf
  165372. ){
  165373. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  165374. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  165375. fts5BufferAppendBlob(&p->rc, &buf,
  165376. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  165377. );
  165378. }
  165379. fts5DataRelease(pData);
  165380. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  165381. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  165382. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  165383. }
  165384. }
  165385. }
  165386. fts5BufferFree(&buf);
  165387. }
  165388. static void fts5MergeChunkCallback(
  165389. Fts5Index *p,
  165390. void *pCtx,
  165391. const u8 *pChunk, int nChunk
  165392. ){
  165393. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  165394. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  165395. }
  165396. /*
  165397. **
  165398. */
  165399. static void fts5IndexMergeLevel(
  165400. Fts5Index *p, /* FTS5 backend object */
  165401. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  165402. int iLvl, /* Level to read input from */
  165403. int *pnRem /* Write up to this many output leaves */
  165404. ){
  165405. Fts5Structure *pStruct = *ppStruct;
  165406. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  165407. Fts5StructureLevel *pLvlOut;
  165408. Fts5IndexIter *pIter = 0; /* Iterator to read input data */
  165409. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  165410. int nInput; /* Number of input segments */
  165411. Fts5SegWriter writer; /* Writer object */
  165412. Fts5StructureSegment *pSeg; /* Output segment */
  165413. Fts5Buffer term;
  165414. int bOldest; /* True if the output segment is the oldest */
  165415. assert( iLvl<pStruct->nLevel );
  165416. assert( pLvl->nMerge<=pLvl->nSeg );
  165417. memset(&writer, 0, sizeof(Fts5SegWriter));
  165418. memset(&term, 0, sizeof(Fts5Buffer));
  165419. if( pLvl->nMerge ){
  165420. pLvlOut = &pStruct->aLevel[iLvl+1];
  165421. assert( pLvlOut->nSeg>0 );
  165422. nInput = pLvl->nMerge;
  165423. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  165424. fts5WriteInit(p, &writer, pSeg->iSegid);
  165425. writer.writer.pgno = pSeg->pgnoLast+1;
  165426. writer.iBtPage = 0;
  165427. }else{
  165428. int iSegid = fts5AllocateSegid(p, pStruct);
  165429. /* Extend the Fts5Structure object as required to ensure the output
  165430. ** segment exists. */
  165431. if( iLvl==pStruct->nLevel-1 ){
  165432. fts5StructureAddLevel(&p->rc, ppStruct);
  165433. pStruct = *ppStruct;
  165434. }
  165435. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  165436. if( p->rc ) return;
  165437. pLvl = &pStruct->aLevel[iLvl];
  165438. pLvlOut = &pStruct->aLevel[iLvl+1];
  165439. fts5WriteInit(p, &writer, iSegid);
  165440. /* Add the new segment to the output level */
  165441. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  165442. pLvlOut->nSeg++;
  165443. pSeg->pgnoFirst = 1;
  165444. pSeg->iSegid = iSegid;
  165445. pStruct->nSegment++;
  165446. /* Read input from all segments in the input level */
  165447. nInput = pLvl->nSeg;
  165448. }
  165449. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  165450. assert( iLvl>=0 );
  165451. for(fts5MultiIterNew(p, pStruct, 0, 0, 0, 0, iLvl, nInput, &pIter);
  165452. fts5MultiIterEof(p, pIter)==0;
  165453. fts5MultiIterNext(p, pIter, 0, 0)
  165454. ){
  165455. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  165456. int nPos; /* position-list size field value */
  165457. int nTerm;
  165458. const u8 *pTerm;
  165459. /* Check for key annihilation. */
  165460. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  165461. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  165462. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  165463. if( pnRem && writer.nLeafWritten>nRem ){
  165464. break;
  165465. }
  165466. /* This is a new term. Append a term to the output segment. */
  165467. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  165468. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  165469. }
  165470. /* Append the rowid to the output */
  165471. /* WRITEPOSLISTSIZE */
  165472. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  165473. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter), nPos);
  165474. /* Append the position-list data to the output */
  165475. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  165476. }
  165477. /* Flush the last leaf page to disk. Set the output segment b-tree height
  165478. ** and last leaf page number at the same time. */
  165479. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  165480. if( fts5MultiIterEof(p, pIter) ){
  165481. int i;
  165482. /* Remove the redundant segments from the %_data table */
  165483. for(i=0; i<nInput; i++){
  165484. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  165485. }
  165486. /* Remove the redundant segments from the input level */
  165487. if( pLvl->nSeg!=nInput ){
  165488. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  165489. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  165490. }
  165491. pStruct->nSegment -= nInput;
  165492. pLvl->nSeg -= nInput;
  165493. pLvl->nMerge = 0;
  165494. if( pSeg->pgnoLast==0 ){
  165495. pLvlOut->nSeg--;
  165496. pStruct->nSegment--;
  165497. }
  165498. }else{
  165499. assert( pSeg->pgnoLast>0 );
  165500. fts5TrimSegments(p, pIter);
  165501. pLvl->nMerge = nInput;
  165502. }
  165503. fts5MultiIterFree(p, pIter);
  165504. fts5BufferFree(&term);
  165505. if( pnRem ) *pnRem -= writer.nLeafWritten;
  165506. }
  165507. /*
  165508. ** Do up to nPg pages of automerge work on the index.
  165509. */
  165510. static void fts5IndexMerge(
  165511. Fts5Index *p, /* FTS5 backend object */
  165512. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  165513. int nPg /* Pages of work to do */
  165514. ){
  165515. int nRem = nPg;
  165516. Fts5Structure *pStruct = *ppStruct;
  165517. while( nRem>0 && p->rc==SQLITE_OK ){
  165518. int iLvl; /* To iterate through levels */
  165519. int iBestLvl = 0; /* Level offering the most input segments */
  165520. int nBest = 0; /* Number of input segments on best level */
  165521. /* Set iBestLvl to the level to read input segments from. */
  165522. assert( pStruct->nLevel>0 );
  165523. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  165524. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  165525. if( pLvl->nMerge ){
  165526. if( pLvl->nMerge>nBest ){
  165527. iBestLvl = iLvl;
  165528. nBest = pLvl->nMerge;
  165529. }
  165530. break;
  165531. }
  165532. if( pLvl->nSeg>nBest ){
  165533. nBest = pLvl->nSeg;
  165534. iBestLvl = iLvl;
  165535. }
  165536. }
  165537. /* If nBest is still 0, then the index must be empty. */
  165538. #ifdef SQLITE_DEBUG
  165539. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  165540. assert( pStruct->aLevel[iLvl].nSeg==0 );
  165541. }
  165542. #endif
  165543. if( nBest<p->pConfig->nAutomerge
  165544. && pStruct->aLevel[iBestLvl].nMerge==0
  165545. ){
  165546. break;
  165547. }
  165548. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  165549. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  165550. fts5StructurePromote(p, iBestLvl+1, pStruct);
  165551. }
  165552. }
  165553. *ppStruct = pStruct;
  165554. }
  165555. /*
  165556. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  165557. ** segment. This function updates the write-counter accordingly and, if
  165558. ** necessary, performs incremental merge work.
  165559. **
  165560. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  165561. ** already occurred, this function is a no-op.
  165562. */
  165563. static void fts5IndexAutomerge(
  165564. Fts5Index *p, /* FTS5 backend object */
  165565. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  165566. int nLeaf /* Number of output leaves just written */
  165567. ){
  165568. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  165569. Fts5Structure *pStruct = *ppStruct;
  165570. u64 nWrite; /* Initial value of write-counter */
  165571. int nWork; /* Number of work-quanta to perform */
  165572. int nRem; /* Number of leaf pages left to write */
  165573. /* Update the write-counter. While doing so, set nWork. */
  165574. nWrite = pStruct->nWriteCounter;
  165575. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  165576. pStruct->nWriteCounter += nLeaf;
  165577. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  165578. fts5IndexMerge(p, ppStruct, nRem);
  165579. }
  165580. }
  165581. static void fts5IndexCrisismerge(
  165582. Fts5Index *p, /* FTS5 backend object */
  165583. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  165584. ){
  165585. const int nCrisis = p->pConfig->nCrisisMerge;
  165586. Fts5Structure *pStruct = *ppStruct;
  165587. int iLvl = 0;
  165588. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  165589. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  165590. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  165591. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  165592. fts5StructurePromote(p, iLvl+1, pStruct);
  165593. iLvl++;
  165594. }
  165595. *ppStruct = pStruct;
  165596. }
  165597. static int fts5IndexReturn(Fts5Index *p){
  165598. int rc = p->rc;
  165599. p->rc = SQLITE_OK;
  165600. return rc;
  165601. }
  165602. typedef struct Fts5FlushCtx Fts5FlushCtx;
  165603. struct Fts5FlushCtx {
  165604. Fts5Index *pIdx;
  165605. Fts5SegWriter writer;
  165606. };
  165607. /*
  165608. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  165609. ** in a 32-bit integer. Return the size of the largest prefix of this
  165610. ** list nMax bytes or less in size.
  165611. */
  165612. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  165613. int ret;
  165614. u32 dummy;
  165615. ret = fts5GetVarint32(aBuf, dummy);
  165616. if( ret<nMax ){
  165617. while( 1 ){
  165618. int i = fts5GetVarint32(&aBuf[ret], dummy);
  165619. if( (ret + i) > nMax ) break;
  165620. ret += i;
  165621. }
  165622. }
  165623. return ret;
  165624. }
  165625. /*
  165626. ** Flush the contents of in-memory hash table iHash to a new level-0
  165627. ** segment on disk. Also update the corresponding structure record.
  165628. **
  165629. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  165630. ** already occurred, this function is a no-op.
  165631. */
  165632. static void fts5FlushOneHash(Fts5Index *p){
  165633. Fts5Hash *pHash = p->pHash;
  165634. Fts5Structure *pStruct;
  165635. int iSegid;
  165636. int pgnoLast = 0; /* Last leaf page number in segment */
  165637. /* Obtain a reference to the index structure and allocate a new segment-id
  165638. ** for the new level-0 segment. */
  165639. pStruct = fts5StructureRead(p);
  165640. iSegid = fts5AllocateSegid(p, pStruct);
  165641. if( iSegid ){
  165642. const int pgsz = p->pConfig->pgsz;
  165643. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  165644. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  165645. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  165646. Fts5SegWriter writer;
  165647. fts5WriteInit(p, &writer, iSegid);
  165648. pBuf = &writer.writer.buf;
  165649. pPgidx = &writer.writer.pgidx;
  165650. /* fts5WriteInit() should have initialized the buffers to (most likely)
  165651. ** the maximum space required. */
  165652. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  165653. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  165654. /* Begin scanning through hash table entries. This loop runs once for each
  165655. ** term/doclist currently stored within the hash table. */
  165656. if( p->rc==SQLITE_OK ){
  165657. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  165658. }
  165659. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  165660. const char *zTerm; /* Buffer containing term */
  165661. const u8 *pDoclist; /* Pointer to doclist for this term */
  165662. int nDoclist; /* Size of doclist in bytes */
  165663. /* Write the term for this entry to disk. */
  165664. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  165665. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  165666. assert( writer.bFirstRowidInPage==0 );
  165667. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  165668. /* The entire doclist will fit on the current leaf. */
  165669. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  165670. }else{
  165671. i64 iRowid = 0;
  165672. i64 iDelta = 0;
  165673. int iOff = 0;
  165674. /* The entire doclist will not fit on this leaf. The following
  165675. ** loop iterates through the poslists that make up the current
  165676. ** doclist. */
  165677. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  165678. int nPos;
  165679. int nCopy;
  165680. int bDummy;
  165681. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  165682. nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  165683. nCopy += nPos;
  165684. iRowid += iDelta;
  165685. if( writer.bFirstRowidInPage ){
  165686. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  165687. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  165688. writer.bFirstRowidInPage = 0;
  165689. fts5WriteDlidxAppend(p, &writer, iRowid);
  165690. }else{
  165691. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  165692. }
  165693. assert( pBuf->n<=pBuf->nSpace );
  165694. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  165695. /* The entire poslist will fit on the current leaf. So copy
  165696. ** it in one go. */
  165697. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  165698. }else{
  165699. /* The entire poslist will not fit on this leaf. So it needs
  165700. ** to be broken into sections. The only qualification being
  165701. ** that each varint must be stored contiguously. */
  165702. const u8 *pPoslist = &pDoclist[iOff];
  165703. int iPos = 0;
  165704. while( p->rc==SQLITE_OK ){
  165705. int nSpace = pgsz - pBuf->n - pPgidx->n;
  165706. int n = 0;
  165707. if( (nCopy - iPos)<=nSpace ){
  165708. n = nCopy - iPos;
  165709. }else{
  165710. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  165711. }
  165712. assert( n>0 );
  165713. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  165714. iPos += n;
  165715. if( (pBuf->n + pPgidx->n)>=pgsz ){
  165716. fts5WriteFlushLeaf(p, &writer);
  165717. }
  165718. if( iPos>=nCopy ) break;
  165719. }
  165720. }
  165721. iOff += nCopy;
  165722. }
  165723. }
  165724. /* TODO2: Doclist terminator written here. */
  165725. /* pBuf->p[pBuf->n++] = '\0'; */
  165726. assert( pBuf->n<=pBuf->nSpace );
  165727. sqlite3Fts5HashScanNext(pHash);
  165728. }
  165729. sqlite3Fts5HashClear(pHash);
  165730. fts5WriteFinish(p, &writer, &pgnoLast);
  165731. /* Update the Fts5Structure. It is written back to the database by the
  165732. ** fts5StructureRelease() call below. */
  165733. if( pStruct->nLevel==0 ){
  165734. fts5StructureAddLevel(&p->rc, &pStruct);
  165735. }
  165736. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  165737. if( p->rc==SQLITE_OK ){
  165738. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  165739. pSeg->iSegid = iSegid;
  165740. pSeg->pgnoFirst = 1;
  165741. pSeg->pgnoLast = pgnoLast;
  165742. pStruct->nSegment++;
  165743. }
  165744. fts5StructurePromote(p, 0, pStruct);
  165745. }
  165746. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  165747. fts5IndexCrisismerge(p, &pStruct);
  165748. fts5StructureWrite(p, pStruct);
  165749. fts5StructureRelease(pStruct);
  165750. }
  165751. /*
  165752. ** Flush any data stored in the in-memory hash tables to the database.
  165753. */
  165754. static void fts5IndexFlush(Fts5Index *p){
  165755. /* Unless it is empty, flush the hash table to disk */
  165756. if( p->nPendingData ){
  165757. assert( p->pHash );
  165758. p->nPendingData = 0;
  165759. fts5FlushOneHash(p);
  165760. }
  165761. }
  165762. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  165763. Fts5Structure *pStruct;
  165764. Fts5Structure *pNew = 0;
  165765. int nSeg = 0;
  165766. assert( p->rc==SQLITE_OK );
  165767. fts5IndexFlush(p);
  165768. pStruct = fts5StructureRead(p);
  165769. if( pStruct ){
  165770. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  165771. nSeg = pStruct->nSegment;
  165772. if( nSeg>1 ){
  165773. int nByte = sizeof(Fts5Structure);
  165774. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  165775. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  165776. }
  165777. }
  165778. if( pNew ){
  165779. Fts5StructureLevel *pLvl;
  165780. int nByte = nSeg * sizeof(Fts5StructureSegment);
  165781. pNew->nLevel = pStruct->nLevel+1;
  165782. pNew->nRef = 1;
  165783. pNew->nWriteCounter = pStruct->nWriteCounter;
  165784. pLvl = &pNew->aLevel[pStruct->nLevel];
  165785. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  165786. if( pLvl->aSeg ){
  165787. int iLvl, iSeg;
  165788. int iSegOut = 0;
  165789. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  165790. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  165791. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  165792. iSegOut++;
  165793. }
  165794. }
  165795. pNew->nSegment = pLvl->nSeg = nSeg;
  165796. }else{
  165797. sqlite3_free(pNew);
  165798. pNew = 0;
  165799. }
  165800. }
  165801. if( pNew ){
  165802. int iLvl = pNew->nLevel-1;
  165803. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  165804. int nRem = FTS5_OPT_WORK_UNIT;
  165805. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  165806. }
  165807. fts5StructureWrite(p, pNew);
  165808. fts5StructureRelease(pNew);
  165809. }
  165810. fts5StructureRelease(pStruct);
  165811. return fts5IndexReturn(p);
  165812. }
  165813. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  165814. Fts5Structure *pStruct;
  165815. pStruct = fts5StructureRead(p);
  165816. if( pStruct && pStruct->nLevel ){
  165817. fts5IndexMerge(p, &pStruct, nMerge);
  165818. fts5StructureWrite(p, pStruct);
  165819. }
  165820. fts5StructureRelease(pStruct);
  165821. return fts5IndexReturn(p);
  165822. }
  165823. static void fts5PoslistCallback(
  165824. Fts5Index *p,
  165825. void *pContext,
  165826. const u8 *pChunk, int nChunk
  165827. ){
  165828. assert_nc( nChunk>=0 );
  165829. if( nChunk>0 ){
  165830. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  165831. }
  165832. }
  165833. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  165834. struct PoslistCallbackCtx {
  165835. Fts5Buffer *pBuf; /* Append to this buffer */
  165836. Fts5Colset *pColset; /* Restrict matches to this column */
  165837. int eState; /* See above */
  165838. };
  165839. /*
  165840. ** TODO: Make this more efficient!
  165841. */
  165842. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  165843. int i;
  165844. for(i=0; i<pColset->nCol; i++){
  165845. if( pColset->aiCol[i]==iCol ) return 1;
  165846. }
  165847. return 0;
  165848. }
  165849. static void fts5PoslistFilterCallback(
  165850. Fts5Index *p,
  165851. void *pContext,
  165852. const u8 *pChunk, int nChunk
  165853. ){
  165854. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  165855. assert_nc( nChunk>=0 );
  165856. if( nChunk>0 ){
  165857. /* Search through to find the first varint with value 1. This is the
  165858. ** start of the next columns hits. */
  165859. int i = 0;
  165860. int iStart = 0;
  165861. if( pCtx->eState==2 ){
  165862. int iCol;
  165863. fts5FastGetVarint32(pChunk, i, iCol);
  165864. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  165865. pCtx->eState = 1;
  165866. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  165867. }else{
  165868. pCtx->eState = 0;
  165869. }
  165870. }
  165871. do {
  165872. while( i<nChunk && pChunk[i]!=0x01 ){
  165873. while( pChunk[i] & 0x80 ) i++;
  165874. i++;
  165875. }
  165876. if( pCtx->eState ){
  165877. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  165878. }
  165879. if( i<nChunk ){
  165880. int iCol;
  165881. iStart = i;
  165882. i++;
  165883. if( i>=nChunk ){
  165884. pCtx->eState = 2;
  165885. }else{
  165886. fts5FastGetVarint32(pChunk, i, iCol);
  165887. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  165888. if( pCtx->eState ){
  165889. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  165890. iStart = i;
  165891. }
  165892. }
  165893. }
  165894. }while( i<nChunk );
  165895. }
  165896. }
  165897. /*
  165898. ** Iterator pIter currently points to a valid entry (not EOF). This
  165899. ** function appends the position list data for the current entry to
  165900. ** buffer pBuf. It does not make a copy of the position-list size
  165901. ** field.
  165902. */
  165903. static void fts5SegiterPoslist(
  165904. Fts5Index *p,
  165905. Fts5SegIter *pSeg,
  165906. Fts5Colset *pColset,
  165907. Fts5Buffer *pBuf
  165908. ){
  165909. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  165910. if( pColset==0 ){
  165911. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  165912. }else{
  165913. PoslistCallbackCtx sCtx;
  165914. sCtx.pBuf = pBuf;
  165915. sCtx.pColset = pColset;
  165916. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  165917. assert( sCtx.eState==0 || sCtx.eState==1 );
  165918. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  165919. }
  165920. }
  165921. }
  165922. /*
  165923. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  165924. ** the position list contains entries for column iCol, then (*pa) is set
  165925. ** to point to the sub-position-list for that column and the number of
  165926. ** bytes in it returned. Or, if the argument position list does not
  165927. ** contain any entries for column iCol, return 0.
  165928. */
  165929. static int fts5IndexExtractCol(
  165930. const u8 **pa, /* IN/OUT: Pointer to poslist */
  165931. int n, /* IN: Size of poslist in bytes */
  165932. int iCol /* Column to extract from poslist */
  165933. ){
  165934. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  165935. const u8 *p = *pa;
  165936. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  165937. u8 prev = 0;
  165938. while( iCol>iCurrent ){
  165939. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  165940. ** not part of a varint */
  165941. while( (prev & 0x80) || *p!=0x01 ){
  165942. prev = *p++;
  165943. if( p==pEnd ) return 0;
  165944. }
  165945. *pa = p++;
  165946. p += fts5GetVarint32(p, iCurrent);
  165947. }
  165948. if( iCol!=iCurrent ) return 0;
  165949. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  165950. ** not part of a varint */
  165951. assert( (prev & 0x80)==0 );
  165952. while( p<pEnd && ((prev & 0x80) || *p!=0x01) ){
  165953. prev = *p++;
  165954. }
  165955. return p - (*pa);
  165956. }
  165957. /*
  165958. ** Iterator pMulti currently points to a valid entry (not EOF). This
  165959. ** function appends the following to buffer pBuf:
  165960. **
  165961. ** * The varint iDelta, and
  165962. ** * the position list that currently points to, including the size field.
  165963. **
  165964. ** If argument pColset is NULL, then the position list is filtered according
  165965. ** to pColset before being appended to the buffer. If this means there are
  165966. ** no entries in the position list, nothing is appended to the buffer (not
  165967. ** even iDelta).
  165968. **
  165969. ** If an error occurs, an error code is left in p->rc.
  165970. */
  165971. static int fts5AppendPoslist(
  165972. Fts5Index *p,
  165973. i64 iDelta,
  165974. Fts5IndexIter *pMulti,
  165975. Fts5Colset *pColset,
  165976. Fts5Buffer *pBuf
  165977. ){
  165978. if( p->rc==SQLITE_OK ){
  165979. Fts5SegIter *pSeg = &pMulti->aSeg[ pMulti->aFirst[1].iFirst ];
  165980. assert( fts5MultiIterEof(p, pMulti)==0 );
  165981. assert( pSeg->nPos>0 );
  165982. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+9+9) ){
  165983. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf
  165984. && (pColset==0 || pColset->nCol==1)
  165985. ){
  165986. const u8 *pPos = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  165987. int nPos;
  165988. if( pColset ){
  165989. nPos = fts5IndexExtractCol(&pPos, pSeg->nPos, pColset->aiCol[0]);
  165990. if( nPos==0 ) return 1;
  165991. }else{
  165992. nPos = pSeg->nPos;
  165993. }
  165994. assert( nPos>0 );
  165995. fts5BufferSafeAppendVarint(pBuf, iDelta);
  165996. fts5BufferSafeAppendVarint(pBuf, nPos*2);
  165997. fts5BufferSafeAppendBlob(pBuf, pPos, nPos);
  165998. }else{
  165999. int iSv1;
  166000. int iSv2;
  166001. int iData;
  166002. /* Append iDelta */
  166003. iSv1 = pBuf->n;
  166004. fts5BufferSafeAppendVarint(pBuf, iDelta);
  166005. /* WRITEPOSLISTSIZE */
  166006. iSv2 = pBuf->n;
  166007. fts5BufferSafeAppendVarint(pBuf, pSeg->nPos*2);
  166008. iData = pBuf->n;
  166009. fts5SegiterPoslist(p, pSeg, pColset, pBuf);
  166010. if( pColset ){
  166011. int nActual = pBuf->n - iData;
  166012. if( nActual!=pSeg->nPos ){
  166013. if( nActual==0 ){
  166014. pBuf->n = iSv1;
  166015. return 1;
  166016. }else{
  166017. int nReq = sqlite3Fts5GetVarintLen((u32)(nActual*2));
  166018. while( iSv2<(iData-nReq) ){ pBuf->p[iSv2++] = 0x80; }
  166019. sqlite3Fts5PutVarint(&pBuf->p[iSv2], nActual*2);
  166020. }
  166021. }
  166022. }
  166023. }
  166024. }
  166025. }
  166026. return 0;
  166027. }
  166028. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  166029. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  166030. assert( pIter->aPoslist );
  166031. if( p>=pIter->aEof ){
  166032. pIter->aPoslist = 0;
  166033. }else{
  166034. i64 iDelta;
  166035. p += fts5GetVarint(p, (u64*)&iDelta);
  166036. pIter->iRowid += iDelta;
  166037. /* Read position list size */
  166038. if( p[0] & 0x80 ){
  166039. int nPos;
  166040. pIter->nSize = fts5GetVarint32(p, nPos);
  166041. pIter->nPoslist = (nPos>>1);
  166042. }else{
  166043. pIter->nPoslist = ((int)(p[0])) >> 1;
  166044. pIter->nSize = 1;
  166045. }
  166046. pIter->aPoslist = p;
  166047. }
  166048. }
  166049. static void fts5DoclistIterInit(
  166050. Fts5Buffer *pBuf,
  166051. Fts5DoclistIter *pIter
  166052. ){
  166053. memset(pIter, 0, sizeof(*pIter));
  166054. pIter->aPoslist = pBuf->p;
  166055. pIter->aEof = &pBuf->p[pBuf->n];
  166056. fts5DoclistIterNext(pIter);
  166057. }
  166058. #if 0
  166059. /*
  166060. ** Append a doclist to buffer pBuf.
  166061. **
  166062. ** This function assumes that space within the buffer has already been
  166063. ** allocated.
  166064. */
  166065. static void fts5MergeAppendDocid(
  166066. Fts5Buffer *pBuf, /* Buffer to write to */
  166067. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  166068. i64 iRowid /* Rowid to append */
  166069. ){
  166070. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  166071. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  166072. *piLastRowid = iRowid;
  166073. }
  166074. #endif
  166075. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  166076. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  166077. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  166078. (iLastRowid) = (iRowid); \
  166079. }
  166080. /*
  166081. ** Buffers p1 and p2 contain doclists. This function merges the content
  166082. ** of the two doclists together and sets buffer p1 to the result before
  166083. ** returning.
  166084. **
  166085. ** If an error occurs, an error code is left in p->rc. If an error has
  166086. ** already occurred, this function is a no-op.
  166087. */
  166088. static void fts5MergePrefixLists(
  166089. Fts5Index *p, /* FTS5 backend object */
  166090. Fts5Buffer *p1, /* First list to merge */
  166091. Fts5Buffer *p2 /* Second list to merge */
  166092. ){
  166093. if( p2->n ){
  166094. i64 iLastRowid = 0;
  166095. Fts5DoclistIter i1;
  166096. Fts5DoclistIter i2;
  166097. Fts5Buffer out;
  166098. Fts5Buffer tmp;
  166099. memset(&out, 0, sizeof(out));
  166100. memset(&tmp, 0, sizeof(tmp));
  166101. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  166102. fts5DoclistIterInit(p1, &i1);
  166103. fts5DoclistIterInit(p2, &i2);
  166104. while( p->rc==SQLITE_OK && (i1.aPoslist!=0 || i2.aPoslist!=0) ){
  166105. if( i2.aPoslist==0 || (i1.aPoslist && i1.iRowid<i2.iRowid) ){
  166106. /* Copy entry from i1 */
  166107. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  166108. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  166109. fts5DoclistIterNext(&i1);
  166110. }
  166111. else if( i1.aPoslist==0 || i2.iRowid!=i1.iRowid ){
  166112. /* Copy entry from i2 */
  166113. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  166114. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  166115. fts5DoclistIterNext(&i2);
  166116. }
  166117. else{
  166118. i64 iPos1 = 0;
  166119. i64 iPos2 = 0;
  166120. int iOff1 = 0;
  166121. int iOff2 = 0;
  166122. u8 *a1 = &i1.aPoslist[i1.nSize];
  166123. u8 *a2 = &i2.aPoslist[i2.nSize];
  166124. Fts5PoslistWriter writer;
  166125. memset(&writer, 0, sizeof(writer));
  166126. /* Merge the two position lists. */
  166127. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  166128. fts5BufferZero(&tmp);
  166129. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  166130. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  166131. while( p->rc==SQLITE_OK && (iPos1>=0 || iPos2>=0) ){
  166132. i64 iNew;
  166133. if( iPos2<0 || (iPos1>=0 && iPos1<iPos2) ){
  166134. iNew = iPos1;
  166135. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  166136. }else{
  166137. iNew = iPos2;
  166138. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  166139. if( iPos1==iPos2 ){
  166140. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1,&iPos1);
  166141. }
  166142. }
  166143. p->rc = sqlite3Fts5PoslistWriterAppend(&tmp, &writer, iNew);
  166144. }
  166145. /* WRITEPOSLISTSIZE */
  166146. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  166147. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  166148. fts5DoclistIterNext(&i1);
  166149. fts5DoclistIterNext(&i2);
  166150. }
  166151. }
  166152. fts5BufferSet(&p->rc, p1, out.n, out.p);
  166153. fts5BufferFree(&tmp);
  166154. fts5BufferFree(&out);
  166155. }
  166156. }
  166157. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  166158. Fts5Buffer tmp = *p1;
  166159. *p1 = *p2;
  166160. *p2 = tmp;
  166161. }
  166162. static void fts5SetupPrefixIter(
  166163. Fts5Index *p, /* Index to read from */
  166164. int bDesc, /* True for "ORDER BY rowid DESC" */
  166165. const u8 *pToken, /* Buffer containing prefix to match */
  166166. int nToken, /* Size of buffer pToken in bytes */
  166167. Fts5Colset *pColset, /* Restrict matches to these columns */
  166168. Fts5IndexIter **ppIter /* OUT: New iterator */
  166169. ){
  166170. Fts5Structure *pStruct;
  166171. Fts5Buffer *aBuf;
  166172. const int nBuf = 32;
  166173. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  166174. pStruct = fts5StructureRead(p);
  166175. if( aBuf && pStruct ){
  166176. const int flags = FTS5INDEX_QUERY_SCAN;
  166177. int i;
  166178. i64 iLastRowid = 0;
  166179. Fts5IndexIter *p1 = 0; /* Iterator used to gather data from index */
  166180. Fts5Data *pData;
  166181. Fts5Buffer doclist;
  166182. int bNewTerm = 1;
  166183. memset(&doclist, 0, sizeof(doclist));
  166184. for(fts5MultiIterNew(p, pStruct, 1, flags, pToken, nToken, -1, 0, &p1);
  166185. fts5MultiIterEof(p, p1)==0;
  166186. fts5MultiIterNext2(p, p1, &bNewTerm)
  166187. ){
  166188. i64 iRowid = fts5MultiIterRowid(p1);
  166189. int nTerm;
  166190. const u8 *pTerm = fts5MultiIterTerm(p1, &nTerm);
  166191. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  166192. if( bNewTerm ){
  166193. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  166194. }
  166195. if( doclist.n>0 && iRowid<=iLastRowid ){
  166196. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  166197. assert( i<nBuf );
  166198. if( aBuf[i].n==0 ){
  166199. fts5BufferSwap(&doclist, &aBuf[i]);
  166200. fts5BufferZero(&doclist);
  166201. }else{
  166202. fts5MergePrefixLists(p, &doclist, &aBuf[i]);
  166203. fts5BufferZero(&aBuf[i]);
  166204. }
  166205. }
  166206. iLastRowid = 0;
  166207. }
  166208. if( !fts5AppendPoslist(p, iRowid-iLastRowid, p1, pColset, &doclist) ){
  166209. iLastRowid = iRowid;
  166210. }
  166211. }
  166212. for(i=0; i<nBuf; i++){
  166213. if( p->rc==SQLITE_OK ){
  166214. fts5MergePrefixLists(p, &doclist, &aBuf[i]);
  166215. }
  166216. fts5BufferFree(&aBuf[i]);
  166217. }
  166218. fts5MultiIterFree(p, p1);
  166219. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  166220. if( pData ){
  166221. pData->p = (u8*)&pData[1];
  166222. pData->nn = pData->szLeaf = doclist.n;
  166223. memcpy(pData->p, doclist.p, doclist.n);
  166224. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  166225. }
  166226. fts5BufferFree(&doclist);
  166227. }
  166228. fts5StructureRelease(pStruct);
  166229. sqlite3_free(aBuf);
  166230. }
  166231. /*
  166232. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  166233. ** to the document with rowid iRowid.
  166234. */
  166235. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  166236. assert( p->rc==SQLITE_OK );
  166237. /* Allocate the hash table if it has not already been allocated */
  166238. if( p->pHash==0 ){
  166239. p->rc = sqlite3Fts5HashNew(&p->pHash, &p->nPendingData);
  166240. }
  166241. /* Flush the hash table to disk if required */
  166242. if( iRowid<p->iWriteRowid
  166243. || (iRowid==p->iWriteRowid && p->bDelete==0)
  166244. || (p->nPendingData > p->pConfig->nHashSize)
  166245. ){
  166246. fts5IndexFlush(p);
  166247. }
  166248. p->iWriteRowid = iRowid;
  166249. p->bDelete = bDelete;
  166250. return fts5IndexReturn(p);
  166251. }
  166252. /*
  166253. ** Commit data to disk.
  166254. */
  166255. static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
  166256. assert( p->rc==SQLITE_OK );
  166257. fts5IndexFlush(p);
  166258. if( bCommit ) fts5CloseReader(p);
  166259. return fts5IndexReturn(p);
  166260. }
  166261. /*
  166262. ** Discard any data stored in the in-memory hash tables. Do not write it
  166263. ** to the database. Additionally, assume that the contents of the %_data
  166264. ** table may have changed on disk. So any in-memory caches of %_data
  166265. ** records must be invalidated.
  166266. */
  166267. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  166268. fts5CloseReader(p);
  166269. fts5IndexDiscardData(p);
  166270. assert( p->rc==SQLITE_OK );
  166271. return SQLITE_OK;
  166272. }
  166273. /*
  166274. ** The %_data table is completely empty when this function is called. This
  166275. ** function populates it with the initial structure objects for each index,
  166276. ** and the initial version of the "averages" record (a zero-byte blob).
  166277. */
  166278. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  166279. Fts5Structure s;
  166280. memset(&s, 0, sizeof(Fts5Structure));
  166281. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  166282. fts5StructureWrite(p, &s);
  166283. return fts5IndexReturn(p);
  166284. }
  166285. /*
  166286. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  166287. ** and initialize the underlying %_data table.
  166288. **
  166289. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  166290. ** Otherwise, set *pp to NULL and return an SQLite error code.
  166291. */
  166292. static int sqlite3Fts5IndexOpen(
  166293. Fts5Config *pConfig,
  166294. int bCreate,
  166295. Fts5Index **pp,
  166296. char **pzErr
  166297. ){
  166298. int rc = SQLITE_OK;
  166299. Fts5Index *p; /* New object */
  166300. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  166301. if( rc==SQLITE_OK ){
  166302. p->pConfig = pConfig;
  166303. p->nWorkUnit = FTS5_WORK_UNIT;
  166304. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  166305. if( p->zDataTbl && bCreate ){
  166306. rc = sqlite3Fts5CreateTable(
  166307. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  166308. );
  166309. if( rc==SQLITE_OK ){
  166310. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  166311. "segid, term, pgno, PRIMARY KEY(segid, term)",
  166312. 1, pzErr
  166313. );
  166314. }
  166315. if( rc==SQLITE_OK ){
  166316. rc = sqlite3Fts5IndexReinit(p);
  166317. }
  166318. }
  166319. }
  166320. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  166321. if( rc ){
  166322. sqlite3Fts5IndexClose(p);
  166323. *pp = 0;
  166324. }
  166325. return rc;
  166326. }
  166327. /*
  166328. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  166329. */
  166330. static int sqlite3Fts5IndexClose(Fts5Index *p){
  166331. int rc = SQLITE_OK;
  166332. if( p ){
  166333. assert( p->pReader==0 );
  166334. sqlite3_finalize(p->pWriter);
  166335. sqlite3_finalize(p->pDeleter);
  166336. sqlite3_finalize(p->pIdxWriter);
  166337. sqlite3_finalize(p->pIdxDeleter);
  166338. sqlite3_finalize(p->pIdxSelect);
  166339. sqlite3Fts5HashFree(p->pHash);
  166340. sqlite3_free(p->zDataTbl);
  166341. sqlite3_free(p);
  166342. }
  166343. return rc;
  166344. }
  166345. /*
  166346. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  166347. ** size. Return the number of bytes in the nChar character prefix of the
  166348. ** buffer, or 0 if there are less than nChar characters in total.
  166349. */
  166350. static int fts5IndexCharlenToBytelen(const char *p, int nByte, int nChar){
  166351. int n = 0;
  166352. int i;
  166353. for(i=0; i<nChar; i++){
  166354. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  166355. if( (unsigned char)p[n++]>=0xc0 ){
  166356. while( (p[n] & 0xc0)==0x80 ) n++;
  166357. }
  166358. }
  166359. return n;
  166360. }
  166361. /*
  166362. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  166363. ** unicode characters in the string.
  166364. */
  166365. static int fts5IndexCharlen(const char *pIn, int nIn){
  166366. int nChar = 0;
  166367. int i = 0;
  166368. while( i<nIn ){
  166369. if( (unsigned char)pIn[i++]>=0xc0 ){
  166370. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  166371. }
  166372. nChar++;
  166373. }
  166374. return nChar;
  166375. }
  166376. /*
  166377. ** Insert or remove data to or from the index. Each time a document is
  166378. ** added to or removed from the index, this function is called one or more
  166379. ** times.
  166380. **
  166381. ** For an insert, it must be called once for each token in the new document.
  166382. ** If the operation is a delete, it must be called (at least) once for each
  166383. ** unique token in the document with an iCol value less than zero. The iPos
  166384. ** argument is ignored for a delete.
  166385. */
  166386. static int sqlite3Fts5IndexWrite(
  166387. Fts5Index *p, /* Index to write to */
  166388. int iCol, /* Column token appears in (-ve -> delete) */
  166389. int iPos, /* Position of token within column */
  166390. const char *pToken, int nToken /* Token to add or remove to or from index */
  166391. ){
  166392. int i; /* Used to iterate through indexes */
  166393. int rc = SQLITE_OK; /* Return code */
  166394. Fts5Config *pConfig = p->pConfig;
  166395. assert( p->rc==SQLITE_OK );
  166396. assert( (iCol<0)==p->bDelete );
  166397. /* Add the entry to the main terms index. */
  166398. rc = sqlite3Fts5HashWrite(
  166399. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  166400. );
  166401. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  166402. int nByte = fts5IndexCharlenToBytelen(pToken, nToken, pConfig->aPrefix[i]);
  166403. if( nByte ){
  166404. rc = sqlite3Fts5HashWrite(p->pHash,
  166405. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  166406. nByte
  166407. );
  166408. }
  166409. }
  166410. return rc;
  166411. }
  166412. /*
  166413. ** Open a new iterator to iterate though all rowid that match the
  166414. ** specified token or token prefix.
  166415. */
  166416. static int sqlite3Fts5IndexQuery(
  166417. Fts5Index *p, /* FTS index to query */
  166418. const char *pToken, int nToken, /* Token (or prefix) to query for */
  166419. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  166420. Fts5Colset *pColset, /* Match these columns only */
  166421. Fts5IndexIter **ppIter /* OUT: New iterator object */
  166422. ){
  166423. Fts5Config *pConfig = p->pConfig;
  166424. Fts5IndexIter *pRet = 0;
  166425. int iIdx = 0;
  166426. Fts5Buffer buf = {0, 0, 0};
  166427. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  166428. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  166429. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  166430. memcpy(&buf.p[1], pToken, nToken);
  166431. #ifdef SQLITE_DEBUG
  166432. /* If the QUERY_TEST_NOIDX flag was specified, then this must be a
  166433. ** prefix-query. Instead of using a prefix-index (if one exists),
  166434. ** evaluate the prefix query using the main FTS index. This is used
  166435. ** for internal sanity checking by the integrity-check in debug
  166436. ** mode only. */
  166437. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  166438. assert( flags & FTS5INDEX_QUERY_PREFIX );
  166439. iIdx = 1+pConfig->nPrefix;
  166440. }else
  166441. #endif
  166442. if( flags & FTS5INDEX_QUERY_PREFIX ){
  166443. int nChar = fts5IndexCharlen(pToken, nToken);
  166444. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  166445. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  166446. }
  166447. }
  166448. if( iIdx<=pConfig->nPrefix ){
  166449. Fts5Structure *pStruct = fts5StructureRead(p);
  166450. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  166451. if( pStruct ){
  166452. fts5MultiIterNew(p, pStruct, 1, flags, buf.p, nToken+1, -1, 0, &pRet);
  166453. fts5StructureRelease(pStruct);
  166454. }
  166455. }else{
  166456. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  166457. buf.p[0] = FTS5_MAIN_PREFIX;
  166458. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  166459. }
  166460. if( p->rc ){
  166461. sqlite3Fts5IterClose(pRet);
  166462. pRet = 0;
  166463. fts5CloseReader(p);
  166464. }
  166465. *ppIter = pRet;
  166466. sqlite3Fts5BufferFree(&buf);
  166467. }
  166468. return fts5IndexReturn(p);
  166469. }
  166470. /*
  166471. ** Return true if the iterator passed as the only argument is at EOF.
  166472. */
  166473. static int sqlite3Fts5IterEof(Fts5IndexIter *pIter){
  166474. assert( pIter->pIndex->rc==SQLITE_OK );
  166475. return pIter->bEof;
  166476. }
  166477. /*
  166478. ** Move to the next matching rowid.
  166479. */
  166480. static int sqlite3Fts5IterNext(Fts5IndexIter *pIter){
  166481. assert( pIter->pIndex->rc==SQLITE_OK );
  166482. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  166483. return fts5IndexReturn(pIter->pIndex);
  166484. }
  166485. /*
  166486. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  166487. */
  166488. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIter){
  166489. Fts5Index *p = pIter->pIndex;
  166490. assert( pIter->pIndex->rc==SQLITE_OK );
  166491. fts5MultiIterNext(p, pIter, 0, 0);
  166492. if( p->rc==SQLITE_OK ){
  166493. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  166494. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  166495. fts5DataRelease(pSeg->pLeaf);
  166496. pSeg->pLeaf = 0;
  166497. pIter->bEof = 1;
  166498. }
  166499. }
  166500. return fts5IndexReturn(pIter->pIndex);
  166501. }
  166502. /*
  166503. ** Move to the next matching rowid that occurs at or after iMatch. The
  166504. ** definition of "at or after" depends on whether this iterator iterates
  166505. ** in ascending or descending rowid order.
  166506. */
  166507. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIter, i64 iMatch){
  166508. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  166509. return fts5IndexReturn(pIter->pIndex);
  166510. }
  166511. /*
  166512. ** Return the current rowid.
  166513. */
  166514. static i64 sqlite3Fts5IterRowid(Fts5IndexIter *pIter){
  166515. return fts5MultiIterRowid(pIter);
  166516. }
  166517. /*
  166518. ** Return the current term.
  166519. */
  166520. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIter, int *pn){
  166521. int n;
  166522. const char *z = (const char*)fts5MultiIterTerm(pIter, &n);
  166523. *pn = n-1;
  166524. return &z[1];
  166525. }
  166526. static int fts5IndexExtractColset (
  166527. Fts5Colset *pColset, /* Colset to filter on */
  166528. const u8 *pPos, int nPos, /* Position list */
  166529. Fts5Buffer *pBuf /* Output buffer */
  166530. ){
  166531. int rc = SQLITE_OK;
  166532. int i;
  166533. fts5BufferZero(pBuf);
  166534. for(i=0; i<pColset->nCol; i++){
  166535. const u8 *pSub = pPos;
  166536. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  166537. if( nSub ){
  166538. fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
  166539. }
  166540. }
  166541. return rc;
  166542. }
  166543. /*
  166544. ** Return a pointer to a buffer containing a copy of the position list for
  166545. ** the current entry. Output variable *pn is set to the size of the buffer
  166546. ** in bytes before returning.
  166547. **
  166548. ** The returned position list does not include the "number of bytes" varint
  166549. ** field that starts the position list on disk.
  166550. */
  166551. static int sqlite3Fts5IterPoslist(
  166552. Fts5IndexIter *pIter,
  166553. Fts5Colset *pColset, /* Column filter (or NULL) */
  166554. const u8 **pp, /* OUT: Pointer to position-list data */
  166555. int *pn, /* OUT: Size of position-list in bytes */
  166556. i64 *piRowid /* OUT: Current rowid */
  166557. ){
  166558. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  166559. assert( pIter->pIndex->rc==SQLITE_OK );
  166560. *piRowid = pSeg->iRowid;
  166561. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  166562. u8 *pPos = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  166563. if( pColset==0 || pIter->bFiltered ){
  166564. *pn = pSeg->nPos;
  166565. *pp = pPos;
  166566. }else if( pColset->nCol==1 ){
  166567. *pp = pPos;
  166568. *pn = fts5IndexExtractCol(pp, pSeg->nPos, pColset->aiCol[0]);
  166569. }else{
  166570. fts5BufferZero(&pIter->poslist);
  166571. fts5IndexExtractColset(pColset, pPos, pSeg->nPos, &pIter->poslist);
  166572. *pp = pIter->poslist.p;
  166573. *pn = pIter->poslist.n;
  166574. }
  166575. }else{
  166576. fts5BufferZero(&pIter->poslist);
  166577. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  166578. *pp = pIter->poslist.p;
  166579. *pn = pIter->poslist.n;
  166580. }
  166581. return fts5IndexReturn(pIter->pIndex);
  166582. }
  166583. /*
  166584. ** This function is similar to sqlite3Fts5IterPoslist(), except that it
  166585. ** copies the position list into the buffer supplied as the second
  166586. ** argument.
  166587. */
  166588. static int sqlite3Fts5IterPoslistBuffer(Fts5IndexIter *pIter, Fts5Buffer *pBuf){
  166589. Fts5Index *p = pIter->pIndex;
  166590. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  166591. assert( p->rc==SQLITE_OK );
  166592. fts5BufferZero(pBuf);
  166593. fts5SegiterPoslist(p, pSeg, 0, pBuf);
  166594. return fts5IndexReturn(p);
  166595. }
  166596. /*
  166597. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  166598. */
  166599. static void sqlite3Fts5IterClose(Fts5IndexIter *pIter){
  166600. if( pIter ){
  166601. Fts5Index *pIndex = pIter->pIndex;
  166602. fts5MultiIterFree(pIter->pIndex, pIter);
  166603. fts5CloseReader(pIndex);
  166604. }
  166605. }
  166606. /*
  166607. ** Read and decode the "averages" record from the database.
  166608. **
  166609. ** Parameter anSize must point to an array of size nCol, where nCol is
  166610. ** the number of user defined columns in the FTS table.
  166611. */
  166612. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  166613. int nCol = p->pConfig->nCol;
  166614. Fts5Data *pData;
  166615. *pnRow = 0;
  166616. memset(anSize, 0, sizeof(i64) * nCol);
  166617. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  166618. if( p->rc==SQLITE_OK && pData->nn ){
  166619. int i = 0;
  166620. int iCol;
  166621. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  166622. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  166623. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  166624. }
  166625. }
  166626. fts5DataRelease(pData);
  166627. return fts5IndexReturn(p);
  166628. }
  166629. /*
  166630. ** Replace the current "averages" record with the contents of the buffer
  166631. ** supplied as the second argument.
  166632. */
  166633. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  166634. assert( p->rc==SQLITE_OK );
  166635. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  166636. return fts5IndexReturn(p);
  166637. }
  166638. /*
  166639. ** Return the total number of blocks this module has read from the %_data
  166640. ** table since it was created.
  166641. */
  166642. static int sqlite3Fts5IndexReads(Fts5Index *p){
  166643. return p->nRead;
  166644. }
  166645. /*
  166646. ** Set the 32-bit cookie value stored at the start of all structure
  166647. ** records to the value passed as the second argument.
  166648. **
  166649. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  166650. ** occurs.
  166651. */
  166652. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  166653. int rc; /* Return code */
  166654. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  166655. u8 aCookie[4]; /* Binary representation of iNew */
  166656. sqlite3_blob *pBlob = 0;
  166657. assert( p->rc==SQLITE_OK );
  166658. sqlite3Fts5Put32(aCookie, iNew);
  166659. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  166660. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  166661. );
  166662. if( rc==SQLITE_OK ){
  166663. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  166664. rc = sqlite3_blob_close(pBlob);
  166665. }
  166666. return rc;
  166667. }
  166668. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  166669. Fts5Structure *pStruct;
  166670. pStruct = fts5StructureRead(p);
  166671. fts5StructureRelease(pStruct);
  166672. return fts5IndexReturn(p);
  166673. }
  166674. /*************************************************************************
  166675. **************************************************************************
  166676. ** Below this point is the implementation of the integrity-check
  166677. ** functionality.
  166678. */
  166679. /*
  166680. ** Return a simple checksum value based on the arguments.
  166681. */
  166682. static u64 fts5IndexEntryCksum(
  166683. i64 iRowid,
  166684. int iCol,
  166685. int iPos,
  166686. int iIdx,
  166687. const char *pTerm,
  166688. int nTerm
  166689. ){
  166690. int i;
  166691. u64 ret = iRowid;
  166692. ret += (ret<<3) + iCol;
  166693. ret += (ret<<3) + iPos;
  166694. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  166695. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  166696. return ret;
  166697. }
  166698. #ifdef SQLITE_DEBUG
  166699. /*
  166700. ** This function is purely an internal test. It does not contribute to
  166701. ** FTS functionality, or even the integrity-check, in any way.
  166702. **
  166703. ** Instead, it tests that the same set of pgno/rowid combinations are
  166704. ** visited regardless of whether the doclist-index identified by parameters
  166705. ** iSegid/iLeaf is iterated in forwards or reverse order.
  166706. */
  166707. static void fts5TestDlidxReverse(
  166708. Fts5Index *p,
  166709. int iSegid, /* Segment id to load from */
  166710. int iLeaf /* Load doclist-index for this leaf */
  166711. ){
  166712. Fts5DlidxIter *pDlidx = 0;
  166713. u64 cksum1 = 13;
  166714. u64 cksum2 = 13;
  166715. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  166716. fts5DlidxIterEof(p, pDlidx)==0;
  166717. fts5DlidxIterNext(p, pDlidx)
  166718. ){
  166719. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  166720. int pgno = fts5DlidxIterPgno(pDlidx);
  166721. assert( pgno>iLeaf );
  166722. cksum1 += iRowid + ((i64)pgno<<32);
  166723. }
  166724. fts5DlidxIterFree(pDlidx);
  166725. pDlidx = 0;
  166726. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  166727. fts5DlidxIterEof(p, pDlidx)==0;
  166728. fts5DlidxIterPrev(p, pDlidx)
  166729. ){
  166730. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  166731. int pgno = fts5DlidxIterPgno(pDlidx);
  166732. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  166733. cksum2 += iRowid + ((i64)pgno<<32);
  166734. }
  166735. fts5DlidxIterFree(pDlidx);
  166736. pDlidx = 0;
  166737. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  166738. }
  166739. static int fts5QueryCksum(
  166740. Fts5Index *p, /* Fts5 index object */
  166741. int iIdx,
  166742. const char *z, /* Index key to query for */
  166743. int n, /* Size of index key in bytes */
  166744. int flags, /* Flags for Fts5IndexQuery */
  166745. u64 *pCksum /* IN/OUT: Checksum value */
  166746. ){
  166747. u64 cksum = *pCksum;
  166748. Fts5IndexIter *pIdxIter = 0;
  166749. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIdxIter);
  166750. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIdxIter) ){
  166751. i64 dummy;
  166752. const u8 *pPos;
  166753. int nPos;
  166754. i64 rowid = sqlite3Fts5IterRowid(pIdxIter);
  166755. rc = sqlite3Fts5IterPoslist(pIdxIter, 0, &pPos, &nPos, &dummy);
  166756. if( rc==SQLITE_OK ){
  166757. Fts5PoslistReader sReader;
  166758. for(sqlite3Fts5PoslistReaderInit(pPos, nPos, &sReader);
  166759. sReader.bEof==0;
  166760. sqlite3Fts5PoslistReaderNext(&sReader)
  166761. ){
  166762. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  166763. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  166764. cksum ^= fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  166765. }
  166766. rc = sqlite3Fts5IterNext(pIdxIter);
  166767. }
  166768. }
  166769. sqlite3Fts5IterClose(pIdxIter);
  166770. *pCksum = cksum;
  166771. return rc;
  166772. }
  166773. /*
  166774. ** This function is also purely an internal test. It does not contribute to
  166775. ** FTS functionality, or even the integrity-check, in any way.
  166776. */
  166777. static void fts5TestTerm(
  166778. Fts5Index *p,
  166779. Fts5Buffer *pPrev, /* Previous term */
  166780. const char *z, int n, /* Possibly new term to test */
  166781. u64 expected,
  166782. u64 *pCksum
  166783. ){
  166784. int rc = p->rc;
  166785. if( pPrev->n==0 ){
  166786. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  166787. }else
  166788. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  166789. u64 cksum3 = *pCksum;
  166790. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  166791. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  166792. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  166793. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  166794. u64 ck1 = 0;
  166795. u64 ck2 = 0;
  166796. /* Check that the results returned for ASC and DESC queries are
  166797. ** the same. If not, call this corruption. */
  166798. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  166799. if( rc==SQLITE_OK ){
  166800. int f = flags|FTS5INDEX_QUERY_DESC;
  166801. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  166802. }
  166803. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  166804. /* If this is a prefix query, check that the results returned if the
  166805. ** the index is disabled are the same. In both ASC and DESC order.
  166806. **
  166807. ** This check may only be performed if the hash table is empty. This
  166808. ** is because the hash table only supports a single scan query at
  166809. ** a time, and the multi-iter loop from which this function is called
  166810. ** is already performing such a scan. */
  166811. if( p->nPendingData==0 ){
  166812. if( iIdx>0 && rc==SQLITE_OK ){
  166813. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  166814. ck2 = 0;
  166815. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  166816. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  166817. }
  166818. if( iIdx>0 && rc==SQLITE_OK ){
  166819. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  166820. ck2 = 0;
  166821. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  166822. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  166823. }
  166824. }
  166825. cksum3 ^= ck1;
  166826. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  166827. if( rc==SQLITE_OK && cksum3!=expected ){
  166828. rc = FTS5_CORRUPT;
  166829. }
  166830. *pCksum = cksum3;
  166831. }
  166832. p->rc = rc;
  166833. }
  166834. #else
  166835. # define fts5TestDlidxReverse(x,y,z)
  166836. # define fts5TestTerm(u,v,w,x,y,z)
  166837. #endif
  166838. /*
  166839. ** Check that:
  166840. **
  166841. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  166842. ** contain zero terms.
  166843. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  166844. ** contain zero rowids.
  166845. */
  166846. static void fts5IndexIntegrityCheckEmpty(
  166847. Fts5Index *p,
  166848. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  166849. int iFirst,
  166850. int iNoRowid,
  166851. int iLast
  166852. ){
  166853. int i;
  166854. /* Now check that the iter.nEmpty leaves following the current leaf
  166855. ** (a) exist and (b) contain no terms. */
  166856. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  166857. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  166858. if( pLeaf ){
  166859. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  166860. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  166861. }
  166862. fts5DataRelease(pLeaf);
  166863. }
  166864. }
  166865. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  166866. int iTermOff = 0;
  166867. int ii;
  166868. Fts5Buffer buf1 = {0,0,0};
  166869. Fts5Buffer buf2 = {0,0,0};
  166870. ii = pLeaf->szLeaf;
  166871. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  166872. int res;
  166873. int iOff;
  166874. int nIncr;
  166875. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  166876. iTermOff += nIncr;
  166877. iOff = iTermOff;
  166878. if( iOff>=pLeaf->szLeaf ){
  166879. p->rc = FTS5_CORRUPT;
  166880. }else if( iTermOff==nIncr ){
  166881. int nByte;
  166882. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  166883. if( (iOff+nByte)>pLeaf->szLeaf ){
  166884. p->rc = FTS5_CORRUPT;
  166885. }else{
  166886. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  166887. }
  166888. }else{
  166889. int nKeep, nByte;
  166890. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  166891. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  166892. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  166893. p->rc = FTS5_CORRUPT;
  166894. }else{
  166895. buf1.n = nKeep;
  166896. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  166897. }
  166898. if( p->rc==SQLITE_OK ){
  166899. res = fts5BufferCompare(&buf1, &buf2);
  166900. if( res<=0 ) p->rc = FTS5_CORRUPT;
  166901. }
  166902. }
  166903. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  166904. }
  166905. fts5BufferFree(&buf1);
  166906. fts5BufferFree(&buf2);
  166907. }
  166908. static void fts5IndexIntegrityCheckSegment(
  166909. Fts5Index *p, /* FTS5 backend object */
  166910. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  166911. ){
  166912. Fts5Config *pConfig = p->pConfig;
  166913. sqlite3_stmt *pStmt = 0;
  166914. int rc2;
  166915. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  166916. int iDlidxPrevLeaf = pSeg->pgnoLast;
  166917. if( pSeg->pgnoFirst==0 ) return;
  166918. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  166919. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  166920. pConfig->zDb, pConfig->zName, pSeg->iSegid
  166921. ));
  166922. /* Iterate through the b-tree hierarchy. */
  166923. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  166924. i64 iRow; /* Rowid for this leaf */
  166925. Fts5Data *pLeaf; /* Data for this leaf */
  166926. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  166927. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  166928. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  166929. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  166930. /* If the leaf in question has already been trimmed from the segment,
  166931. ** ignore this b-tree entry. Otherwise, load it into memory. */
  166932. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  166933. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  166934. pLeaf = fts5DataRead(p, iRow);
  166935. if( pLeaf==0 ) break;
  166936. /* Check that the leaf contains at least one term, and that it is equal
  166937. ** to or larger than the split-key in zIdxTerm. Also check that if there
  166938. ** is also a rowid pointer within the leaf page header, it points to a
  166939. ** location before the term. */
  166940. if( pLeaf->nn<=pLeaf->szLeaf ){
  166941. p->rc = FTS5_CORRUPT;
  166942. }else{
  166943. int iOff; /* Offset of first term on leaf */
  166944. int iRowidOff; /* Offset of first rowid on leaf */
  166945. int nTerm; /* Size of term on leaf in bytes */
  166946. int res; /* Comparison of term and split-key */
  166947. iOff = fts5LeafFirstTermOff(pLeaf);
  166948. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  166949. if( iRowidOff>=iOff ){
  166950. p->rc = FTS5_CORRUPT;
  166951. }else{
  166952. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  166953. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  166954. if( res==0 ) res = nTerm - nIdxTerm;
  166955. if( res<0 ) p->rc = FTS5_CORRUPT;
  166956. }
  166957. fts5IntegrityCheckPgidx(p, pLeaf);
  166958. }
  166959. fts5DataRelease(pLeaf);
  166960. if( p->rc ) break;
  166961. /* Now check that the iter.nEmpty leaves following the current leaf
  166962. ** (a) exist and (b) contain no terms. */
  166963. fts5IndexIntegrityCheckEmpty(
  166964. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  166965. );
  166966. if( p->rc ) break;
  166967. /* If there is a doclist-index, check that it looks right. */
  166968. if( bIdxDlidx ){
  166969. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  166970. int iPrevLeaf = iIdxLeaf;
  166971. int iSegid = pSeg->iSegid;
  166972. int iPg = 0;
  166973. i64 iKey;
  166974. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  166975. fts5DlidxIterEof(p, pDlidx)==0;
  166976. fts5DlidxIterNext(p, pDlidx)
  166977. ){
  166978. /* Check any rowid-less pages that occur before the current leaf. */
  166979. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  166980. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  166981. pLeaf = fts5DataRead(p, iKey);
  166982. if( pLeaf ){
  166983. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  166984. fts5DataRelease(pLeaf);
  166985. }
  166986. }
  166987. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  166988. /* Check that the leaf page indicated by the iterator really does
  166989. ** contain the rowid suggested by the same. */
  166990. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  166991. pLeaf = fts5DataRead(p, iKey);
  166992. if( pLeaf ){
  166993. i64 iRowid;
  166994. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  166995. ASSERT_SZLEAF_OK(pLeaf);
  166996. if( iRowidOff>=pLeaf->szLeaf ){
  166997. p->rc = FTS5_CORRUPT;
  166998. }else{
  166999. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  167000. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  167001. }
  167002. fts5DataRelease(pLeaf);
  167003. }
  167004. }
  167005. iDlidxPrevLeaf = iPg;
  167006. fts5DlidxIterFree(pDlidx);
  167007. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  167008. }else{
  167009. iDlidxPrevLeaf = pSeg->pgnoLast;
  167010. /* TODO: Check there is no doclist index */
  167011. }
  167012. iIdxPrevLeaf = iIdxLeaf;
  167013. }
  167014. rc2 = sqlite3_finalize(pStmt);
  167015. if( p->rc==SQLITE_OK ) p->rc = rc2;
  167016. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  167017. #if 0
  167018. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  167019. p->rc = FTS5_CORRUPT;
  167020. }
  167021. #endif
  167022. }
  167023. /*
  167024. ** Run internal checks to ensure that the FTS index (a) is internally
  167025. ** consistent and (b) contains entries for which the XOR of the checksums
  167026. ** as calculated by fts5IndexEntryCksum() is cksum.
  167027. **
  167028. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  167029. ** checksum does not match. Return SQLITE_OK if all checks pass without
  167030. ** error, or some other SQLite error code if another error (e.g. OOM)
  167031. ** occurs.
  167032. */
  167033. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  167034. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  167035. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  167036. Fts5IndexIter *pIter; /* Used to iterate through entire index */
  167037. Fts5Structure *pStruct; /* Index structure */
  167038. #ifdef SQLITE_DEBUG
  167039. /* Used by extra internal tests only run if NDEBUG is not defined */
  167040. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  167041. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  167042. #endif
  167043. /* Load the FTS index structure */
  167044. pStruct = fts5StructureRead(p);
  167045. /* Check that the internal nodes of each segment match the leaves */
  167046. if( pStruct ){
  167047. int iLvl, iSeg;
  167048. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  167049. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  167050. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  167051. fts5IndexIntegrityCheckSegment(p, pSeg);
  167052. }
  167053. }
  167054. }
  167055. /* The cksum argument passed to this function is a checksum calculated
  167056. ** based on all expected entries in the FTS index (including prefix index
  167057. ** entries). This block checks that a checksum calculated based on the
  167058. ** actual contents of FTS index is identical.
  167059. **
  167060. ** Two versions of the same checksum are calculated. The first (stack
  167061. ** variable cksum2) based on entries extracted from the full-text index
  167062. ** while doing a linear scan of each individual index in turn.
  167063. **
  167064. ** As each term visited by the linear scans, a separate query for the
  167065. ** same term is performed. cksum3 is calculated based on the entries
  167066. ** extracted by these queries.
  167067. */
  167068. for(fts5MultiIterNew(p, pStruct, 0, 0, 0, 0, -1, 0, &pIter);
  167069. fts5MultiIterEof(p, pIter)==0;
  167070. fts5MultiIterNext(p, pIter, 0, 0)
  167071. ){
  167072. int n; /* Size of term in bytes */
  167073. i64 iPos = 0; /* Position read from poslist */
  167074. int iOff = 0; /* Offset within poslist */
  167075. i64 iRowid = fts5MultiIterRowid(pIter);
  167076. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  167077. /* If this is a new term, query for it. Update cksum3 with the results. */
  167078. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  167079. poslist.n = 0;
  167080. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst] , 0, &poslist);
  167081. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  167082. int iCol = FTS5_POS2COLUMN(iPos);
  167083. int iTokOff = FTS5_POS2OFFSET(iPos);
  167084. cksum2 ^= fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  167085. }
  167086. }
  167087. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  167088. fts5MultiIterFree(p, pIter);
  167089. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  167090. fts5StructureRelease(pStruct);
  167091. #ifdef SQLITE_DEBUG
  167092. fts5BufferFree(&term);
  167093. #endif
  167094. fts5BufferFree(&poslist);
  167095. return fts5IndexReturn(p);
  167096. }
  167097. /*
  167098. ** Calculate and return a checksum that is the XOR of the index entry
  167099. ** checksum of all entries that would be generated by the token specified
  167100. ** by the final 5 arguments.
  167101. */
  167102. static u64 sqlite3Fts5IndexCksum(
  167103. Fts5Config *pConfig, /* Configuration object */
  167104. i64 iRowid, /* Document term appears in */
  167105. int iCol, /* Column term appears in */
  167106. int iPos, /* Position term appears in */
  167107. const char *pTerm, int nTerm /* Term at iPos */
  167108. ){
  167109. u64 ret = 0; /* Return value */
  167110. int iIdx; /* For iterating through indexes */
  167111. ret = fts5IndexEntryCksum(iRowid, iCol, iPos, 0, pTerm, nTerm);
  167112. for(iIdx=0; iIdx<pConfig->nPrefix; iIdx++){
  167113. int nByte = fts5IndexCharlenToBytelen(pTerm, nTerm, pConfig->aPrefix[iIdx]);
  167114. if( nByte ){
  167115. ret ^= fts5IndexEntryCksum(iRowid, iCol, iPos, iIdx+1, pTerm, nByte);
  167116. }
  167117. }
  167118. return ret;
  167119. }
  167120. /*************************************************************************
  167121. **************************************************************************
  167122. ** Below this point is the implementation of the fts5_decode() scalar
  167123. ** function only.
  167124. */
  167125. /*
  167126. ** Decode a segment-data rowid from the %_data table. This function is
  167127. ** the opposite of macro FTS5_SEGMENT_ROWID().
  167128. */
  167129. static void fts5DecodeRowid(
  167130. i64 iRowid, /* Rowid from %_data table */
  167131. int *piSegid, /* OUT: Segment id */
  167132. int *pbDlidx, /* OUT: Dlidx flag */
  167133. int *piHeight, /* OUT: Height */
  167134. int *piPgno /* OUT: Page number */
  167135. ){
  167136. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  167137. iRowid >>= FTS5_DATA_PAGE_B;
  167138. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  167139. iRowid >>= FTS5_DATA_HEIGHT_B;
  167140. *pbDlidx = (int)(iRowid & 0x0001);
  167141. iRowid >>= FTS5_DATA_DLI_B;
  167142. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  167143. }
  167144. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  167145. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  167146. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  167147. if( iSegid==0 ){
  167148. if( iKey==FTS5_AVERAGES_ROWID ){
  167149. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  167150. }else{
  167151. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  167152. }
  167153. }
  167154. else{
  167155. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  167156. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  167157. );
  167158. }
  167159. }
  167160. static void fts5DebugStructure(
  167161. int *pRc, /* IN/OUT: error code */
  167162. Fts5Buffer *pBuf,
  167163. Fts5Structure *p
  167164. ){
  167165. int iLvl, iSeg; /* Iterate through levels, segments */
  167166. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  167167. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  167168. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  167169. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  167170. );
  167171. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  167172. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  167173. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  167174. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  167175. );
  167176. }
  167177. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  167178. }
  167179. }
  167180. /*
  167181. ** This is part of the fts5_decode() debugging aid.
  167182. **
  167183. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  167184. ** function appends a human-readable representation of the same object
  167185. ** to the buffer passed as the second argument.
  167186. */
  167187. static void fts5DecodeStructure(
  167188. int *pRc, /* IN/OUT: error code */
  167189. Fts5Buffer *pBuf,
  167190. const u8 *pBlob, int nBlob
  167191. ){
  167192. int rc; /* Return code */
  167193. Fts5Structure *p = 0; /* Decoded structure object */
  167194. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  167195. if( rc!=SQLITE_OK ){
  167196. *pRc = rc;
  167197. return;
  167198. }
  167199. fts5DebugStructure(pRc, pBuf, p);
  167200. fts5StructureRelease(p);
  167201. }
  167202. /*
  167203. ** This is part of the fts5_decode() debugging aid.
  167204. **
  167205. ** Arguments pBlob/nBlob contain an "averages" record. This function
  167206. ** appends a human-readable representation of record to the buffer passed
  167207. ** as the second argument.
  167208. */
  167209. static void fts5DecodeAverages(
  167210. int *pRc, /* IN/OUT: error code */
  167211. Fts5Buffer *pBuf,
  167212. const u8 *pBlob, int nBlob
  167213. ){
  167214. int i = 0;
  167215. const char *zSpace = "";
  167216. while( i<nBlob ){
  167217. u64 iVal;
  167218. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  167219. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  167220. zSpace = " ";
  167221. }
  167222. }
  167223. /*
  167224. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  167225. ** each varint and append its string representation to buffer pBuf. Return
  167226. ** after either the input buffer is exhausted or a 0 value is read.
  167227. **
  167228. ** The return value is the number of bytes read from the input buffer.
  167229. */
  167230. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  167231. int iOff = 0;
  167232. while( iOff<n ){
  167233. int iVal;
  167234. iOff += fts5GetVarint32(&a[iOff], iVal);
  167235. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  167236. }
  167237. return iOff;
  167238. }
  167239. /*
  167240. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  167241. ** may or may not finish within the buffer. This function appends a text
  167242. ** representation of the part of the doclist that is present to buffer
  167243. ** pBuf.
  167244. **
  167245. ** The return value is the number of bytes read from the input buffer.
  167246. */
  167247. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  167248. i64 iDocid = 0;
  167249. int iOff = 0;
  167250. if( n>0 ){
  167251. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  167252. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  167253. }
  167254. while( iOff<n ){
  167255. int nPos;
  167256. int bDel;
  167257. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  167258. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  167259. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  167260. if( iOff<n ){
  167261. i64 iDelta;
  167262. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  167263. iDocid += iDelta;
  167264. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  167265. }
  167266. }
  167267. return iOff;
  167268. }
  167269. /*
  167270. ** The implementation of user-defined scalar function fts5_decode().
  167271. */
  167272. static void fts5DecodeFunction(
  167273. sqlite3_context *pCtx, /* Function call context */
  167274. int nArg, /* Number of args (always 2) */
  167275. sqlite3_value **apVal /* Function arguments */
  167276. ){
  167277. i64 iRowid; /* Rowid for record being decoded */
  167278. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  167279. const u8 *aBlob; int n; /* Record to decode */
  167280. u8 *a = 0;
  167281. Fts5Buffer s; /* Build up text to return here */
  167282. int rc = SQLITE_OK; /* Return code */
  167283. int nSpace = 0;
  167284. assert( nArg==2 );
  167285. memset(&s, 0, sizeof(Fts5Buffer));
  167286. iRowid = sqlite3_value_int64(apVal[0]);
  167287. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  167288. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  167289. ** buffer overreads even if the record is corrupt. */
  167290. n = sqlite3_value_bytes(apVal[1]);
  167291. aBlob = sqlite3_value_blob(apVal[1]);
  167292. nSpace = n + FTS5_DATA_ZERO_PADDING;
  167293. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  167294. if( a==0 ) goto decode_out;
  167295. memcpy(a, aBlob, n);
  167296. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  167297. fts5DebugRowid(&rc, &s, iRowid);
  167298. if( bDlidx ){
  167299. Fts5Data dlidx;
  167300. Fts5DlidxLvl lvl;
  167301. dlidx.p = a;
  167302. dlidx.nn = n;
  167303. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  167304. lvl.pData = &dlidx;
  167305. lvl.iLeafPgno = iPgno;
  167306. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  167307. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  167308. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  167309. );
  167310. }
  167311. }else if( iSegid==0 ){
  167312. if( iRowid==FTS5_AVERAGES_ROWID ){
  167313. fts5DecodeAverages(&rc, &s, a, n);
  167314. }else{
  167315. fts5DecodeStructure(&rc, &s, a, n);
  167316. }
  167317. }else{
  167318. Fts5Buffer term; /* Current term read from page */
  167319. int szLeaf; /* Offset of pgidx in a[] */
  167320. int iPgidxOff;
  167321. int iPgidxPrev = 0; /* Previous value read from pgidx */
  167322. int iTermOff = 0;
  167323. int iRowidOff = 0;
  167324. int iOff;
  167325. int nDoclist;
  167326. memset(&term, 0, sizeof(Fts5Buffer));
  167327. if( n<4 ){
  167328. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  167329. goto decode_out;
  167330. }else{
  167331. iRowidOff = fts5GetU16(&a[0]);
  167332. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  167333. if( iPgidxOff<n ){
  167334. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  167335. }
  167336. }
  167337. /* Decode the position list tail at the start of the page */
  167338. if( iRowidOff!=0 ){
  167339. iOff = iRowidOff;
  167340. }else if( iTermOff!=0 ){
  167341. iOff = iTermOff;
  167342. }else{
  167343. iOff = szLeaf;
  167344. }
  167345. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  167346. /* Decode any more doclist data that appears on the page before the
  167347. ** first term. */
  167348. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  167349. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  167350. while( iPgidxOff<n ){
  167351. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  167352. int nByte; /* Bytes of data */
  167353. int iEnd;
  167354. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  167355. iPgidxPrev += nByte;
  167356. iOff = iPgidxPrev;
  167357. if( iPgidxOff<n ){
  167358. fts5GetVarint32(&a[iPgidxOff], nByte);
  167359. iEnd = iPgidxPrev + nByte;
  167360. }else{
  167361. iEnd = szLeaf;
  167362. }
  167363. if( bFirst==0 ){
  167364. iOff += fts5GetVarint32(&a[iOff], nByte);
  167365. term.n = nByte;
  167366. }
  167367. iOff += fts5GetVarint32(&a[iOff], nByte);
  167368. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  167369. iOff += nByte;
  167370. sqlite3Fts5BufferAppendPrintf(
  167371. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  167372. );
  167373. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  167374. }
  167375. fts5BufferFree(&term);
  167376. }
  167377. decode_out:
  167378. sqlite3_free(a);
  167379. if( rc==SQLITE_OK ){
  167380. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  167381. }else{
  167382. sqlite3_result_error_code(pCtx, rc);
  167383. }
  167384. fts5BufferFree(&s);
  167385. }
  167386. /*
  167387. ** The implementation of user-defined scalar function fts5_rowid().
  167388. */
  167389. static void fts5RowidFunction(
  167390. sqlite3_context *pCtx, /* Function call context */
  167391. int nArg, /* Number of args (always 2) */
  167392. sqlite3_value **apVal /* Function arguments */
  167393. ){
  167394. const char *zArg;
  167395. if( nArg==0 ){
  167396. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  167397. }else{
  167398. zArg = (const char*)sqlite3_value_text(apVal[0]);
  167399. if( 0==sqlite3_stricmp(zArg, "segment") ){
  167400. i64 iRowid;
  167401. int segid, pgno;
  167402. if( nArg!=3 ){
  167403. sqlite3_result_error(pCtx,
  167404. "should be: fts5_rowid('segment', segid, pgno))", -1
  167405. );
  167406. }else{
  167407. segid = sqlite3_value_int(apVal[1]);
  167408. pgno = sqlite3_value_int(apVal[2]);
  167409. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  167410. sqlite3_result_int64(pCtx, iRowid);
  167411. }
  167412. }else{
  167413. sqlite3_result_error(pCtx,
  167414. "first arg to fts5_rowid() must be 'segment'" , -1
  167415. );
  167416. }
  167417. }
  167418. }
  167419. /*
  167420. ** This is called as part of registering the FTS5 module with database
  167421. ** connection db. It registers several user-defined scalar functions useful
  167422. ** with FTS5.
  167423. **
  167424. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  167425. ** SQLite error code is returned instead.
  167426. */
  167427. static int sqlite3Fts5IndexInit(sqlite3 *db){
  167428. int rc = sqlite3_create_function(
  167429. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  167430. );
  167431. if( rc==SQLITE_OK ){
  167432. rc = sqlite3_create_function(
  167433. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  167434. );
  167435. }
  167436. return rc;
  167437. }
  167438. /*
  167439. ** 2014 Jun 09
  167440. **
  167441. ** The author disclaims copyright to this source code. In place of
  167442. ** a legal notice, here is a blessing:
  167443. **
  167444. ** May you do good and not evil.
  167445. ** May you find forgiveness for yourself and forgive others.
  167446. ** May you share freely, never taking more than you give.
  167447. **
  167448. ******************************************************************************
  167449. **
  167450. ** This is an SQLite module implementing full-text search.
  167451. */
  167452. /* #include "fts5Int.h" */
  167453. /*
  167454. ** This variable is set to false when running tests for which the on disk
  167455. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  167456. ** assert() conditions in the fts5 code are activated - conditions that are
  167457. ** only true if it is guaranteed that the fts5 database is not corrupt.
  167458. */
  167459. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  167460. typedef struct Fts5Auxdata Fts5Auxdata;
  167461. typedef struct Fts5Auxiliary Fts5Auxiliary;
  167462. typedef struct Fts5Cursor Fts5Cursor;
  167463. typedef struct Fts5Sorter Fts5Sorter;
  167464. typedef struct Fts5Table Fts5Table;
  167465. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  167466. /*
  167467. ** NOTES ON TRANSACTIONS:
  167468. **
  167469. ** SQLite invokes the following virtual table methods as transactions are
  167470. ** opened and closed by the user:
  167471. **
  167472. ** xBegin(): Start of a new transaction.
  167473. ** xSync(): Initial part of two-phase commit.
  167474. ** xCommit(): Final part of two-phase commit.
  167475. ** xRollback(): Rollback the transaction.
  167476. **
  167477. ** Anything that is required as part of a commit that may fail is performed
  167478. ** in the xSync() callback. Current versions of SQLite ignore any errors
  167479. ** returned by xCommit().
  167480. **
  167481. ** And as sub-transactions are opened/closed:
  167482. **
  167483. ** xSavepoint(int S): Open savepoint S.
  167484. ** xRelease(int S): Commit and close savepoint S.
  167485. ** xRollbackTo(int S): Rollback to start of savepoint S.
  167486. **
  167487. ** During a write-transaction the fts5_index.c module may cache some data
  167488. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  167489. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  167490. ** is called.
  167491. **
  167492. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  167493. ** structure is used to record the current transaction state. This information
  167494. ** is not required, but it is used in the assert() statements executed by
  167495. ** function fts5CheckTransactionState() (see below).
  167496. */
  167497. struct Fts5TransactionState {
  167498. int eState; /* 0==closed, 1==open, 2==synced */
  167499. int iSavepoint; /* Number of open savepoints (0 -> none) */
  167500. };
  167501. /*
  167502. ** A single object of this type is allocated when the FTS5 module is
  167503. ** registered with a database handle. It is used to store pointers to
  167504. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  167505. */
  167506. struct Fts5Global {
  167507. fts5_api api; /* User visible part of object (see fts5.h) */
  167508. sqlite3 *db; /* Associated database connection */
  167509. i64 iNextId; /* Used to allocate unique cursor ids */
  167510. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  167511. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  167512. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  167513. Fts5Cursor *pCsr; /* First in list of all open cursors */
  167514. };
  167515. /*
  167516. ** Each auxiliary function registered with the FTS5 module is represented
  167517. ** by an object of the following type. All such objects are stored as part
  167518. ** of the Fts5Global.pAux list.
  167519. */
  167520. struct Fts5Auxiliary {
  167521. Fts5Global *pGlobal; /* Global context for this function */
  167522. char *zFunc; /* Function name (nul-terminated) */
  167523. void *pUserData; /* User-data pointer */
  167524. fts5_extension_function xFunc; /* Callback function */
  167525. void (*xDestroy)(void*); /* Destructor function */
  167526. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  167527. };
  167528. /*
  167529. ** Each tokenizer module registered with the FTS5 module is represented
  167530. ** by an object of the following type. All such objects are stored as part
  167531. ** of the Fts5Global.pTok list.
  167532. */
  167533. struct Fts5TokenizerModule {
  167534. char *zName; /* Name of tokenizer */
  167535. void *pUserData; /* User pointer passed to xCreate() */
  167536. fts5_tokenizer x; /* Tokenizer functions */
  167537. void (*xDestroy)(void*); /* Destructor function */
  167538. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  167539. };
  167540. /*
  167541. ** Virtual-table object.
  167542. */
  167543. struct Fts5Table {
  167544. sqlite3_vtab base; /* Base class used by SQLite core */
  167545. Fts5Config *pConfig; /* Virtual table configuration */
  167546. Fts5Index *pIndex; /* Full-text index */
  167547. Fts5Storage *pStorage; /* Document store */
  167548. Fts5Global *pGlobal; /* Global (connection wide) data */
  167549. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  167550. #ifdef SQLITE_DEBUG
  167551. struct Fts5TransactionState ts;
  167552. #endif
  167553. };
  167554. struct Fts5MatchPhrase {
  167555. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  167556. int nTerm; /* Size of phrase in terms */
  167557. };
  167558. /*
  167559. ** pStmt:
  167560. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  167561. **
  167562. ** aIdx[]:
  167563. ** There is one entry in the aIdx[] array for each phrase in the query,
  167564. ** the value of which is the offset within aPoslist[] following the last
  167565. ** byte of the position list for the corresponding phrase.
  167566. */
  167567. struct Fts5Sorter {
  167568. sqlite3_stmt *pStmt;
  167569. i64 iRowid; /* Current rowid */
  167570. const u8 *aPoslist; /* Position lists for current row */
  167571. int nIdx; /* Number of entries in aIdx[] */
  167572. int aIdx[1]; /* Offsets into aPoslist for current row */
  167573. };
  167574. /*
  167575. ** Virtual-table cursor object.
  167576. **
  167577. ** iSpecial:
  167578. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  167579. ** then this variable contains the result of the query.
  167580. **
  167581. ** iFirstRowid, iLastRowid:
  167582. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  167583. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  167584. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  167585. ** WHERE clause in the user's query might have been:
  167586. **
  167587. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  167588. **
  167589. ** If the cursor iterates in descending order of rowid, iFirstRowid
  167590. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  167591. ** the lower.
  167592. */
  167593. struct Fts5Cursor {
  167594. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  167595. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  167596. int *aColumnSize; /* Values for xColumnSize() */
  167597. i64 iCsrId; /* Cursor id */
  167598. /* Zero from this point onwards on cursor reset */
  167599. int ePlan; /* FTS5_PLAN_XXX value */
  167600. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  167601. i64 iFirstRowid; /* Return no rowids earlier than this */
  167602. i64 iLastRowid; /* Return no rowids later than this */
  167603. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  167604. Fts5Expr *pExpr; /* Expression for MATCH queries */
  167605. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  167606. int csrflags; /* Mask of cursor flags (see below) */
  167607. i64 iSpecial; /* Result of special query */
  167608. /* "rank" function. Populated on demand from vtab.xColumn(). */
  167609. char *zRank; /* Custom rank function */
  167610. char *zRankArgs; /* Custom rank function args */
  167611. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  167612. int nRankArg; /* Number of trailing arguments for rank() */
  167613. sqlite3_value **apRankArg; /* Array of trailing arguments */
  167614. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  167615. /* Auxiliary data storage */
  167616. Fts5Auxiliary *pAux; /* Currently executing extension function */
  167617. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  167618. /* Cache used by auxiliary functions xInst() and xInstCount() */
  167619. Fts5PoslistReader *aInstIter; /* One for each phrase */
  167620. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  167621. int nInstCount; /* Number of phrase instances */
  167622. int *aInst; /* 3 integers per phrase instance */
  167623. };
  167624. /*
  167625. ** Bits that make up the "idxNum" parameter passed indirectly by
  167626. ** xBestIndex() to xFilter().
  167627. */
  167628. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  167629. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  167630. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  167631. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  167632. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  167633. #define FTS5_BI_ORDER_RANK 0x0020
  167634. #define FTS5_BI_ORDER_ROWID 0x0040
  167635. #define FTS5_BI_ORDER_DESC 0x0080
  167636. /*
  167637. ** Values for Fts5Cursor.csrflags
  167638. */
  167639. #define FTS5CSR_REQUIRE_CONTENT 0x01
  167640. #define FTS5CSR_REQUIRE_DOCSIZE 0x02
  167641. #define FTS5CSR_REQUIRE_INST 0x04
  167642. #define FTS5CSR_EOF 0x08
  167643. #define FTS5CSR_FREE_ZRANK 0x10
  167644. #define FTS5CSR_REQUIRE_RESEEK 0x20
  167645. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  167646. #define BitFlagTest(x,y) (((x) & (y))!=0)
  167647. /*
  167648. ** Macros to Set(), Clear() and Test() cursor flags.
  167649. */
  167650. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  167651. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  167652. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  167653. struct Fts5Auxdata {
  167654. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  167655. void *pPtr; /* Pointer value */
  167656. void(*xDelete)(void*); /* Destructor */
  167657. Fts5Auxdata *pNext; /* Next object in linked list */
  167658. };
  167659. #ifdef SQLITE_DEBUG
  167660. #define FTS5_BEGIN 1
  167661. #define FTS5_SYNC 2
  167662. #define FTS5_COMMIT 3
  167663. #define FTS5_ROLLBACK 4
  167664. #define FTS5_SAVEPOINT 5
  167665. #define FTS5_RELEASE 6
  167666. #define FTS5_ROLLBACKTO 7
  167667. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  167668. switch( op ){
  167669. case FTS5_BEGIN:
  167670. assert( p->ts.eState==0 );
  167671. p->ts.eState = 1;
  167672. p->ts.iSavepoint = -1;
  167673. break;
  167674. case FTS5_SYNC:
  167675. assert( p->ts.eState==1 );
  167676. p->ts.eState = 2;
  167677. break;
  167678. case FTS5_COMMIT:
  167679. assert( p->ts.eState==2 );
  167680. p->ts.eState = 0;
  167681. break;
  167682. case FTS5_ROLLBACK:
  167683. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  167684. p->ts.eState = 0;
  167685. break;
  167686. case FTS5_SAVEPOINT:
  167687. assert( p->ts.eState==1 );
  167688. assert( iSavepoint>=0 );
  167689. assert( iSavepoint>p->ts.iSavepoint );
  167690. p->ts.iSavepoint = iSavepoint;
  167691. break;
  167692. case FTS5_RELEASE:
  167693. assert( p->ts.eState==1 );
  167694. assert( iSavepoint>=0 );
  167695. assert( iSavepoint<=p->ts.iSavepoint );
  167696. p->ts.iSavepoint = iSavepoint-1;
  167697. break;
  167698. case FTS5_ROLLBACKTO:
  167699. assert( p->ts.eState==1 );
  167700. assert( iSavepoint>=0 );
  167701. assert( iSavepoint<=p->ts.iSavepoint );
  167702. p->ts.iSavepoint = iSavepoint;
  167703. break;
  167704. }
  167705. }
  167706. #else
  167707. # define fts5CheckTransactionState(x,y,z)
  167708. #endif
  167709. /*
  167710. ** Return true if pTab is a contentless table.
  167711. */
  167712. static int fts5IsContentless(Fts5Table *pTab){
  167713. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  167714. }
  167715. /*
  167716. ** Delete a virtual table handle allocated by fts5InitVtab().
  167717. */
  167718. static void fts5FreeVtab(Fts5Table *pTab){
  167719. if( pTab ){
  167720. sqlite3Fts5IndexClose(pTab->pIndex);
  167721. sqlite3Fts5StorageClose(pTab->pStorage);
  167722. sqlite3Fts5ConfigFree(pTab->pConfig);
  167723. sqlite3_free(pTab);
  167724. }
  167725. }
  167726. /*
  167727. ** The xDisconnect() virtual table method.
  167728. */
  167729. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  167730. fts5FreeVtab((Fts5Table*)pVtab);
  167731. return SQLITE_OK;
  167732. }
  167733. /*
  167734. ** The xDestroy() virtual table method.
  167735. */
  167736. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  167737. Fts5Table *pTab = (Fts5Table*)pVtab;
  167738. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  167739. if( rc==SQLITE_OK ){
  167740. fts5FreeVtab((Fts5Table*)pVtab);
  167741. }
  167742. return rc;
  167743. }
  167744. /*
  167745. ** This function is the implementation of both the xConnect and xCreate
  167746. ** methods of the FTS3 virtual table.
  167747. **
  167748. ** The argv[] array contains the following:
  167749. **
  167750. ** argv[0] -> module name ("fts5")
  167751. ** argv[1] -> database name
  167752. ** argv[2] -> table name
  167753. ** argv[...] -> "column name" and other module argument fields.
  167754. */
  167755. static int fts5InitVtab(
  167756. int bCreate, /* True for xCreate, false for xConnect */
  167757. sqlite3 *db, /* The SQLite database connection */
  167758. void *pAux, /* Hash table containing tokenizers */
  167759. int argc, /* Number of elements in argv array */
  167760. const char * const *argv, /* xCreate/xConnect argument array */
  167761. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  167762. char **pzErr /* Write any error message here */
  167763. ){
  167764. Fts5Global *pGlobal = (Fts5Global*)pAux;
  167765. const char **azConfig = (const char**)argv;
  167766. int rc = SQLITE_OK; /* Return code */
  167767. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  167768. Fts5Table *pTab = 0; /* New virtual table object */
  167769. /* Allocate the new vtab object and parse the configuration */
  167770. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  167771. if( rc==SQLITE_OK ){
  167772. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  167773. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  167774. }
  167775. if( rc==SQLITE_OK ){
  167776. pTab->pConfig = pConfig;
  167777. pTab->pGlobal = pGlobal;
  167778. }
  167779. /* Open the index sub-system */
  167780. if( rc==SQLITE_OK ){
  167781. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  167782. }
  167783. /* Open the storage sub-system */
  167784. if( rc==SQLITE_OK ){
  167785. rc = sqlite3Fts5StorageOpen(
  167786. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  167787. );
  167788. }
  167789. /* Call sqlite3_declare_vtab() */
  167790. if( rc==SQLITE_OK ){
  167791. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  167792. }
  167793. /* Load the initial configuration */
  167794. if( rc==SQLITE_OK ){
  167795. assert( pConfig->pzErrmsg==0 );
  167796. pConfig->pzErrmsg = pzErr;
  167797. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  167798. sqlite3Fts5IndexRollback(pTab->pIndex);
  167799. pConfig->pzErrmsg = 0;
  167800. }
  167801. if( rc!=SQLITE_OK ){
  167802. fts5FreeVtab(pTab);
  167803. pTab = 0;
  167804. }else if( bCreate ){
  167805. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  167806. }
  167807. *ppVTab = (sqlite3_vtab*)pTab;
  167808. return rc;
  167809. }
  167810. /*
  167811. ** The xConnect() and xCreate() methods for the virtual table. All the
  167812. ** work is done in function fts5InitVtab().
  167813. */
  167814. static int fts5ConnectMethod(
  167815. sqlite3 *db, /* Database connection */
  167816. void *pAux, /* Pointer to tokenizer hash table */
  167817. int argc, /* Number of elements in argv array */
  167818. const char * const *argv, /* xCreate/xConnect argument array */
  167819. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  167820. char **pzErr /* OUT: sqlite3_malloc'd error message */
  167821. ){
  167822. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  167823. }
  167824. static int fts5CreateMethod(
  167825. sqlite3 *db, /* Database connection */
  167826. void *pAux, /* Pointer to tokenizer hash table */
  167827. int argc, /* Number of elements in argv array */
  167828. const char * const *argv, /* xCreate/xConnect argument array */
  167829. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  167830. char **pzErr /* OUT: sqlite3_malloc'd error message */
  167831. ){
  167832. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  167833. }
  167834. /*
  167835. ** The different query plans.
  167836. */
  167837. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  167838. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  167839. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  167840. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  167841. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  167842. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  167843. /*
  167844. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  167845. ** extension is currently being used by a version of SQLite too old to
  167846. ** support index-info flags. In that case this function is a no-op.
  167847. */
  167848. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  167849. #if SQLITE_VERSION_NUMBER>=3008012
  167850. #ifndef SQLITE_CORE
  167851. if( sqlite3_libversion_number()>=3008012 )
  167852. #endif
  167853. {
  167854. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  167855. }
  167856. #endif
  167857. }
  167858. /*
  167859. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  167860. ** WHERE constraint, it searches for the following:
  167861. **
  167862. ** 1. A MATCH constraint against the special column.
  167863. ** 2. A MATCH constraint against the "rank" column.
  167864. ** 3. An == constraint against the rowid column.
  167865. ** 4. A < or <= constraint against the rowid column.
  167866. ** 5. A > or >= constraint against the rowid column.
  167867. **
  167868. ** Within the ORDER BY, either:
  167869. **
  167870. ** 5. ORDER BY rank [ASC|DESC]
  167871. ** 6. ORDER BY rowid [ASC|DESC]
  167872. **
  167873. ** Costs are assigned as follows:
  167874. **
  167875. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  167876. ** cost is unconditionally set to 1e50 (a really big number).
  167877. **
  167878. ** a) If a MATCH operator is present, the cost depends on the other
  167879. ** constraints also present. As follows:
  167880. **
  167881. ** * No other constraints: cost=1000.0
  167882. ** * One rowid range constraint: cost=750.0
  167883. ** * Both rowid range constraints: cost=500.0
  167884. ** * An == rowid constraint: cost=100.0
  167885. **
  167886. ** b) Otherwise, if there is no MATCH:
  167887. **
  167888. ** * No other constraints: cost=1000000.0
  167889. ** * One rowid range constraint: cost=750000.0
  167890. ** * Both rowid range constraints: cost=250000.0
  167891. ** * An == rowid constraint: cost=10.0
  167892. **
  167893. ** Costs are not modified by the ORDER BY clause.
  167894. */
  167895. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  167896. Fts5Table *pTab = (Fts5Table*)pVTab;
  167897. Fts5Config *pConfig = pTab->pConfig;
  167898. int idxFlags = 0; /* Parameter passed through to xFilter() */
  167899. int bHasMatch;
  167900. int iNext;
  167901. int i;
  167902. struct Constraint {
  167903. int op; /* Mask against sqlite3_index_constraint.op */
  167904. int fts5op; /* FTS5 mask for idxFlags */
  167905. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  167906. int omit; /* True to omit this if found */
  167907. int iConsIndex; /* Index in pInfo->aConstraint[] */
  167908. } aConstraint[] = {
  167909. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  167910. FTS5_BI_MATCH, 1, 1, -1},
  167911. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  167912. FTS5_BI_RANK, 2, 1, -1},
  167913. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  167914. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  167915. FTS5_BI_ROWID_LE, 0, 0, -1},
  167916. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  167917. FTS5_BI_ROWID_GE, 0, 0, -1},
  167918. };
  167919. int aColMap[3];
  167920. aColMap[0] = -1;
  167921. aColMap[1] = pConfig->nCol;
  167922. aColMap[2] = pConfig->nCol+1;
  167923. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  167924. for(i=0; i<pInfo->nConstraint; i++){
  167925. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  167926. int j;
  167927. for(j=0; j<(int)ArraySize(aConstraint); j++){
  167928. struct Constraint *pC = &aConstraint[j];
  167929. if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
  167930. if( p->usable ){
  167931. pC->iConsIndex = i;
  167932. idxFlags |= pC->fts5op;
  167933. }else if( j==0 ){
  167934. /* As there exists an unusable MATCH constraint this is an
  167935. ** unusable plan. Set a prohibitively high cost. */
  167936. pInfo->estimatedCost = 1e50;
  167937. return SQLITE_OK;
  167938. }
  167939. }
  167940. }
  167941. }
  167942. /* Set idxFlags flags for the ORDER BY clause */
  167943. if( pInfo->nOrderBy==1 ){
  167944. int iSort = pInfo->aOrderBy[0].iColumn;
  167945. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  167946. idxFlags |= FTS5_BI_ORDER_RANK;
  167947. }else if( iSort==-1 ){
  167948. idxFlags |= FTS5_BI_ORDER_ROWID;
  167949. }
  167950. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  167951. pInfo->orderByConsumed = 1;
  167952. if( pInfo->aOrderBy[0].desc ){
  167953. idxFlags |= FTS5_BI_ORDER_DESC;
  167954. }
  167955. }
  167956. }
  167957. /* Calculate the estimated cost based on the flags set in idxFlags. */
  167958. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  167959. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  167960. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  167961. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  167962. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  167963. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  167964. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  167965. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  167966. }else{
  167967. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  167968. }
  167969. /* Assign argvIndex values to each constraint in use. */
  167970. iNext = 1;
  167971. for(i=0; i<(int)ArraySize(aConstraint); i++){
  167972. struct Constraint *pC = &aConstraint[i];
  167973. if( pC->iConsIndex>=0 ){
  167974. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  167975. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  167976. }
  167977. }
  167978. pInfo->idxNum = idxFlags;
  167979. return SQLITE_OK;
  167980. }
  167981. /*
  167982. ** Implementation of xOpen method.
  167983. */
  167984. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  167985. Fts5Table *pTab = (Fts5Table*)pVTab;
  167986. Fts5Config *pConfig = pTab->pConfig;
  167987. Fts5Cursor *pCsr; /* New cursor object */
  167988. int nByte; /* Bytes of space to allocate */
  167989. int rc = SQLITE_OK; /* Return code */
  167990. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  167991. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  167992. if( pCsr ){
  167993. Fts5Global *pGlobal = pTab->pGlobal;
  167994. memset(pCsr, 0, nByte);
  167995. pCsr->aColumnSize = (int*)&pCsr[1];
  167996. pCsr->pNext = pGlobal->pCsr;
  167997. pGlobal->pCsr = pCsr;
  167998. pCsr->iCsrId = ++pGlobal->iNextId;
  167999. }else{
  168000. rc = SQLITE_NOMEM;
  168001. }
  168002. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  168003. return rc;
  168004. }
  168005. static int fts5StmtType(Fts5Cursor *pCsr){
  168006. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  168007. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  168008. }
  168009. return FTS5_STMT_LOOKUP;
  168010. }
  168011. /*
  168012. ** This function is called after the cursor passed as the only argument
  168013. ** is moved to point at a different row. It clears all cached data
  168014. ** specific to the previous row stored by the cursor object.
  168015. */
  168016. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  168017. CsrFlagSet(pCsr,
  168018. FTS5CSR_REQUIRE_CONTENT
  168019. | FTS5CSR_REQUIRE_DOCSIZE
  168020. | FTS5CSR_REQUIRE_INST
  168021. );
  168022. }
  168023. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  168024. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  168025. Fts5Auxdata *pData;
  168026. Fts5Auxdata *pNext;
  168027. sqlite3_free(pCsr->aInstIter);
  168028. sqlite3_free(pCsr->aInst);
  168029. if( pCsr->pStmt ){
  168030. int eStmt = fts5StmtType(pCsr);
  168031. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  168032. }
  168033. if( pCsr->pSorter ){
  168034. Fts5Sorter *pSorter = pCsr->pSorter;
  168035. sqlite3_finalize(pSorter->pStmt);
  168036. sqlite3_free(pSorter);
  168037. }
  168038. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  168039. sqlite3Fts5ExprFree(pCsr->pExpr);
  168040. }
  168041. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  168042. pNext = pData->pNext;
  168043. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  168044. sqlite3_free(pData);
  168045. }
  168046. sqlite3_finalize(pCsr->pRankArgStmt);
  168047. sqlite3_free(pCsr->apRankArg);
  168048. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  168049. sqlite3_free(pCsr->zRank);
  168050. sqlite3_free(pCsr->zRankArgs);
  168051. }
  168052. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  168053. }
  168054. /*
  168055. ** Close the cursor. For additional information see the documentation
  168056. ** on the xClose method of the virtual table interface.
  168057. */
  168058. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  168059. if( pCursor ){
  168060. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  168061. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  168062. Fts5Cursor **pp;
  168063. fts5FreeCursorComponents(pCsr);
  168064. /* Remove the cursor from the Fts5Global.pCsr list */
  168065. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  168066. *pp = pCsr->pNext;
  168067. sqlite3_free(pCsr);
  168068. }
  168069. return SQLITE_OK;
  168070. }
  168071. static int fts5SorterNext(Fts5Cursor *pCsr){
  168072. Fts5Sorter *pSorter = pCsr->pSorter;
  168073. int rc;
  168074. rc = sqlite3_step(pSorter->pStmt);
  168075. if( rc==SQLITE_DONE ){
  168076. rc = SQLITE_OK;
  168077. CsrFlagSet(pCsr, FTS5CSR_EOF);
  168078. }else if( rc==SQLITE_ROW ){
  168079. const u8 *a;
  168080. const u8 *aBlob;
  168081. int nBlob;
  168082. int i;
  168083. int iOff = 0;
  168084. rc = SQLITE_OK;
  168085. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  168086. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  168087. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  168088. for(i=0; i<(pSorter->nIdx-1); i++){
  168089. int iVal;
  168090. a += fts5GetVarint32(a, iVal);
  168091. iOff += iVal;
  168092. pSorter->aIdx[i] = iOff;
  168093. }
  168094. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  168095. pSorter->aPoslist = a;
  168096. fts5CsrNewrow(pCsr);
  168097. }
  168098. return rc;
  168099. }
  168100. /*
  168101. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  168102. ** open on table pTab.
  168103. */
  168104. static void fts5TripCursors(Fts5Table *pTab){
  168105. Fts5Cursor *pCsr;
  168106. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  168107. if( pCsr->ePlan==FTS5_PLAN_MATCH
  168108. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  168109. ){
  168110. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  168111. }
  168112. }
  168113. }
  168114. /*
  168115. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  168116. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  168117. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  168118. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  168119. **
  168120. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  168121. ** to 1 before returning. Otherwise, leave it unchanged.
  168122. **
  168123. ** Return SQLITE_OK if successful or if no reseek was required, or an
  168124. ** error code if an error occurred.
  168125. */
  168126. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  168127. int rc = SQLITE_OK;
  168128. assert( *pbSkip==0 );
  168129. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  168130. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  168131. int bDesc = pCsr->bDesc;
  168132. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  168133. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  168134. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  168135. *pbSkip = 1;
  168136. }
  168137. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  168138. fts5CsrNewrow(pCsr);
  168139. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  168140. CsrFlagSet(pCsr, FTS5CSR_EOF);
  168141. }
  168142. }
  168143. return rc;
  168144. }
  168145. /*
  168146. ** Advance the cursor to the next row in the table that matches the
  168147. ** search criteria.
  168148. **
  168149. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  168150. ** even if we reach end-of-file. The fts5EofMethod() will be called
  168151. ** subsequently to determine whether or not an EOF was hit.
  168152. */
  168153. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  168154. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  168155. int rc = SQLITE_OK;
  168156. assert( (pCsr->ePlan<3)==
  168157. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  168158. );
  168159. if( pCsr->ePlan<3 ){
  168160. int bSkip = 0;
  168161. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  168162. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  168163. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  168164. CsrFlagSet(pCsr, FTS5CSR_EOF);
  168165. }
  168166. fts5CsrNewrow(pCsr);
  168167. }else{
  168168. switch( pCsr->ePlan ){
  168169. case FTS5_PLAN_SPECIAL: {
  168170. CsrFlagSet(pCsr, FTS5CSR_EOF);
  168171. break;
  168172. }
  168173. case FTS5_PLAN_SORTED_MATCH: {
  168174. rc = fts5SorterNext(pCsr);
  168175. break;
  168176. }
  168177. default:
  168178. rc = sqlite3_step(pCsr->pStmt);
  168179. if( rc!=SQLITE_ROW ){
  168180. CsrFlagSet(pCsr, FTS5CSR_EOF);
  168181. rc = sqlite3_reset(pCsr->pStmt);
  168182. }else{
  168183. rc = SQLITE_OK;
  168184. }
  168185. break;
  168186. }
  168187. }
  168188. return rc;
  168189. }
  168190. static sqlite3_stmt *fts5PrepareStatement(
  168191. int *pRc,
  168192. Fts5Config *pConfig,
  168193. const char *zFmt,
  168194. ...
  168195. ){
  168196. sqlite3_stmt *pRet = 0;
  168197. va_list ap;
  168198. va_start(ap, zFmt);
  168199. if( *pRc==SQLITE_OK ){
  168200. int rc;
  168201. char *zSql = sqlite3_vmprintf(zFmt, ap);
  168202. if( zSql==0 ){
  168203. rc = SQLITE_NOMEM;
  168204. }else{
  168205. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
  168206. if( rc!=SQLITE_OK ){
  168207. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  168208. }
  168209. sqlite3_free(zSql);
  168210. }
  168211. *pRc = rc;
  168212. }
  168213. va_end(ap);
  168214. return pRet;
  168215. }
  168216. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  168217. Fts5Config *pConfig = pTab->pConfig;
  168218. Fts5Sorter *pSorter;
  168219. int nPhrase;
  168220. int nByte;
  168221. int rc = SQLITE_OK;
  168222. const char *zRank = pCsr->zRank;
  168223. const char *zRankArgs = pCsr->zRankArgs;
  168224. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  168225. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  168226. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  168227. if( pSorter==0 ) return SQLITE_NOMEM;
  168228. memset(pSorter, 0, nByte);
  168229. pSorter->nIdx = nPhrase;
  168230. /* TODO: It would be better to have some system for reusing statement
  168231. ** handles here, rather than preparing a new one for each query. But that
  168232. ** is not possible as SQLite reference counts the virtual table objects.
  168233. ** And since the statement required here reads from this very virtual
  168234. ** table, saving it creates a circular reference.
  168235. **
  168236. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  168237. pSorter->pStmt = fts5PrepareStatement(&rc, pConfig,
  168238. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  168239. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  168240. (zRankArgs ? ", " : ""),
  168241. (zRankArgs ? zRankArgs : ""),
  168242. bDesc ? "DESC" : "ASC"
  168243. );
  168244. pCsr->pSorter = pSorter;
  168245. if( rc==SQLITE_OK ){
  168246. assert( pTab->pSortCsr==0 );
  168247. pTab->pSortCsr = pCsr;
  168248. rc = fts5SorterNext(pCsr);
  168249. pTab->pSortCsr = 0;
  168250. }
  168251. if( rc!=SQLITE_OK ){
  168252. sqlite3_finalize(pSorter->pStmt);
  168253. sqlite3_free(pSorter);
  168254. pCsr->pSorter = 0;
  168255. }
  168256. return rc;
  168257. }
  168258. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  168259. int rc;
  168260. Fts5Expr *pExpr = pCsr->pExpr;
  168261. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  168262. if( sqlite3Fts5ExprEof(pExpr) ){
  168263. CsrFlagSet(pCsr, FTS5CSR_EOF);
  168264. }
  168265. fts5CsrNewrow(pCsr);
  168266. return rc;
  168267. }
  168268. /*
  168269. ** Process a "special" query. A special query is identified as one with a
  168270. ** MATCH expression that begins with a '*' character. The remainder of
  168271. ** the text passed to the MATCH operator are used as the special query
  168272. ** parameters.
  168273. */
  168274. static int fts5SpecialMatch(
  168275. Fts5Table *pTab,
  168276. Fts5Cursor *pCsr,
  168277. const char *zQuery
  168278. ){
  168279. int rc = SQLITE_OK; /* Return code */
  168280. const char *z = zQuery; /* Special query text */
  168281. int n; /* Number of bytes in text at z */
  168282. while( z[0]==' ' ) z++;
  168283. for(n=0; z[n] && z[n]!=' '; n++);
  168284. assert( pTab->base.zErrMsg==0 );
  168285. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  168286. if( 0==sqlite3_strnicmp("reads", z, n) ){
  168287. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  168288. }
  168289. else if( 0==sqlite3_strnicmp("id", z, n) ){
  168290. pCsr->iSpecial = pCsr->iCsrId;
  168291. }
  168292. else{
  168293. /* An unrecognized directive. Return an error message. */
  168294. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  168295. rc = SQLITE_ERROR;
  168296. }
  168297. return rc;
  168298. }
  168299. /*
  168300. ** Search for an auxiliary function named zName that can be used with table
  168301. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  168302. ** structure. Otherwise, if no such function exists, return NULL.
  168303. */
  168304. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  168305. Fts5Auxiliary *pAux;
  168306. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  168307. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  168308. }
  168309. /* No function of the specified name was found. Return 0. */
  168310. return 0;
  168311. }
  168312. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  168313. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  168314. Fts5Config *pConfig = pTab->pConfig;
  168315. int rc = SQLITE_OK;
  168316. Fts5Auxiliary *pAux = 0;
  168317. const char *zRank = pCsr->zRank;
  168318. const char *zRankArgs = pCsr->zRankArgs;
  168319. if( zRankArgs ){
  168320. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  168321. if( zSql ){
  168322. sqlite3_stmt *pStmt = 0;
  168323. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
  168324. sqlite3_free(zSql);
  168325. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  168326. if( rc==SQLITE_OK ){
  168327. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  168328. int nByte;
  168329. pCsr->nRankArg = sqlite3_column_count(pStmt);
  168330. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  168331. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  168332. if( rc==SQLITE_OK ){
  168333. int i;
  168334. for(i=0; i<pCsr->nRankArg; i++){
  168335. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  168336. }
  168337. }
  168338. pCsr->pRankArgStmt = pStmt;
  168339. }else{
  168340. rc = sqlite3_finalize(pStmt);
  168341. assert( rc!=SQLITE_OK );
  168342. }
  168343. }
  168344. }
  168345. }
  168346. if( rc==SQLITE_OK ){
  168347. pAux = fts5FindAuxiliary(pTab, zRank);
  168348. if( pAux==0 ){
  168349. assert( pTab->base.zErrMsg==0 );
  168350. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  168351. rc = SQLITE_ERROR;
  168352. }
  168353. }
  168354. pCsr->pRank = pAux;
  168355. return rc;
  168356. }
  168357. static int fts5CursorParseRank(
  168358. Fts5Config *pConfig,
  168359. Fts5Cursor *pCsr,
  168360. sqlite3_value *pRank
  168361. ){
  168362. int rc = SQLITE_OK;
  168363. if( pRank ){
  168364. const char *z = (const char*)sqlite3_value_text(pRank);
  168365. char *zRank = 0;
  168366. char *zRankArgs = 0;
  168367. if( z==0 ){
  168368. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  168369. }else{
  168370. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  168371. }
  168372. if( rc==SQLITE_OK ){
  168373. pCsr->zRank = zRank;
  168374. pCsr->zRankArgs = zRankArgs;
  168375. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  168376. }else if( rc==SQLITE_ERROR ){
  168377. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  168378. "parse error in rank function: %s", z
  168379. );
  168380. }
  168381. }else{
  168382. if( pConfig->zRank ){
  168383. pCsr->zRank = (char*)pConfig->zRank;
  168384. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  168385. }else{
  168386. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  168387. pCsr->zRankArgs = 0;
  168388. }
  168389. }
  168390. return rc;
  168391. }
  168392. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  168393. if( pVal ){
  168394. int eType = sqlite3_value_numeric_type(pVal);
  168395. if( eType==SQLITE_INTEGER ){
  168396. return sqlite3_value_int64(pVal);
  168397. }
  168398. }
  168399. return iDefault;
  168400. }
  168401. /*
  168402. ** This is the xFilter interface for the virtual table. See
  168403. ** the virtual table xFilter method documentation for additional
  168404. ** information.
  168405. **
  168406. ** There are three possible query strategies:
  168407. **
  168408. ** 1. Full-text search using a MATCH operator.
  168409. ** 2. A by-rowid lookup.
  168410. ** 3. A full-table scan.
  168411. */
  168412. static int fts5FilterMethod(
  168413. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  168414. int idxNum, /* Strategy index */
  168415. const char *idxStr, /* Unused */
  168416. int nVal, /* Number of elements in apVal */
  168417. sqlite3_value **apVal /* Arguments for the indexing scheme */
  168418. ){
  168419. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  168420. Fts5Config *pConfig = pTab->pConfig;
  168421. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  168422. int rc = SQLITE_OK; /* Error code */
  168423. int iVal = 0; /* Counter for apVal[] */
  168424. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  168425. int bOrderByRank; /* True if ORDER BY rank */
  168426. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  168427. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  168428. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  168429. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  168430. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  168431. char **pzErrmsg = pConfig->pzErrmsg;
  168432. if( pCsr->ePlan ){
  168433. fts5FreeCursorComponents(pCsr);
  168434. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  168435. }
  168436. assert( pCsr->pStmt==0 );
  168437. assert( pCsr->pExpr==0 );
  168438. assert( pCsr->csrflags==0 );
  168439. assert( pCsr->pRank==0 );
  168440. assert( pCsr->zRank==0 );
  168441. assert( pCsr->zRankArgs==0 );
  168442. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  168443. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  168444. /* Decode the arguments passed through to this function.
  168445. **
  168446. ** Note: The following set of if(...) statements must be in the same
  168447. ** order as the corresponding entries in the struct at the top of
  168448. ** fts5BestIndexMethod(). */
  168449. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  168450. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  168451. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  168452. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  168453. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  168454. assert( iVal==nVal );
  168455. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  168456. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  168457. /* Set the cursor upper and lower rowid limits. Only some strategies
  168458. ** actually use them. This is ok, as the xBestIndex() method leaves the
  168459. ** sqlite3_index_constraint.omit flag clear for range constraints
  168460. ** on the rowid field. */
  168461. if( pRowidEq ){
  168462. pRowidLe = pRowidGe = pRowidEq;
  168463. }
  168464. if( bDesc ){
  168465. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  168466. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  168467. }else{
  168468. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  168469. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  168470. }
  168471. if( pTab->pSortCsr ){
  168472. /* If pSortCsr is non-NULL, then this call is being made as part of
  168473. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  168474. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  168475. ** return results to the user for this query. The current cursor
  168476. ** (pCursor) is used to execute the query issued by function
  168477. ** fts5CursorFirstSorted() above. */
  168478. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  168479. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  168480. assert( pCsr->iLastRowid==LARGEST_INT64 );
  168481. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  168482. pCsr->ePlan = FTS5_PLAN_SOURCE;
  168483. pCsr->pExpr = pTab->pSortCsr->pExpr;
  168484. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  168485. }else if( pMatch ){
  168486. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  168487. if( zExpr==0 ) zExpr = "";
  168488. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  168489. if( rc==SQLITE_OK ){
  168490. if( zExpr[0]=='*' ){
  168491. /* The user has issued a query of the form "MATCH '*...'". This
  168492. ** indicates that the MATCH expression is not a full text query,
  168493. ** but a request for an internal parameter. */
  168494. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  168495. }else{
  168496. char **pzErr = &pTab->base.zErrMsg;
  168497. rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
  168498. if( rc==SQLITE_OK ){
  168499. if( bOrderByRank ){
  168500. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  168501. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  168502. }else{
  168503. pCsr->ePlan = FTS5_PLAN_MATCH;
  168504. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  168505. }
  168506. }
  168507. }
  168508. }
  168509. }else if( pConfig->zContent==0 ){
  168510. *pConfig->pzErrmsg = sqlite3_mprintf(
  168511. "%s: table does not support scanning", pConfig->zName
  168512. );
  168513. rc = SQLITE_ERROR;
  168514. }else{
  168515. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  168516. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  168517. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  168518. rc = sqlite3Fts5StorageStmt(
  168519. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  168520. );
  168521. if( rc==SQLITE_OK ){
  168522. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  168523. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  168524. }else{
  168525. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  168526. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  168527. }
  168528. rc = fts5NextMethod(pCursor);
  168529. }
  168530. }
  168531. pConfig->pzErrmsg = pzErrmsg;
  168532. return rc;
  168533. }
  168534. /*
  168535. ** This is the xEof method of the virtual table. SQLite calls this
  168536. ** routine to find out if it has reached the end of a result set.
  168537. */
  168538. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  168539. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  168540. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  168541. }
  168542. /*
  168543. ** Return the rowid that the cursor currently points to.
  168544. */
  168545. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  168546. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  168547. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  168548. || pCsr->ePlan==FTS5_PLAN_SOURCE
  168549. );
  168550. if( pCsr->pSorter ){
  168551. return pCsr->pSorter->iRowid;
  168552. }else{
  168553. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  168554. }
  168555. }
  168556. /*
  168557. ** This is the xRowid method. The SQLite core calls this routine to
  168558. ** retrieve the rowid for the current row of the result set. fts5
  168559. ** exposes %_content.rowid as the rowid for the virtual table. The
  168560. ** rowid should be written to *pRowid.
  168561. */
  168562. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  168563. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  168564. int ePlan = pCsr->ePlan;
  168565. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  168566. switch( ePlan ){
  168567. case FTS5_PLAN_SPECIAL:
  168568. *pRowid = 0;
  168569. break;
  168570. case FTS5_PLAN_SOURCE:
  168571. case FTS5_PLAN_MATCH:
  168572. case FTS5_PLAN_SORTED_MATCH:
  168573. *pRowid = fts5CursorRowid(pCsr);
  168574. break;
  168575. default:
  168576. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  168577. break;
  168578. }
  168579. return SQLITE_OK;
  168580. }
  168581. /*
  168582. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  168583. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  168584. **
  168585. ** If argument bErrormsg is true and an error occurs, an error message may
  168586. ** be left in sqlite3_vtab.zErrMsg.
  168587. */
  168588. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  168589. int rc = SQLITE_OK;
  168590. /* If the cursor does not yet have a statement handle, obtain one now. */
  168591. if( pCsr->pStmt==0 ){
  168592. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  168593. int eStmt = fts5StmtType(pCsr);
  168594. rc = sqlite3Fts5StorageStmt(
  168595. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  168596. );
  168597. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  168598. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  168599. }
  168600. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  168601. assert( pCsr->pExpr );
  168602. sqlite3_reset(pCsr->pStmt);
  168603. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  168604. rc = sqlite3_step(pCsr->pStmt);
  168605. if( rc==SQLITE_ROW ){
  168606. rc = SQLITE_OK;
  168607. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  168608. }else{
  168609. rc = sqlite3_reset(pCsr->pStmt);
  168610. if( rc==SQLITE_OK ){
  168611. rc = FTS5_CORRUPT;
  168612. }
  168613. }
  168614. }
  168615. return rc;
  168616. }
  168617. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  168618. va_list ap; /* ... printf arguments */
  168619. va_start(ap, zFormat);
  168620. assert( p->base.zErrMsg==0 );
  168621. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  168622. va_end(ap);
  168623. }
  168624. /*
  168625. ** This function is called to handle an FTS INSERT command. In other words,
  168626. ** an INSERT statement of the form:
  168627. **
  168628. ** INSERT INTO fts(fts) VALUES($pCmd)
  168629. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  168630. **
  168631. ** Argument pVal is the value assigned to column "fts" by the INSERT
  168632. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  168633. ** error code if an error occurs.
  168634. **
  168635. ** The commands implemented by this function are documented in the "Special
  168636. ** INSERT Directives" section of the documentation. It should be updated if
  168637. ** more commands are added to this function.
  168638. */
  168639. static int fts5SpecialInsert(
  168640. Fts5Table *pTab, /* Fts5 table object */
  168641. const char *zCmd, /* Text inserted into table-name column */
  168642. sqlite3_value *pVal /* Value inserted into rank column */
  168643. ){
  168644. Fts5Config *pConfig = pTab->pConfig;
  168645. int rc = SQLITE_OK;
  168646. int bError = 0;
  168647. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  168648. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  168649. fts5SetVtabError(pTab,
  168650. "'delete-all' may only be used with a "
  168651. "contentless or external content fts5 table"
  168652. );
  168653. rc = SQLITE_ERROR;
  168654. }else{
  168655. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  168656. }
  168657. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  168658. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  168659. fts5SetVtabError(pTab,
  168660. "'rebuild' may not be used with a contentless fts5 table"
  168661. );
  168662. rc = SQLITE_ERROR;
  168663. }else{
  168664. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  168665. }
  168666. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  168667. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  168668. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  168669. int nMerge = sqlite3_value_int(pVal);
  168670. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  168671. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  168672. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  168673. #ifdef SQLITE_DEBUG
  168674. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  168675. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  168676. #endif
  168677. }else{
  168678. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  168679. if( rc==SQLITE_OK ){
  168680. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  168681. }
  168682. if( rc==SQLITE_OK ){
  168683. if( bError ){
  168684. rc = SQLITE_ERROR;
  168685. }else{
  168686. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  168687. }
  168688. }
  168689. }
  168690. return rc;
  168691. }
  168692. static int fts5SpecialDelete(
  168693. Fts5Table *pTab,
  168694. sqlite3_value **apVal,
  168695. sqlite3_int64 *piRowid
  168696. ){
  168697. int rc = SQLITE_OK;
  168698. int eType1 = sqlite3_value_type(apVal[1]);
  168699. if( eType1==SQLITE_INTEGER ){
  168700. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  168701. rc = sqlite3Fts5StorageSpecialDelete(pTab->pStorage, iDel, &apVal[2]);
  168702. }
  168703. return rc;
  168704. }
  168705. static void fts5StorageInsert(
  168706. int *pRc,
  168707. Fts5Table *pTab,
  168708. sqlite3_value **apVal,
  168709. i64 *piRowid
  168710. ){
  168711. int rc = *pRc;
  168712. if( rc==SQLITE_OK ){
  168713. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  168714. }
  168715. if( rc==SQLITE_OK ){
  168716. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  168717. }
  168718. *pRc = rc;
  168719. }
  168720. /*
  168721. ** This function is the implementation of the xUpdate callback used by
  168722. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  168723. ** inserted, updated or deleted.
  168724. **
  168725. ** A delete specifies a single argument - the rowid of the row to remove.
  168726. **
  168727. ** Update and insert operations pass:
  168728. **
  168729. ** 1. The "old" rowid, or NULL.
  168730. ** 2. The "new" rowid.
  168731. ** 3. Values for each of the nCol matchable columns.
  168732. ** 4. Values for the two hidden columns (<tablename> and "rank").
  168733. */
  168734. static int fts5UpdateMethod(
  168735. sqlite3_vtab *pVtab, /* Virtual table handle */
  168736. int nArg, /* Size of argument array */
  168737. sqlite3_value **apVal, /* Array of arguments */
  168738. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  168739. ){
  168740. Fts5Table *pTab = (Fts5Table*)pVtab;
  168741. Fts5Config *pConfig = pTab->pConfig;
  168742. int eType0; /* value_type() of apVal[0] */
  168743. int rc = SQLITE_OK; /* Return code */
  168744. /* A transaction must be open when this is called. */
  168745. assert( pTab->ts.eState==1 );
  168746. assert( pVtab->zErrMsg==0 );
  168747. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  168748. assert( nArg==1
  168749. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  168750. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  168751. );
  168752. assert( pTab->pConfig->pzErrmsg==0 );
  168753. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  168754. /* Put any active cursors into REQUIRE_SEEK state. */
  168755. fts5TripCursors(pTab);
  168756. eType0 = sqlite3_value_type(apVal[0]);
  168757. if( eType0==SQLITE_NULL
  168758. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  168759. ){
  168760. /* A "special" INSERT op. These are handled separately. */
  168761. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  168762. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  168763. && 0==sqlite3_stricmp("delete", z)
  168764. ){
  168765. rc = fts5SpecialDelete(pTab, apVal, pRowid);
  168766. }else{
  168767. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  168768. }
  168769. }else{
  168770. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  168771. ** any conflict on the rowid value must be detected before any
  168772. ** modifications are made to the database file. There are 4 cases:
  168773. **
  168774. ** 1) DELETE
  168775. ** 2) UPDATE (rowid not modified)
  168776. ** 3) UPDATE (rowid modified)
  168777. ** 4) INSERT
  168778. **
  168779. ** Cases 3 and 4 may violate the rowid constraint.
  168780. */
  168781. int eConflict = SQLITE_ABORT;
  168782. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  168783. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  168784. }
  168785. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  168786. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  168787. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  168788. ** This is not suported. */
  168789. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  168790. pTab->base.zErrMsg = sqlite3_mprintf(
  168791. "cannot %s contentless fts5 table: %s",
  168792. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  168793. );
  168794. rc = SQLITE_ERROR;
  168795. }
  168796. /* Case 1: DELETE */
  168797. else if( nArg==1 ){
  168798. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  168799. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel);
  168800. }
  168801. /* Case 2: INSERT */
  168802. else if( eType0!=SQLITE_INTEGER ){
  168803. /* If this is a REPLACE, first remove the current entry (if any) */
  168804. if( eConflict==SQLITE_REPLACE
  168805. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  168806. ){
  168807. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  168808. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew);
  168809. }
  168810. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  168811. }
  168812. /* Case 2: UPDATE */
  168813. else{
  168814. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  168815. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  168816. if( iOld!=iNew ){
  168817. if( eConflict==SQLITE_REPLACE ){
  168818. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
  168819. if( rc==SQLITE_OK ){
  168820. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew);
  168821. }
  168822. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  168823. }else{
  168824. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  168825. if( rc==SQLITE_OK ){
  168826. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
  168827. }
  168828. if( rc==SQLITE_OK ){
  168829. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  168830. }
  168831. }
  168832. }else{
  168833. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld);
  168834. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  168835. }
  168836. }
  168837. }
  168838. pTab->pConfig->pzErrmsg = 0;
  168839. return rc;
  168840. }
  168841. /*
  168842. ** Implementation of xSync() method.
  168843. */
  168844. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  168845. int rc;
  168846. Fts5Table *pTab = (Fts5Table*)pVtab;
  168847. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  168848. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  168849. fts5TripCursors(pTab);
  168850. rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
  168851. pTab->pConfig->pzErrmsg = 0;
  168852. return rc;
  168853. }
  168854. /*
  168855. ** Implementation of xBegin() method.
  168856. */
  168857. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  168858. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  168859. return SQLITE_OK;
  168860. }
  168861. /*
  168862. ** Implementation of xCommit() method. This is a no-op. The contents of
  168863. ** the pending-terms hash-table have already been flushed into the database
  168864. ** by fts5SyncMethod().
  168865. */
  168866. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  168867. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  168868. return SQLITE_OK;
  168869. }
  168870. /*
  168871. ** Implementation of xRollback(). Discard the contents of the pending-terms
  168872. ** hash-table. Any changes made to the database are reverted by SQLite.
  168873. */
  168874. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  168875. int rc;
  168876. Fts5Table *pTab = (Fts5Table*)pVtab;
  168877. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  168878. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  168879. return rc;
  168880. }
  168881. static void *fts5ApiUserData(Fts5Context *pCtx){
  168882. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  168883. return pCsr->pAux->pUserData;
  168884. }
  168885. static int fts5ApiColumnCount(Fts5Context *pCtx){
  168886. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  168887. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  168888. }
  168889. static int fts5ApiColumnTotalSize(
  168890. Fts5Context *pCtx,
  168891. int iCol,
  168892. sqlite3_int64 *pnToken
  168893. ){
  168894. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  168895. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  168896. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  168897. }
  168898. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  168899. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  168900. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  168901. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  168902. }
  168903. static int fts5ApiTokenize(
  168904. Fts5Context *pCtx,
  168905. const char *pText, int nText,
  168906. void *pUserData,
  168907. int (*xToken)(void*, int, const char*, int, int, int)
  168908. ){
  168909. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  168910. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  168911. return sqlite3Fts5Tokenize(
  168912. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  168913. );
  168914. }
  168915. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  168916. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  168917. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  168918. }
  168919. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  168920. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  168921. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  168922. }
  168923. static int fts5CsrPoslist(Fts5Cursor *pCsr, int iPhrase, const u8 **pa){
  168924. int n;
  168925. if( pCsr->pSorter ){
  168926. Fts5Sorter *pSorter = pCsr->pSorter;
  168927. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  168928. n = pSorter->aIdx[iPhrase] - i1;
  168929. *pa = &pSorter->aPoslist[i1];
  168930. }else{
  168931. n = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  168932. }
  168933. return n;
  168934. }
  168935. /*
  168936. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  168937. ** correctly for the current view. Return SQLITE_OK if successful, or an
  168938. ** SQLite error code otherwise.
  168939. */
  168940. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  168941. int rc = SQLITE_OK;
  168942. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  168943. int nIter; /* Number of iterators/phrases */
  168944. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  168945. if( pCsr->aInstIter==0 ){
  168946. int nByte = sizeof(Fts5PoslistReader) * nIter;
  168947. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  168948. }
  168949. aIter = pCsr->aInstIter;
  168950. if( aIter ){
  168951. int nInst = 0; /* Number instances seen so far */
  168952. int i;
  168953. /* Initialize all iterators */
  168954. for(i=0; i<nIter; i++){
  168955. const u8 *a;
  168956. int n = fts5CsrPoslist(pCsr, i, &a);
  168957. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  168958. }
  168959. while( 1 ){
  168960. int *aInst;
  168961. int iBest = -1;
  168962. for(i=0; i<nIter; i++){
  168963. if( (aIter[i].bEof==0)
  168964. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  168965. ){
  168966. iBest = i;
  168967. }
  168968. }
  168969. if( iBest<0 ) break;
  168970. nInst++;
  168971. if( nInst>=pCsr->nInstAlloc ){
  168972. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  168973. aInst = (int*)sqlite3_realloc(
  168974. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  168975. );
  168976. if( aInst ){
  168977. pCsr->aInst = aInst;
  168978. }else{
  168979. rc = SQLITE_NOMEM;
  168980. break;
  168981. }
  168982. }
  168983. aInst = &pCsr->aInst[3 * (nInst-1)];
  168984. aInst[0] = iBest;
  168985. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  168986. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  168987. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  168988. }
  168989. pCsr->nInstCount = nInst;
  168990. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  168991. }
  168992. return rc;
  168993. }
  168994. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  168995. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  168996. int rc = SQLITE_OK;
  168997. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  168998. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  168999. *pnInst = pCsr->nInstCount;
  169000. }
  169001. return rc;
  169002. }
  169003. static int fts5ApiInst(
  169004. Fts5Context *pCtx,
  169005. int iIdx,
  169006. int *piPhrase,
  169007. int *piCol,
  169008. int *piOff
  169009. ){
  169010. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  169011. int rc = SQLITE_OK;
  169012. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  169013. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  169014. ){
  169015. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  169016. rc = SQLITE_RANGE;
  169017. }else{
  169018. *piPhrase = pCsr->aInst[iIdx*3];
  169019. *piCol = pCsr->aInst[iIdx*3 + 1];
  169020. *piOff = pCsr->aInst[iIdx*3 + 2];
  169021. }
  169022. }
  169023. return rc;
  169024. }
  169025. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  169026. return fts5CursorRowid((Fts5Cursor*)pCtx);
  169027. }
  169028. static int fts5ApiColumnText(
  169029. Fts5Context *pCtx,
  169030. int iCol,
  169031. const char **pz,
  169032. int *pn
  169033. ){
  169034. int rc = SQLITE_OK;
  169035. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  169036. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  169037. *pz = 0;
  169038. *pn = 0;
  169039. }else{
  169040. rc = fts5SeekCursor(pCsr, 0);
  169041. if( rc==SQLITE_OK ){
  169042. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  169043. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  169044. }
  169045. }
  169046. return rc;
  169047. }
  169048. static int fts5ColumnSizeCb(
  169049. void *pContext, /* Pointer to int */
  169050. int tflags,
  169051. const char *pToken, /* Buffer containing token */
  169052. int nToken, /* Size of token in bytes */
  169053. int iStart, /* Start offset of token */
  169054. int iEnd /* End offset of token */
  169055. ){
  169056. int *pCnt = (int*)pContext;
  169057. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  169058. (*pCnt)++;
  169059. }
  169060. return SQLITE_OK;
  169061. }
  169062. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  169063. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  169064. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  169065. Fts5Config *pConfig = pTab->pConfig;
  169066. int rc = SQLITE_OK;
  169067. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  169068. if( pConfig->bColumnsize ){
  169069. i64 iRowid = fts5CursorRowid(pCsr);
  169070. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  169071. }else if( pConfig->zContent==0 ){
  169072. int i;
  169073. for(i=0; i<pConfig->nCol; i++){
  169074. if( pConfig->abUnindexed[i]==0 ){
  169075. pCsr->aColumnSize[i] = -1;
  169076. }
  169077. }
  169078. }else{
  169079. int i;
  169080. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  169081. if( pConfig->abUnindexed[i]==0 ){
  169082. const char *z; int n;
  169083. void *p = (void*)(&pCsr->aColumnSize[i]);
  169084. pCsr->aColumnSize[i] = 0;
  169085. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  169086. if( rc==SQLITE_OK ){
  169087. rc = sqlite3Fts5Tokenize(
  169088. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  169089. );
  169090. }
  169091. }
  169092. }
  169093. }
  169094. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  169095. }
  169096. if( iCol<0 ){
  169097. int i;
  169098. *pnToken = 0;
  169099. for(i=0; i<pConfig->nCol; i++){
  169100. *pnToken += pCsr->aColumnSize[i];
  169101. }
  169102. }else if( iCol<pConfig->nCol ){
  169103. *pnToken = pCsr->aColumnSize[iCol];
  169104. }else{
  169105. *pnToken = 0;
  169106. rc = SQLITE_RANGE;
  169107. }
  169108. return rc;
  169109. }
  169110. /*
  169111. ** Implementation of the xSetAuxdata() method.
  169112. */
  169113. static int fts5ApiSetAuxdata(
  169114. Fts5Context *pCtx, /* Fts5 context */
  169115. void *pPtr, /* Pointer to save as auxdata */
  169116. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  169117. ){
  169118. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  169119. Fts5Auxdata *pData;
  169120. /* Search through the cursors list of Fts5Auxdata objects for one that
  169121. ** corresponds to the currently executing auxiliary function. */
  169122. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  169123. if( pData->pAux==pCsr->pAux ) break;
  169124. }
  169125. if( pData ){
  169126. if( pData->xDelete ){
  169127. pData->xDelete(pData->pPtr);
  169128. }
  169129. }else{
  169130. int rc = SQLITE_OK;
  169131. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  169132. if( pData==0 ){
  169133. if( xDelete ) xDelete(pPtr);
  169134. return rc;
  169135. }
  169136. pData->pAux = pCsr->pAux;
  169137. pData->pNext = pCsr->pAuxdata;
  169138. pCsr->pAuxdata = pData;
  169139. }
  169140. pData->xDelete = xDelete;
  169141. pData->pPtr = pPtr;
  169142. return SQLITE_OK;
  169143. }
  169144. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  169145. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  169146. Fts5Auxdata *pData;
  169147. void *pRet = 0;
  169148. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  169149. if( pData->pAux==pCsr->pAux ) break;
  169150. }
  169151. if( pData ){
  169152. pRet = pData->pPtr;
  169153. if( bClear ){
  169154. pData->pPtr = 0;
  169155. pData->xDelete = 0;
  169156. }
  169157. }
  169158. return pRet;
  169159. }
  169160. static void fts5ApiPhraseNext(
  169161. Fts5Context *pCtx,
  169162. Fts5PhraseIter *pIter,
  169163. int *piCol, int *piOff
  169164. ){
  169165. if( pIter->a>=pIter->b ){
  169166. *piCol = -1;
  169167. *piOff = -1;
  169168. }else{
  169169. int iVal;
  169170. pIter->a += fts5GetVarint32(pIter->a, iVal);
  169171. if( iVal==1 ){
  169172. pIter->a += fts5GetVarint32(pIter->a, iVal);
  169173. *piCol = iVal;
  169174. *piOff = 0;
  169175. pIter->a += fts5GetVarint32(pIter->a, iVal);
  169176. }
  169177. *piOff += (iVal-2);
  169178. }
  169179. }
  169180. static void fts5ApiPhraseFirst(
  169181. Fts5Context *pCtx,
  169182. int iPhrase,
  169183. Fts5PhraseIter *pIter,
  169184. int *piCol, int *piOff
  169185. ){
  169186. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  169187. int n = fts5CsrPoslist(pCsr, iPhrase, &pIter->a);
  169188. pIter->b = &pIter->a[n];
  169189. *piCol = 0;
  169190. *piOff = 0;
  169191. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  169192. }
  169193. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  169194. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  169195. );
  169196. static const Fts5ExtensionApi sFts5Api = {
  169197. 2, /* iVersion */
  169198. fts5ApiUserData,
  169199. fts5ApiColumnCount,
  169200. fts5ApiRowCount,
  169201. fts5ApiColumnTotalSize,
  169202. fts5ApiTokenize,
  169203. fts5ApiPhraseCount,
  169204. fts5ApiPhraseSize,
  169205. fts5ApiInstCount,
  169206. fts5ApiInst,
  169207. fts5ApiRowid,
  169208. fts5ApiColumnText,
  169209. fts5ApiColumnSize,
  169210. fts5ApiQueryPhrase,
  169211. fts5ApiSetAuxdata,
  169212. fts5ApiGetAuxdata,
  169213. fts5ApiPhraseFirst,
  169214. fts5ApiPhraseNext,
  169215. };
  169216. /*
  169217. ** Implementation of API function xQueryPhrase().
  169218. */
  169219. static int fts5ApiQueryPhrase(
  169220. Fts5Context *pCtx,
  169221. int iPhrase,
  169222. void *pUserData,
  169223. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  169224. ){
  169225. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  169226. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  169227. int rc;
  169228. Fts5Cursor *pNew = 0;
  169229. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  169230. if( rc==SQLITE_OK ){
  169231. Fts5Config *pConf = pTab->pConfig;
  169232. pNew->ePlan = FTS5_PLAN_MATCH;
  169233. pNew->iFirstRowid = SMALLEST_INT64;
  169234. pNew->iLastRowid = LARGEST_INT64;
  169235. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  169236. rc = sqlite3Fts5ExprClonePhrase(pConf, pCsr->pExpr, iPhrase, &pNew->pExpr);
  169237. }
  169238. if( rc==SQLITE_OK ){
  169239. for(rc = fts5CursorFirst(pTab, pNew, 0);
  169240. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  169241. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  169242. ){
  169243. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  169244. if( rc!=SQLITE_OK ){
  169245. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  169246. break;
  169247. }
  169248. }
  169249. }
  169250. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  169251. return rc;
  169252. }
  169253. static void fts5ApiInvoke(
  169254. Fts5Auxiliary *pAux,
  169255. Fts5Cursor *pCsr,
  169256. sqlite3_context *context,
  169257. int argc,
  169258. sqlite3_value **argv
  169259. ){
  169260. assert( pCsr->pAux==0 );
  169261. pCsr->pAux = pAux;
  169262. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  169263. pCsr->pAux = 0;
  169264. }
  169265. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  169266. Fts5Cursor *pCsr;
  169267. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  169268. if( pCsr->iCsrId==iCsrId ) break;
  169269. }
  169270. return pCsr;
  169271. }
  169272. static void fts5ApiCallback(
  169273. sqlite3_context *context,
  169274. int argc,
  169275. sqlite3_value **argv
  169276. ){
  169277. Fts5Auxiliary *pAux;
  169278. Fts5Cursor *pCsr;
  169279. i64 iCsrId;
  169280. assert( argc>=1 );
  169281. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  169282. iCsrId = sqlite3_value_int64(argv[0]);
  169283. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  169284. if( pCsr==0 ){
  169285. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  169286. sqlite3_result_error(context, zErr, -1);
  169287. sqlite3_free(zErr);
  169288. }else{
  169289. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  169290. }
  169291. }
  169292. /*
  169293. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  169294. ** object. Or NULL If the cursor id does not exist.
  169295. **
  169296. ** If successful, set *ppConfig to point to the associated config object
  169297. ** before returning.
  169298. */
  169299. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  169300. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  169301. i64 iCsrId, /* Id of cursor to find */
  169302. Fts5Config **ppConfig /* OUT: Configuration object */
  169303. ){
  169304. Fts5Cursor *pCsr;
  169305. Fts5Table *pTab;
  169306. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  169307. pTab = (Fts5Table*)pCsr->base.pVtab;
  169308. *ppConfig = pTab->pConfig;
  169309. return pTab->pIndex;
  169310. }
  169311. /*
  169312. ** Return a "position-list blob" corresponding to the current position of
  169313. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  169314. ** the current position-list for each phrase in the query associated with
  169315. ** cursor pCsr.
  169316. **
  169317. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  169318. ** the number of phrases in the query. Following the varints are the
  169319. ** concatenated position lists for each phrase, in order.
  169320. **
  169321. ** The first varint (if it exists) contains the size of the position list
  169322. ** for phrase 0. The second (same disclaimer) contains the size of position
  169323. ** list 1. And so on. There is no size field for the final position list,
  169324. ** as it can be derived from the total size of the blob.
  169325. */
  169326. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  169327. int i;
  169328. int rc = SQLITE_OK;
  169329. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  169330. Fts5Buffer val;
  169331. memset(&val, 0, sizeof(Fts5Buffer));
  169332. /* Append the varints */
  169333. for(i=0; i<(nPhrase-1); i++){
  169334. const u8 *dummy;
  169335. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  169336. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  169337. }
  169338. /* Append the position lists */
  169339. for(i=0; i<nPhrase; i++){
  169340. const u8 *pPoslist;
  169341. int nPoslist;
  169342. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  169343. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  169344. }
  169345. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  169346. return rc;
  169347. }
  169348. /*
  169349. ** This is the xColumn method, called by SQLite to request a value from
  169350. ** the row that the supplied cursor currently points to.
  169351. */
  169352. static int fts5ColumnMethod(
  169353. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  169354. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  169355. int iCol /* Index of column to read value from */
  169356. ){
  169357. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  169358. Fts5Config *pConfig = pTab->pConfig;
  169359. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  169360. int rc = SQLITE_OK;
  169361. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  169362. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  169363. if( iCol==pConfig->nCol ){
  169364. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  169365. }
  169366. }else
  169367. if( iCol==pConfig->nCol ){
  169368. /* User is requesting the value of the special column with the same name
  169369. ** as the table. Return the cursor integer id number. This value is only
  169370. ** useful in that it may be passed as the first argument to an FTS5
  169371. ** auxiliary function. */
  169372. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  169373. }else if( iCol==pConfig->nCol+1 ){
  169374. /* The value of the "rank" column. */
  169375. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  169376. fts5PoslistBlob(pCtx, pCsr);
  169377. }else if(
  169378. pCsr->ePlan==FTS5_PLAN_MATCH
  169379. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  169380. ){
  169381. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  169382. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  169383. }
  169384. }
  169385. }else if( !fts5IsContentless(pTab) ){
  169386. rc = fts5SeekCursor(pCsr, 1);
  169387. if( rc==SQLITE_OK ){
  169388. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  169389. }
  169390. }
  169391. return rc;
  169392. }
  169393. /*
  169394. ** This routine implements the xFindFunction method for the FTS3
  169395. ** virtual table.
  169396. */
  169397. static int fts5FindFunctionMethod(
  169398. sqlite3_vtab *pVtab, /* Virtual table handle */
  169399. int nArg, /* Number of SQL function arguments */
  169400. const char *zName, /* Name of SQL function */
  169401. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  169402. void **ppArg /* OUT: User data for *pxFunc */
  169403. ){
  169404. Fts5Table *pTab = (Fts5Table*)pVtab;
  169405. Fts5Auxiliary *pAux;
  169406. pAux = fts5FindAuxiliary(pTab, zName);
  169407. if( pAux ){
  169408. *pxFunc = fts5ApiCallback;
  169409. *ppArg = (void*)pAux;
  169410. return 1;
  169411. }
  169412. /* No function of the specified name was found. Return 0. */
  169413. return 0;
  169414. }
  169415. /*
  169416. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  169417. */
  169418. static int fts5RenameMethod(
  169419. sqlite3_vtab *pVtab, /* Virtual table handle */
  169420. const char *zName /* New name of table */
  169421. ){
  169422. Fts5Table *pTab = (Fts5Table*)pVtab;
  169423. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  169424. }
  169425. /*
  169426. ** The xSavepoint() method.
  169427. **
  169428. ** Flush the contents of the pending-terms table to disk.
  169429. */
  169430. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  169431. Fts5Table *pTab = (Fts5Table*)pVtab;
  169432. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  169433. fts5TripCursors(pTab);
  169434. return sqlite3Fts5StorageSync(pTab->pStorage, 0);
  169435. }
  169436. /*
  169437. ** The xRelease() method.
  169438. **
  169439. ** This is a no-op.
  169440. */
  169441. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  169442. Fts5Table *pTab = (Fts5Table*)pVtab;
  169443. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  169444. fts5TripCursors(pTab);
  169445. return sqlite3Fts5StorageSync(pTab->pStorage, 0);
  169446. }
  169447. /*
  169448. ** The xRollbackTo() method.
  169449. **
  169450. ** Discard the contents of the pending terms table.
  169451. */
  169452. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  169453. Fts5Table *pTab = (Fts5Table*)pVtab;
  169454. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  169455. fts5TripCursors(pTab);
  169456. return sqlite3Fts5StorageRollback(pTab->pStorage);
  169457. }
  169458. /*
  169459. ** Register a new auxiliary function with global context pGlobal.
  169460. */
  169461. static int fts5CreateAux(
  169462. fts5_api *pApi, /* Global context (one per db handle) */
  169463. const char *zName, /* Name of new function */
  169464. void *pUserData, /* User data for aux. function */
  169465. fts5_extension_function xFunc, /* Aux. function implementation */
  169466. void(*xDestroy)(void*) /* Destructor for pUserData */
  169467. ){
  169468. Fts5Global *pGlobal = (Fts5Global*)pApi;
  169469. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  169470. if( rc==SQLITE_OK ){
  169471. Fts5Auxiliary *pAux;
  169472. int nName; /* Size of zName in bytes, including \0 */
  169473. int nByte; /* Bytes of space to allocate */
  169474. nName = (int)strlen(zName) + 1;
  169475. nByte = sizeof(Fts5Auxiliary) + nName;
  169476. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  169477. if( pAux ){
  169478. memset(pAux, 0, nByte);
  169479. pAux->zFunc = (char*)&pAux[1];
  169480. memcpy(pAux->zFunc, zName, nName);
  169481. pAux->pGlobal = pGlobal;
  169482. pAux->pUserData = pUserData;
  169483. pAux->xFunc = xFunc;
  169484. pAux->xDestroy = xDestroy;
  169485. pAux->pNext = pGlobal->pAux;
  169486. pGlobal->pAux = pAux;
  169487. }else{
  169488. rc = SQLITE_NOMEM;
  169489. }
  169490. }
  169491. return rc;
  169492. }
  169493. /*
  169494. ** Register a new tokenizer. This is the implementation of the
  169495. ** fts5_api.xCreateTokenizer() method.
  169496. */
  169497. static int fts5CreateTokenizer(
  169498. fts5_api *pApi, /* Global context (one per db handle) */
  169499. const char *zName, /* Name of new function */
  169500. void *pUserData, /* User data for aux. function */
  169501. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  169502. void(*xDestroy)(void*) /* Destructor for pUserData */
  169503. ){
  169504. Fts5Global *pGlobal = (Fts5Global*)pApi;
  169505. Fts5TokenizerModule *pNew;
  169506. int nName; /* Size of zName and its \0 terminator */
  169507. int nByte; /* Bytes of space to allocate */
  169508. int rc = SQLITE_OK;
  169509. nName = (int)strlen(zName) + 1;
  169510. nByte = sizeof(Fts5TokenizerModule) + nName;
  169511. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  169512. if( pNew ){
  169513. memset(pNew, 0, nByte);
  169514. pNew->zName = (char*)&pNew[1];
  169515. memcpy(pNew->zName, zName, nName);
  169516. pNew->pUserData = pUserData;
  169517. pNew->x = *pTokenizer;
  169518. pNew->xDestroy = xDestroy;
  169519. pNew->pNext = pGlobal->pTok;
  169520. pGlobal->pTok = pNew;
  169521. if( pNew->pNext==0 ){
  169522. pGlobal->pDfltTok = pNew;
  169523. }
  169524. }else{
  169525. rc = SQLITE_NOMEM;
  169526. }
  169527. return rc;
  169528. }
  169529. static Fts5TokenizerModule *fts5LocateTokenizer(
  169530. Fts5Global *pGlobal,
  169531. const char *zName
  169532. ){
  169533. Fts5TokenizerModule *pMod = 0;
  169534. if( zName==0 ){
  169535. pMod = pGlobal->pDfltTok;
  169536. }else{
  169537. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  169538. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  169539. }
  169540. }
  169541. return pMod;
  169542. }
  169543. /*
  169544. ** Find a tokenizer. This is the implementation of the
  169545. ** fts5_api.xFindTokenizer() method.
  169546. */
  169547. static int fts5FindTokenizer(
  169548. fts5_api *pApi, /* Global context (one per db handle) */
  169549. const char *zName, /* Name of new function */
  169550. void **ppUserData,
  169551. fts5_tokenizer *pTokenizer /* Populate this object */
  169552. ){
  169553. int rc = SQLITE_OK;
  169554. Fts5TokenizerModule *pMod;
  169555. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  169556. if( pMod ){
  169557. *pTokenizer = pMod->x;
  169558. *ppUserData = pMod->pUserData;
  169559. }else{
  169560. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  169561. rc = SQLITE_ERROR;
  169562. }
  169563. return rc;
  169564. }
  169565. static int sqlite3Fts5GetTokenizer(
  169566. Fts5Global *pGlobal,
  169567. const char **azArg,
  169568. int nArg,
  169569. Fts5Tokenizer **ppTok,
  169570. fts5_tokenizer **ppTokApi,
  169571. char **pzErr
  169572. ){
  169573. Fts5TokenizerModule *pMod;
  169574. int rc = SQLITE_OK;
  169575. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  169576. if( pMod==0 ){
  169577. assert( nArg>0 );
  169578. rc = SQLITE_ERROR;
  169579. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  169580. }else{
  169581. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  169582. *ppTokApi = &pMod->x;
  169583. if( rc!=SQLITE_OK && pzErr ){
  169584. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  169585. }
  169586. }
  169587. if( rc!=SQLITE_OK ){
  169588. *ppTokApi = 0;
  169589. *ppTok = 0;
  169590. }
  169591. return rc;
  169592. }
  169593. static void fts5ModuleDestroy(void *pCtx){
  169594. Fts5TokenizerModule *pTok, *pNextTok;
  169595. Fts5Auxiliary *pAux, *pNextAux;
  169596. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  169597. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  169598. pNextAux = pAux->pNext;
  169599. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  169600. sqlite3_free(pAux);
  169601. }
  169602. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  169603. pNextTok = pTok->pNext;
  169604. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  169605. sqlite3_free(pTok);
  169606. }
  169607. sqlite3_free(pGlobal);
  169608. }
  169609. static void fts5Fts5Func(
  169610. sqlite3_context *pCtx, /* Function call context */
  169611. int nArg, /* Number of args */
  169612. sqlite3_value **apVal /* Function arguments */
  169613. ){
  169614. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  169615. char buf[8];
  169616. assert( nArg==0 );
  169617. assert( sizeof(buf)>=sizeof(pGlobal) );
  169618. memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
  169619. sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
  169620. }
  169621. /*
  169622. ** Implementation of fts5_source_id() function.
  169623. */
  169624. static void fts5SourceIdFunc(
  169625. sqlite3_context *pCtx, /* Function call context */
  169626. int nArg, /* Number of args */
  169627. sqlite3_value **apVal /* Function arguments */
  169628. ){
  169629. assert( nArg==0 );
  169630. sqlite3_result_text(pCtx, "fts5: 2016-01-13 21:41:56 254419c36766225ca542ae873ed38255e3fb8588", -1, SQLITE_TRANSIENT);
  169631. }
  169632. static int fts5Init(sqlite3 *db){
  169633. static const sqlite3_module fts5Mod = {
  169634. /* iVersion */ 2,
  169635. /* xCreate */ fts5CreateMethod,
  169636. /* xConnect */ fts5ConnectMethod,
  169637. /* xBestIndex */ fts5BestIndexMethod,
  169638. /* xDisconnect */ fts5DisconnectMethod,
  169639. /* xDestroy */ fts5DestroyMethod,
  169640. /* xOpen */ fts5OpenMethod,
  169641. /* xClose */ fts5CloseMethod,
  169642. /* xFilter */ fts5FilterMethod,
  169643. /* xNext */ fts5NextMethod,
  169644. /* xEof */ fts5EofMethod,
  169645. /* xColumn */ fts5ColumnMethod,
  169646. /* xRowid */ fts5RowidMethod,
  169647. /* xUpdate */ fts5UpdateMethod,
  169648. /* xBegin */ fts5BeginMethod,
  169649. /* xSync */ fts5SyncMethod,
  169650. /* xCommit */ fts5CommitMethod,
  169651. /* xRollback */ fts5RollbackMethod,
  169652. /* xFindFunction */ fts5FindFunctionMethod,
  169653. /* xRename */ fts5RenameMethod,
  169654. /* xSavepoint */ fts5SavepointMethod,
  169655. /* xRelease */ fts5ReleaseMethod,
  169656. /* xRollbackTo */ fts5RollbackToMethod,
  169657. };
  169658. int rc;
  169659. Fts5Global *pGlobal = 0;
  169660. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  169661. if( pGlobal==0 ){
  169662. rc = SQLITE_NOMEM;
  169663. }else{
  169664. void *p = (void*)pGlobal;
  169665. memset(pGlobal, 0, sizeof(Fts5Global));
  169666. pGlobal->db = db;
  169667. pGlobal->api.iVersion = 2;
  169668. pGlobal->api.xCreateFunction = fts5CreateAux;
  169669. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  169670. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  169671. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  169672. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  169673. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  169674. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  169675. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  169676. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  169677. if( rc==SQLITE_OK ){
  169678. rc = sqlite3_create_function(
  169679. db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  169680. );
  169681. }
  169682. if( rc==SQLITE_OK ){
  169683. rc = sqlite3_create_function(
  169684. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  169685. );
  169686. }
  169687. }
  169688. return rc;
  169689. }
  169690. /*
  169691. ** The following functions are used to register the module with SQLite. If
  169692. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  169693. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  169694. **
  169695. ** Or, if this module is being built as a loadable extension,
  169696. ** sqlite3Fts5Init() is omitted and the two standard entry points
  169697. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  169698. */
  169699. #ifndef SQLITE_CORE
  169700. #ifdef _WIN32
  169701. __declspec(dllexport)
  169702. #endif
  169703. SQLITE_API int SQLITE_STDCALL sqlite3_fts_init(
  169704. sqlite3 *db,
  169705. char **pzErrMsg,
  169706. const sqlite3_api_routines *pApi
  169707. ){
  169708. SQLITE_EXTENSION_INIT2(pApi);
  169709. (void)pzErrMsg; /* Unused parameter */
  169710. return fts5Init(db);
  169711. }
  169712. #ifdef _WIN32
  169713. __declspec(dllexport)
  169714. #endif
  169715. SQLITE_API int SQLITE_STDCALL sqlite3_fts5_init(
  169716. sqlite3 *db,
  169717. char **pzErrMsg,
  169718. const sqlite3_api_routines *pApi
  169719. ){
  169720. SQLITE_EXTENSION_INIT2(pApi);
  169721. (void)pzErrMsg; /* Unused parameter */
  169722. return fts5Init(db);
  169723. }
  169724. #else
  169725. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  169726. return fts5Init(db);
  169727. }
  169728. #endif
  169729. /*
  169730. ** 2014 May 31
  169731. **
  169732. ** The author disclaims copyright to this source code. In place of
  169733. ** a legal notice, here is a blessing:
  169734. **
  169735. ** May you do good and not evil.
  169736. ** May you find forgiveness for yourself and forgive others.
  169737. ** May you share freely, never taking more than you give.
  169738. **
  169739. ******************************************************************************
  169740. **
  169741. */
  169742. /* #include "fts5Int.h" */
  169743. struct Fts5Storage {
  169744. Fts5Config *pConfig;
  169745. Fts5Index *pIndex;
  169746. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  169747. i64 nTotalRow; /* Total number of rows in FTS table */
  169748. i64 *aTotalSize; /* Total sizes of each column */
  169749. sqlite3_stmt *aStmt[11];
  169750. };
  169751. #if FTS5_STMT_SCAN_ASC!=0
  169752. # error "FTS5_STMT_SCAN_ASC mismatch"
  169753. #endif
  169754. #if FTS5_STMT_SCAN_DESC!=1
  169755. # error "FTS5_STMT_SCAN_DESC mismatch"
  169756. #endif
  169757. #if FTS5_STMT_LOOKUP!=2
  169758. # error "FTS5_STMT_LOOKUP mismatch"
  169759. #endif
  169760. #define FTS5_STMT_INSERT_CONTENT 3
  169761. #define FTS5_STMT_REPLACE_CONTENT 4
  169762. #define FTS5_STMT_DELETE_CONTENT 5
  169763. #define FTS5_STMT_REPLACE_DOCSIZE 6
  169764. #define FTS5_STMT_DELETE_DOCSIZE 7
  169765. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  169766. #define FTS5_STMT_REPLACE_CONFIG 9
  169767. #define FTS5_STMT_SCAN 10
  169768. /*
  169769. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  169770. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  169771. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  169772. ** occurs.
  169773. */
  169774. static int fts5StorageGetStmt(
  169775. Fts5Storage *p, /* Storage handle */
  169776. int eStmt, /* FTS5_STMT_XXX constant */
  169777. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  169778. char **pzErrMsg /* OUT: Error message (if any) */
  169779. ){
  169780. int rc = SQLITE_OK;
  169781. /* If there is no %_docsize table, there should be no requests for
  169782. ** statements to operate on it. */
  169783. assert( p->pConfig->bColumnsize || (
  169784. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  169785. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  169786. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  169787. ));
  169788. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  169789. if( p->aStmt[eStmt]==0 ){
  169790. const char *azStmt[] = {
  169791. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  169792. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  169793. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  169794. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  169795. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  169796. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  169797. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  169798. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  169799. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  169800. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  169801. "SELECT %s FROM %s AS T", /* SCAN */
  169802. };
  169803. Fts5Config *pC = p->pConfig;
  169804. char *zSql = 0;
  169805. switch( eStmt ){
  169806. case FTS5_STMT_SCAN:
  169807. zSql = sqlite3_mprintf(azStmt[eStmt],
  169808. pC->zContentExprlist, pC->zContent
  169809. );
  169810. break;
  169811. case FTS5_STMT_SCAN_ASC:
  169812. case FTS5_STMT_SCAN_DESC:
  169813. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  169814. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  169815. pC->zContentRowid
  169816. );
  169817. break;
  169818. case FTS5_STMT_LOOKUP:
  169819. zSql = sqlite3_mprintf(azStmt[eStmt],
  169820. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  169821. );
  169822. break;
  169823. case FTS5_STMT_INSERT_CONTENT:
  169824. case FTS5_STMT_REPLACE_CONTENT: {
  169825. int nCol = pC->nCol + 1;
  169826. char *zBind;
  169827. int i;
  169828. zBind = sqlite3_malloc(1 + nCol*2);
  169829. if( zBind ){
  169830. for(i=0; i<nCol; i++){
  169831. zBind[i*2] = '?';
  169832. zBind[i*2 + 1] = ',';
  169833. }
  169834. zBind[i*2-1] = '\0';
  169835. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  169836. sqlite3_free(zBind);
  169837. }
  169838. break;
  169839. }
  169840. default:
  169841. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  169842. break;
  169843. }
  169844. if( zSql==0 ){
  169845. rc = SQLITE_NOMEM;
  169846. }else{
  169847. rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
  169848. sqlite3_free(zSql);
  169849. if( rc!=SQLITE_OK && pzErrMsg ){
  169850. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  169851. }
  169852. }
  169853. }
  169854. *ppStmt = p->aStmt[eStmt];
  169855. return rc;
  169856. }
  169857. static int fts5ExecPrintf(
  169858. sqlite3 *db,
  169859. char **pzErr,
  169860. const char *zFormat,
  169861. ...
  169862. ){
  169863. int rc;
  169864. va_list ap; /* ... printf arguments */
  169865. char *zSql;
  169866. va_start(ap, zFormat);
  169867. zSql = sqlite3_vmprintf(zFormat, ap);
  169868. if( zSql==0 ){
  169869. rc = SQLITE_NOMEM;
  169870. }else{
  169871. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  169872. sqlite3_free(zSql);
  169873. }
  169874. va_end(ap);
  169875. return rc;
  169876. }
  169877. /*
  169878. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  169879. ** code otherwise.
  169880. */
  169881. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  169882. int rc = fts5ExecPrintf(pConfig->db, 0,
  169883. "DROP TABLE IF EXISTS %Q.'%q_data';"
  169884. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  169885. "DROP TABLE IF EXISTS %Q.'%q_config';",
  169886. pConfig->zDb, pConfig->zName,
  169887. pConfig->zDb, pConfig->zName,
  169888. pConfig->zDb, pConfig->zName
  169889. );
  169890. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  169891. rc = fts5ExecPrintf(pConfig->db, 0,
  169892. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  169893. pConfig->zDb, pConfig->zName
  169894. );
  169895. }
  169896. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  169897. rc = fts5ExecPrintf(pConfig->db, 0,
  169898. "DROP TABLE IF EXISTS %Q.'%q_content';",
  169899. pConfig->zDb, pConfig->zName
  169900. );
  169901. }
  169902. return rc;
  169903. }
  169904. static void fts5StorageRenameOne(
  169905. Fts5Config *pConfig, /* Current FTS5 configuration */
  169906. int *pRc, /* IN/OUT: Error code */
  169907. const char *zTail, /* Tail of table name e.g. "data", "config" */
  169908. const char *zName /* New name of FTS5 table */
  169909. ){
  169910. if( *pRc==SQLITE_OK ){
  169911. *pRc = fts5ExecPrintf(pConfig->db, 0,
  169912. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  169913. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  169914. );
  169915. }
  169916. }
  169917. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  169918. Fts5Config *pConfig = pStorage->pConfig;
  169919. int rc = sqlite3Fts5StorageSync(pStorage, 1);
  169920. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  169921. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  169922. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  169923. if( pConfig->bColumnsize ){
  169924. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  169925. }
  169926. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  169927. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  169928. }
  169929. return rc;
  169930. }
  169931. /*
  169932. ** Create the shadow table named zPost, with definition zDefn. Return
  169933. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  169934. */
  169935. static int sqlite3Fts5CreateTable(
  169936. Fts5Config *pConfig, /* FTS5 configuration */
  169937. const char *zPost, /* Shadow table to create (e.g. "content") */
  169938. const char *zDefn, /* Columns etc. for shadow table */
  169939. int bWithout, /* True for without rowid */
  169940. char **pzErr /* OUT: Error message */
  169941. ){
  169942. int rc;
  169943. char *zErr = 0;
  169944. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  169945. pConfig->zDb, pConfig->zName, zPost, zDefn, bWithout?" WITHOUT ROWID":""
  169946. );
  169947. if( zErr ){
  169948. *pzErr = sqlite3_mprintf(
  169949. "fts5: error creating shadow table %q_%s: %s",
  169950. pConfig->zName, zPost, zErr
  169951. );
  169952. sqlite3_free(zErr);
  169953. }
  169954. return rc;
  169955. }
  169956. /*
  169957. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  169958. ** and initialize the underlying tables
  169959. **
  169960. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  169961. ** Otherwise, set *pp to NULL and return an SQLite error code.
  169962. */
  169963. static int sqlite3Fts5StorageOpen(
  169964. Fts5Config *pConfig,
  169965. Fts5Index *pIndex,
  169966. int bCreate,
  169967. Fts5Storage **pp,
  169968. char **pzErr /* OUT: Error message */
  169969. ){
  169970. int rc = SQLITE_OK;
  169971. Fts5Storage *p; /* New object */
  169972. int nByte; /* Bytes of space to allocate */
  169973. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  169974. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  169975. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  169976. if( !p ) return SQLITE_NOMEM;
  169977. memset(p, 0, nByte);
  169978. p->aTotalSize = (i64*)&p[1];
  169979. p->pConfig = pConfig;
  169980. p->pIndex = pIndex;
  169981. if( bCreate ){
  169982. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  169983. int nDefn = 32 + pConfig->nCol*10;
  169984. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  169985. if( zDefn==0 ){
  169986. rc = SQLITE_NOMEM;
  169987. }else{
  169988. int i;
  169989. int iOff;
  169990. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  169991. iOff = (int)strlen(zDefn);
  169992. for(i=0; i<pConfig->nCol; i++){
  169993. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  169994. iOff += (int)strlen(&zDefn[iOff]);
  169995. }
  169996. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  169997. }
  169998. sqlite3_free(zDefn);
  169999. }
  170000. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  170001. rc = sqlite3Fts5CreateTable(
  170002. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  170003. );
  170004. }
  170005. if( rc==SQLITE_OK ){
  170006. rc = sqlite3Fts5CreateTable(
  170007. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  170008. );
  170009. }
  170010. if( rc==SQLITE_OK ){
  170011. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  170012. }
  170013. }
  170014. if( rc ){
  170015. sqlite3Fts5StorageClose(p);
  170016. *pp = 0;
  170017. }
  170018. return rc;
  170019. }
  170020. /*
  170021. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  170022. */
  170023. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  170024. int rc = SQLITE_OK;
  170025. if( p ){
  170026. int i;
  170027. /* Finalize all SQL statements */
  170028. for(i=0; i<(int)ArraySize(p->aStmt); i++){
  170029. sqlite3_finalize(p->aStmt[i]);
  170030. }
  170031. sqlite3_free(p);
  170032. }
  170033. return rc;
  170034. }
  170035. typedef struct Fts5InsertCtx Fts5InsertCtx;
  170036. struct Fts5InsertCtx {
  170037. Fts5Storage *pStorage;
  170038. int iCol;
  170039. int szCol; /* Size of column value in tokens */
  170040. };
  170041. /*
  170042. ** Tokenization callback used when inserting tokens into the FTS index.
  170043. */
  170044. static int fts5StorageInsertCallback(
  170045. void *pContext, /* Pointer to Fts5InsertCtx object */
  170046. int tflags,
  170047. const char *pToken, /* Buffer containing token */
  170048. int nToken, /* Size of token in bytes */
  170049. int iStart, /* Start offset of token */
  170050. int iEnd /* End offset of token */
  170051. ){
  170052. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  170053. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  170054. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  170055. pCtx->szCol++;
  170056. }
  170057. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  170058. }
  170059. /*
  170060. ** If a row with rowid iDel is present in the %_content table, add the
  170061. ** delete-markers to the FTS index necessary to delete it. Do not actually
  170062. ** remove the %_content row at this time though.
  170063. */
  170064. static int fts5StorageDeleteFromIndex(Fts5Storage *p, i64 iDel){
  170065. Fts5Config *pConfig = p->pConfig;
  170066. sqlite3_stmt *pSeek; /* SELECT to read row iDel from %_data */
  170067. int rc; /* Return code */
  170068. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  170069. if( rc==SQLITE_OK ){
  170070. int rc2;
  170071. sqlite3_bind_int64(pSeek, 1, iDel);
  170072. if( sqlite3_step(pSeek)==SQLITE_ROW ){
  170073. int iCol;
  170074. Fts5InsertCtx ctx;
  170075. ctx.pStorage = p;
  170076. ctx.iCol = -1;
  170077. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  170078. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  170079. if( pConfig->abUnindexed[iCol-1] ) continue;
  170080. ctx.szCol = 0;
  170081. rc = sqlite3Fts5Tokenize(pConfig,
  170082. FTS5_TOKENIZE_DOCUMENT,
  170083. (const char*)sqlite3_column_text(pSeek, iCol),
  170084. sqlite3_column_bytes(pSeek, iCol),
  170085. (void*)&ctx,
  170086. fts5StorageInsertCallback
  170087. );
  170088. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  170089. }
  170090. p->nTotalRow--;
  170091. }
  170092. rc2 = sqlite3_reset(pSeek);
  170093. if( rc==SQLITE_OK ) rc = rc2;
  170094. }
  170095. return rc;
  170096. }
  170097. /*
  170098. ** Insert a record into the %_docsize table. Specifically, do:
  170099. **
  170100. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  170101. **
  170102. ** If there is no %_docsize table (as happens if the columnsize=0 option
  170103. ** is specified when the FTS5 table is created), this function is a no-op.
  170104. */
  170105. static int fts5StorageInsertDocsize(
  170106. Fts5Storage *p, /* Storage module to write to */
  170107. i64 iRowid, /* id value */
  170108. Fts5Buffer *pBuf /* sz value */
  170109. ){
  170110. int rc = SQLITE_OK;
  170111. if( p->pConfig->bColumnsize ){
  170112. sqlite3_stmt *pReplace = 0;
  170113. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  170114. if( rc==SQLITE_OK ){
  170115. sqlite3_bind_int64(pReplace, 1, iRowid);
  170116. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  170117. sqlite3_step(pReplace);
  170118. rc = sqlite3_reset(pReplace);
  170119. }
  170120. }
  170121. return rc;
  170122. }
  170123. /*
  170124. ** Load the contents of the "averages" record from disk into the
  170125. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  170126. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  170127. ** that the contents of aTotalSize[] and nTotalRow are valid until
  170128. ** further notice.
  170129. **
  170130. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  170131. ** occurs.
  170132. */
  170133. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  170134. int rc = SQLITE_OK;
  170135. if( p->bTotalsValid==0 ){
  170136. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  170137. p->bTotalsValid = bCache;
  170138. }
  170139. return rc;
  170140. }
  170141. /*
  170142. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  170143. ** variables in the "averages" record on disk.
  170144. **
  170145. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  170146. ** occurs.
  170147. */
  170148. static int fts5StorageSaveTotals(Fts5Storage *p){
  170149. int nCol = p->pConfig->nCol;
  170150. int i;
  170151. Fts5Buffer buf;
  170152. int rc = SQLITE_OK;
  170153. memset(&buf, 0, sizeof(buf));
  170154. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  170155. for(i=0; i<nCol; i++){
  170156. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  170157. }
  170158. if( rc==SQLITE_OK ){
  170159. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  170160. }
  170161. sqlite3_free(buf.p);
  170162. return rc;
  170163. }
  170164. /*
  170165. ** Remove a row from the FTS table.
  170166. */
  170167. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel){
  170168. Fts5Config *pConfig = p->pConfig;
  170169. int rc;
  170170. sqlite3_stmt *pDel = 0;
  170171. rc = fts5StorageLoadTotals(p, 1);
  170172. /* Delete the index records */
  170173. if( rc==SQLITE_OK ){
  170174. rc = fts5StorageDeleteFromIndex(p, iDel);
  170175. }
  170176. /* Delete the %_docsize record */
  170177. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  170178. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  170179. if( rc==SQLITE_OK ){
  170180. sqlite3_bind_int64(pDel, 1, iDel);
  170181. sqlite3_step(pDel);
  170182. rc = sqlite3_reset(pDel);
  170183. }
  170184. }
  170185. /* Delete the %_content record */
  170186. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  170187. if( rc==SQLITE_OK ){
  170188. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  170189. }
  170190. if( rc==SQLITE_OK ){
  170191. sqlite3_bind_int64(pDel, 1, iDel);
  170192. sqlite3_step(pDel);
  170193. rc = sqlite3_reset(pDel);
  170194. }
  170195. }
  170196. /* Write the averages record */
  170197. if( rc==SQLITE_OK ){
  170198. rc = fts5StorageSaveTotals(p);
  170199. }
  170200. return rc;
  170201. }
  170202. static int sqlite3Fts5StorageSpecialDelete(
  170203. Fts5Storage *p,
  170204. i64 iDel,
  170205. sqlite3_value **apVal
  170206. ){
  170207. Fts5Config *pConfig = p->pConfig;
  170208. int rc;
  170209. sqlite3_stmt *pDel = 0;
  170210. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL );
  170211. rc = fts5StorageLoadTotals(p, 1);
  170212. /* Delete the index records */
  170213. if( rc==SQLITE_OK ){
  170214. int iCol;
  170215. Fts5InsertCtx ctx;
  170216. ctx.pStorage = p;
  170217. ctx.iCol = -1;
  170218. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  170219. for(iCol=0; rc==SQLITE_OK && iCol<pConfig->nCol; iCol++){
  170220. if( pConfig->abUnindexed[iCol] ) continue;
  170221. ctx.szCol = 0;
  170222. rc = sqlite3Fts5Tokenize(pConfig,
  170223. FTS5_TOKENIZE_DOCUMENT,
  170224. (const char*)sqlite3_value_text(apVal[iCol]),
  170225. sqlite3_value_bytes(apVal[iCol]),
  170226. (void*)&ctx,
  170227. fts5StorageInsertCallback
  170228. );
  170229. p->aTotalSize[iCol] -= (i64)ctx.szCol;
  170230. }
  170231. p->nTotalRow--;
  170232. }
  170233. /* Delete the %_docsize record */
  170234. if( pConfig->bColumnsize ){
  170235. if( rc==SQLITE_OK ){
  170236. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  170237. }
  170238. if( rc==SQLITE_OK ){
  170239. sqlite3_bind_int64(pDel, 1, iDel);
  170240. sqlite3_step(pDel);
  170241. rc = sqlite3_reset(pDel);
  170242. }
  170243. }
  170244. /* Write the averages record */
  170245. if( rc==SQLITE_OK ){
  170246. rc = fts5StorageSaveTotals(p);
  170247. }
  170248. return rc;
  170249. }
  170250. /*
  170251. ** Delete all entries in the FTS5 index.
  170252. */
  170253. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  170254. Fts5Config *pConfig = p->pConfig;
  170255. int rc;
  170256. /* Delete the contents of the %_data and %_docsize tables. */
  170257. rc = fts5ExecPrintf(pConfig->db, 0,
  170258. "DELETE FROM %Q.'%q_data';"
  170259. "DELETE FROM %Q.'%q_idx';",
  170260. pConfig->zDb, pConfig->zName,
  170261. pConfig->zDb, pConfig->zName
  170262. );
  170263. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  170264. rc = fts5ExecPrintf(pConfig->db, 0,
  170265. "DELETE FROM %Q.'%q_docsize';",
  170266. pConfig->zDb, pConfig->zName
  170267. );
  170268. }
  170269. /* Reinitialize the %_data table. This call creates the initial structure
  170270. ** and averages records. */
  170271. if( rc==SQLITE_OK ){
  170272. rc = sqlite3Fts5IndexReinit(p->pIndex);
  170273. }
  170274. if( rc==SQLITE_OK ){
  170275. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  170276. }
  170277. return rc;
  170278. }
  170279. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  170280. Fts5Buffer buf = {0,0,0};
  170281. Fts5Config *pConfig = p->pConfig;
  170282. sqlite3_stmt *pScan = 0;
  170283. Fts5InsertCtx ctx;
  170284. int rc;
  170285. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  170286. ctx.pStorage = p;
  170287. rc = sqlite3Fts5StorageDeleteAll(p);
  170288. if( rc==SQLITE_OK ){
  170289. rc = fts5StorageLoadTotals(p, 1);
  170290. }
  170291. if( rc==SQLITE_OK ){
  170292. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  170293. }
  170294. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  170295. i64 iRowid = sqlite3_column_int64(pScan, 0);
  170296. sqlite3Fts5BufferZero(&buf);
  170297. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  170298. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  170299. ctx.szCol = 0;
  170300. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  170301. rc = sqlite3Fts5Tokenize(pConfig,
  170302. FTS5_TOKENIZE_DOCUMENT,
  170303. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  170304. sqlite3_column_bytes(pScan, ctx.iCol+1),
  170305. (void*)&ctx,
  170306. fts5StorageInsertCallback
  170307. );
  170308. }
  170309. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  170310. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  170311. }
  170312. p->nTotalRow++;
  170313. if( rc==SQLITE_OK ){
  170314. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  170315. }
  170316. }
  170317. sqlite3_free(buf.p);
  170318. /* Write the averages record */
  170319. if( rc==SQLITE_OK ){
  170320. rc = fts5StorageSaveTotals(p);
  170321. }
  170322. return rc;
  170323. }
  170324. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  170325. return sqlite3Fts5IndexOptimize(p->pIndex);
  170326. }
  170327. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  170328. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  170329. }
  170330. /*
  170331. ** Allocate a new rowid. This is used for "external content" tables when
  170332. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  170333. ** by inserting a dummy row into the %_docsize table. The dummy will be
  170334. ** overwritten later.
  170335. **
  170336. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  170337. ** this case the user is required to provide a rowid explicitly.
  170338. */
  170339. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  170340. int rc = SQLITE_MISMATCH;
  170341. if( p->pConfig->bColumnsize ){
  170342. sqlite3_stmt *pReplace = 0;
  170343. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  170344. if( rc==SQLITE_OK ){
  170345. sqlite3_bind_null(pReplace, 1);
  170346. sqlite3_bind_null(pReplace, 2);
  170347. sqlite3_step(pReplace);
  170348. rc = sqlite3_reset(pReplace);
  170349. }
  170350. if( rc==SQLITE_OK ){
  170351. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  170352. }
  170353. }
  170354. return rc;
  170355. }
  170356. /*
  170357. ** Insert a new row into the FTS content table.
  170358. */
  170359. static int sqlite3Fts5StorageContentInsert(
  170360. Fts5Storage *p,
  170361. sqlite3_value **apVal,
  170362. i64 *piRowid
  170363. ){
  170364. Fts5Config *pConfig = p->pConfig;
  170365. int rc = SQLITE_OK;
  170366. /* Insert the new row into the %_content table. */
  170367. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  170368. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  170369. *piRowid = sqlite3_value_int64(apVal[1]);
  170370. }else{
  170371. rc = fts5StorageNewRowid(p, piRowid);
  170372. }
  170373. }else{
  170374. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  170375. int i; /* Counter variable */
  170376. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  170377. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  170378. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  170379. }
  170380. if( rc==SQLITE_OK ){
  170381. sqlite3_step(pInsert);
  170382. rc = sqlite3_reset(pInsert);
  170383. }
  170384. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  170385. }
  170386. return rc;
  170387. }
  170388. /*
  170389. ** Insert new entries into the FTS index and %_docsize table.
  170390. */
  170391. static int sqlite3Fts5StorageIndexInsert(
  170392. Fts5Storage *p,
  170393. sqlite3_value **apVal,
  170394. i64 iRowid
  170395. ){
  170396. Fts5Config *pConfig = p->pConfig;
  170397. int rc = SQLITE_OK; /* Return code */
  170398. Fts5InsertCtx ctx; /* Tokenization callback context object */
  170399. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  170400. memset(&buf, 0, sizeof(Fts5Buffer));
  170401. ctx.pStorage = p;
  170402. rc = fts5StorageLoadTotals(p, 1);
  170403. if( rc==SQLITE_OK ){
  170404. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  170405. }
  170406. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  170407. ctx.szCol = 0;
  170408. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  170409. rc = sqlite3Fts5Tokenize(pConfig,
  170410. FTS5_TOKENIZE_DOCUMENT,
  170411. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  170412. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  170413. (void*)&ctx,
  170414. fts5StorageInsertCallback
  170415. );
  170416. }
  170417. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  170418. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  170419. }
  170420. p->nTotalRow++;
  170421. /* Write the %_docsize record */
  170422. if( rc==SQLITE_OK ){
  170423. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  170424. }
  170425. sqlite3_free(buf.p);
  170426. /* Write the averages record */
  170427. if( rc==SQLITE_OK ){
  170428. rc = fts5StorageSaveTotals(p);
  170429. }
  170430. return rc;
  170431. }
  170432. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  170433. Fts5Config *pConfig = p->pConfig;
  170434. char *zSql;
  170435. int rc;
  170436. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  170437. pConfig->zDb, pConfig->zName, zSuffix
  170438. );
  170439. if( zSql==0 ){
  170440. rc = SQLITE_NOMEM;
  170441. }else{
  170442. sqlite3_stmt *pCnt = 0;
  170443. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  170444. if( rc==SQLITE_OK ){
  170445. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  170446. *pnRow = sqlite3_column_int64(pCnt, 0);
  170447. }
  170448. rc = sqlite3_finalize(pCnt);
  170449. }
  170450. }
  170451. sqlite3_free(zSql);
  170452. return rc;
  170453. }
  170454. /*
  170455. ** Context object used by sqlite3Fts5StorageIntegrity().
  170456. */
  170457. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  170458. struct Fts5IntegrityCtx {
  170459. i64 iRowid;
  170460. int iCol;
  170461. int szCol;
  170462. u64 cksum;
  170463. Fts5Config *pConfig;
  170464. };
  170465. /*
  170466. ** Tokenization callback used by integrity check.
  170467. */
  170468. static int fts5StorageIntegrityCallback(
  170469. void *pContext, /* Pointer to Fts5InsertCtx object */
  170470. int tflags,
  170471. const char *pToken, /* Buffer containing token */
  170472. int nToken, /* Size of token in bytes */
  170473. int iStart, /* Start offset of token */
  170474. int iEnd /* End offset of token */
  170475. ){
  170476. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  170477. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  170478. pCtx->szCol++;
  170479. }
  170480. pCtx->cksum ^= sqlite3Fts5IndexCksum(
  170481. pCtx->pConfig, pCtx->iRowid, pCtx->iCol, pCtx->szCol-1, pToken, nToken
  170482. );
  170483. return SQLITE_OK;
  170484. }
  170485. /*
  170486. ** Check that the contents of the FTS index match that of the %_content
  170487. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  170488. ** some other SQLite error code if an error occurs while attempting to
  170489. ** determine this.
  170490. */
  170491. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  170492. Fts5Config *pConfig = p->pConfig;
  170493. int rc; /* Return code */
  170494. int *aColSize; /* Array of size pConfig->nCol */
  170495. i64 *aTotalSize; /* Array of size pConfig->nCol */
  170496. Fts5IntegrityCtx ctx;
  170497. sqlite3_stmt *pScan;
  170498. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  170499. ctx.pConfig = p->pConfig;
  170500. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  170501. if( !aTotalSize ) return SQLITE_NOMEM;
  170502. aColSize = (int*)&aTotalSize[pConfig->nCol];
  170503. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  170504. /* Generate the expected index checksum based on the contents of the
  170505. ** %_content table. This block stores the checksum in ctx.cksum. */
  170506. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  170507. if( rc==SQLITE_OK ){
  170508. int rc2;
  170509. while( SQLITE_ROW==sqlite3_step(pScan) ){
  170510. int i;
  170511. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  170512. ctx.szCol = 0;
  170513. if( pConfig->bColumnsize ){
  170514. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  170515. }
  170516. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  170517. if( pConfig->abUnindexed[i] ) continue;
  170518. ctx.iCol = i;
  170519. ctx.szCol = 0;
  170520. rc = sqlite3Fts5Tokenize(pConfig,
  170521. FTS5_TOKENIZE_DOCUMENT,
  170522. (const char*)sqlite3_column_text(pScan, i+1),
  170523. sqlite3_column_bytes(pScan, i+1),
  170524. (void*)&ctx,
  170525. fts5StorageIntegrityCallback
  170526. );
  170527. if( pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  170528. rc = FTS5_CORRUPT;
  170529. }
  170530. aTotalSize[i] += ctx.szCol;
  170531. }
  170532. if( rc!=SQLITE_OK ) break;
  170533. }
  170534. rc2 = sqlite3_reset(pScan);
  170535. if( rc==SQLITE_OK ) rc = rc2;
  170536. }
  170537. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  170538. if( rc==SQLITE_OK ){
  170539. int i;
  170540. rc = fts5StorageLoadTotals(p, 0);
  170541. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  170542. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  170543. }
  170544. }
  170545. /* Check that the %_docsize and %_content tables contain the expected
  170546. ** number of rows. */
  170547. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  170548. i64 nRow = 0;
  170549. rc = fts5StorageCount(p, "content", &nRow);
  170550. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  170551. }
  170552. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  170553. i64 nRow = 0;
  170554. rc = fts5StorageCount(p, "docsize", &nRow);
  170555. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  170556. }
  170557. /* Pass the expected checksum down to the FTS index module. It will
  170558. ** verify, amongst other things, that it matches the checksum generated by
  170559. ** inspecting the index itself. */
  170560. if( rc==SQLITE_OK ){
  170561. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  170562. }
  170563. sqlite3_free(aTotalSize);
  170564. return rc;
  170565. }
  170566. /*
  170567. ** Obtain an SQLite statement handle that may be used to read data from the
  170568. ** %_content table.
  170569. */
  170570. static int sqlite3Fts5StorageStmt(
  170571. Fts5Storage *p,
  170572. int eStmt,
  170573. sqlite3_stmt **pp,
  170574. char **pzErrMsg
  170575. ){
  170576. int rc;
  170577. assert( eStmt==FTS5_STMT_SCAN_ASC
  170578. || eStmt==FTS5_STMT_SCAN_DESC
  170579. || eStmt==FTS5_STMT_LOOKUP
  170580. );
  170581. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  170582. if( rc==SQLITE_OK ){
  170583. assert( p->aStmt[eStmt]==*pp );
  170584. p->aStmt[eStmt] = 0;
  170585. }
  170586. return rc;
  170587. }
  170588. /*
  170589. ** Release an SQLite statement handle obtained via an earlier call to
  170590. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  170591. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  170592. */
  170593. static void sqlite3Fts5StorageStmtRelease(
  170594. Fts5Storage *p,
  170595. int eStmt,
  170596. sqlite3_stmt *pStmt
  170597. ){
  170598. assert( eStmt==FTS5_STMT_SCAN_ASC
  170599. || eStmt==FTS5_STMT_SCAN_DESC
  170600. || eStmt==FTS5_STMT_LOOKUP
  170601. );
  170602. if( p->aStmt[eStmt]==0 ){
  170603. sqlite3_reset(pStmt);
  170604. p->aStmt[eStmt] = pStmt;
  170605. }else{
  170606. sqlite3_finalize(pStmt);
  170607. }
  170608. }
  170609. static int fts5StorageDecodeSizeArray(
  170610. int *aCol, int nCol, /* Array to populate */
  170611. const u8 *aBlob, int nBlob /* Record to read varints from */
  170612. ){
  170613. int i;
  170614. int iOff = 0;
  170615. for(i=0; i<nCol; i++){
  170616. if( iOff>=nBlob ) return 1;
  170617. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  170618. }
  170619. return (iOff!=nBlob);
  170620. }
  170621. /*
  170622. ** Argument aCol points to an array of integers containing one entry for
  170623. ** each table column. This function reads the %_docsize record for the
  170624. ** specified rowid and populates aCol[] with the results.
  170625. **
  170626. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  170627. ** otherwise.
  170628. */
  170629. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  170630. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  170631. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  170632. int rc; /* Return Code */
  170633. assert( p->pConfig->bColumnsize );
  170634. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  170635. if( rc==SQLITE_OK ){
  170636. int bCorrupt = 1;
  170637. sqlite3_bind_int64(pLookup, 1, iRowid);
  170638. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  170639. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  170640. int nBlob = sqlite3_column_bytes(pLookup, 0);
  170641. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  170642. bCorrupt = 0;
  170643. }
  170644. }
  170645. rc = sqlite3_reset(pLookup);
  170646. if( bCorrupt && rc==SQLITE_OK ){
  170647. rc = FTS5_CORRUPT;
  170648. }
  170649. }
  170650. return rc;
  170651. }
  170652. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  170653. int rc = fts5StorageLoadTotals(p, 0);
  170654. if( rc==SQLITE_OK ){
  170655. *pnToken = 0;
  170656. if( iCol<0 ){
  170657. int i;
  170658. for(i=0; i<p->pConfig->nCol; i++){
  170659. *pnToken += p->aTotalSize[i];
  170660. }
  170661. }else if( iCol<p->pConfig->nCol ){
  170662. *pnToken = p->aTotalSize[iCol];
  170663. }else{
  170664. rc = SQLITE_RANGE;
  170665. }
  170666. }
  170667. return rc;
  170668. }
  170669. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  170670. int rc = fts5StorageLoadTotals(p, 0);
  170671. if( rc==SQLITE_OK ){
  170672. *pnRow = p->nTotalRow;
  170673. }
  170674. return rc;
  170675. }
  170676. /*
  170677. ** Flush any data currently held in-memory to disk.
  170678. */
  170679. static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
  170680. if( bCommit && p->bTotalsValid ){
  170681. int rc = fts5StorageSaveTotals(p);
  170682. p->bTotalsValid = 0;
  170683. if( rc!=SQLITE_OK ) return rc;
  170684. }
  170685. return sqlite3Fts5IndexSync(p->pIndex, bCommit);
  170686. }
  170687. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  170688. p->bTotalsValid = 0;
  170689. return sqlite3Fts5IndexRollback(p->pIndex);
  170690. }
  170691. static int sqlite3Fts5StorageConfigValue(
  170692. Fts5Storage *p,
  170693. const char *z,
  170694. sqlite3_value *pVal,
  170695. int iVal
  170696. ){
  170697. sqlite3_stmt *pReplace = 0;
  170698. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  170699. if( rc==SQLITE_OK ){
  170700. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  170701. if( pVal ){
  170702. sqlite3_bind_value(pReplace, 2, pVal);
  170703. }else{
  170704. sqlite3_bind_int(pReplace, 2, iVal);
  170705. }
  170706. sqlite3_step(pReplace);
  170707. rc = sqlite3_reset(pReplace);
  170708. }
  170709. if( rc==SQLITE_OK && pVal ){
  170710. int iNew = p->pConfig->iCookie + 1;
  170711. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  170712. if( rc==SQLITE_OK ){
  170713. p->pConfig->iCookie = iNew;
  170714. }
  170715. }
  170716. return rc;
  170717. }
  170718. /*
  170719. ** 2014 May 31
  170720. **
  170721. ** The author disclaims copyright to this source code. In place of
  170722. ** a legal notice, here is a blessing:
  170723. **
  170724. ** May you do good and not evil.
  170725. ** May you find forgiveness for yourself and forgive others.
  170726. ** May you share freely, never taking more than you give.
  170727. **
  170728. ******************************************************************************
  170729. */
  170730. /* #include "fts5Int.h" */
  170731. /**************************************************************************
  170732. ** Start of ascii tokenizer implementation.
  170733. */
  170734. /*
  170735. ** For tokenizers with no "unicode" modifier, the set of token characters
  170736. ** is the same as the set of ASCII range alphanumeric characters.
  170737. */
  170738. static unsigned char aAsciiTokenChar[128] = {
  170739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  170740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  170741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  170742. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  170743. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  170744. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  170745. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  170746. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  170747. };
  170748. typedef struct AsciiTokenizer AsciiTokenizer;
  170749. struct AsciiTokenizer {
  170750. unsigned char aTokenChar[128];
  170751. };
  170752. static void fts5AsciiAddExceptions(
  170753. AsciiTokenizer *p,
  170754. const char *zArg,
  170755. int bTokenChars
  170756. ){
  170757. int i;
  170758. for(i=0; zArg[i]; i++){
  170759. if( (zArg[i] & 0x80)==0 ){
  170760. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  170761. }
  170762. }
  170763. }
  170764. /*
  170765. ** Delete a "ascii" tokenizer.
  170766. */
  170767. static void fts5AsciiDelete(Fts5Tokenizer *p){
  170768. sqlite3_free(p);
  170769. }
  170770. /*
  170771. ** Create an "ascii" tokenizer.
  170772. */
  170773. static int fts5AsciiCreate(
  170774. void *pCtx,
  170775. const char **azArg, int nArg,
  170776. Fts5Tokenizer **ppOut
  170777. ){
  170778. int rc = SQLITE_OK;
  170779. AsciiTokenizer *p = 0;
  170780. if( nArg%2 ){
  170781. rc = SQLITE_ERROR;
  170782. }else{
  170783. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  170784. if( p==0 ){
  170785. rc = SQLITE_NOMEM;
  170786. }else{
  170787. int i;
  170788. memset(p, 0, sizeof(AsciiTokenizer));
  170789. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  170790. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  170791. const char *zArg = azArg[i+1];
  170792. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  170793. fts5AsciiAddExceptions(p, zArg, 1);
  170794. }else
  170795. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  170796. fts5AsciiAddExceptions(p, zArg, 0);
  170797. }else{
  170798. rc = SQLITE_ERROR;
  170799. }
  170800. }
  170801. if( rc!=SQLITE_OK ){
  170802. fts5AsciiDelete((Fts5Tokenizer*)p);
  170803. p = 0;
  170804. }
  170805. }
  170806. }
  170807. *ppOut = (Fts5Tokenizer*)p;
  170808. return rc;
  170809. }
  170810. static void asciiFold(char *aOut, const char *aIn, int nByte){
  170811. int i;
  170812. for(i=0; i<nByte; i++){
  170813. char c = aIn[i];
  170814. if( c>='A' && c<='Z' ) c += 32;
  170815. aOut[i] = c;
  170816. }
  170817. }
  170818. /*
  170819. ** Tokenize some text using the ascii tokenizer.
  170820. */
  170821. static int fts5AsciiTokenize(
  170822. Fts5Tokenizer *pTokenizer,
  170823. void *pCtx,
  170824. int flags,
  170825. const char *pText, int nText,
  170826. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  170827. ){
  170828. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  170829. int rc = SQLITE_OK;
  170830. int ie;
  170831. int is = 0;
  170832. char aFold[64];
  170833. int nFold = sizeof(aFold);
  170834. char *pFold = aFold;
  170835. unsigned char *a = p->aTokenChar;
  170836. while( is<nText && rc==SQLITE_OK ){
  170837. int nByte;
  170838. /* Skip any leading divider characters. */
  170839. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  170840. is++;
  170841. }
  170842. if( is==nText ) break;
  170843. /* Count the token characters */
  170844. ie = is+1;
  170845. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  170846. ie++;
  170847. }
  170848. /* Fold to lower case */
  170849. nByte = ie-is;
  170850. if( nByte>nFold ){
  170851. if( pFold!=aFold ) sqlite3_free(pFold);
  170852. pFold = sqlite3_malloc(nByte*2);
  170853. if( pFold==0 ){
  170854. rc = SQLITE_NOMEM;
  170855. break;
  170856. }
  170857. nFold = nByte*2;
  170858. }
  170859. asciiFold(pFold, &pText[is], nByte);
  170860. /* Invoke the token callback */
  170861. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  170862. is = ie+1;
  170863. }
  170864. if( pFold!=aFold ) sqlite3_free(pFold);
  170865. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  170866. return rc;
  170867. }
  170868. /**************************************************************************
  170869. ** Start of unicode61 tokenizer implementation.
  170870. */
  170871. /*
  170872. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  170873. ** from the sqlite3 source file utf.c. If this file is compiled as part
  170874. ** of the amalgamation, they are not required.
  170875. */
  170876. #ifndef SQLITE_AMALGAMATION
  170877. static const unsigned char sqlite3Utf8Trans1[] = {
  170878. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  170879. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  170880. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  170881. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  170882. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  170883. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  170884. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  170885. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  170886. };
  170887. #define READ_UTF8(zIn, zTerm, c) \
  170888. c = *(zIn++); \
  170889. if( c>=0xc0 ){ \
  170890. c = sqlite3Utf8Trans1[c-0xc0]; \
  170891. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  170892. c = (c<<6) + (0x3f & *(zIn++)); \
  170893. } \
  170894. if( c<0x80 \
  170895. || (c&0xFFFFF800)==0xD800 \
  170896. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  170897. }
  170898. #define WRITE_UTF8(zOut, c) { \
  170899. if( c<0x00080 ){ \
  170900. *zOut++ = (unsigned char)(c&0xFF); \
  170901. } \
  170902. else if( c<0x00800 ){ \
  170903. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  170904. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  170905. } \
  170906. else if( c<0x10000 ){ \
  170907. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  170908. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  170909. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  170910. }else{ \
  170911. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  170912. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  170913. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  170914. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  170915. } \
  170916. }
  170917. #endif /* ifndef SQLITE_AMALGAMATION */
  170918. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  170919. struct Unicode61Tokenizer {
  170920. unsigned char aTokenChar[128]; /* ASCII range token characters */
  170921. char *aFold; /* Buffer to fold text into */
  170922. int nFold; /* Size of aFold[] in bytes */
  170923. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  170924. int nException;
  170925. int *aiException;
  170926. };
  170927. static int fts5UnicodeAddExceptions(
  170928. Unicode61Tokenizer *p, /* Tokenizer object */
  170929. const char *z, /* Characters to treat as exceptions */
  170930. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  170931. ){
  170932. int rc = SQLITE_OK;
  170933. int n = (int)strlen(z);
  170934. int *aNew;
  170935. if( n>0 ){
  170936. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  170937. if( aNew ){
  170938. int nNew = p->nException;
  170939. const unsigned char *zCsr = (const unsigned char*)z;
  170940. const unsigned char *zTerm = (const unsigned char*)&z[n];
  170941. while( zCsr<zTerm ){
  170942. int iCode;
  170943. int bToken;
  170944. READ_UTF8(zCsr, zTerm, iCode);
  170945. if( iCode<128 ){
  170946. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  170947. }else{
  170948. bToken = sqlite3Fts5UnicodeIsalnum(iCode);
  170949. assert( (bToken==0 || bToken==1) );
  170950. assert( (bTokenChars==0 || bTokenChars==1) );
  170951. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  170952. int i;
  170953. for(i=0; i<nNew; i++){
  170954. if( aNew[i]>iCode ) break;
  170955. }
  170956. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  170957. aNew[i] = iCode;
  170958. nNew++;
  170959. }
  170960. }
  170961. }
  170962. p->aiException = aNew;
  170963. p->nException = nNew;
  170964. }else{
  170965. rc = SQLITE_NOMEM;
  170966. }
  170967. }
  170968. return rc;
  170969. }
  170970. /*
  170971. ** Return true if the p->aiException[] array contains the value iCode.
  170972. */
  170973. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  170974. if( p->nException>0 ){
  170975. int *a = p->aiException;
  170976. int iLo = 0;
  170977. int iHi = p->nException-1;
  170978. while( iHi>=iLo ){
  170979. int iTest = (iHi + iLo) / 2;
  170980. if( iCode==a[iTest] ){
  170981. return 1;
  170982. }else if( iCode>a[iTest] ){
  170983. iLo = iTest+1;
  170984. }else{
  170985. iHi = iTest-1;
  170986. }
  170987. }
  170988. }
  170989. return 0;
  170990. }
  170991. /*
  170992. ** Delete a "unicode61" tokenizer.
  170993. */
  170994. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  170995. if( pTok ){
  170996. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  170997. sqlite3_free(p->aiException);
  170998. sqlite3_free(p->aFold);
  170999. sqlite3_free(p);
  171000. }
  171001. return;
  171002. }
  171003. /*
  171004. ** Create a "unicode61" tokenizer.
  171005. */
  171006. static int fts5UnicodeCreate(
  171007. void *pCtx,
  171008. const char **azArg, int nArg,
  171009. Fts5Tokenizer **ppOut
  171010. ){
  171011. int rc = SQLITE_OK; /* Return code */
  171012. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  171013. if( nArg%2 ){
  171014. rc = SQLITE_ERROR;
  171015. }else{
  171016. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  171017. if( p ){
  171018. int i;
  171019. memset(p, 0, sizeof(Unicode61Tokenizer));
  171020. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  171021. p->bRemoveDiacritic = 1;
  171022. p->nFold = 64;
  171023. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  171024. if( p->aFold==0 ){
  171025. rc = SQLITE_NOMEM;
  171026. }
  171027. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  171028. const char *zArg = azArg[i+1];
  171029. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  171030. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  171031. rc = SQLITE_ERROR;
  171032. }
  171033. p->bRemoveDiacritic = (zArg[0]=='1');
  171034. }else
  171035. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  171036. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  171037. }else
  171038. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  171039. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  171040. }else{
  171041. rc = SQLITE_ERROR;
  171042. }
  171043. }
  171044. }else{
  171045. rc = SQLITE_NOMEM;
  171046. }
  171047. if( rc!=SQLITE_OK ){
  171048. fts5UnicodeDelete((Fts5Tokenizer*)p);
  171049. p = 0;
  171050. }
  171051. *ppOut = (Fts5Tokenizer*)p;
  171052. }
  171053. return rc;
  171054. }
  171055. /*
  171056. ** Return true if, for the purposes of tokenizing with the tokenizer
  171057. ** passed as the first argument, codepoint iCode is considered a token
  171058. ** character (not a separator).
  171059. */
  171060. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  171061. assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  171062. return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
  171063. }
  171064. static int fts5UnicodeTokenize(
  171065. Fts5Tokenizer *pTokenizer,
  171066. void *pCtx,
  171067. int flags,
  171068. const char *pText, int nText,
  171069. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  171070. ){
  171071. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  171072. int rc = SQLITE_OK;
  171073. unsigned char *a = p->aTokenChar;
  171074. unsigned char *zTerm = (unsigned char*)&pText[nText];
  171075. unsigned char *zCsr = (unsigned char *)pText;
  171076. /* Output buffer */
  171077. char *aFold = p->aFold;
  171078. int nFold = p->nFold;
  171079. const char *pEnd = &aFold[nFold-6];
  171080. /* Each iteration of this loop gobbles up a contiguous run of separators,
  171081. ** then the next token. */
  171082. while( rc==SQLITE_OK ){
  171083. int iCode; /* non-ASCII codepoint read from input */
  171084. char *zOut = aFold;
  171085. int is;
  171086. int ie;
  171087. /* Skip any separator characters. */
  171088. while( 1 ){
  171089. if( zCsr>=zTerm ) goto tokenize_done;
  171090. if( *zCsr & 0x80 ) {
  171091. /* A character outside of the ascii range. Skip past it if it is
  171092. ** a separator character. Or break out of the loop if it is not. */
  171093. is = zCsr - (unsigned char*)pText;
  171094. READ_UTF8(zCsr, zTerm, iCode);
  171095. if( fts5UnicodeIsAlnum(p, iCode) ){
  171096. goto non_ascii_tokenchar;
  171097. }
  171098. }else{
  171099. if( a[*zCsr] ){
  171100. is = zCsr - (unsigned char*)pText;
  171101. goto ascii_tokenchar;
  171102. }
  171103. zCsr++;
  171104. }
  171105. }
  171106. /* Run through the tokenchars. Fold them into the output buffer along
  171107. ** the way. */
  171108. while( zCsr<zTerm ){
  171109. /* Grow the output buffer so that there is sufficient space to fit the
  171110. ** largest possible utf-8 character. */
  171111. if( zOut>pEnd ){
  171112. aFold = sqlite3_malloc(nFold*2);
  171113. if( aFold==0 ){
  171114. rc = SQLITE_NOMEM;
  171115. goto tokenize_done;
  171116. }
  171117. zOut = &aFold[zOut - p->aFold];
  171118. memcpy(aFold, p->aFold, nFold);
  171119. sqlite3_free(p->aFold);
  171120. p->aFold = aFold;
  171121. p->nFold = nFold = nFold*2;
  171122. pEnd = &aFold[nFold-6];
  171123. }
  171124. if( *zCsr & 0x80 ){
  171125. /* An non-ascii-range character. Fold it into the output buffer if
  171126. ** it is a token character, or break out of the loop if it is not. */
  171127. READ_UTF8(zCsr, zTerm, iCode);
  171128. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  171129. non_ascii_tokenchar:
  171130. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  171131. if( iCode ) WRITE_UTF8(zOut, iCode);
  171132. }else{
  171133. break;
  171134. }
  171135. }else if( a[*zCsr]==0 ){
  171136. /* An ascii-range separator character. End of token. */
  171137. break;
  171138. }else{
  171139. ascii_tokenchar:
  171140. if( *zCsr>='A' && *zCsr<='Z' ){
  171141. *zOut++ = *zCsr + 32;
  171142. }else{
  171143. *zOut++ = *zCsr;
  171144. }
  171145. zCsr++;
  171146. }
  171147. ie = zCsr - (unsigned char*)pText;
  171148. }
  171149. /* Invoke the token callback */
  171150. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  171151. }
  171152. tokenize_done:
  171153. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  171154. return rc;
  171155. }
  171156. /**************************************************************************
  171157. ** Start of porter stemmer implementation.
  171158. */
  171159. /* Any tokens larger than this (in bytes) are passed through without
  171160. ** stemming. */
  171161. #define FTS5_PORTER_MAX_TOKEN 64
  171162. typedef struct PorterTokenizer PorterTokenizer;
  171163. struct PorterTokenizer {
  171164. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  171165. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  171166. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  171167. };
  171168. /*
  171169. ** Delete a "porter" tokenizer.
  171170. */
  171171. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  171172. if( pTok ){
  171173. PorterTokenizer *p = (PorterTokenizer*)pTok;
  171174. if( p->pTokenizer ){
  171175. p->tokenizer.xDelete(p->pTokenizer);
  171176. }
  171177. sqlite3_free(p);
  171178. }
  171179. }
  171180. /*
  171181. ** Create a "porter" tokenizer.
  171182. */
  171183. static int fts5PorterCreate(
  171184. void *pCtx,
  171185. const char **azArg, int nArg,
  171186. Fts5Tokenizer **ppOut
  171187. ){
  171188. fts5_api *pApi = (fts5_api*)pCtx;
  171189. int rc = SQLITE_OK;
  171190. PorterTokenizer *pRet;
  171191. void *pUserdata = 0;
  171192. const char *zBase = "unicode61";
  171193. if( nArg>0 ){
  171194. zBase = azArg[0];
  171195. }
  171196. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  171197. if( pRet ){
  171198. memset(pRet, 0, sizeof(PorterTokenizer));
  171199. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  171200. }else{
  171201. rc = SQLITE_NOMEM;
  171202. }
  171203. if( rc==SQLITE_OK ){
  171204. int nArg2 = (nArg>0 ? nArg-1 : 0);
  171205. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  171206. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  171207. }
  171208. if( rc!=SQLITE_OK ){
  171209. fts5PorterDelete((Fts5Tokenizer*)pRet);
  171210. pRet = 0;
  171211. }
  171212. *ppOut = (Fts5Tokenizer*)pRet;
  171213. return rc;
  171214. }
  171215. typedef struct PorterContext PorterContext;
  171216. struct PorterContext {
  171217. void *pCtx;
  171218. int (*xToken)(void*, int, const char*, int, int, int);
  171219. char *aBuf;
  171220. };
  171221. typedef struct PorterRule PorterRule;
  171222. struct PorterRule {
  171223. const char *zSuffix;
  171224. int nSuffix;
  171225. int (*xCond)(char *zStem, int nStem);
  171226. const char *zOutput;
  171227. int nOutput;
  171228. };
  171229. #if 0
  171230. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  171231. int ret = -1;
  171232. int nBuf = *pnBuf;
  171233. PorterRule *p;
  171234. for(p=aRule; p->zSuffix; p++){
  171235. assert( strlen(p->zSuffix)==p->nSuffix );
  171236. assert( strlen(p->zOutput)==p->nOutput );
  171237. if( nBuf<p->nSuffix ) continue;
  171238. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  171239. }
  171240. if( p->zSuffix ){
  171241. int nStem = nBuf - p->nSuffix;
  171242. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  171243. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  171244. *pnBuf = nStem + p->nOutput;
  171245. ret = p - aRule;
  171246. }
  171247. }
  171248. return ret;
  171249. }
  171250. #endif
  171251. static int fts5PorterIsVowel(char c, int bYIsVowel){
  171252. return (
  171253. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  171254. );
  171255. }
  171256. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  171257. int i;
  171258. int bCons = bPrevCons;
  171259. /* Scan for a vowel */
  171260. for(i=0; i<nStem; i++){
  171261. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  171262. }
  171263. /* Scan for a consonent */
  171264. for(i++; i<nStem; i++){
  171265. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  171266. }
  171267. return 0;
  171268. }
  171269. /* porter rule condition: (m > 0) */
  171270. static int fts5Porter_MGt0(char *zStem, int nStem){
  171271. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  171272. }
  171273. /* porter rule condition: (m > 1) */
  171274. static int fts5Porter_MGt1(char *zStem, int nStem){
  171275. int n;
  171276. n = fts5PorterGobbleVC(zStem, nStem, 0);
  171277. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  171278. return 1;
  171279. }
  171280. return 0;
  171281. }
  171282. /* porter rule condition: (m = 1) */
  171283. static int fts5Porter_MEq1(char *zStem, int nStem){
  171284. int n;
  171285. n = fts5PorterGobbleVC(zStem, nStem, 0);
  171286. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  171287. return 1;
  171288. }
  171289. return 0;
  171290. }
  171291. /* porter rule condition: (*o) */
  171292. static int fts5Porter_Ostar(char *zStem, int nStem){
  171293. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  171294. return 0;
  171295. }else{
  171296. int i;
  171297. int mask = 0;
  171298. int bCons = 0;
  171299. for(i=0; i<nStem; i++){
  171300. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  171301. assert( bCons==0 || bCons==1 );
  171302. mask = (mask << 1) + bCons;
  171303. }
  171304. return ((mask & 0x0007)==0x0005);
  171305. }
  171306. }
  171307. /* porter rule condition: (m > 1 and (*S or *T)) */
  171308. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  171309. assert( nStem>0 );
  171310. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  171311. && fts5Porter_MGt1(zStem, nStem);
  171312. }
  171313. /* porter rule condition: (*v*) */
  171314. static int fts5Porter_Vowel(char *zStem, int nStem){
  171315. int i;
  171316. for(i=0; i<nStem; i++){
  171317. if( fts5PorterIsVowel(zStem[i], i>0) ){
  171318. return 1;
  171319. }
  171320. }
  171321. return 0;
  171322. }
  171323. /**************************************************************************
  171324. ***************************************************************************
  171325. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  171326. */
  171327. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  171328. int ret = 0;
  171329. int nBuf = *pnBuf;
  171330. switch( aBuf[nBuf-2] ){
  171331. case 'a':
  171332. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  171333. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  171334. *pnBuf = nBuf - 2;
  171335. }
  171336. }
  171337. break;
  171338. case 'c':
  171339. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  171340. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  171341. *pnBuf = nBuf - 4;
  171342. }
  171343. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  171344. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  171345. *pnBuf = nBuf - 4;
  171346. }
  171347. }
  171348. break;
  171349. case 'e':
  171350. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  171351. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  171352. *pnBuf = nBuf - 2;
  171353. }
  171354. }
  171355. break;
  171356. case 'i':
  171357. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  171358. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  171359. *pnBuf = nBuf - 2;
  171360. }
  171361. }
  171362. break;
  171363. case 'l':
  171364. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  171365. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  171366. *pnBuf = nBuf - 4;
  171367. }
  171368. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  171369. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  171370. *pnBuf = nBuf - 4;
  171371. }
  171372. }
  171373. break;
  171374. case 'n':
  171375. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  171376. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  171377. *pnBuf = nBuf - 3;
  171378. }
  171379. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  171380. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  171381. *pnBuf = nBuf - 5;
  171382. }
  171383. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  171384. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  171385. *pnBuf = nBuf - 4;
  171386. }
  171387. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  171388. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  171389. *pnBuf = nBuf - 3;
  171390. }
  171391. }
  171392. break;
  171393. case 'o':
  171394. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  171395. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  171396. *pnBuf = nBuf - 3;
  171397. }
  171398. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  171399. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  171400. *pnBuf = nBuf - 2;
  171401. }
  171402. }
  171403. break;
  171404. case 's':
  171405. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  171406. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  171407. *pnBuf = nBuf - 3;
  171408. }
  171409. }
  171410. break;
  171411. case 't':
  171412. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  171413. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  171414. *pnBuf = nBuf - 3;
  171415. }
  171416. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  171417. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  171418. *pnBuf = nBuf - 3;
  171419. }
  171420. }
  171421. break;
  171422. case 'u':
  171423. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  171424. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  171425. *pnBuf = nBuf - 3;
  171426. }
  171427. }
  171428. break;
  171429. case 'v':
  171430. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  171431. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  171432. *pnBuf = nBuf - 3;
  171433. }
  171434. }
  171435. break;
  171436. case 'z':
  171437. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  171438. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  171439. *pnBuf = nBuf - 3;
  171440. }
  171441. }
  171442. break;
  171443. }
  171444. return ret;
  171445. }
  171446. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  171447. int ret = 0;
  171448. int nBuf = *pnBuf;
  171449. switch( aBuf[nBuf-2] ){
  171450. case 'a':
  171451. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  171452. memcpy(&aBuf[nBuf-2], "ate", 3);
  171453. *pnBuf = nBuf - 2 + 3;
  171454. ret = 1;
  171455. }
  171456. break;
  171457. case 'b':
  171458. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  171459. memcpy(&aBuf[nBuf-2], "ble", 3);
  171460. *pnBuf = nBuf - 2 + 3;
  171461. ret = 1;
  171462. }
  171463. break;
  171464. case 'i':
  171465. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  171466. memcpy(&aBuf[nBuf-2], "ize", 3);
  171467. *pnBuf = nBuf - 2 + 3;
  171468. ret = 1;
  171469. }
  171470. break;
  171471. }
  171472. return ret;
  171473. }
  171474. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  171475. int ret = 0;
  171476. int nBuf = *pnBuf;
  171477. switch( aBuf[nBuf-2] ){
  171478. case 'a':
  171479. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  171480. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  171481. memcpy(&aBuf[nBuf-7], "ate", 3);
  171482. *pnBuf = nBuf - 7 + 3;
  171483. }
  171484. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  171485. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  171486. memcpy(&aBuf[nBuf-6], "tion", 4);
  171487. *pnBuf = nBuf - 6 + 4;
  171488. }
  171489. }
  171490. break;
  171491. case 'c':
  171492. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  171493. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  171494. memcpy(&aBuf[nBuf-4], "ence", 4);
  171495. *pnBuf = nBuf - 4 + 4;
  171496. }
  171497. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  171498. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  171499. memcpy(&aBuf[nBuf-4], "ance", 4);
  171500. *pnBuf = nBuf - 4 + 4;
  171501. }
  171502. }
  171503. break;
  171504. case 'e':
  171505. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  171506. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  171507. memcpy(&aBuf[nBuf-4], "ize", 3);
  171508. *pnBuf = nBuf - 4 + 3;
  171509. }
  171510. }
  171511. break;
  171512. case 'g':
  171513. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  171514. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  171515. memcpy(&aBuf[nBuf-4], "log", 3);
  171516. *pnBuf = nBuf - 4 + 3;
  171517. }
  171518. }
  171519. break;
  171520. case 'l':
  171521. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  171522. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  171523. memcpy(&aBuf[nBuf-3], "ble", 3);
  171524. *pnBuf = nBuf - 3 + 3;
  171525. }
  171526. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  171527. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  171528. memcpy(&aBuf[nBuf-4], "al", 2);
  171529. *pnBuf = nBuf - 4 + 2;
  171530. }
  171531. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  171532. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171533. memcpy(&aBuf[nBuf-5], "ent", 3);
  171534. *pnBuf = nBuf - 5 + 3;
  171535. }
  171536. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  171537. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  171538. memcpy(&aBuf[nBuf-3], "e", 1);
  171539. *pnBuf = nBuf - 3 + 1;
  171540. }
  171541. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  171542. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171543. memcpy(&aBuf[nBuf-5], "ous", 3);
  171544. *pnBuf = nBuf - 5 + 3;
  171545. }
  171546. }
  171547. break;
  171548. case 'o':
  171549. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  171550. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  171551. memcpy(&aBuf[nBuf-7], "ize", 3);
  171552. *pnBuf = nBuf - 7 + 3;
  171553. }
  171554. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  171555. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171556. memcpy(&aBuf[nBuf-5], "ate", 3);
  171557. *pnBuf = nBuf - 5 + 3;
  171558. }
  171559. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  171560. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  171561. memcpy(&aBuf[nBuf-4], "ate", 3);
  171562. *pnBuf = nBuf - 4 + 3;
  171563. }
  171564. }
  171565. break;
  171566. case 's':
  171567. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  171568. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171569. memcpy(&aBuf[nBuf-5], "al", 2);
  171570. *pnBuf = nBuf - 5 + 2;
  171571. }
  171572. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  171573. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  171574. memcpy(&aBuf[nBuf-7], "ive", 3);
  171575. *pnBuf = nBuf - 7 + 3;
  171576. }
  171577. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  171578. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  171579. memcpy(&aBuf[nBuf-7], "ful", 3);
  171580. *pnBuf = nBuf - 7 + 3;
  171581. }
  171582. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  171583. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  171584. memcpy(&aBuf[nBuf-7], "ous", 3);
  171585. *pnBuf = nBuf - 7 + 3;
  171586. }
  171587. }
  171588. break;
  171589. case 't':
  171590. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  171591. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171592. memcpy(&aBuf[nBuf-5], "al", 2);
  171593. *pnBuf = nBuf - 5 + 2;
  171594. }
  171595. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  171596. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171597. memcpy(&aBuf[nBuf-5], "ive", 3);
  171598. *pnBuf = nBuf - 5 + 3;
  171599. }
  171600. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  171601. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  171602. memcpy(&aBuf[nBuf-6], "ble", 3);
  171603. *pnBuf = nBuf - 6 + 3;
  171604. }
  171605. }
  171606. break;
  171607. }
  171608. return ret;
  171609. }
  171610. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  171611. int ret = 0;
  171612. int nBuf = *pnBuf;
  171613. switch( aBuf[nBuf-2] ){
  171614. case 'a':
  171615. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  171616. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  171617. memcpy(&aBuf[nBuf-4], "ic", 2);
  171618. *pnBuf = nBuf - 4 + 2;
  171619. }
  171620. }
  171621. break;
  171622. case 's':
  171623. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  171624. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  171625. *pnBuf = nBuf - 4;
  171626. }
  171627. }
  171628. break;
  171629. case 't':
  171630. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  171631. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171632. memcpy(&aBuf[nBuf-5], "ic", 2);
  171633. *pnBuf = nBuf - 5 + 2;
  171634. }
  171635. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  171636. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171637. memcpy(&aBuf[nBuf-5], "ic", 2);
  171638. *pnBuf = nBuf - 5 + 2;
  171639. }
  171640. }
  171641. break;
  171642. case 'u':
  171643. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  171644. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  171645. *pnBuf = nBuf - 3;
  171646. }
  171647. }
  171648. break;
  171649. case 'v':
  171650. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  171651. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171652. *pnBuf = nBuf - 5;
  171653. }
  171654. }
  171655. break;
  171656. case 'z':
  171657. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  171658. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  171659. memcpy(&aBuf[nBuf-5], "al", 2);
  171660. *pnBuf = nBuf - 5 + 2;
  171661. }
  171662. }
  171663. break;
  171664. }
  171665. return ret;
  171666. }
  171667. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  171668. int ret = 0;
  171669. int nBuf = *pnBuf;
  171670. switch( aBuf[nBuf-2] ){
  171671. case 'e':
  171672. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  171673. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  171674. memcpy(&aBuf[nBuf-3], "ee", 2);
  171675. *pnBuf = nBuf - 3 + 2;
  171676. }
  171677. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  171678. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  171679. *pnBuf = nBuf - 2;
  171680. ret = 1;
  171681. }
  171682. }
  171683. break;
  171684. case 'n':
  171685. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  171686. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  171687. *pnBuf = nBuf - 3;
  171688. ret = 1;
  171689. }
  171690. }
  171691. break;
  171692. }
  171693. return ret;
  171694. }
  171695. /*
  171696. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  171697. ***************************************************************************
  171698. **************************************************************************/
  171699. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  171700. int nBuf = *pnBuf;
  171701. if( aBuf[nBuf-1]=='s' ){
  171702. if( aBuf[nBuf-2]=='e' ){
  171703. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  171704. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  171705. ){
  171706. *pnBuf = nBuf-2;
  171707. }else{
  171708. *pnBuf = nBuf-1;
  171709. }
  171710. }
  171711. else if( aBuf[nBuf-2]!='s' ){
  171712. *pnBuf = nBuf-1;
  171713. }
  171714. }
  171715. }
  171716. static int fts5PorterCb(
  171717. void *pCtx,
  171718. int tflags,
  171719. const char *pToken,
  171720. int nToken,
  171721. int iStart,
  171722. int iEnd
  171723. ){
  171724. PorterContext *p = (PorterContext*)pCtx;
  171725. char *aBuf;
  171726. int nBuf;
  171727. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  171728. aBuf = p->aBuf;
  171729. nBuf = nToken;
  171730. memcpy(aBuf, pToken, nBuf);
  171731. /* Step 1. */
  171732. fts5PorterStep1A(aBuf, &nBuf);
  171733. if( fts5PorterStep1B(aBuf, &nBuf) ){
  171734. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  171735. char c = aBuf[nBuf-1];
  171736. if( fts5PorterIsVowel(c, 0)==0
  171737. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  171738. ){
  171739. nBuf--;
  171740. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  171741. aBuf[nBuf++] = 'e';
  171742. }
  171743. }
  171744. }
  171745. /* Step 1C. */
  171746. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  171747. aBuf[nBuf-1] = 'i';
  171748. }
  171749. /* Steps 2 through 4. */
  171750. fts5PorterStep2(aBuf, &nBuf);
  171751. fts5PorterStep3(aBuf, &nBuf);
  171752. fts5PorterStep4(aBuf, &nBuf);
  171753. /* Step 5a. */
  171754. assert( nBuf>0 );
  171755. if( aBuf[nBuf-1]=='e' ){
  171756. if( fts5Porter_MGt1(aBuf, nBuf-1)
  171757. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  171758. ){
  171759. nBuf--;
  171760. }
  171761. }
  171762. /* Step 5b. */
  171763. if( nBuf>1 && aBuf[nBuf-1]=='l'
  171764. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  171765. ){
  171766. nBuf--;
  171767. }
  171768. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  171769. pass_through:
  171770. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  171771. }
  171772. /*
  171773. ** Tokenize using the porter tokenizer.
  171774. */
  171775. static int fts5PorterTokenize(
  171776. Fts5Tokenizer *pTokenizer,
  171777. void *pCtx,
  171778. int flags,
  171779. const char *pText, int nText,
  171780. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  171781. ){
  171782. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  171783. PorterContext sCtx;
  171784. sCtx.xToken = xToken;
  171785. sCtx.pCtx = pCtx;
  171786. sCtx.aBuf = p->aBuf;
  171787. return p->tokenizer.xTokenize(
  171788. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  171789. );
  171790. }
  171791. /*
  171792. ** Register all built-in tokenizers with FTS5.
  171793. */
  171794. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  171795. struct BuiltinTokenizer {
  171796. const char *zName;
  171797. fts5_tokenizer x;
  171798. } aBuiltin[] = {
  171799. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  171800. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  171801. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  171802. };
  171803. int rc = SQLITE_OK; /* Return code */
  171804. int i; /* To iterate through builtin functions */
  171805. for(i=0; rc==SQLITE_OK && i<(int)ArraySize(aBuiltin); i++){
  171806. rc = pApi->xCreateTokenizer(pApi,
  171807. aBuiltin[i].zName,
  171808. (void*)pApi,
  171809. &aBuiltin[i].x,
  171810. 0
  171811. );
  171812. }
  171813. return rc;
  171814. }
  171815. /*
  171816. ** 2012 May 25
  171817. **
  171818. ** The author disclaims copyright to this source code. In place of
  171819. ** a legal notice, here is a blessing:
  171820. **
  171821. ** May you do good and not evil.
  171822. ** May you find forgiveness for yourself and forgive others.
  171823. ** May you share freely, never taking more than you give.
  171824. **
  171825. ******************************************************************************
  171826. */
  171827. /*
  171828. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  171829. */
  171830. /* #include <assert.h> */
  171831. /*
  171832. ** Return true if the argument corresponds to a unicode codepoint
  171833. ** classified as either a letter or a number. Otherwise false.
  171834. **
  171835. ** The results are undefined if the value passed to this function
  171836. ** is less than zero.
  171837. */
  171838. static int sqlite3Fts5UnicodeIsalnum(int c){
  171839. /* Each unsigned integer in the following array corresponds to a contiguous
  171840. ** range of unicode codepoints that are not either letters or numbers (i.e.
  171841. ** codepoints for which this function should return 0).
  171842. **
  171843. ** The most significant 22 bits in each 32-bit value contain the first
  171844. ** codepoint in the range. The least significant 10 bits are used to store
  171845. ** the size of the range (always at least 1). In other words, the value
  171846. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  171847. ** C. It is not possible to represent a range larger than 1023 codepoints
  171848. ** using this format.
  171849. */
  171850. static const unsigned int aEntry[] = {
  171851. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  171852. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  171853. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  171854. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  171855. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  171856. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  171857. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  171858. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  171859. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  171860. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  171861. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  171862. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  171863. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  171864. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  171865. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  171866. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  171867. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  171868. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  171869. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  171870. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  171871. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  171872. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  171873. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  171874. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  171875. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  171876. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  171877. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  171878. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  171879. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  171880. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  171881. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  171882. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  171883. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  171884. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  171885. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  171886. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  171887. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  171888. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  171889. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  171890. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  171891. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  171892. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  171893. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  171894. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  171895. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  171896. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  171897. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  171898. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  171899. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  171900. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  171901. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  171902. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  171903. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  171904. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  171905. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  171906. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  171907. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  171908. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  171909. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  171910. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  171911. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  171912. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  171913. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  171914. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  171915. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  171916. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  171917. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  171918. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  171919. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  171920. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  171921. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  171922. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  171923. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  171924. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  171925. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  171926. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  171927. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  171928. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  171929. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  171930. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  171931. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  171932. 0x380400F0,
  171933. };
  171934. static const unsigned int aAscii[4] = {
  171935. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  171936. };
  171937. if( c<128 ){
  171938. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  171939. }else if( c<(1<<22) ){
  171940. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  171941. int iRes = 0;
  171942. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  171943. int iLo = 0;
  171944. while( iHi>=iLo ){
  171945. int iTest = (iHi + iLo) / 2;
  171946. if( key >= aEntry[iTest] ){
  171947. iRes = iTest;
  171948. iLo = iTest+1;
  171949. }else{
  171950. iHi = iTest-1;
  171951. }
  171952. }
  171953. assert( aEntry[0]<key );
  171954. assert( key>=aEntry[iRes] );
  171955. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  171956. }
  171957. return 1;
  171958. }
  171959. /*
  171960. ** If the argument is a codepoint corresponding to a lowercase letter
  171961. ** in the ASCII range with a diacritic added, return the codepoint
  171962. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  171963. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  171964. ** E"). The resuls of passing a codepoint that corresponds to an
  171965. ** uppercase letter are undefined.
  171966. */
  171967. static int fts5_remove_diacritic(int c){
  171968. unsigned short aDia[] = {
  171969. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  171970. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  171971. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  171972. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  171973. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  171974. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  171975. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  171976. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  171977. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  171978. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  171979. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  171980. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  171981. 62924, 63050, 63082, 63274, 63390,
  171982. };
  171983. char aChar[] = {
  171984. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  171985. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  171986. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  171987. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  171988. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  171989. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  171990. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  171991. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  171992. 'e', 'i', 'o', 'u', 'y',
  171993. };
  171994. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  171995. int iRes = 0;
  171996. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  171997. int iLo = 0;
  171998. while( iHi>=iLo ){
  171999. int iTest = (iHi + iLo) / 2;
  172000. if( key >= aDia[iTest] ){
  172001. iRes = iTest;
  172002. iLo = iTest+1;
  172003. }else{
  172004. iHi = iTest-1;
  172005. }
  172006. }
  172007. assert( key>=aDia[iRes] );
  172008. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  172009. }
  172010. /*
  172011. ** Return true if the argument interpreted as a unicode codepoint
  172012. ** is a diacritical modifier character.
  172013. */
  172014. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  172015. unsigned int mask0 = 0x08029FDF;
  172016. unsigned int mask1 = 0x000361F8;
  172017. if( c<768 || c>817 ) return 0;
  172018. return (c < 768+32) ?
  172019. (mask0 & (1 << (c-768))) :
  172020. (mask1 & (1 << (c-768-32)));
  172021. }
  172022. /*
  172023. ** Interpret the argument as a unicode codepoint. If the codepoint
  172024. ** is an upper case character that has a lower case equivalent,
  172025. ** return the codepoint corresponding to the lower case version.
  172026. ** Otherwise, return a copy of the argument.
  172027. **
  172028. ** The results are undefined if the value passed to this function
  172029. ** is less than zero.
  172030. */
  172031. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  172032. /* Each entry in the following array defines a rule for folding a range
  172033. ** of codepoints to lower case. The rule applies to a range of nRange
  172034. ** codepoints starting at codepoint iCode.
  172035. **
  172036. ** If the least significant bit in flags is clear, then the rule applies
  172037. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  172038. ** need to be folded). Or, if it is set, then the rule only applies to
  172039. ** every second codepoint in the range, starting with codepoint C.
  172040. **
  172041. ** The 7 most significant bits in flags are an index into the aiOff[]
  172042. ** array. If a specific codepoint C does require folding, then its lower
  172043. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  172044. **
  172045. ** The contents of this array are generated by parsing the CaseFolding.txt
  172046. ** file distributed as part of the "Unicode Character Database". See
  172047. ** http://www.unicode.org for details.
  172048. */
  172049. static const struct TableEntry {
  172050. unsigned short iCode;
  172051. unsigned char flags;
  172052. unsigned char nRange;
  172053. } aEntry[] = {
  172054. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  172055. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  172056. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  172057. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  172058. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  172059. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  172060. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  172061. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  172062. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  172063. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  172064. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  172065. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  172066. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  172067. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  172068. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  172069. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  172070. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  172071. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  172072. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  172073. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  172074. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  172075. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  172076. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  172077. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  172078. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  172079. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  172080. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  172081. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  172082. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  172083. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  172084. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  172085. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  172086. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  172087. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  172088. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  172089. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  172090. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  172091. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  172092. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  172093. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  172094. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  172095. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  172096. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  172097. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  172098. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  172099. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  172100. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  172101. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  172102. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  172103. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  172104. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  172105. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  172106. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  172107. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  172108. {65313, 14, 26},
  172109. };
  172110. static const unsigned short aiOff[] = {
  172111. 1, 2, 8, 15, 16, 26, 28, 32,
  172112. 37, 38, 40, 48, 63, 64, 69, 71,
  172113. 79, 80, 116, 202, 203, 205, 206, 207,
  172114. 209, 210, 211, 213, 214, 217, 218, 219,
  172115. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  172116. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  172117. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  172118. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  172119. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  172120. 65514, 65521, 65527, 65528, 65529,
  172121. };
  172122. int ret = c;
  172123. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  172124. if( c<128 ){
  172125. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  172126. }else if( c<65536 ){
  172127. const struct TableEntry *p;
  172128. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  172129. int iLo = 0;
  172130. int iRes = -1;
  172131. assert( c>aEntry[0].iCode );
  172132. while( iHi>=iLo ){
  172133. int iTest = (iHi + iLo) / 2;
  172134. int cmp = (c - aEntry[iTest].iCode);
  172135. if( cmp>=0 ){
  172136. iRes = iTest;
  172137. iLo = iTest+1;
  172138. }else{
  172139. iHi = iTest-1;
  172140. }
  172141. }
  172142. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  172143. p = &aEntry[iRes];
  172144. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  172145. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  172146. assert( ret>0 );
  172147. }
  172148. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  172149. }
  172150. else if( c>=66560 && c<66600 ){
  172151. ret = c + 40;
  172152. }
  172153. return ret;
  172154. }
  172155. /*
  172156. ** 2015 May 30
  172157. **
  172158. ** The author disclaims copyright to this source code. In place of
  172159. ** a legal notice, here is a blessing:
  172160. **
  172161. ** May you do good and not evil.
  172162. ** May you find forgiveness for yourself and forgive others.
  172163. ** May you share freely, never taking more than you give.
  172164. **
  172165. ******************************************************************************
  172166. **
  172167. ** Routines for varint serialization and deserialization.
  172168. */
  172169. /* #include "fts5Int.h" */
  172170. /*
  172171. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  172172. ** Except, this version does handle the single byte case that the core
  172173. ** version depends on being handled before its function is called.
  172174. */
  172175. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  172176. u32 a,b;
  172177. /* The 1-byte case. Overwhelmingly the most common. */
  172178. a = *p;
  172179. /* a: p0 (unmasked) */
  172180. if (!(a&0x80))
  172181. {
  172182. /* Values between 0 and 127 */
  172183. *v = a;
  172184. return 1;
  172185. }
  172186. /* The 2-byte case */
  172187. p++;
  172188. b = *p;
  172189. /* b: p1 (unmasked) */
  172190. if (!(b&0x80))
  172191. {
  172192. /* Values between 128 and 16383 */
  172193. a &= 0x7f;
  172194. a = a<<7;
  172195. *v = a | b;
  172196. return 2;
  172197. }
  172198. /* The 3-byte case */
  172199. p++;
  172200. a = a<<14;
  172201. a |= *p;
  172202. /* a: p0<<14 | p2 (unmasked) */
  172203. if (!(a&0x80))
  172204. {
  172205. /* Values between 16384 and 2097151 */
  172206. a &= (0x7f<<14)|(0x7f);
  172207. b &= 0x7f;
  172208. b = b<<7;
  172209. *v = a | b;
  172210. return 3;
  172211. }
  172212. /* A 32-bit varint is used to store size information in btrees.
  172213. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  172214. ** A 3-byte varint is sufficient, for example, to record the size
  172215. ** of a 1048569-byte BLOB or string.
  172216. **
  172217. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  172218. ** rare larger cases can be handled by the slower 64-bit varint
  172219. ** routine.
  172220. */
  172221. {
  172222. u64 v64;
  172223. u8 n;
  172224. p -= 2;
  172225. n = sqlite3Fts5GetVarint(p, &v64);
  172226. *v = (u32)v64;
  172227. assert( n>3 && n<=9 );
  172228. return n;
  172229. }
  172230. }
  172231. /*
  172232. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  172233. ** are defined here rather than simply putting the constant expressions
  172234. ** inline in order to work around bugs in the RVT compiler.
  172235. **
  172236. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  172237. **
  172238. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  172239. */
  172240. #define SLOT_2_0 0x001fc07f
  172241. #define SLOT_4_2_0 0xf01fc07f
  172242. /*
  172243. ** Read a 64-bit variable-length integer from memory starting at p[0].
  172244. ** Return the number of bytes read. The value is stored in *v.
  172245. */
  172246. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  172247. u32 a,b,s;
  172248. a = *p;
  172249. /* a: p0 (unmasked) */
  172250. if (!(a&0x80))
  172251. {
  172252. *v = a;
  172253. return 1;
  172254. }
  172255. p++;
  172256. b = *p;
  172257. /* b: p1 (unmasked) */
  172258. if (!(b&0x80))
  172259. {
  172260. a &= 0x7f;
  172261. a = a<<7;
  172262. a |= b;
  172263. *v = a;
  172264. return 2;
  172265. }
  172266. /* Verify that constants are precomputed correctly */
  172267. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  172268. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  172269. p++;
  172270. a = a<<14;
  172271. a |= *p;
  172272. /* a: p0<<14 | p2 (unmasked) */
  172273. if (!(a&0x80))
  172274. {
  172275. a &= SLOT_2_0;
  172276. b &= 0x7f;
  172277. b = b<<7;
  172278. a |= b;
  172279. *v = a;
  172280. return 3;
  172281. }
  172282. /* CSE1 from below */
  172283. a &= SLOT_2_0;
  172284. p++;
  172285. b = b<<14;
  172286. b |= *p;
  172287. /* b: p1<<14 | p3 (unmasked) */
  172288. if (!(b&0x80))
  172289. {
  172290. b &= SLOT_2_0;
  172291. /* moved CSE1 up */
  172292. /* a &= (0x7f<<14)|(0x7f); */
  172293. a = a<<7;
  172294. a |= b;
  172295. *v = a;
  172296. return 4;
  172297. }
  172298. /* a: p0<<14 | p2 (masked) */
  172299. /* b: p1<<14 | p3 (unmasked) */
  172300. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  172301. /* moved CSE1 up */
  172302. /* a &= (0x7f<<14)|(0x7f); */
  172303. b &= SLOT_2_0;
  172304. s = a;
  172305. /* s: p0<<14 | p2 (masked) */
  172306. p++;
  172307. a = a<<14;
  172308. a |= *p;
  172309. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  172310. if (!(a&0x80))
  172311. {
  172312. /* we can skip these cause they were (effectively) done above in calc'ing s */
  172313. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  172314. /* b &= (0x7f<<14)|(0x7f); */
  172315. b = b<<7;
  172316. a |= b;
  172317. s = s>>18;
  172318. *v = ((u64)s)<<32 | a;
  172319. return 5;
  172320. }
  172321. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  172322. s = s<<7;
  172323. s |= b;
  172324. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  172325. p++;
  172326. b = b<<14;
  172327. b |= *p;
  172328. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  172329. if (!(b&0x80))
  172330. {
  172331. /* we can skip this cause it was (effectively) done above in calc'ing s */
  172332. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  172333. a &= SLOT_2_0;
  172334. a = a<<7;
  172335. a |= b;
  172336. s = s>>18;
  172337. *v = ((u64)s)<<32 | a;
  172338. return 6;
  172339. }
  172340. p++;
  172341. a = a<<14;
  172342. a |= *p;
  172343. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  172344. if (!(a&0x80))
  172345. {
  172346. a &= SLOT_4_2_0;
  172347. b &= SLOT_2_0;
  172348. b = b<<7;
  172349. a |= b;
  172350. s = s>>11;
  172351. *v = ((u64)s)<<32 | a;
  172352. return 7;
  172353. }
  172354. /* CSE2 from below */
  172355. a &= SLOT_2_0;
  172356. p++;
  172357. b = b<<14;
  172358. b |= *p;
  172359. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  172360. if (!(b&0x80))
  172361. {
  172362. b &= SLOT_4_2_0;
  172363. /* moved CSE2 up */
  172364. /* a &= (0x7f<<14)|(0x7f); */
  172365. a = a<<7;
  172366. a |= b;
  172367. s = s>>4;
  172368. *v = ((u64)s)<<32 | a;
  172369. return 8;
  172370. }
  172371. p++;
  172372. a = a<<15;
  172373. a |= *p;
  172374. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  172375. /* moved CSE2 up */
  172376. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  172377. b &= SLOT_2_0;
  172378. b = b<<8;
  172379. a |= b;
  172380. s = s<<4;
  172381. b = p[-4];
  172382. b &= 0x7f;
  172383. b = b>>3;
  172384. s |= b;
  172385. *v = ((u64)s)<<32 | a;
  172386. return 9;
  172387. }
  172388. /*
  172389. ** The variable-length integer encoding is as follows:
  172390. **
  172391. ** KEY:
  172392. ** A = 0xxxxxxx 7 bits of data and one flag bit
  172393. ** B = 1xxxxxxx 7 bits of data and one flag bit
  172394. ** C = xxxxxxxx 8 bits of data
  172395. **
  172396. ** 7 bits - A
  172397. ** 14 bits - BA
  172398. ** 21 bits - BBA
  172399. ** 28 bits - BBBA
  172400. ** 35 bits - BBBBA
  172401. ** 42 bits - BBBBBA
  172402. ** 49 bits - BBBBBBA
  172403. ** 56 bits - BBBBBBBA
  172404. ** 64 bits - BBBBBBBBC
  172405. */
  172406. #ifdef SQLITE_NOINLINE
  172407. # define FTS5_NOINLINE SQLITE_NOINLINE
  172408. #else
  172409. # define FTS5_NOINLINE
  172410. #endif
  172411. /*
  172412. ** Write a 64-bit variable-length integer to memory starting at p[0].
  172413. ** The length of data write will be between 1 and 9 bytes. The number
  172414. ** of bytes written is returned.
  172415. **
  172416. ** A variable-length integer consists of the lower 7 bits of each byte
  172417. ** for all bytes that have the 8th bit set and one byte with the 8th
  172418. ** bit clear. Except, if we get to the 9th byte, it stores the full
  172419. ** 8 bits and is the last byte.
  172420. */
  172421. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  172422. int i, j, n;
  172423. u8 buf[10];
  172424. if( v & (((u64)0xff000000)<<32) ){
  172425. p[8] = (u8)v;
  172426. v >>= 8;
  172427. for(i=7; i>=0; i--){
  172428. p[i] = (u8)((v & 0x7f) | 0x80);
  172429. v >>= 7;
  172430. }
  172431. return 9;
  172432. }
  172433. n = 0;
  172434. do{
  172435. buf[n++] = (u8)((v & 0x7f) | 0x80);
  172436. v >>= 7;
  172437. }while( v!=0 );
  172438. buf[0] &= 0x7f;
  172439. assert( n<=9 );
  172440. for(i=0, j=n-1; j>=0; j--, i++){
  172441. p[i] = buf[j];
  172442. }
  172443. return n;
  172444. }
  172445. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  172446. if( v<=0x7f ){
  172447. p[0] = v&0x7f;
  172448. return 1;
  172449. }
  172450. if( v<=0x3fff ){
  172451. p[0] = ((v>>7)&0x7f)|0x80;
  172452. p[1] = v&0x7f;
  172453. return 2;
  172454. }
  172455. return fts5PutVarint64(p,v);
  172456. }
  172457. static int sqlite3Fts5GetVarintLen(u32 iVal){
  172458. if( iVal<(1 << 7 ) ) return 1;
  172459. if( iVal<(1 << 14) ) return 2;
  172460. if( iVal<(1 << 21) ) return 3;
  172461. if( iVal<(1 << 28) ) return 4;
  172462. return 5;
  172463. }
  172464. /*
  172465. ** 2015 May 08
  172466. **
  172467. ** The author disclaims copyright to this source code. In place of
  172468. ** a legal notice, here is a blessing:
  172469. **
  172470. ** May you do good and not evil.
  172471. ** May you find forgiveness for yourself and forgive others.
  172472. ** May you share freely, never taking more than you give.
  172473. **
  172474. ******************************************************************************
  172475. **
  172476. ** This is an SQLite virtual table module implementing direct access to an
  172477. ** existing FTS5 index. The module may create several different types of
  172478. ** tables:
  172479. **
  172480. ** col:
  172481. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  172482. **
  172483. ** One row for each term/column combination. The value of $doc is set to
  172484. ** the number of fts5 rows that contain at least one instance of term
  172485. ** $term within column $col. Field $cnt is set to the total number of
  172486. ** instances of term $term in column $col (in any row of the fts5 table).
  172487. **
  172488. ** row:
  172489. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  172490. **
  172491. ** One row for each term in the database. The value of $doc is set to
  172492. ** the number of fts5 rows that contain at least one instance of term
  172493. ** $term. Field $cnt is set to the total number of instances of term
  172494. ** $term in the database.
  172495. */
  172496. /* #include "fts5Int.h" */
  172497. typedef struct Fts5VocabTable Fts5VocabTable;
  172498. typedef struct Fts5VocabCursor Fts5VocabCursor;
  172499. struct Fts5VocabTable {
  172500. sqlite3_vtab base;
  172501. char *zFts5Tbl; /* Name of fts5 table */
  172502. char *zFts5Db; /* Db containing fts5 table */
  172503. sqlite3 *db; /* Database handle */
  172504. Fts5Global *pGlobal; /* FTS5 global object for this database */
  172505. int eType; /* FTS5_VOCAB_COL or ROW */
  172506. };
  172507. struct Fts5VocabCursor {
  172508. sqlite3_vtab_cursor base;
  172509. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  172510. Fts5Index *pIndex; /* Associated FTS5 index */
  172511. int bEof; /* True if this cursor is at EOF */
  172512. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  172513. int nLeTerm; /* Size of zLeTerm in bytes */
  172514. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  172515. /* These are used by 'col' tables only */
  172516. Fts5Config *pConfig; /* Fts5 table configuration */
  172517. int iCol;
  172518. i64 *aCnt;
  172519. i64 *aDoc;
  172520. /* Output values used by 'row' and 'col' tables */
  172521. i64 rowid; /* This table's current rowid value */
  172522. Fts5Buffer term; /* Current value of 'term' column */
  172523. };
  172524. #define FTS5_VOCAB_COL 0
  172525. #define FTS5_VOCAB_ROW 1
  172526. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  172527. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  172528. /*
  172529. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  172530. */
  172531. #define FTS5_VOCAB_TERM_EQ 0x01
  172532. #define FTS5_VOCAB_TERM_GE 0x02
  172533. #define FTS5_VOCAB_TERM_LE 0x04
  172534. /*
  172535. ** Translate a string containing an fts5vocab table type to an
  172536. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  172537. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  172538. ** and return SQLITE_ERROR.
  172539. */
  172540. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  172541. int rc = SQLITE_OK;
  172542. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  172543. if( rc==SQLITE_OK ){
  172544. sqlite3Fts5Dequote(zCopy);
  172545. if( sqlite3_stricmp(zCopy, "col")==0 ){
  172546. *peType = FTS5_VOCAB_COL;
  172547. }else
  172548. if( sqlite3_stricmp(zCopy, "row")==0 ){
  172549. *peType = FTS5_VOCAB_ROW;
  172550. }else
  172551. {
  172552. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  172553. rc = SQLITE_ERROR;
  172554. }
  172555. sqlite3_free(zCopy);
  172556. }
  172557. return rc;
  172558. }
  172559. /*
  172560. ** The xDisconnect() virtual table method.
  172561. */
  172562. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  172563. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  172564. sqlite3_free(pTab);
  172565. return SQLITE_OK;
  172566. }
  172567. /*
  172568. ** The xDestroy() virtual table method.
  172569. */
  172570. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  172571. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  172572. sqlite3_free(pTab);
  172573. return SQLITE_OK;
  172574. }
  172575. /*
  172576. ** This function is the implementation of both the xConnect and xCreate
  172577. ** methods of the FTS3 virtual table.
  172578. **
  172579. ** The argv[] array contains the following:
  172580. **
  172581. ** argv[0] -> module name ("fts5vocab")
  172582. ** argv[1] -> database name
  172583. ** argv[2] -> table name
  172584. **
  172585. ** then:
  172586. **
  172587. ** argv[3] -> name of fts5 table
  172588. ** argv[4] -> type of fts5vocab table
  172589. **
  172590. ** or, for tables in the TEMP schema only.
  172591. **
  172592. ** argv[3] -> name of fts5 tables database
  172593. ** argv[4] -> name of fts5 table
  172594. ** argv[5] -> type of fts5vocab table
  172595. */
  172596. static int fts5VocabInitVtab(
  172597. sqlite3 *db, /* The SQLite database connection */
  172598. void *pAux, /* Pointer to Fts5Global object */
  172599. int argc, /* Number of elements in argv array */
  172600. const char * const *argv, /* xCreate/xConnect argument array */
  172601. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  172602. char **pzErr /* Write any error message here */
  172603. ){
  172604. const char *azSchema[] = {
  172605. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  172606. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")"
  172607. };
  172608. Fts5VocabTable *pRet = 0;
  172609. int rc = SQLITE_OK; /* Return code */
  172610. int bDb;
  172611. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  172612. if( argc!=5 && bDb==0 ){
  172613. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  172614. rc = SQLITE_ERROR;
  172615. }else{
  172616. int nByte; /* Bytes of space to allocate */
  172617. const char *zDb = bDb ? argv[3] : argv[1];
  172618. const char *zTab = bDb ? argv[4] : argv[3];
  172619. const char *zType = bDb ? argv[5] : argv[4];
  172620. int nDb = (int)strlen(zDb)+1;
  172621. int nTab = (int)strlen(zTab)+1;
  172622. int eType = 0;
  172623. rc = fts5VocabTableType(zType, pzErr, &eType);
  172624. if( rc==SQLITE_OK ){
  172625. assert( eType>=0 && eType<sizeof(azSchema)/sizeof(azSchema[0]) );
  172626. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  172627. }
  172628. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  172629. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  172630. if( pRet ){
  172631. pRet->pGlobal = (Fts5Global*)pAux;
  172632. pRet->eType = eType;
  172633. pRet->db = db;
  172634. pRet->zFts5Tbl = (char*)&pRet[1];
  172635. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  172636. memcpy(pRet->zFts5Tbl, zTab, nTab);
  172637. memcpy(pRet->zFts5Db, zDb, nDb);
  172638. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  172639. sqlite3Fts5Dequote(pRet->zFts5Db);
  172640. }
  172641. }
  172642. *ppVTab = (sqlite3_vtab*)pRet;
  172643. return rc;
  172644. }
  172645. /*
  172646. ** The xConnect() and xCreate() methods for the virtual table. All the
  172647. ** work is done in function fts5VocabInitVtab().
  172648. */
  172649. static int fts5VocabConnectMethod(
  172650. sqlite3 *db, /* Database connection */
  172651. void *pAux, /* Pointer to tokenizer hash table */
  172652. int argc, /* Number of elements in argv array */
  172653. const char * const *argv, /* xCreate/xConnect argument array */
  172654. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  172655. char **pzErr /* OUT: sqlite3_malloc'd error message */
  172656. ){
  172657. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  172658. }
  172659. static int fts5VocabCreateMethod(
  172660. sqlite3 *db, /* Database connection */
  172661. void *pAux, /* Pointer to tokenizer hash table */
  172662. int argc, /* Number of elements in argv array */
  172663. const char * const *argv, /* xCreate/xConnect argument array */
  172664. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  172665. char **pzErr /* OUT: sqlite3_malloc'd error message */
  172666. ){
  172667. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  172668. }
  172669. /*
  172670. ** Implementation of the xBestIndex method.
  172671. */
  172672. static int fts5VocabBestIndexMethod(
  172673. sqlite3_vtab *pVTab,
  172674. sqlite3_index_info *pInfo
  172675. ){
  172676. int i;
  172677. int iTermEq = -1;
  172678. int iTermGe = -1;
  172679. int iTermLe = -1;
  172680. int idxNum = 0;
  172681. int nArg = 0;
  172682. for(i=0; i<pInfo->nConstraint; i++){
  172683. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  172684. if( p->usable==0 ) continue;
  172685. if( p->iColumn==0 ){ /* term column */
  172686. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  172687. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  172688. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  172689. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  172690. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  172691. }
  172692. }
  172693. if( iTermEq>=0 ){
  172694. idxNum |= FTS5_VOCAB_TERM_EQ;
  172695. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  172696. pInfo->estimatedCost = 100;
  172697. }else{
  172698. pInfo->estimatedCost = 1000000;
  172699. if( iTermGe>=0 ){
  172700. idxNum |= FTS5_VOCAB_TERM_GE;
  172701. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  172702. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  172703. }
  172704. if( iTermLe>=0 ){
  172705. idxNum |= FTS5_VOCAB_TERM_LE;
  172706. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  172707. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  172708. }
  172709. }
  172710. pInfo->idxNum = idxNum;
  172711. return SQLITE_OK;
  172712. }
  172713. /*
  172714. ** Implementation of xOpen method.
  172715. */
  172716. static int fts5VocabOpenMethod(
  172717. sqlite3_vtab *pVTab,
  172718. sqlite3_vtab_cursor **ppCsr
  172719. ){
  172720. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  172721. Fts5Index *pIndex = 0;
  172722. Fts5Config *pConfig = 0;
  172723. Fts5VocabCursor *pCsr = 0;
  172724. int rc = SQLITE_OK;
  172725. sqlite3_stmt *pStmt = 0;
  172726. char *zSql = 0;
  172727. zSql = sqlite3Fts5Mprintf(&rc,
  172728. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  172729. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  172730. );
  172731. if( zSql ){
  172732. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  172733. }
  172734. sqlite3_free(zSql);
  172735. assert( rc==SQLITE_OK || pStmt==0 );
  172736. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  172737. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  172738. i64 iId = sqlite3_column_int64(pStmt, 0);
  172739. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
  172740. }
  172741. if( rc==SQLITE_OK && pIndex==0 ){
  172742. rc = sqlite3_finalize(pStmt);
  172743. pStmt = 0;
  172744. if( rc==SQLITE_OK ){
  172745. pVTab->zErrMsg = sqlite3_mprintf(
  172746. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  172747. );
  172748. rc = SQLITE_ERROR;
  172749. }
  172750. }
  172751. if( rc==SQLITE_OK ){
  172752. int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  172753. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  172754. }
  172755. if( pCsr ){
  172756. pCsr->pIndex = pIndex;
  172757. pCsr->pStmt = pStmt;
  172758. pCsr->pConfig = pConfig;
  172759. pCsr->aCnt = (i64*)&pCsr[1];
  172760. pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
  172761. }else{
  172762. sqlite3_finalize(pStmt);
  172763. }
  172764. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  172765. return rc;
  172766. }
  172767. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  172768. pCsr->rowid = 0;
  172769. sqlite3Fts5IterClose(pCsr->pIter);
  172770. pCsr->pIter = 0;
  172771. sqlite3_free(pCsr->zLeTerm);
  172772. pCsr->nLeTerm = -1;
  172773. pCsr->zLeTerm = 0;
  172774. }
  172775. /*
  172776. ** Close the cursor. For additional information see the documentation
  172777. ** on the xClose method of the virtual table interface.
  172778. */
  172779. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  172780. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  172781. fts5VocabResetCursor(pCsr);
  172782. sqlite3Fts5BufferFree(&pCsr->term);
  172783. sqlite3_finalize(pCsr->pStmt);
  172784. sqlite3_free(pCsr);
  172785. return SQLITE_OK;
  172786. }
  172787. /*
  172788. ** Advance the cursor to the next row in the table.
  172789. */
  172790. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  172791. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  172792. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  172793. int rc = SQLITE_OK;
  172794. int nCol = pCsr->pConfig->nCol;
  172795. pCsr->rowid++;
  172796. if( pTab->eType==FTS5_VOCAB_COL ){
  172797. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  172798. if( pCsr->aCnt[pCsr->iCol] ) break;
  172799. }
  172800. }
  172801. if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
  172802. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  172803. pCsr->bEof = 1;
  172804. }else{
  172805. const char *zTerm;
  172806. int nTerm;
  172807. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  172808. if( pCsr->nLeTerm>=0 ){
  172809. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  172810. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  172811. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  172812. pCsr->bEof = 1;
  172813. return SQLITE_OK;
  172814. }
  172815. }
  172816. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  172817. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  172818. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  172819. pCsr->iCol = 0;
  172820. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  172821. while( rc==SQLITE_OK ){
  172822. i64 dummy;
  172823. const u8 *pPos; int nPos; /* Position list */
  172824. i64 iPos = 0; /* 64-bit position read from poslist */
  172825. int iOff = 0; /* Current offset within position list */
  172826. rc = sqlite3Fts5IterPoslist(pCsr->pIter, 0, &pPos, &nPos, &dummy);
  172827. if( rc==SQLITE_OK ){
  172828. if( pTab->eType==FTS5_VOCAB_ROW ){
  172829. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  172830. pCsr->aCnt[0]++;
  172831. }
  172832. pCsr->aDoc[0]++;
  172833. }else{
  172834. int iCol = -1;
  172835. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  172836. int ii = FTS5_POS2COLUMN(iPos);
  172837. pCsr->aCnt[ii]++;
  172838. if( iCol!=ii ){
  172839. pCsr->aDoc[ii]++;
  172840. iCol = ii;
  172841. }
  172842. }
  172843. }
  172844. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  172845. }
  172846. if( rc==SQLITE_OK ){
  172847. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  172848. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
  172849. break;
  172850. }
  172851. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  172852. }
  172853. }
  172854. }
  172855. }
  172856. if( pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  172857. while( pCsr->aCnt[pCsr->iCol]==0 ) pCsr->iCol++;
  172858. assert( pCsr->iCol<pCsr->pConfig->nCol );
  172859. }
  172860. return rc;
  172861. }
  172862. /*
  172863. ** This is the xFilter implementation for the virtual table.
  172864. */
  172865. static int fts5VocabFilterMethod(
  172866. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  172867. int idxNum, /* Strategy index */
  172868. const char *idxStr, /* Unused */
  172869. int nVal, /* Number of elements in apVal */
  172870. sqlite3_value **apVal /* Arguments for the indexing scheme */
  172871. ){
  172872. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  172873. int rc = SQLITE_OK;
  172874. int iVal = 0;
  172875. int f = FTS5INDEX_QUERY_SCAN;
  172876. const char *zTerm = 0;
  172877. int nTerm = 0;
  172878. sqlite3_value *pEq = 0;
  172879. sqlite3_value *pGe = 0;
  172880. sqlite3_value *pLe = 0;
  172881. fts5VocabResetCursor(pCsr);
  172882. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  172883. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  172884. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  172885. if( pEq ){
  172886. zTerm = (const char *)sqlite3_value_text(pEq);
  172887. nTerm = sqlite3_value_bytes(pEq);
  172888. f = 0;
  172889. }else{
  172890. if( pGe ){
  172891. zTerm = (const char *)sqlite3_value_text(pGe);
  172892. nTerm = sqlite3_value_bytes(pGe);
  172893. }
  172894. if( pLe ){
  172895. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  172896. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  172897. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  172898. if( pCsr->zLeTerm==0 ){
  172899. rc = SQLITE_NOMEM;
  172900. }else{
  172901. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  172902. }
  172903. }
  172904. }
  172905. if( rc==SQLITE_OK ){
  172906. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  172907. }
  172908. if( rc==SQLITE_OK ){
  172909. rc = fts5VocabNextMethod(pCursor);
  172910. }
  172911. return rc;
  172912. }
  172913. /*
  172914. ** This is the xEof method of the virtual table. SQLite calls this
  172915. ** routine to find out if it has reached the end of a result set.
  172916. */
  172917. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  172918. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  172919. return pCsr->bEof;
  172920. }
  172921. static int fts5VocabColumnMethod(
  172922. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  172923. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  172924. int iCol /* Index of column to read value from */
  172925. ){
  172926. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  172927. if( iCol==0 ){
  172928. sqlite3_result_text(
  172929. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  172930. );
  172931. }
  172932. else if( ((Fts5VocabTable*)(pCursor->pVtab))->eType==FTS5_VOCAB_COL ){
  172933. assert( iCol==1 || iCol==2 || iCol==3 );
  172934. if( iCol==1 ){
  172935. const char *z = pCsr->pConfig->azCol[pCsr->iCol];
  172936. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  172937. }else if( iCol==2 ){
  172938. sqlite3_result_int64(pCtx, pCsr->aDoc[pCsr->iCol]);
  172939. }else{
  172940. sqlite3_result_int64(pCtx, pCsr->aCnt[pCsr->iCol]);
  172941. }
  172942. }else{
  172943. assert( iCol==1 || iCol==2 );
  172944. if( iCol==1 ){
  172945. sqlite3_result_int64(pCtx, pCsr->aDoc[0]);
  172946. }else{
  172947. sqlite3_result_int64(pCtx, pCsr->aCnt[0]);
  172948. }
  172949. }
  172950. return SQLITE_OK;
  172951. }
  172952. /*
  172953. ** This is the xRowid method. The SQLite core calls this routine to
  172954. ** retrieve the rowid for the current row of the result set. The
  172955. ** rowid should be written to *pRowid.
  172956. */
  172957. static int fts5VocabRowidMethod(
  172958. sqlite3_vtab_cursor *pCursor,
  172959. sqlite_int64 *pRowid
  172960. ){
  172961. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  172962. *pRowid = pCsr->rowid;
  172963. return SQLITE_OK;
  172964. }
  172965. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  172966. static const sqlite3_module fts5Vocab = {
  172967. /* iVersion */ 2,
  172968. /* xCreate */ fts5VocabCreateMethod,
  172969. /* xConnect */ fts5VocabConnectMethod,
  172970. /* xBestIndex */ fts5VocabBestIndexMethod,
  172971. /* xDisconnect */ fts5VocabDisconnectMethod,
  172972. /* xDestroy */ fts5VocabDestroyMethod,
  172973. /* xOpen */ fts5VocabOpenMethod,
  172974. /* xClose */ fts5VocabCloseMethod,
  172975. /* xFilter */ fts5VocabFilterMethod,
  172976. /* xNext */ fts5VocabNextMethod,
  172977. /* xEof */ fts5VocabEofMethod,
  172978. /* xColumn */ fts5VocabColumnMethod,
  172979. /* xRowid */ fts5VocabRowidMethod,
  172980. /* xUpdate */ 0,
  172981. /* xBegin */ 0,
  172982. /* xSync */ 0,
  172983. /* xCommit */ 0,
  172984. /* xRollback */ 0,
  172985. /* xFindFunction */ 0,
  172986. /* xRename */ 0,
  172987. /* xSavepoint */ 0,
  172988. /* xRelease */ 0,
  172989. /* xRollbackTo */ 0,
  172990. };
  172991. void *p = (void*)pGlobal;
  172992. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  172993. }
  172994. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  172995. /************** End of fts5.c ************************************************/